List of usage examples for java.util Vector toArray
@SuppressWarnings("unchecked") public synchronized <T> T[] toArray(T[] a)
From source file:org.schabi.newpipe.services.youtube.YoutubeVideoExtractor.java
private VideoInfo.AudioStream[] parseDashManifest(String dashManifest, String decryptoinCode) { if (!dashManifest.contains("/signature/")) { String encryptedSig = matchGroup1("/s/([a-fA-F0-9\\.]+)", dashManifest); String decryptedSig;/* w ww . j ava 2s .c o m*/ decryptedSig = decryptSignature(encryptedSig, decryptoinCode); dashManifest = dashManifest.replace("/s/" + encryptedSig, "/signature/" + decryptedSig); } String dashDoc = Downloader.download(dashManifest); Vector<VideoInfo.AudioStream> audioStreams = new Vector<>(); try { XmlPullParser parser = Xml.newPullParser(); parser.setInput(new StringReader(dashDoc)); int eventType = parser.getEventType(); String tagName = ""; String currentMimeType = ""; int currentBandwidth = -1; int currentSamplingRate = -1; boolean currentTagIsBaseUrl = false; while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: tagName = parser.getName(); if (tagName.equals("AdaptationSet")) { currentMimeType = parser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "mimeType"); } else if (tagName.equals("Representation") && currentMimeType.contains("audio")) { currentBandwidth = Integer .parseInt(parser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "bandwidth")); currentSamplingRate = Integer.parseInt( parser.getAttributeValue(XmlPullParser.NO_NAMESPACE, "audioSamplingRate")); } else if (tagName.equals("BaseURL")) { currentTagIsBaseUrl = true; } break; case XmlPullParser.TEXT: if (currentTagIsBaseUrl && (currentMimeType.contains("audio"))) { int format = -1; if (currentMimeType.equals(MediaFormat.WEBMA.mimeType)) { format = MediaFormat.WEBMA.id; } else if (currentMimeType.equals(MediaFormat.M4A.mimeType)) { format = MediaFormat.M4A.id; } audioStreams.add(new VideoInfo.AudioStream(parser.getText(), format, currentBandwidth, currentSamplingRate)); } case XmlPullParser.END_TAG: if (tagName.equals("AdaptationSet")) { currentMimeType = ""; } else if (tagName.equals("BaseURL")) { currentTagIsBaseUrl = false; } break; default: } eventType = parser.next(); } } catch (Exception e) { e.printStackTrace(); } return audioStreams.toArray(new VideoInfo.AudioStream[audioStreams.size()]); }
From source file:org.apache.ojb.broker.metadata.ClassDescriptor.java
/** * Return an array of PK FieldDescription sorted ascending * according to the field-descriptions getOrder() property *//*from w w w . j a v a 2 s . co m*/ public FieldDescriptor[] getPkFields() { if (m_PkFieldDescriptors == null) { // 1. collect all Primary Key fields from Field list Vector vec = new Vector(); // 1.a if descriptor describes an interface: take PK fields from an implementors ClassDescriptor if (m_isInterface) { if (getExtentClasses().size() == 0) { throw new PersistenceBrokerException( "No Implementors declared for interface " + this.getClassOfObject().getName()); } Class implementor = (Class) getExtentClasses().get(0); ClassDescriptor implCld = this.getRepository().getDescriptorFor(implementor); m_PkFieldDescriptors = implCld.getPkFields(); } else { FieldDescriptor[] fields; // 1.b if not an interface The classdescriptor must have FieldDescriptors fields = getFieldDescriptions(); // now collect all PK fields for (int i = 0; i < fields.length; i++) { FieldDescriptor fd = fields[i]; if (fd.isPrimaryKey()) { vec.add(fd); } } // 2. Sort fields according to their getOrder() Property Collections.sort(vec, FieldDescriptor.getComparator()); m_PkFieldDescriptors = (FieldDescriptor[]) vec.toArray(new FieldDescriptor[vec.size()]); } } return m_PkFieldDescriptors; }
From source file:de.juwimm.cms.remote.ViewServiceSpringImpl.java
/** * @see de.juwimm.cms.remote.ViewServiceSpring#getAllViewComponents4UnitAndStatus(java.lang.Integer, java.lang.Integer, int) *//*from w w w . ja v a 2 s . c om*/ @Override protected ViewComponentValue[] handleGetAllViewComponents4UnitAndStatus(Integer unitId, Integer viewDocumentId, int intStatus) throws Exception { try { Vector<ViewComponentValue> vec = new Vector<ViewComponentValue>(); ViewComponentHbm view = super.getViewComponentHbmDao().find4Unit(unitId, viewDocumentId); this.getAllViewComponentsChildren4Status(view, vec, intStatus, unitId); return vec.toArray(new ViewComponentValue[0]); } catch (Exception e) { throw new UserException(e.getMessage()); } }
From source file:alberthsu.sunshine.app.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us./* w w w . ja va 2 s . co m*/ */ private void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting) throws JSONException { // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; final String OWM_COORD_LAT = "lat"; final String OWM_COORD_LONG = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_DATETIME = "dt"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject coordJSON = cityJson.getJSONObject(OWM_COORD); double cityLatitude = coordJSON.getLong(OWM_COORD_LAT); double cityLongitude = coordJSON.getLong(OWM_COORD_LONG); Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude); // Insert the location into the database. long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Get and insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". dateTime = dayForecast.getLong(OWM_DATETIME); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationID); weatherValues.put(WeatherEntry.COLUMN_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L))); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } }
From source file:com.adkdevelopment.earthquakesurvival.data.syncadapter.SyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {/*from w ww .ja va 2 s . com*/ Context context = getContext(); App.getApiManager().getEarthquakeService().getData().enqueue(new Callback<EarthquakeObject>() { @Override public void onResponse(Call<EarthquakeObject> call, Response<EarthquakeObject> response) { EarthquakeObject earthquake = response.body(); Vector<ContentValues> cVVector = new Vector<>(earthquake.getFeatures().size()); double currentBiggest = 0.0; ContentValues notifyValues = null; for (Feature each : earthquake.getFeatures()) { ContentValues earthquakeValues = new ContentValues(); earthquakeValues.put(EarthquakeColumns.PLACE, each.getProperties().getPlace()); earthquakeValues.put(EarthquakeColumns.ID_EARTH, each.getId()); earthquakeValues.put(EarthquakeColumns.MAG, each.getProperties().getMag()); earthquakeValues.put(EarthquakeColumns.TYPE, each.getProperties().getType()); earthquakeValues.put(EarthquakeColumns.ALERT, each.getProperties().getAlert()); earthquakeValues.put(EarthquakeColumns.TIME, each.getProperties().getTime()); earthquakeValues.put(EarthquakeColumns.URL, each.getProperties().getUrl()); earthquakeValues.put(EarthquakeColumns.DETAIL, each.getProperties().getDetail()); earthquakeValues.put(EarthquakeColumns.DEPTH, each.getGeometry().getCoordinates().get(2)); earthquakeValues.put(EarthquakeColumns.LONGITUDE, each.getGeometry().getCoordinates().get(0)); earthquakeValues.put(EarthquakeColumns.LATITUDE, each.getGeometry().getCoordinates().get(1)); LatLng latLng = new LatLng(each.getGeometry().getCoordinates().get(1), each.getGeometry().getCoordinates().get(0)); LatLng location = LocationUtils.getLocation(context); earthquakeValues.put(EarthquakeColumns.DISTANCE, LocationUtils.getDistance(latLng, location)); cVVector.add(earthquakeValues); if (each.getProperties().getMag() != null && each.getProperties().getMag() > currentBiggest) { currentBiggest = each.getProperties().getMag(); notifyValues = new ContentValues(earthquakeValues); notifyValues.put(EarthquakeColumns.PLACE, Utilities.formatEarthquakePlace(each.getProperties().getPlace())); } } int inserted = 0; // add to database ContentResolver resolver = context.getContentResolver(); if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = resolver.bulkInsert(EarthquakeColumns.CONTENT_URI, cvArray); } // Set the date to day minus one to delete old data from the database Date date = new Date(); date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS); int deleted = resolver.delete(EarthquakeColumns.CONTENT_URI, EarthquakeColumns.TIME + " <= ?", new String[] { String.valueOf(date.getTime()) }); Log.v(TAG, "Service Complete. " + inserted + " Inserted, " + deleted + " deleted"); sendNotification(notifyValues); } @Override public void onFailure(Call<EarthquakeObject> call, Throwable t) { Log.e(TAG, "onFailure: " + t.toString()); } }); App.getNewsManager().getNewsService().getNews().enqueue(new Callback<Rss>() { @Override public void onResponse(Call<Rss> call, Response<Rss> response) { Channel news = response.body().getChannel(); Vector<ContentValues> cVVector = new Vector<>(news.getItem().size()); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.getDefault()); Date date = new Date(); for (Item each : news.getItem()) { ContentValues weatherValues = new ContentValues(); try { date = simpleDateFormat.parse(each.getPubDate()); } catch (ParseException e) { Log.e(TAG, "e:" + e); } weatherValues.put(NewsColumns.DATE, date.getTime()); weatherValues.put(NewsColumns.TITLE, each.getTitle()); weatherValues.put(NewsColumns.DESCRIPTION, Html.toHtml(new SpannedString(each.getDescription()))); weatherValues.put(NewsColumns.URL, each.getLink()); weatherValues.put(NewsColumns.GUID, each.getGuid().getContent()); cVVector.add(weatherValues); } int inserted = 0; // add to database ContentResolver resolver = getContext().getContentResolver(); if (cVVector.size() > 0) { // Student: call bulkInsert to add the weatherEntries to the database here ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = resolver.bulkInsert(NewsColumns.CONTENT_URI, cvArray); } // Set the date to day minus two to delete old data from the database date = new Date(); date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS * 3); int deleted = resolver.delete(NewsColumns.CONTENT_URI, NewsColumns.DATE + " <= ?", new String[] { String.valueOf(date.getTime()) }); } @Override public void onFailure(Call<Rss> call, Throwable t) { Log.e(TAG, "onFailure: " + t.toString()); } }); // TODO: 4/22/16 possible refactoring //checking the last update and notify if it' the first of the day SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String lastNotificationKey = context.getString(R.string.sharedprefs_key_last_countupdate); long lastSync = prefs.getLong(lastNotificationKey, DateUtils.DAY_IN_MILLIS); if (System.currentTimeMillis() - lastSync >= Utilities.getSyncIntervalPrefs(context) * DateUtils.SECOND_IN_MILLIS) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US); Date date = new Date(System.currentTimeMillis()); String startTime[] = new String[] { simpleDateFormat.format(date.getTime() - DateUtils.YEAR_IN_MILLIS), simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS * 30), simpleDateFormat.format(date.getTime() - DateUtils.WEEK_IN_MILLIS), simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS) }; String endTime = simpleDateFormat.format(date); int iterator = 1; while (iterator < CountColumns.ALL_COLUMNS.length) { final int round = iterator; App.getApiManager().getEarthquakeService().getEarthquakeStats(startTime[round - 1], endTime) .enqueue(new Callback<CountEarthquakes>() { @Override public void onResponse(Call<CountEarthquakes> call, Response<CountEarthquakes> response) { ContentValues count = new ContentValues(); count.put(CountColumns.ALL_COLUMNS[round], response.body().getCount()); ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query(CountColumns.CONTENT_URI, null, null, null, null); if (cursor != null) { if (cursor.getCount() < 1) { long inserted = ContentUris .parseId(contentResolver.insert(CountColumns.CONTENT_URI, count)); //Log.d(TAG, "inserted:" + inserted); } else { int updated = contentResolver.update(CountColumns.CONTENT_URI, count, CountColumns._ID + " = ?", new String[] { "1" }); //Log.d(TAG, "updated: " + updated); } cursor.close(); } } @Override public void onFailure(Call<CountEarthquakes> call, Throwable t) { Log.e(TAG, "Error: " + t); } }); iterator++; } //refreshing last sync prefs.edit().putLong(lastNotificationKey, System.currentTimeMillis()).apply(); } // notify PagerActivity that data has been updated context.getContentResolver().notifyChange(EarthquakeColumns.CONTENT_URI, null, false); context.getContentResolver().notifyChange(NewsColumns.CONTENT_URI, null, false); context.getContentResolver().notifyChange(CountColumns.CONTENT_URI, null, false); updateWidgets(); }
From source file:com.swisscom.android.sunshine.data.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us./* ww w . jav a2 s . c o m*/ */ private Void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting) throws JSONException { // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; final String OWM_COORD_LAT = "lat"; final String OWM_COORD_LONG = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_DATETIME = "dt"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject coordJSON = cityJson.getJSONObject(OWM_COORD); double cityLatitude = coordJSON.getLong(OWM_COORD_LAT); double cityLongitude = coordJSON.getLong(OWM_COORD_LONG); Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude); // Insert the location into the database. long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Get and insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". dateTime = dayForecast.getLong(OWM_DATETIME); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationID); weatherValues.put(WeatherEntry.COLUMN_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L))); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); int rowsInserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); Log.v(LOG_TAG, "inserted " + rowsInserted + " rows of weather data"); } return null; }
From source file:de.juwimm.cms.remote.ViewServiceSpringImpl.java
/** * @see de.juwimm.cms.remote.ViewServiceSpring#getViewDocuments4Site(java.lang.Integer) *///w w w .jav a2 s.c o m @Override protected ViewDocumentValue[] handleGetViewDocuments4Site(Integer siteId) throws Exception { try { Vector<ViewDocumentValue> vec = new Vector<ViewDocumentValue>(); Iterator it = super.getViewDocumentHbmDao().findAll(siteId).iterator(); while (it.hasNext()) { vec.addElement(((ViewDocumentHbm) it.next()).getDao()); } return vec.toArray(new ViewDocumentValue[0]); } catch (Exception e) { throw new UserException(e.getMessage()); } }
From source file:com.udacity.sunshine.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us.//from w ww . jav a2 s . c o m */ private void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting) throws JSONException { // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; final String OWM_COORD_LAT = "lat"; final String OWM_COORD_LONG = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_DATETIME = "dt"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject coordJSON = cityJson.getJSONObject(OWM_COORD); double cityLatitude = coordJSON.getLong(OWM_COORD_LAT); double cityLongitude = coordJSON.getLong(OWM_COORD_LONG); Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude); // Insert the location into the database. long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Get and insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". dateTime = dayForecast.getLong(OWM_DATETIME); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationID); weatherValues.put(WeatherEntry.COLUMN_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L))); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " inserted."); }
From source file:com.example.danstormont.sunshine.app.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us./*from ww w . j ava 2s .co m*/ */ private void getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationSetting) throws JSONException { // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; final String OWM_COORD_LAT = "lat"; final String OWM_COORD_LONG = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_DATETIME = "dt"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject coordJSON = cityJson.getJSONObject(OWM_COORD); double cityLatitude = coordJSON.getDouble(OWM_COORD_LAT); double cityLongitude = coordJSON.getDouble(OWM_COORD_LONG); Log.v(LOG_TAG, cityName + ", with coord: " + cityLatitude + " " + cityLongitude); // Insert the location into the database. long locationID = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Get and insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // The date/time is returned as a long. We need to convert that // into something human-readable, since most people won't read "1400356800" as // "this saturday". dateTime = dayForecast.getLong(OWM_DATETIME); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationID); weatherValues.put(WeatherEntry.COLUMN_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L))); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); int rowsInserted = mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, cvArray); Log.v(LOG_TAG, "inserted " + rowsInserted + " rows of weather data"); } // Use a DEBUG variable to gate whether or not you do this, so you can easily // turn it on and off, and so that it's easy to see what you can rip out if // you ever want to remove it. if (DEBUG) { Cursor weatherCursor = mContext.getContentResolver().query(WeatherEntry.CONTENT_URI, null, null, null, null); if (weatherCursor.moveToFirst()) { ContentValues resultValues = new ContentValues(); DatabaseUtils.cursorRowToContentValues(weatherCursor, resultValues); Log.v(LOG_TAG, "Query succeeded! **********"); for (String key : resultValues.keySet()) { Log.v(LOG_TAG, key + ": " + resultValues.getAsString(key)); } } else { Log.v(LOG_TAG, "Query failed! :( **********"); } } } }
From source file:no.feide.moria.directory.backend.JNDIBackend.java
/** * Retrieves a list of attributes from an element. * @param ldap/*from w w w. ja va2 s . com*/ * A prepared LDAP context. Cannot be <code>null</code>. * @param rdn * The relative DN (to the DN in the LDAP context * <code>ldap</code>). Cannot be <code>null</code>. * @param attributes * The requested attribute's names. Also indirectly referenced * attributes on the form * <code>someReferenceAttribute:someIndirectAttribute</code>, * where the DN in the reference attribute * <code>someReferenceAttribute</code> is followed to look up * <code>someIndirectAttribute</code> from another element. * @return The requested attributes (<code>String</code> names and * <code>String[]</code> values), if they did exist in the * external backend. Otherwise returns those attributes that could * actually be read, this may be an empty <code>HashMap</code>. * Returns an empty <code>HashMap</code> if * <code>attributes</code> is <code>null</code> or an empty * array. Note that attribute values are mapped to * <code>String</code> using ISO-8859-1. * @throws BackendException * If unable to read the attributes from the backend. * @throws NullPointerException * If <code>ldap</code> or <code>rdn</code> is * <code>null</code>. * @see javax.naming.directory.InitialDirContext#getAttributes(java.lang.String, * java.lang.String[]) */ private HashMap<String, String[]> getAttributes(final InitialLdapContext ldap, final String rdn, final String[] attributes) throws BackendException { // Sanity checks. if (ldap == null) throw new NullPointerException("LDAP context cannot be NULL"); if (rdn == null) throw new NullPointerException("RDN cannot be NULL"); if ((attributes == null) || (attributes.length == 0)) return new HashMap<String, String[]>(); // Used to remember attributes to be read through references later on. Hashtable<String, Vector> attributeReferences = new Hashtable<String, Vector>(); // Strip down request, resolving references and removing duplicates. Vector<String> strippedAttributeRequest = new Vector<String>(); for (int i = 0; i < attributes.length; i++) { int indexOfSplitCharacter = attributes[i] .indexOf(DirectoryManagerBackend.ATTRIBUTE_REFERENCE_SEPARATOR); if (indexOfSplitCharacter == -1) { // A regular attribute request. if (!strippedAttributeRequest.contains(attributes[i])) strippedAttributeRequest.add(attributes[i]); } else { // A referenced attribute request. final String referencingAttribute = attributes[i].substring(0, indexOfSplitCharacter); if (!strippedAttributeRequest.contains(referencingAttribute)) strippedAttributeRequest.add(referencingAttribute); // Add to list of attributes to be read through each reference. if (!attributeReferences.containsKey(referencingAttribute)) { // Add new reference. Vector<String> referencedAttribute = new Vector<String>(); referencedAttribute.add(attributes[i].substring(indexOfSplitCharacter + 1)); attributeReferences.put(referencingAttribute, referencedAttribute); } else { // Update existing reference. Vector<String> referencedAttribute = attributeReferences.get(referencingAttribute); if (!referencedAttribute.contains(attributes[i].substring(indexOfSplitCharacter + 1))) referencedAttribute.add(attributes[i].substring(indexOfSplitCharacter + 1)); } } } // The context provider URL and DN, for later logging. String url = "unknown backend"; String dn = "unknown dn"; // Get the attributes from an already initialized LDAP connection. Attributes rawAttributes = null; try { // Remember the URL and bind DN, for later logging. final Hashtable environment = ldap.getEnvironment(); url = (String) environment.get(Context.PROVIDER_URL); dn = (String) environment.get(Context.SECURITY_PRINCIPAL); // Get the attributes. rawAttributes = ldap.getAttributes(rdn, strippedAttributeRequest.toArray(new String[] {})); } catch (NameNotFoundException e) { // Successful authentication but missing user element; no attributes // returned and the event is logged. log.logWarn("No LDAP element found (DN was '" + dn + "')", mySessionTicket); rawAttributes = new BasicAttributes(); } catch (NamingException e) { String a = new String(); for (int i = 0; i < attributes.length; i++) a = a + attributes[i] + ", "; throw new BackendException("Unable to read attribute(s) '" + a.substring(0, a.length() - 2) + "' from '" + rdn + "' on '" + url + "'", e); } // Translate retrieved attributes from Attributes to HashMap. HashMap<String, String[]> convertedAttributes = new HashMap<String, String[]>(); for (int i = 0; i < attributes.length; i++) { // Did we get any attribute back at all? final String requestedAttribute = attributes[i]; Attribute rawAttribute = rawAttributes.get(requestedAttribute); if (rawAttribute == null) { // Attribute was not returned. log.logDebug("Requested attribute '" + requestedAttribute + "' not found on '" + url + "'", mySessionTicket); } else { // Map the attribute values to String[]. ArrayList<String> convertedAttributeValues = new ArrayList<String>(rawAttribute.size()); for (int j = 0; j < rawAttribute.size(); j++) { try { // We either have a String or a byte[]. String convertedAttributeValue = null; try { // Encode String. convertedAttributeValue = new String(((String) rawAttribute.get(j)).getBytes(), DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET); } catch (ClassCastException e) { // Encode byte[] to String. convertedAttributeValue = new String(Base64.encodeBase64((byte[]) rawAttribute.get(j)), DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET); } convertedAttributeValues.add(convertedAttributeValue); } catch (NamingException e) { throw new BackendException("Unable to read attribute value of '" + rawAttribute.getID() + "' from '" + url + "'", e); } catch (UnsupportedEncodingException e) { throw new BackendException( "Unable to use " + DirectoryManagerBackend.ATTRIBUTE_VALUE_CHARSET + " encoding", e); } } convertedAttributes.put(requestedAttribute, convertedAttributeValues.toArray(new String[] {})); } } // Follow references to look up any indirectly referenced attributes. Enumeration<String> keys = attributeReferences.keys(); while (keys.hasMoreElements()) { // Do we have a reference? final String referencingAttribute = keys.nextElement(); final String[] referencingValues = convertedAttributes.get(referencingAttribute); if (referencingValues == null) { // No reference was found in this attribute. log.logDebug("Found no DN references in attribute '" + referencingAttribute + "'", mySessionTicket); } else { // One (or more) references was found in this attribute. if (referencingValues.length > 1) log.logDebug("Found " + referencingValues.length + " DN references in attribute '" + referencingAttribute + "'; ignoring all but first", mySessionTicket); log.logDebug("Following reference '" + referencingValues[0] + "' found in '" + referencingAttribute + "' to look up attribute(s) '" + attributeReferences.get(referencingAttribute).toString(), mySessionTicket); String providerURL = null; // To be used later. try { // Follow the reference. providerURL = (String) ldap.getEnvironment().get(Context.PROVIDER_URL); providerURL = providerURL.substring(0, providerURL.lastIndexOf("/") + 1) + referencingValues[0]; ldap.addToEnvironment(Context.PROVIDER_URL, providerURL); } catch (NamingException e) { throw new BackendException("Unable to update provider URL in LDAP environment", e); } // Add any referenced attributes returned. HashMap additionalAttributes = getAttributes(ldap, providerURL, (String[]) attributeReferences.get(referencingAttribute).toArray(new String[] {})); Iterator i = additionalAttributes.keySet().iterator(); while (i.hasNext()) { String attributeName = (String) i.next(); convertedAttributes.put(referencingAttribute + DirectoryManagerBackend.ATTRIBUTE_REFERENCE_SEPARATOR + attributeName, (String[]) additionalAttributes.get(attributeName)); } } } return convertedAttributes; }