public static Car instantiateCar(String object) { if (object == null) return null; ObjectInputStream ois = null; try { Base64InputStream b64 = new Base64InputStream(new ByteArrayInputStream(object.getBytes()), Base64.DEFAULT); ois = new ObjectInputStream(b64); Car car = (Car) ois.readObject(); return car; } catch (StreamCorruptedException e) { logger.warn(e.getMessage(), e); } catch (IOException e) { logger.warn(e.getMessage(), e); } catch (ClassNotFoundException e) { logger.warn(e.getMessage(), e); } finally { if (ois != null) try { ois.close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } } return null; }
private void getCarsFromCache() { File directory; try { directory = Util.resolveExternalStorageBaseFolder(); File f = new File(directory, CarManager.CAR_CACHE_FILE_NAME); if (f.isFile()) { BufferedReader bufferedReader = new BufferedReader(new FileReader(f)); String content = ""; String line = ""; while ((line = bufferedReader.readLine()) != null) { content = content.concat(line); } bufferedReader.close(); JSONArray cars = new JSONArray(content); addSensorsToList(cars); } } catch (IOException e) { logger.warn(e.getMessage(), e); } catch (JSONException e) { logger.warn(e.getMessage(), e); } }
public static String serializeCar(Car car) { ObjectOutputStream oos = null; Base64OutputStream b64 = null; try { ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream(); oos = new ObjectOutputStream(byteArrayOut); oos.writeObject(car); oos.flush(); ByteArrayOutputStream out = new ByteArrayOutputStream(); b64 = new Base64OutputStream(out, Base64.DEFAULT); b64.write(byteArrayOut.toByteArray()); b64.flush(); b64.close(); out.flush(); out.close(); String result = new String(out.toByteArray()); return result; } catch (IOException e) { logger.warn(e.getMessage(), e); } finally { if (oos != null) try { b64.close(); oos.close(); } catch (IOException e) { logger.warn(e.getMessage(), e); } } return null; }
private void addSensorsToList(JSONArray res) { for (int i = 0; i < res.length(); i++) { String typeString; JSONObject properties; String carId; try { typeString = ((JSONObject) res.get(i)).optString("type", "none"); properties = ((JSONObject) res.get(i)).getJSONObject("properties"); carId = properties.getString("id"); } catch (JSONException e) { logger.warn(e.getMessage(), e); continue; } if (typeString.equals(SENSOR_TYPE)) { try { sensors.add(Car.fromJsonWithStrictEngineDisplacement(properties)); } catch (JSONException e) { logger.warn( String.format( "Car '%s' not supported: %s", carId != null ? carId : "null", e.getMessage())); } } } SensorAdapter adapter = new SensorAdapter(); sensorSpinner.setAdapter(adapter); int index = adapter.getInitialSelectedItem(); sensorSpinner.setSelection(index); }
public void getCarList() { sensorDlProgress.setVisibility(View.VISIBLE); sensorSpinner.setVisibility(View.GONE); sensorRetryButton.setVisibility(View.GONE); sensors = new ArrayList<Car>(); if (((SettingsActivity) getContext()).isConnectedToInternet()) { try { new SensorDownloadTask().execute().get(); } catch (Exception e) { logger.warn(e.getMessage(), e); Toast.makeText(getContext(), "Could not retrieve cars from server", Toast.LENGTH_SHORT) .show(); } // TODO add possibility to update cache // downloadSensors(true); } else { getCarsFromCache(); } if (sensors.isEmpty()) { logger.warn("Got no cars neither from server nor from cache."); // TODO show warning that no cars were found i18n Toast.makeText( getContext(), "Could not retrieve cars from server or local cache", Toast.LENGTH_SHORT) .show(); } sensorDlProgress.setVisibility(View.GONE); sensorSpinner.setVisibility(View.VISIBLE); }
/** * Creates a Track and adds its contents to the DB layer (adapter). * * @param json the input json object * @param adapter the DB layer adapter * @return the Track object * @throws JSONException parsing fails or contains unexpected properties * @throws ParseException if DateTime parsing fails */ public static Track fromJson(JSONObject json, DbAdapter adapter) throws JSONException, ParseException { JSONObject trackProperties = json.getJSONObject("properties"); Track t = Track.createRemoteTrack(trackProperties.getString("id"), adapter); String trackName = "unnamed Track #" + t.getId(); try { trackName = trackProperties.getString("name"); } catch (JSONException e) { logger.warn(e.getMessage(), e); } t.setName(trackName); String description = ""; try { description = trackProperties.getString("description"); } catch (JSONException e) { logger.warn(e.getMessage(), e); } t.setDescription(description); JSONObject sensorProperties = trackProperties.getJSONObject("sensor").getJSONObject("properties"); t.setCar(Car.fromJson(sensorProperties)); // include server properties tracks created, modified? t.dbAdapter.updateTrack(t); // Log.i("track_id",t.getId()+" "+((DbAdapterRemote) // dbAdapter).trackExistsInDatabase(t.getId())+" "+dbAdapter.getNumberOfStoredTracks()); Measurement recycleMeasurement; List<Measurement> measurements = new ArrayList<Measurement>(); JSONArray features = json.getJSONArray("features"); logger.info( "Parsing measurements of track " + t.getRemoteID() + ". Count: " + features.length()); for (int j = 0; j < features.length(); j++) { JSONObject measurementJsonObject = features.getJSONObject(j); recycleMeasurement = Measurement.fromJson(measurementJsonObject); recycleMeasurement.setTrack(t); measurements.add(recycleMeasurement); } t.setMeasurementsAsArrayList(measurements); logger.info("Storing measurements in database"); t.storeMeasurementsInDbAdapter(); return t; }
/** @return the measurements */ public List<Measurement> getMeasurements() { if ((measurements == null || measurements.isEmpty()) && dbAdapter != null) { try { this.measurements = dbAdapter.getAllMeasurementsForTrack(this); } catch (TrackWithoutMeasurementsException e) { logger.warn(e.getMessage(), e); } } return measurements; }
private void storeMeasurementsInDbAdapter() { if (this.dbAdapter != null) { for (Measurement measurement : measurements) { try { this.dbAdapter.insertMeasurement(measurement); } catch (MeasurementsException e) { logger.warn(e.getMessage(), e); } } } }
/** * Use this method only to insert "fresh" measurements, not to recreate a Track from the database * Use {@code insertMeasurement(ArrayList<Measurement> measurements)} instead Inserts measurments * into the Track and into the database! * * @param measurement * @throws TrackAlreadyFinishedException * @throws MeasurementsException */ public void addMeasurement(Measurement measurement) throws TrackAlreadyFinishedException { measurement.setTrack(Track.this); this.measurements.add(measurement); if (this.dbAdapter != null) { try { this.dbAdapter.insertNewMeasurement(measurement); } catch (MeasurementsException e) { logger.severe("This should never happen", e); return; } } else { logger.warn("DbAdapter was null! Could not insert measurement"); } }
/** * Returns the average co2 emission for the track. * * @return */ public double getCO2Average() { double co2Average = 0.0; try { for (Measurement measurement : measurements) { if (measurement.getProperty(CONSUMPTION) != null) { co2Average = co2Average + consumptionAlgorithm.calculateCO2FromConsumption( measurement.getProperty(CONSUMPTION)); } } co2Average = co2Average / measurements.size(); } catch (FuelConsumptionException e) { logger.warn(e.getMessage(), e); } return co2Average; }
public double getFuelConsumptionPerHour() throws UnsupportedFuelTypeException { if (consumptionPerHour == null) { consumptionPerHour = 0.0; int consideredCount = 0; for (int i = 0; i < measurements.size(); i++) { try { consumptionPerHour = consumptionPerHour + consumptionAlgorithm.calculateConsumption(measurements.get(i)); consideredCount++; } catch (FuelConsumptionException e) { logger.warn(e.getMessage()); } } consumptionPerHour = consumptionPerHour / consideredCount; } return consumptionPerHour; }
protected String downloadSensors() throws Exception { HttpGet getRequest = new HttpGet(ECApplication.BASE_URL + "/sensors"); getRequest.addHeader("Accept-Encoding", "application/json"); try { HttpResponse response = HTTPClient.execute(getRequest); String content = HTTPClient.readResponse(response.getEntity()); JSONObject parentObject = new JSONObject(content); JSONArray res = (JSONArray) parentObject.get("sensors"); addSensorsToList(res); } catch (Exception e) { logger.warn(e.getMessage(), e); throw e; } return ""; }