MocaUtil.java :  » UnTagged » moca » org » moca » util » Android Open Source

Android Open Source » UnTagged » moca 
moca » org » moca » util » MocaUtil.java
package org.moca.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Random;

import javax.xml.parsers.ParserConfigurationException;

import org.moca.R;
import org.moca.db.MocaDB.ImageSQLFormat;
import org.moca.db.MocaDB.NotificationSQLFormat;
import org.moca.db.MocaDB.PatientSQLFormat;
import org.moca.db.MocaDB.ProcedureSQLFormat;
import org.moca.db.MocaDB.SavedProcedureSQLFormat;
import org.moca.db.MocaDB.SoundSQLFormat;
import org.moca.net.APIException;
import org.moca.net.MDSInterface;
import org.moca.net.ProcedureInfo;
import org.moca.procedure.Procedure;
import org.moca.procedure.ProcedureParseException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.util.Log;


public class MocaUtil {
  public static final String TAG = MocaUtil.class.toString();

    private static final String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String randomString(String prefix, int length) {
      return randomString(prefix, length, alphabet);
    }
    
    public static String randomString(String prefix, int length, String alphabet) {
        StringBuilder sb = new StringBuilder(prefix);
        Random r = new Random();
        int alphabetlength = alphabet.length();
        
        for(int i=0; i<length; i++) {           
            sb.append(alphabet.charAt(r.nextInt(alphabetlength-1)));
        }
        
        return sb.toString();
    } 
    
    public static void errorAlert(Context context, String message) {
        createDialog(context, "Error", message).show();
    }
    
    public static AlertDialog createDialog(Context context, String title, String message) {
        Builder dialogBuilder = new Builder(context);
        dialogBuilder.setPositiveButton("OK", null);
        dialogBuilder.setTitle(title);
        dialogBuilder.setMessage(message);
        return dialogBuilder.create();
    }
    
    public static String getNodeAttributeOrDefault(Node node, String name, String defaultValue) {
        NamedNodeMap attributes = node.getAttributes();
        Node valueNode = attributes.getNamedItem(name);
        String value = defaultValue;
        if(valueNode != null) 
            value = valueNode.getNodeValue();
        return value;
    }
    
    public static <ExceptionType extends Exception> String getNodeAttributeOrFail(Node node, String name, ExceptionType e) throws ExceptionType {
        NamedNodeMap attributes = node.getAttributes();
        Node valueNode = attributes.getNamedItem(name);
        if(valueNode == null)
            throw e;
        return valueNode.getNodeValue();
    }
    

    /**
     * Utility method for deleting all the elements from a given content URI. You have to provide the name of the primary key column.
     * @param ctx the context whose content resolver to use to lookup the URI
     * @param contentUri the content URI to delete all the items from
     * @param idColumn the column of the primary key for the URI
     */
    private static void deleteContentUri(Context ctx, Uri contentUri, String idColumn) {
      ctx.getContentResolver().delete(contentUri, null, null);
    }
    
    /**
     * Deleted all Procedures, SavedProcedures, Images, Sounds, and Notifications from the database.
     * @param ctx
     */
    public static void clearDatabase(Context ctx) {
      deleteContentUri(ctx, ProcedureSQLFormat.CONTENT_URI, ProcedureSQLFormat._ID);
      deleteContentUri(ctx, SavedProcedureSQLFormat.CONTENT_URI, SavedProcedureSQLFormat._ID);
      deleteContentUri(ctx, ImageSQLFormat.CONTENT_URI, ImageSQLFormat._ID);
      deleteContentUri(ctx, SoundSQLFormat.CONTENT_URI, SoundSQLFormat._ID);
      deleteContentUri(ctx, NotificationSQLFormat.CONTENT_URI, NotificationSQLFormat._ID);
    }
    
    public static void clearPatientData(Context ctx) {
      deleteContentUri(ctx, PatientSQLFormat.CONTENT_URI, PatientSQLFormat._ID);
    }
    
    public static void updateProcedureDatabase(Context ctx, ContentResolver cr) throws APIException { 
      List<ProcedureInfo> procedures;
      try {
        procedures = MDSInterface.getAvailableProcedures(ctx);
      } catch (APIException e) {
        Log.e(TAG, "Could not update procedure database because got an exception while getting available procedures: " + e);
        return;
      }
      Log.i(TAG, "Received list of available procedures: " + procedures);

      for (ProcedureInfo info : procedures) {
        try {
          Log.i(TAG, "Inserting procedure " + info.id);
          String procedureData = MDSInterface.getProcedure(ctx, info.id);
          insertProcedure(ctx, procedureData);
        } catch(APIException e) {
          // Propagate APIExceptions 
          throw e;
        } catch(Exception e) {
          Log.e(TAG, "While installing procedure " + info.id + " got exception: " + e);
        } 
        
      }
    }
    
