StockUtility.java :  » Stock » stockindia » org » bt » nsestocky » util » Android Open Source

Android Open Source » Stock » stockindia 
stockindia » org » bt » nsestocky » util » StockUtility.java
package org.bt.nsestocky.util;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.apache.http.client.ClientProtocolException;
import org.bt.android.R;
import org.bt.nsestocky.activity.StockIndiaMainMenu;
import org.bt.nsestocky.data.Stock;
import org.bt.nsestocky.data.StockDBHelper;

import com.admob.android.ads.AdManager;
import com.admob.android.ads.AdView;
import com.admob.android.ads.SimpleAdListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.telephony.SmsManager;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;

public class StockUtility implements IStockyConstants {
  private static SharedPreferences prefs;
  private static Context ctx;
  private final static ScheduledExecutorService scheduler =
         Executors.newScheduledThreadPool(1);
   
  public static ScheduledFuture scheduledTaskHandler;
  
  private static NotificationManager nm;
  private static SmsManager sm;  
   
   public static int MAX_LIST_SIZE=10;
   
  public static void initialize(Context c){
    
    if(prefs==null){
      prefs= ((Activity)c).getPreferences(Context.MODE_WORLD_WRITEABLE);
    }
    ctx=c;
    nm= (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    sm= SmsManager.getDefault();
    
  }
  
  public static SharedPreferences getPrefs(){
    return prefs;
  }
  
  public static boolean checkReachMaxSize(){
    return StockDBHelper.getBSEStocksList().size()>=MAX_LIST_SIZE;
  }
  
  public static void showLongToast(String text) {
    Toast t=Toast.makeText(ctx, text, Toast.LENGTH_LONG);
     t.setGravity(Gravity.CENTER, t.getXOffset() / 2, t.getYOffset() / 2);
       t.show();
    
  }
  
  public static void showShortToast(String text) {
    Toast t=Toast.makeText(ctx, text, Toast.LENGTH_SHORT);
     t.setGravity(Gravity.CENTER, t.getXOffset() / 2, t.getYOffset() / 2);
       t.show();
    
  }
  
  
  
  
  public static InputStream getStreamFromServer(String url) throws IOException{
    URL u = new URL(url);
    return u.openStream();
  }
  
  public static Object fetchStockFromAppEng(String stock) {
    System.out.println("Stock Entered: "+stock);
    String reqSymbol = stock.replace("&", "%26");
    reqSymbol = reqSymbol.replace(" ","+");        
    Stock stockObj=null;
    List<Stock> stocksList = new ArrayList();
      try {      
        InputStream is=getStreamFromServer(appEngineURL + reqSymbol);
        System.out.println(appEngineURL + reqSymbol);
        if(is!=null){
          DataInputStream bs = new DataInputStream(is);
          String lineString;
            while ((lineString = bs.readLine()) != null) {
              if(lineString.trim().length()!=0){
                if("0".equals(lineString.trim())){
                  return parseStocks(bs);
                }else{
                stockObj=parseStockObj(lineString);
                stocksList.add(stockObj);
                }
              }
            }
          if(stocksList.size()>0)
            return stocksList;              
      }
    }catch (Exception e) {
      e.printStackTrace();
    }
    return null;      
  
  }
  
  public static Object fetchStockFromBSE(String stock) {
    System.out.println("Stock Entered: "+stock);
//    HttpClient client = getDefaultHttpClient();
//    ClientConnectionManager ccm=client.getConnectionManager();
//    ccm.closeExpiredConnections();
    String reqSymbol = stock.replace("&", "%26");
    reqSymbol = reqSymbol.replace(" ","+");
    DataInputStream bs = null;
      String lineString;
//      HttpGet request = null;
//      HttpResponse resp=null;
      int i=0;
      String code=null;
      try{
        Long.parseLong(stock);
        code=stock;
      }catch(Exception e){}
    if(code==null)
      code=prefs.getString(stock, null);    
    Stock stockObj=null;
      try {      
      if (code == null) {
        InputStream is=getStreamFromServer(bseCodeURL + reqSymbol);
        if(is!=null){
//        if (resp.getStatusLine().getStatusCode() == 200) {
          int lineNum = 24;
          bs = new DataInputStream(is);
          List<Stock> stockList = new ArrayList();
          while ((lineString = bs.readLine()) != null) {
            i++;
            System.out.println(lineString);
            if (i == lineNum) {
              Stock s = new Stock();
              lineString = lineString.trim();
              if(lineString.startsWith("<anchor>")){
              code = lineString.substring(
                  lineString.lastIndexOf("=") + 1,
                  lineString.lastIndexOf("\""));
              stock = lineString.substring(8,lineString.indexOf("<", 2));
//              s.setCode(code);
              s.setCompanyName(stock);
              s.setSymbol(code);
              if(stockList.contains(s)){
                break;
              }
              stockList.add(s);              
              System.out.println(code);
              prefs.edit().putString(stock, code).commit();
              lineNum = lineNum+9;
              }
//              break;
            }
          }
          bs.close();
          
          if(stockList.size()>1){
            return stockList;
          }else if(stockList.size()==1){
            code = stockList.get(0).getSymbol();
          }
        }
      }
      if (code != null) {
        
//        request = new HttpGet(bseDetailURL + code);
        InputStream is=getStreamFromServer(bseDetailURL + code);
        if(is!=null){
//        resp = client.execute(request);
//        if (resp.getStatusLine().getStatusCode() == 200) {
          i = 0;
          bs = new DataInputStream(is);
          stockObj = new Stock(stock);
          while ((lineString = bs.readLine()) != null) {
            i++;
            if (i == 14) {
              String ltt = parseBSEDetail(lineString, "<p>");
              stockObj.setLastTradedTime(ltt);
            } else if (i == 17) {
              String companyName = parseBSEDetail(lineString,
                  "<td>");
              stockObj.setCompanyName(companyName);
              stockObj.setSymbol(code);
//              stockObj.setCode(code);
              stock=companyName;
              lineString = bs.readLine();
              stockObj.setOpen(parseFloatBSEDetail(lineString,
                  "<td>"));
              lineString = bs.readLine();
              stockObj.setHigh(parseFloatBSEDetail(lineString,
                  "<td>"));
              lineString = bs.readLine();
              stockObj.setLow(parseFloatBSEDetail(lineString,
                  "<td>"));
              lineString = bs.readLine();
              stockObj.setLastTradedPrice(parseFloatBSEDetail(
                  lineString, "<td>"));
              lineString = bs.readLine();
              stockObj.setChange(parseFloatBSEDetail(lineString,
                  "<td>"));
              stockObj.setExchange(BSE_EXCHANGE);
              System.out.println(stockObj);
              break;
            }
          }
          prefs.edit().putString(stock, code).commit();
        }

        return stockObj;        
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
//    finally{
//      ccm.shutdown();
//    }
    return null;    
  }
  
  
  
  private static Object parseStocks(DataInputStream bs) throws IOException {
    String lineString;
    Properties p = new Properties();
    while ((lineString = bs.readLine()) != null) {
      if(lineString.trim().length()!=0){
        String[] str = lineString.split("=");
        p.setProperty(str[0], str[1]);
      }
    }
    return p;
  }

  private static Stock parseStockObj(String lineString) {
    String str[]=lineString.split(",");
    Stock s = new Stock();
    s.setLastTradedTime(str[0]);
    s.setCompanyName(str[1]);
    s.setSymbol(str[7]);
    s.setOpen(Float.parseFloat(str[2]));
    s.setHigh(Float.parseFloat(str[3]));
    s.setLow(Float.parseFloat(str[4]));
    s.setLastTradedPrice(Float.parseFloat(str[5]));    
    s.setChange(Float.parseFloat(str[6]));
    return s;
  }

  public static Float parseFloatBSEDetail(String lineString,String startString){
    String retString= lineString.substring(lineString.lastIndexOf(startString)+startString.length(), lineString.indexOf("<br/>"));
    int commaIndex=-1;
    if((commaIndex=retString.indexOf(','))!=-1){
      retString = new StringBuffer(retString).deleteCharAt(commaIndex).toString();
    }
    return Float.parseFloat(retString);
  }
  
  public static String parseBSEDetail(String lineString,String startString){
    return lineString.substring(lineString.lastIndexOf(startString)+startString.length(), lineString.indexOf("<br/>"));
  }
  

  public static void getBSEIndex(){
    if(isNetConnected()){
        try {
          InputStream is=getStreamFromServer(bseHomeURL);
        if(is!=null){
          DataInputStream dis = new DataInputStream(is);
          String lineString;
          int i=0;
          Editor ed=prefs.edit();
          while((lineString=dis.readLine())!=null){
            if(!"".equals(lineString)&& ++i==14){
              ed.putString(BSE_INDEX_LTT_KEY,getBSELTT(lineString));
              lineString=dis.readLine();
              ed.putFloat(BSE_INDEX_KEY, getBSESensex(lineString.trim()));
              lineString=dis.readLine();
              ed.putFloat(BSE_INDEX_CHG_KEY,getBSEChange(lineString.trim()));
              break;
            }
          }
          ed.commit();
        }
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

  }
  
  private static Float getBSEChange(String lineString) {
    String change=lineString.substring(lineString.indexOf("<td>")+4, lineString.indexOf("</td>")).trim();
    return Float.parseFloat(change);
    
  }

  private static Float getBSESensex(String lineString) {
    String sensex=lineString.substring(lineString.lastIndexOf("<td>")+4, lineString.indexOf("<br/>")).trim();
    return Float.parseFloat(sensex);
    
  }

  private static String getBSELTT(String lineString) {
    String day=lineString.substring(lineString.indexOf("<td>")+4, lineString.indexOf("</td>")).trim();
    String time=lineString.substring(lineString.lastIndexOf("<td>")+4, lineString.indexOf("<br/>")-8);
    return new StringBuffer(day).append(" ").append(time).toString();
    
  }
  
  
  
  
  

  private static ConnectivityManager connMgr;
  
  
   public static boolean isNetConnected() {
         if(connMgr==null)
     connMgr=(ConnectivityManager)
 ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
       
         NetworkInfo info=connMgr.getActiveNetworkInfo();
         return(info!=null && info.isConnected());
     
   }
   
   
   public static void scheduleAutoRef(int refInterval){
//     refInterval = 30;
     System.out.println("Scheduling with Refinterval: "+refInterval);
      if(StockUtility.isNetConnected()){
        if(scheduledTaskHandler!=null)
          scheduledTaskHandler.cancel(true);
        scheduledTaskHandler= scheduler.scheduleAtFixedRate(new Runnable(){

        public void run() {
          System.out.println("Inside run..");
          
          refreshAll();          
        }
        
      }, refInterval, refInterval, TimeUnit.SECONDS);
      }
      
    }
   
   public static void refreshAll(){
//     List<Stock> stocksList = StockDBHelper.getBSEStocksList();
//      StringBuffer sb = new StringBuffer();
//      int i=0;
//      for (Stock stock : stocksList) {
//        if(i++!=0)              
//          sb.append(",");
//        sb.append(stock.getSymbol());
//      }
//      List<Stock> newStocksList = new ArrayList();  
//      if(StockUtility.isNetConnected() && sb.length()>0){
//        newStocksList = (List<Stock>) fetchStockFromAppEng(sb.toString());
//      }
//      if(newStocksList!=null){
//        for (int j = 0; j < newStocksList.size(); j++) {
//          Stock stockObj = newStocksList.get(j);
//          updatePortFolioDetails(stockObj, stocksList.get(j));
//          if(stockObj!=null)
//          StockDBHelper.updateStock(stockObj);
//        }
//        getBSEIndex();
//        setNotification();
//      }
     List<Stock> stocksList = StockDBHelper.getBSEStocksList();
      for (Stock stock:stocksList) {
        Object obj= fetchStockFromBSE(stock.getSymbol());
        if(obj instanceof Stock){
          Stock stockObj = (Stock) obj;
          updatePortFolioDetails(stockObj, stock);
          if(stockObj!=null)
          StockDBHelper.updateStock(stockObj);
        }            
      }
      getBSEIndex();
      setNotification();
      
   }
   

   public static String constructNotifyString(){
     StringBuffer sb = new StringBuffer();
     sb.append("SENSEX: ");
     sb.append(prefs.getFloat(BSE_INDEX_KEY, 0));
     sb.append("(");
     sb.append(prefs.getFloat(BSE_INDEX_CHG_KEY, 0));
     sb.append(")");
     sb.append(" ,");
     List<Stock> stocksList = StockDBHelper.getBSEStocksList();
     int count= stocksList.size();    
     if(count>5)
       count=5;
     for (int i = 0; i < count; i++) {
      Stock stock = stocksList.get(i);
      sb.append(stock.displayString());
      sb.append(" ");      
    }
     return sb.toString();
   }
   
   public static void updatePortFolioDetails(Stock newStock, Stock oldStock) {
     if(newStock!=null && oldStock!=null){
      newStock.setNumShares(oldStock.getNumShares());
      newStock.setAlertValue(oldStock.getAlertValue());
      newStock.setCostPrice(oldStock.getCostPrice());
      newStock.setOperation(oldStock.getOperation());  
     }
    }
  public static void fetchBSEAsync() {
     new AsyncTask() {
        protected Object doInBackground(Object... params) {
          getBSEIndex();
          return null;
        }

        @Override
        protected void onPostExecute(Object result) {
          setNotification();
        }
        
          }.execute((Object[])null);
    
  }
  
  public static void fetchFromServer() {
     new AsyncTask() {
        protected Object doInBackground(Object... params) {
          return contactAppEngine();
        }
         protected void onPostExecute(java.lang.Object result){
//           if(result!=null){
//             String message = (String) result;
//             boolean isMessageAlreadyShown=new Boolean(prefs.getString(MESSAGE_SHOWN, "false"));
//              if(!isMessageAlreadyShown){
//             showLongToast(message);
//              prefs.edit().putString(MESSAGE_SHOWN, "true");              
//              prefs.edit().commit();
//              System.out.println(prefs.getString(MESSAGE_SHOWN, "fals"));
//              }
//           }
         }

        
          }.execute((Object[])null);
    
  }
  
  
  protected static String contactAppEngine() {
    
    try {
//      LocationManager lm=(LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
//      Location l=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

      DataInputStream dis = new DataInputStream(getStreamFromServer(appEngineURL+"req=init"));
      String lineString;
//      StringBuffer sb = new StringBuffer();
//      Boolean showForSure=false;;
//      while ((lineString = dis.readLine()) != null) {
//        if(lineString.trim().length()!=0){
//          if("true".equals(lineString) || "false".equals(lineString)){
//            showForSure=new Boolean(lineString);
//          }else
//          sb.append(lineString);
//        }
//      }
//      boolean isMessageAlreadyShown=prefs.getBoolean(MESSAGE_SHOWN, false);
//      if(showForSure || !isMessageAlreadyShown){
//        return sb.toString();
      dis.close();
//      }
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return null;
  }

  public static String getHelpText(){
    StringBuffer sb = new StringBuffer();
    sb.append("1. My Stocks --> Add(Menu) to add new stocks to your watchlist");
    sb.append("\n\n2. BSE: \n   BSE supports query by stock code/name only not by symbol, so user should enter company name/code (refer to www.bseindia.com)" +
        "\n   e.g. a. INFOSYS for INFOSYS TECHNOLOGIES" +
        "\n        b. TATA will match for TATA MOTORS, TATA STEEL etc.. so list of companies will be shown" +
        "\n       c. If you know scrip code directly enter the code ,  i.e 500209 for INFOSYS ");
    sb.append("\n\n3. Select the stock and click on refresh/delete icons to refresh or delete selected stock\n\n");
    sb.append("4. My Portfolio --> select a stock to enter your portfolio\n\n");
    sb.append("5. New features will be added if and only if there is GOOD SUPPORT/RATING from the users\n " +
        "(Remember its free and I should get some motivation to continue development :) )\n\n");
    sb.append("6. Suggestions/Issues write to me -> appsnaindia@gmail.com");
    return sb.toString();
    
  }
  public static Stock getDummyStock(){
      Stock s= new Stock();
      s.setSymbol("TCS");
      s.setCompanyName("Tata Consultancy Services");
      s.setHigh(100.23f);
      s.setLow(90.25f);
      s.setChange(9.02f);
      s.setLastTradedPrice(99.02f);
      s.setLastTradedTime("10:25:55");
      s.setCostPrice(95.24f);
      s.setNumShares(55);
      s.setPrev(92.25f);
      s.setOpen(93.5f);     
      return s;
    }
  
  
  public static void setNotification() {
    nm.cancel(NOTIFICATION_ID);
      PendingIntent pi = PendingIntent.getActivity(ctx, 0, new Intent(ctx,StockIndiaMainMenu.class), Intent.FLAG_ACTIVITY_NO_HISTORY);
//      RemoteViews rv = new RemoteViews(ctx.getPackageName(), R.layout.statusbar);
      String notifyString = constructNotifyString();
//      rv.setTextViewText(R.id.statustext, notifyString);
//      rv.setTextColor(R.id.statustext, Color.BLACK);int notificationID = 10;

      Notification n = new Notification(R.drawable.stock, notifyString, System.currentTimeMillis());
      n.tickerText=notifyString;
      n.contentIntent=pi;
      n.setLatestEventInfo(ctx, "BSE", constructNotifyString(), pi);
//      n.contentView=rv;
      nm.notify(NOTIFICATION_ID, n);
      
  }
  
  public static void sendSMS(String number){
    PendingIntent pi = PendingIntent.getActivity(ctx,  0,
              new Intent(ctx, StockIndiaMainMenu.class), 0);
    sm.sendTextMessage(number, null, SMS_MESSAGE, pi, null);
  }
  
  public static int netGainLoss(){
    List<Stock> stocksList = new ArrayList(StockDBHelper.getBSEStocksList());
    Float netValue=0f;
    for (Stock stock : stocksList) {
      if(stock.getNumShares()!=null && stock.getCostPrice()!=null){
        netValue+=stock.getNumShares()*(stock.getLastTradedPrice()-stock.getCostPrice());
      }
    }    
    return Math.round(netValue);
  }

  public static void initAd(Activity activity) {
    AdManager.setTestDevices( new String[] { AdManager.TEST_EMULATOR } );
      AdView ad = (AdView) activity.findViewById(R.id.ad);
        ad.setAdListener(new SimpleAdListener());
        ad.setVisibility(View.VISIBLE);
        ad.requestFreshAd();
    
  }
  
  public static boolean checkNumber(String str){
      try{
        Integer.parseInt(str);
        return true;
      }catch (Exception e) {
      return false;
    }
    }
  
  public static void donateMeWebView(Activity activity){
    AlertDialog.Builder ab = new AlertDialog.Builder(activity);
    WebView wv= new WebView(activity);
//    wv.loadData(data, "text/html", "utf8");
    ab.setView(wv);
    ab.show();
    
  }
  /*
    private static final String INMOBI_ADVIEW_TAG = "InMobiAdViewArea";
      private static Thread adRefresher;
    private static InMobiAdRenderer adRenderer;
    private static boolean execute;
    private static Activity adActivity;
      
      public static void initInMobiAd(InMobiAdDelegate delegate,Activity activity){
        adRenderer = InMobiRuntime.initializeAdRenderer(delegate, activity);
         execute = true;
           adRefresher = new Thread() {

               @Override
               public void run() {
                   while (execute) {
                       try {
                           loadNewInMobiAd();
                           Thread.sleep(20 * 1000);// 60 seconds
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
               }
           };
           adRefresher.start();

      }
   private static void loadNewInMobiAd() {
          Future<Boolean> adLoadResult = null;

          adLoadResult = adRenderer.loadNewAd();
          for (int i = 0; i < 60 && !adLoadResult.isDone(); i++) {
              try {
                  Thread.sleep(500);
              } catch (InterruptedException e) {
                  Log.e("InMobiSampleApp", "interrupted exception, waiting for ad to load");
              }
          }
          boolean isRequestSuccessful = retrieveAdLoadResult(adLoadResult);
          if (isRequestSuccessful && execute) {
              addInMobiAdView();
          }

      }

   private static FrameLayout parentView;
      public static void addInMobiAdView() {
         
            adActivity.runOnUiThread(new Runnable() {               

          public void run() {
            setAd(parentView);                    
                  }
              });
          }
//      else {
//              return;
//          }

//      }

      protected static void setAd(FrameLayout v) {
        if(adRenderer.getViewArea()!=null){
         LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 0, 0, 0);
            params.gravity=Gravity.BOTTOM;
             View adViewArea =    adRenderer.getViewArea();
             adViewArea.setTag(INMOBI_ADVIEW_TAG);
             int childCount=v.getChildCount();                      
             if(childCount>1){
               v.removeViewAt(0);
             }
             v.addView(adViewArea,0,params);
        }
      
    }

    private static boolean retrieveAdLoadResult(Future<Boolean> adLoadResult) {

          boolean status = false;
          try { 
              if (adLoadResult.isDone()) {
                  status = adLoadResult.get().booleanValue();
              }
          } catch (InterruptedException interruptedException) {
              Log.e("InMobiSampleApp", "error loading ad", interruptedException);
          } catch (ExecutionException executionException) {
              Log.e("InMobiSampleApp", "error loading ad", executionException);
          }
          return status;

      }

    public static void setAdActivity(Activity activity,
        FrameLayout rl) {
      adActivity = activity;
      if(parentView!=null){
         int childCount=parentView.getChildCount();                      
                 if(childCount>1){
                   parentView.removeViewAt(0);
                 }
                 
                 setAd(rl);
      }
      parentView = rl;
      
    }
    */
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.