/** * Get a form instance and case enabled parsing factory */ private static TransactionParserFactory getFactory(final SQLiteDatabase db) { final Hashtable<String, String> formInstanceNamespaces; if (CommCareApplication._().getCurrentApp() != null) { formInstanceNamespaces = FormSaveUtil.getNamespaceToFilePathMap(CommCareApplication._()); } else { formInstanceNamespaces = null; } return new TransactionParserFactory() { @Override public TransactionParser getParser(KXmlParser parser) { String namespace = parser.getNamespace(); if (namespace != null && formInstanceNamespaces != null && formInstanceNamespaces.containsKey(namespace)) { return new FormInstanceXmlParser(parser, CommCareApplication._(), Collections.unmodifiableMap(formInstanceNamespaces), CommCareApplication._().getCurrentApp().fsPath(GlobalConstants.FILE_CC_FORMS)); } else if(CaseXmlParser.CASE_XML_NAMESPACE.equals(parser.getNamespace()) && "case".equalsIgnoreCase(parser.getName())) { return new AndroidCaseXmlParser(parser, getCaseStorage(db), new EntityStorageCache("case", db), new CaseIndexTable(db)) { protected SQLiteDatabase getDbHandle() { return db; } }; } return null; } }; }
/* * (non-Javadoc) * @see org.commcare.android.tasks.templates.CommCareTask#doTaskBackground(java.lang.Object[]) */ @Override protected Boolean doTaskBackground(Void... params) { publishProgress(Localization.get("bulk.form.send.start")); //sanity check if(!(dumpDirectory.isDirectory())){ return false; } File[] files = dumpDirectory.listFiles(); int counter = 0; results = new Long [files.length]; for(int i = 0; i < files.length ; ++i ) { //Assume failure results[i] = FormUploadUtil.FAILURE; } boolean allSuccessful = true; for(int i=0;i<files.length;i++){ publishProgress(Localization.get("bulk.send.dialog.progress",new String[]{""+ (i+1)})); File f = files[i]; if(!(f.isDirectory())){ Log.e("send","Encountered non form entry in file dump folder at path: " + f.getAbsolutePath()); CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(StockMessages.Send_MalformedFile, new String[] {null, f.getName()}, MALFORMED_FILE_CATEGORY)); continue; } try{ User user = CommCareApplication._().getSession().getLoggedInUser(); results[i] = FormUploadUtil.sendInstance(counter,f,url, user); if(results[i] == FormUploadUtil.FULL_SUCCESS){ FileUtil.deleteFile(f); } else if(results[i] == FormUploadUtil.TRANSPORT_FAILURE){ allSuccessful = false; publishProgress(Localization.get("bulk.send.transport.error")); return false; } else{ allSuccessful = false; CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(StockMessages.Send_MalformedFile, new String[] {null, f.getName()}, MALFORMED_FILE_CATEGORY)); publishProgress(Localization.get("bulk.send.file.error", new String[] {f.getAbsolutePath()})); } counter++; } catch(SessionUnavailableException | FileNotFoundException fe){ Log.e("E", Localization.get("bulk.send.file.error", new String[] {f.getAbsolutePath()}), fe); publishProgress(Localization.get("bulk.send.file.error", new String[] {fe.getMessage()})); } } return allSuccessful; }
/* (non-Javadoc) * @see android.os.AsyncTask#onCancelled() */ @Override protected void onCancelled() { super.onCancelled(); if(this.formSubmissionListener != null) { formSubmissionListener.endSubmissionProcess(); } CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(ProcessIssues.LoggedOut)); }
@Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); String licenseKey = getLicenseKey(); map = new MapView(this, licenseKey); this.setContentView(map); mGeoCoder = new Geocoder(this); // Get the location manager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // Define the criteria how to select the locatioin provider -> use // default Criteria criteria = new Criteria(); String provider = mLocationManager.getBestProvider(criteria, false); Location location = mLocationManager.getLastKnownLocation(provider); session = CommCareApplication._().getCurrentSession(); Vector<Entry> entries = session.getEntriesForCommand(session.getCommand()); prototype = entries.elementAt(0); SessionDatum selectDatum = session.getNeededDatum(); Detail detail = session.getDetail(selectDatum.getShortDetail()); NodeEntityFactory factory = new NodeEntityFactory(detail, this.getEC()); Vector<TreeReference> references = getEC().expandReference(selectDatum.getNodeset()); entities = new Vector<Entity<TreeReference>>(); for(TreeReference ref : references) { entities.add(factory.getEntity(ref)); } Log.d(TAG, "Entities generated"); map.displayZoomControls(true); mMyLocationOverlay = new MyLocationOverlay(this, map); mMyLocationOverlay.runOnFirstFix(new Runnable() { public void run() { map.getController().animateTo(mMyLocationOverlay.getMyLocation()); }}); double[] boundHints = new double[4]; // Initialize the location fields if (location != null) { double lat = location.getLatitude(); double lng = location.getLongitude(); //lLat boundHints[0] = lat -1; //lLng boundHints[1] = lng -1; //uLat boundHints[2] = lat + 1; //rLon boundHints[3] = lng + 1; } else { //no location } Drawable defaultMarker = this.getResources().getDrawable(R.drawable.marker); mEntityOverlay = new EntityOverlay(this, defaultMarker, map) { @Override protected void selected(TreeReference ref) { Intent i = new Intent(EntityMapActivity.this.getIntent()); SerializationUtil.serializeToIntent(i, EntityDetailActivity.CONTEXT_REFERENCE, ref); setResult(RESULT_OK, i); EntityMapActivity.this.finish(); } }; Log.d(TAG, "Loading addresses..."); int legit = 0; int bogus = 0; EntityOverlayItemFactory overlayFactory = new EntityOverlayItemFactory(detail, defaultMarker); SqlStorage<GeocodeCacheModel> geoCache = CommCareApplication._().getUserStorage(GeocodeCacheModel.STORAGE_KEY, GeocodeCacheModel.class); for(Entity<TreeReference> e : entities) { for(int i = 0 ; i < detail.getHeaderForms().length; ++i ){ if("address".equals(detail.getTemplateForms()[i])) { String val = e.getFieldString(i).trim(); if(val != null && val != "") { GeoPoint gp = null; try { GeoPointData data = new GeoPointData().cast(new UncastData(val)); if(data != null) { int lat = (int) (data.getValue()[0] * 1E6); int lng = (int) (data.getValue()[1] * 1E6); gp = new GeoPoint(lat, lng); } } catch(Exception ex) { //We might not have a geopoint at all. Don't even trip } boolean cached = false; try { GeocodeCacheModel record = geoCache.getRecordForValue(GeocodeCacheModel.META_LOCATION, val); cached = true; if(record.dataExists()){ gp = record.getGeoPoint(); } } catch(NoSuchElementException nsee) { //no record! } //If we don't have a geopoint, let's try to find our address if(!cached && boundHints != null) { try { List<Address> addresses = mGeoCoder.getFromLocationName(val, 3, boundHints[0], boundHints[1], boundHints[2], boundHints[3]); for(Address a : addresses) { if(a.hasLatitude() && a.hasLongitude()) { int lat = (int) (a.getLatitude() * 1E6); int lng = (int) (a.getLongitude() * 1E6); gp = new GeoPoint(lat, lng); try { geoCache.write(new GeocodeCacheModel(val, lat, lng)); } catch (StorageFullException e1) { //this is the worst exception ever. } legit++; break; } } //We didn't find an address, make a miss record if(gp == null) { try { geoCache.write(GeocodeCacheModel.NoHitRecord(val)); } catch (StorageFullException e1) { //this is the worst exception ever. } } } catch (IOException e1) { e1.printStackTrace(); //Yo. What? I guess bad connection? } } //Ok, so now we have an address or not. If we _do_ have one, let's have some fun if(gp != null) { OverlayItem overlayItem = overlayFactory.generateOverlay(gp, e); mEntityOverlay.addOverlay(overlayItem, e.getElement()); } else { bogus++; } } } } } Log.d(TAG, "Loaded. " + legit +" addresses discovered, " + bogus + " could not be located"); if(legit != 0 && mEntityOverlay.getCenter() != null) { map.getController().animateTo(mEntityOverlay.getCenter()); } else if(location != null) { int lat = (int) (location.getLatitude() * 1E6); int lng = (int) (location.getLongitude() * 1E6); GeoPoint point = new GeoPoint(lat, lng); map.getController().animateTo(point); } map.getOverlays().add(mMyLocationOverlay); //The overlay crashes out if you try to draw it and it's empty, //so only add it if we found something. if(mEntityOverlay.size() > 0) { map.getOverlays().add(mEntityOverlay); } map.getController().setZoom(18); map.setClickable(true); map.setEnabled(true); Log.d(TAG, "Done loading"); }
public IStorageUtilityIndexed cachedStorage() throws SessionUnavailableException{ if (storage == null) { storage = CommCareApplication._().getUserStorage(User.class); } return storage; }