    private static void insertProcedure(Context ctx, String procedureData) throws IOException, ProcedureParseException, SAXException, ParserConfigurationException {
      String title = MocaUtil.randomString("Procedure ", 10);
        String author = "";
        
        //Insert "Find Patient" pages in front of every procedure
        //Convert xml to string
        int idFindPatient = R.raw.findpatient;
        InputStream rsFindPatient = ctx.getResources().openRawResource(idFindPatient);
        byte[] dataFindPatient = new byte[rsFindPatient.available()];
        rsFindPatient.read(dataFindPatient);
        String originalXMLFindPatient = new String(dataFindPatient);
        
        //Remove the Procedure XML header/footer from findpatient.xml
        String findPatientHeader = "<Procedure title=\"Find Patient\">";
        String findPatientFooter = "<//Procedure>";
        String xmlFindPatient = "";
        int strLength = originalXMLFindPatient.length();
        xmlFindPatient = originalXMLFindPatient.substring(findPatientHeader.length()+1,strLength-findPatientFooter.length()-1);            
        
        //Modify the procedure xml
        //Insert the "Find Patient" pages after the Procedure tag and before the procedure's pages
        String startProcHeader = "<Procedure title=";
        String xmlFullProcedure = procedureData;
        if(procedureData.startsWith(startProcHeader))
        {  
          int endOfProcedureTag = procedureData.indexOf(">")+1;
          //Procedure Tag
          String xmlHeader = procedureData.substring(0,endOfProcedureTag);
          //Rest of Procedure
          String xmlRestOfProcedure = procedureData.substring(endOfProcedureTag+1);
          //New Complete Procedure with Find Patient XML
          xmlFullProcedure = xmlHeader + xmlFindPatient + xmlRestOfProcedure;
        }
                    
        Procedure p = Procedure.fromXMLString(xmlFullProcedure);
        title = p.getTitle();
        author = p.getAuthor();
        
        ContentValues cv = new ContentValues();
        cv.put(ProcedureSQLFormat.TITLE, title);
        cv.put(ProcedureSQLFormat.AUTHOR, author);
         
        cv.put(ProcedureSQLFormat.PROCEDURE, xmlFullProcedure);
        ctx.getContentResolver().insert(ProcedureSQLFormat.CONTENT_URI, cv);
        
    }
    
    
    private static void insertProcedureFromRawResource(Context ctx, int id) {
        
        String title = MocaUtil.randomString("Procedure ", 10);
        String author = "";
        String xml;
        try {
            InputStream rs = ctx.getResources().openRawResource(id);
            byte[] data = new byte[rs.available()];
            rs.read(data);
            xml = new String(data);
            
            insertProcedure(ctx, xml);
            return;

        } catch(Exception e) {
            Log.e(TAG, "Couldn't add procedure id=" + id + ", title = " + title + ", to db. Exception : " + e.toString());
        }
    }
    
    /**
     * Loading Moca with XML-described procedures is currently hard-coded. New files can be 
     * added or removed here.
     */
    public static void loadDefaultDatabase(Context ctx) {
      /*insertProcedure(ctx, R.raw.bronchitis);
      insertProcedure(ctx, R.raw.cervicalcancer);
      insertProcedure(ctx, R.raw.surgery_demo);
      
      insertProcedure(ctx, R.raw.tbcontact);
      insertProcedure(ctx, R.raw.multiupload_test); */
      insertProcedureFromRawResource(ctx, R.raw.upload_test);
      insertProcedureFromRawResource(ctx, R.raw.hiv);
      insertProcedureFromRawResource(ctx, R.raw.cervicalcancer);
      insertProcedureFromRawResource(ctx, R.raw.prenatal);
      insertProcedureFromRawResource(ctx, R.raw.surgery);
      insertProcedureFromRawResource(ctx, R.raw.derma);
      insertProcedureFromRawResource(ctx, R.raw.teleradiology);
      insertProcedureFromRawResource(ctx, R.raw.ophthalmology);
      insertProcedureFromRawResource(ctx, R.raw.tbcontact2);
      insertProcedureFromRawResource(ctx, R.raw.tbpatient);
    }

    /** 
     * Returns true 
     * @param c - The current context
     * @return true if Android has either a wifi or cellular connection active
     */
  public static boolean checkConnection(Context c) {
    try {
      //Log.i(TAG, "In checkConnection()");
      TelephonyManager telMan = (TelephonyManager) c.getSystemService(Context.TELEPHONY_SERVICE);
      WifiManager wifiMan = (WifiManager) c.getSystemService(Context.WIFI_SERVICE);
      int dataState = telMan.getDataState();
      Log.i(TAG, "telMan.getDataState(): " + dataState);
      //Log.i(TAG, "TelephonyManager.DATA_CONNECTED: " + TelephonyManager.DATA_CONNECTED);
      if (dataState == TelephonyManager.DATA_CONNECTED || (wifiMan.isWifiEnabled() && wifiMan.pingSupplicant()))
        return true;
      else
        return false;
    }
    catch (Exception e) {
      Log.e(TAG, "Exception in checkConnection(): " + e.toString());
      return false;
    }
  }
}
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.