List of usage examples for java.util Vector toArray
@SuppressWarnings("unchecked") public synchronized <T> T[] toArray(T[] a)
From source file:ceruleanotter.github.com.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./* www .j a va 2 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. // The function referenced here is not yet implemented, so we've commented it out for now. long locationID = insertLocationInDatabase(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"); } }
From source file:de.juwimm.cms.remote.ViewServiceSpringImpl.java
/** * @see de.juwimm.cms.remote.ViewServiceSpring#getParents4ViewComponent(java.lang.Integer) *///from w w w . j av a 2s .c om @Override protected Integer[] handleGetParents4ViewComponent(Integer viewComponentId) throws Exception { try { ViewComponentHbm view = super.getViewComponentHbmDao().load(viewComponentId); Vector<Integer> vec = new Vector<Integer>(); Vector<Integer> topDown = new Vector<Integer>(); ViewComponentHbm parentView = view; while ((parentView = parentView.getParent()) != null) { vec.addElement(parentView.getViewComponentId()); } for (int i = vec.size() - 1; i > -1; i--) { topDown.addElement(vec.elementAt(i)); } return topDown.toArray(new Integer[0]); } catch (Exception e) { throw new UserException(e.getMessage()); } }
From source file:com.iyedb.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. * <p/>//w ww .j a v a 2 s .co m * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ 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 = insertLocationInDatabase(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()) { Log.v(LOG_TAG, "Query succeeded! **********"); } else { Log.v(LOG_TAG, "Query failed! :( **********"); } } } }
From source file:com.josenaves.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 . j av a 2s. 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(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationID); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATETEXT, WeatherContract.getDbDateString(new Date(dateTime * 1000L))); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); mContext.getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, cvArray); } }
From source file:com.flexoodb.common.FlexUtils.java
/** * obtains the XML equivalent of the elements and its values found in the passed object. * * @param classname name of the class that will be used as the root element for this object, if null it will use the objects natural class name. * @param obj the object containing the elements that will be used to populate the XML. * @param includeflextag true if the final XML will include the tag or not. * @param usefilename set to true if the object you're passing (ie is only relevant) has a binary (ie byte array) field and you want to overried the field content to contain the filename instead of the actual byte array string. * @return XML string./*from w ww . ja va 2 s . c o m*/ * @see Hashtable *@see Element */ static public String getXML(String classname, Object obj, boolean includeflextag, boolean usefilename) throws Exception { Class c = obj.getClass(); //Method[] m = c.getMethods(); Vector ve = retrieveMethods(obj.getClass(), null); Method[] m = new Method[ve.size()]; ve.toArray(m); String name, retval; StringBuilder main = new StringBuilder(); String id = null; String parentid = null; if (c.getSimpleName().endsWith("Class")) { return ""; } if (classname == null) { classname = c.getSimpleName(); } classname = classname.toLowerCase(); StringBuffer xml = new StringBuffer(); for (int i = 0; i < m.length; i++) { name = m[i].getName(); retval = m[i].getReturnType().getName(); if (retval.equalsIgnoreCase("void") && name.startsWith("set")) { // we get the method name String field = name.substring(3); String getter = (m[i].getParameterTypes()[0].getSimpleName().equals("boolean") ? "is" : "get") + field; try { Method met = c.getMethod(getter, (Class[]) null); Object o = null; try { o = met.invoke(obj, (Object[]) null); } catch (Exception g) { // no content } field = field.toLowerCase(); //System.out.println(i+">>>> name "+name+" field:"+field+" type:"+t+" "+o); if (o != null) { String t = met.getReturnType().getSimpleName(); if (t.endsWith("Date")) { if ((o + "").trim().startsWith("0003-11-30T00:00:00")) { xml.append("<" + field + " type=\"" + t + "\"><![CDATA[ ]]></" + field + ">"); } else { String dt = ((new SimpleDateFormat(_dateformat)).format((Date) o)); dt = dt.replaceFirst("00:00:00", ""); xml.append( "<" + field + " type=\"" + t + "\"><![CDATA[" + dt + "]]></" + field + ">"); } } else if (t.endsWith("XMLGregorianCalendar")) { // 2009-01-01T10:00:00.000+08:00 if ((o + "").trim().startsWith("0003-11-30T00:00:00")) { xml.append("<" + field + " type=\"" + t + "\"><![CDATA[ ]]></" + field + ">"); } else { Date d = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S")).parse(o + ""); String dt = (new SimpleDateFormat(_dateformat)).format(d); dt = dt.replaceFirst("00:00:00", ""); xml.append( "<" + field + " type=\"" + t + "\"><![CDATA[" + dt + "]]></" + field + ">"); } } else if (t.endsWith("byte[]")) { if (usefilename) { FileContainer fc = extractFileFromMimeMessage((byte[]) o); xml.append("<" + field + " type=\"" + t + "\"><![CDATA[" + (fc == null || fc.getFileName() == null ? "" : fc.getFileName()) + "]]></" + field + ">"); } else { xml.append("<" + field + " type=\"" + t + "\"><![CDATA[" + new String((byte[]) o) + "]]></" + field + ">"); //xml.append("<"+field+" type=\""+t+"\"><![CDATA["+new String(fc.getByteArray())+"]]></"+field+">"); } } else if (t.toLowerCase().endsWith("boolean")) { xml.append("<" + field + " type=\"" + t + "\"><![CDATA[" + o + "]]></" + field + ">"); } else { if (indexable(t)) { if (field.equals("id")) { id = o.toString(); } else if (field.equals("parentid")) { parentid = o.toString(); } else { // 2013-01-15 yujb reverted to not replacing '%' with &#037; xml.append("<" + field + " type=\"" + t + "\"><![CDATA[" + o.toString() + "]]></" + field + ">"); //xml.append("<"+field+" type=\""+t+"\"><![CDATA["+replaceString(o.toString(),"%","&#037;")+"]]></"+field+">"); } } else { if (c.getSimpleName().endsWith("FlexContainer") && field.equals("object")) { xml.append(getXML(null, o, false, usefilename)); } } } } else { xml.append("<" + field + " type=\"" + met.getReturnType().getSimpleName() + "\"/>"); } } catch (Exception f) { //throw f; f.printStackTrace(); // attempt a get. } } else { // what if this is a list? if (retval.endsWith("List")) { String getter = m[i].getName(); Method met = c.getMethod(getter, (Class[]) null); List o = null; try { o = (List) met.invoke(obj, (Object[]) null); } catch (Exception g) { // no content g.printStackTrace(); } if (o != null) { Iterator it = o.iterator(); while (it.hasNext()) { Object lo = it.next(); xml.append(getXML(null, lo, false, usefilename)); } } } else if (retval.endsWith("ConcurrentHashMap")) { String getter = m[i].getName(); Method met = c.getMethod(getter, (Class[]) null); ConcurrentHashMap o = null; try { o = (ConcurrentHashMap) met.invoke(obj, (Object[]) null); } catch (Exception g) { // no content g.printStackTrace(); } if (o != null) { Enumeration en = o.keys(); while (en.hasMoreElements()) { String el = (String) en.nextElement(); Vector<FlexContainer> children = (Vector<FlexContainer>) o.get(el); Iterator it = children.iterator(); xml.append("<" + el + "typerecords total=\"" + children.size() + "\" from=\"0\" to=\"" + children.size() + "\" returned=\"" + children.size() + "\"/>"); xml.append("<" + el + "typelist>"); while (it.hasNext()) { FlexContainer lo = (FlexContainer) it.next(); xml.append("<flexcontainer id=\"" + lo.getId() + "\" parentid=\"" + lo.getParentId() + "\">" + getXML(null, lo, false, usefilename) + "</flexcontainer>"); } xml.append("</" + el + "typelist>"); } } } else { if (!name.startsWith("get") && !retval.startsWith("java") && !retval.endsWith("byte[]") && !retval.equals("int") && !retval.equals("boolean") && !retval.equals("void")) // if complex { String getter = m[i].getName(); Method met = c.getMethod(getter, (Class[]) null); Object o = null; try { o = met.invoke(obj, (Object[]) null); } catch (Exception g) { // no content g.printStackTrace(); } //System.out.println(i+">>>> name "+name+" field:"+getter.substring(3)+" retval:"+retval+" "+o); if (o != null) { xml.append(getXML(getter.substring(3), o, false, usefilename)); } } } } } // then we get the complex types! /*Field[] f = c.getDeclaredFields(); for (int i=0;i<f.length;i++) { String pname = f[i].getType().getSimpleName(); if (pname.equals("List")) { Type type = f[i].getGenericType(); ParameterizedType t = (ParameterizedType)type; Class c1 = (Class) t.getActualTypeArguments()[0]; String getter = f[i].getName(); String n = (getter.substring(0,1).toUpperCase())+getter.substring(1); getter = "get"+n; Method met = c.getMethod(getter, (Class[])null); List o = null; try { o = (List) met.invoke(obj,(Object[])null); } catch (Exception g) { // no content g.printStackTrace(); } if (o!=null) { Iterator it = o.iterator(); while (it.hasNext()) { Object lo = it.next(); xml.append(getXML(n,lo,false)); } } } else { } }*/ // then we check for parent classes // check for superclass /*Class sc = c.getSuperclass(); if (!sc.getSimpleName().equals("Object")) { xml.append(getXML(sc.getName(),sc.newInstance(),false)); }*/ if (!c.getSimpleName().endsWith("FlexContainer")) { //main.append("<"+classname+" id=\""+id+"\">"); main.append("<" + classname + ">"); xml.append("</" + classname + ">"); } if (includeflextag) { if (c.getSimpleName().equals("FlexContainer")) { main.append("<" + classname + " id=\"" + id + "\" parentid=\"" + parentid + "\">"); } else { main.append("<" + classname + ">"); } main.append(xml); main.append("</flexcontainer>"); } else { main.append(xml); } //System.out.println("\n>>>>\n"+main+"\n<<<<<"); return main.toString(); }
From source file:de.juwimm.cms.remote.ViewServiceSpringImpl.java
/** * @see de.juwimm.cms.remote.ViewServiceSpring#getViewComponentChildren(java.lang.Integer) *//*from ww w.ja v a 2 s .c o m*/ @Override protected ViewComponentValue[] handleGetViewComponentChildren(Integer parentId) throws Exception { try { if (log.isDebugEnabled()) log.debug("begin getViewComponentChildren"); ViewComponentHbm view = super.getViewComponentHbmDao().load(parentId); if (view.isLeaf()) { throw new UserException("node is a leaf."); } Vector<ViewComponentValue> vec = new Vector<ViewComponentValue>(); for (Iterator i = view.getChildren().iterator(); i.hasNext();) { ViewComponentHbm vcHbm = (ViewComponentHbm) i.next(); ViewComponentValue vc = vcHbm.getDao(-1); vec.addElement(vc); } if (log.isDebugEnabled()) log.debug("end getViewComponentChildren"); return vec.toArray(new ViewComponentValue[0]); } catch (Exception e) { throw new UserException(e.getMessage()); } }
From source file:com.example.conor.dotaapp.FetchMatchTask.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 .ja va 2 s .c o m*/ */ private void getMatchDataFromJson(String matchJsonStr, String steamId) throws JSONException { //LOG TAGS final String LOG_TAG = FetchMatchTask.class.getSimpleName(); //final String LOG_MATCH_JSON = "Match JSON Object"; final String LOG_MATCH_ARRAY = "Match JSON Array"; //JSON strings final String OWM_MATCHES = "matches"; final String OWM_MATCHID = "match_id"; final String OWM_START = "start_time"; final String OWM_PLAYERS = "players"; //final String OWM_PLAYERID = "account_id"; //final String OWM_HEROID = "hero_id"; final String OWM_RESULT = "result"; //Get number of matches to display from settings SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(mContext); String numberOfMatches = sharedPrefs.getString(mContext.getString(R.string.num_matches_key), mContext.getString(R.string.num_matches_default)); int numMatches = Integer.parseInt(numberOfMatches); try { JSONObject matchJson = new JSONObject(matchJsonStr); JSONArray matchArray = matchJson.getJSONObject(OWM_RESULT).getJSONArray(OWM_MATCHES); Log.v(LOG_MATCH_ARRAY, "matchArray: " + matchArray); Vector<ContentValues> cVVector = new Vector<ContentValues>(matchArray.length()); //String array to hold results of each match String[] resultStrs = new String[numMatches]; //For loop to loop through all matches //ATM: matchArray.length() = 5 for (int i = 0; i < matchArray.length(); i++) { // For now, using the format "Date, hero, match_id" String hero, match_id, dateTime; long date; // Get the JSON object representing a single match JSONObject singleMatch = matchArray.getJSONObject(i); Log.v(LOG_TAG, "Single Match JSONObject: " + singleMatch); //Get match_id of a single match match_id = singleMatch.getString(OWM_MATCHID); Log.v(LOG_TAG, "match_id: " + match_id); //Change date from UTC to readable date. Get Long value first date = Long.parseLong(singleMatch.getString(OWM_START)); //Output actual date instead of just seconds for start_time dateTime = getReadableDateString(date); /** * rest of JSON code is for match data * */ //Array of players JSONArray allPlayers = matchArray.getJSONObject(i).getJSONArray(OWM_PLAYERS); Log.v(LOG_TAG, "allPlayers JSONArray: " + allPlayers); //Returns single Hero Object with JSONObject heroObject = singleMatch.getJSONArray(OWM_PLAYERS).getJSONObject(0); Log.v(LOG_TAG, "heroObject: " + heroObject); hero = heroObject.getString("hero_id"); Log.v(LOG_TAG, "Hero ID: " + hero); for (int j = 0; j < allPlayers.length(); j++) { JSONObject singlePlayer = allPlayers.getJSONObject(j); } //Add strings to resultStrs at index i resultStrs[i] = "Date: " + dateTime + ", Hero: " + hero + ", Match ID: " + match_id; Log.v(LOG_TAG, "ResultStrs[" + i + "]: " + resultStrs[i]); for (Object s : resultStrs) { Log.v(LOG_TAG, "Dota Data to Display: " + s); } /** * END OF JSON DATA */ //Insert data into match table ContentValues matchValues = new ContentValues(); matchValues.put(MatchEntry.COLUMN_MATCH_KEY, match_id); matchValues.put(MatchEntry.COLUMN_START_TIME, dateTime); matchValues.put(MatchEntry.COLUMN_P_ACCOUNT_ID, steamId); cVVector.add(matchValues); } int inserted = 0; // add to database using bulkInsert if (cVVector.size() > 0) { ContentValues[] cvArray = new ContentValues[cVVector.size()]; cVVector.toArray(cvArray); inserted = mContext.getContentResolver().bulkInsert(MatchEntry.CONTENT_URI, cvArray); } // Sort order: Ascending, by date. String sortOrder = MatchEntry.COLUMN_START_TIME + " ASC"; Uri matchForPlayerUri = MatchEntry.buildMatchPlayerWithStartTime(steamId, System.currentTimeMillis()); //display bulk insert Cursor cur = mContext.getContentResolver().query(matchForPlayerUri, null, null, null, sortOrder); //Display cursor ////NULL CURSOR Log.e(LOG_TAG, "Cursor: " + cur); cVVector = new Vector<ContentValues>(cur.getCount()); if (cur.moveToFirst()) { do { ContentValues cv = new ContentValues(); DatabaseUtils.cursorRowToContentValues(cur, cv); cVVector.add(cv); } while (cur.moveToNext()); } Log.d(LOG_TAG, "FetchMatchTask Complete. " + inserted + " Inserted"); //String[] resultStrsActual = convertContentValuesToUXFormat(cVVector); //return resultStrsActual; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } //return null; }
From source file:com.izforge.izpack.compiler.CompilerConfig.java
protected void addDynamicVariables(IXMLElement data) throws CompilerException { notifyCompilerListener("addDynamicVariables", CompilerListener.BEGIN, data); // We get the dynamic variable list IXMLElement root = data.getFirstChildNamed("dynamicvariables"); if (root == null) { return;/*from w w w . j a v a 2 s . c o m*/ } Map<String, List<DynamicVariable>> dynamicvariables = packager.getDynamicVariables(); for (IXMLElement var : root.getChildrenNamed("variable")) { String name = xmlCompilerHelper.requireAttribute(var, "name"); DynamicVariable dynamicVariable = new DynamicVariableImpl(); dynamicVariable.setName(name); // Check for plain value String value = var.getAttribute("value"); if (value != null) { dynamicVariable.setValue(new PlainValue(value)); } else { IXMLElement valueElement = var.getFirstChildNamed("value"); if (valueElement != null) { value = valueElement.getContent(); if (value == null) { assertionHelper.parseError("Empty value element for dynamic variable " + name); } dynamicVariable.setValue(new PlainValue(value)); } } // Check for environment variable value value = var.getAttribute("environment"); if (value != null) { if (dynamicVariable.getValue() == null) { dynamicVariable.setValue(new EnvironmentValue(value)); } else { // unexpected combination of variable attributes assertionHelper .parseError("Ambiguous environment value definition for dynamic variable " + name); } } // Check for registry value value = var.getAttribute("regkey"); if (value != null) { String regroot = var.getAttribute("regroot"); String regvalue = var.getAttribute("regvalue"); if (dynamicVariable.getValue() == null) { dynamicVariable.setValue(new RegistryValue(regroot, value, regvalue)); } else { // unexpected combination of variable attributes assertionHelper.parseError("Ambiguous registry value definition for dynamic variable " + name); } } // Check for value from plain config file value = var.getAttribute("file"); if (value != null) { String stype = var.getAttribute("type"); String filesection = var.getAttribute("section"); String filekey = xmlCompilerHelper.requireAttribute(var, "key"); if (dynamicVariable.getValue() == null) { dynamicVariable.setValue( new PlainConfigFileValue(value, getConfigFileType(name, stype), filesection, filekey)); } else { // unexpected combination of variable attributes assertionHelper.parseError("Ambiguous file value definition for dynamic variable " + name); } } // Check for value from config file entry in a zip file value = var.getAttribute("zipfile"); if (value != null) { String entryname = xmlCompilerHelper.requireAttribute(var, "entry"); String stype = var.getAttribute("type"); String filesection = var.getAttribute("section"); String filekey = xmlCompilerHelper.requireAttribute(var, "key"); if (dynamicVariable.getValue() == null) { dynamicVariable.setValue(new ZipEntryConfigFileValue(value, entryname, getConfigFileType(name, stype), filesection, filekey)); } else { // unexpected combination of variable attributes assertionHelper.parseError("Ambiguous file value definition for dynamic variable " + name); } } // Check for value from config file entry in a jar file value = var.getAttribute("jarfile"); if (value != null) { String entryname = xmlCompilerHelper.requireAttribute(var, "entry"); String stype = var.getAttribute("type"); String filesection = var.getAttribute("section"); String filekey = xmlCompilerHelper.requireAttribute(var, "key"); if (dynamicVariable.getValue() == null) { dynamicVariable.setValue(new JarEntryConfigValue(value, entryname, getConfigFileType(name, stype), filesection, filekey)); } else { // unexpected combination of variable attributes assertionHelper.parseError("Ambiguous file value definition for dynamic variable " + name); } } // Check for result of execution value = var.getAttribute("executable"); if (value != null) { if (dynamicVariable.getValue() == null) { String dir = var.getAttribute("dir"); String exectype = var.getAttribute("type"); String boolval = var.getAttribute("stderr"); boolean stderr = true; if (boolval != null) { stderr = Boolean.parseBoolean(boolval); } if (value.length() <= 0) { assertionHelper.parseError("No command given in definition of dynamic variable " + name); } Vector<String> cmd = new Vector<String>(); cmd.add(value); List<IXMLElement> args = var.getChildrenNamed("arg"); if (args != null) { for (IXMLElement arg : args) { String content = arg.getContent(); if (content != null) { cmd.add(content); } } } String[] cmdarr = new String[cmd.size()]; if (exectype.equalsIgnoreCase("process") || exectype == null) { dynamicVariable.setValue(new ExecValue(cmd.toArray(cmdarr), dir, false, stderr)); } else if (exectype.equalsIgnoreCase("shell")) { dynamicVariable.setValue(new ExecValue(cmd.toArray(cmdarr), dir, true, stderr)); } else { assertionHelper.parseError( "Bad execution type " + exectype + " given for dynamic variable " + name); } } else { // unexpected combination of variable attributes assertionHelper .parseError("Ambiguous execution output value definition for dynamic variable " + name); } } if (dynamicVariable.getValue() == null) { assertionHelper.parseError("No value specified at all for dynamic variable " + name); } // Check whether dynamic variable has to be evaluated only once during installation value = var.getAttribute("checkonce"); if (value != null) { dynamicVariable.setCheckonce(Boolean.valueOf(value)); } // Check whether evaluation failures of the dynamic variable should be ignored value = var.getAttribute("ignorefailure"); if (value != null) { dynamicVariable.setIgnoreFailure(Boolean.valueOf(value)); } // Nested value filters IXMLElement filters = var.getFirstChildNamed("filters"); if (filters != null) { List<IXMLElement> filterList = filters.getChildren(); for (IXMLElement filterElement : filterList) { if (filterElement.getName().equals("regex")) { String expression = filterElement.getAttribute("regexp"); String selectexpr = filterElement.getAttribute("select"); String replaceexpr = filterElement.getAttribute("replace"); String defaultvalue = filterElement.getAttribute("defaultvalue"); String scasesensitive = filterElement.getAttribute("casesensitive"); String sglobal = filterElement.getAttribute("global"); dynamicVariable.addFilter(new RegularExpressionFilter(expression, selectexpr, replaceexpr, defaultvalue, Boolean.valueOf(scasesensitive != null ? scasesensitive : "true"), Boolean.valueOf(sglobal != null ? sglobal : "false"))); } else if (filterElement.getName().equals("location")) { String basedir = filterElement.getAttribute("basedir"); dynamicVariable.addFilter(new LocationFilter(basedir)); } } } try { dynamicVariable.validate(); } catch (Exception e) { assertionHelper .parseError("Error in definition of dynamic variable " + name + ": " + e.getMessage()); } List<DynamicVariable> dynamicValues = new ArrayList<DynamicVariable>(); if (dynamicvariables.containsKey(name)) { dynamicValues = dynamicvariables.get(name); } else { dynamicvariables.put(name, dynamicValues); } String conditionid = var.getAttribute("condition"); dynamicVariable.setConditionid(conditionid); if (dynamicValues.remove(dynamicVariable)) { assertionHelper.parseWarn(var, "Dynamic Variable '" + name + "' will be overwritten"); } dynamicValues.add(dynamicVariable); } notifyCompilerListener("addDynamicVariables", CompilerListener.END, data); }
From source file:com.example.diego.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. * <p/>/*from ww w. ja va 2s . c o m*/ * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ private String[] 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); Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); String[] resultStrs = new String[numDays]; 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); String highAndLow = formatHighLows(high, low); String day = getReadableDateString(dateTime); resultStrs[i] = day + " - " + description + " - " + highAndLow; } ContentValues[] contentValuesToBulkInsert = new ContentValues[cVVector.size()]; cVVector.toArray(contentValuesToBulkInsert); mContext.getContentResolver().bulkInsert(WeatherEntry.CONTENT_URI, contentValuesToBulkInsert); return resultStrs; }
From source file:gda.device.detector.pixium.PixiumDetector.java
@Override public Object readout() throws DeviceException { final Vector<String> output = new Vector<>(); final String absolutePath = scanSaveFolder.getAbsolutePath() + File.separator; final NXDetectorData dataTree = new NXDetectorData(); try {//from w ww .ja v a 2s. c o m if (hdfFormat) { print("Frames collected: " + controller.getHdf().getFile().getNumCaptured_RBV()); if (controller.getHdf().getFile().getNumCapture_RBV() == controller.getHdf().getFile() .getNumCaptured_RBV()) { // when capturing completed, must wait for buffer to write out and full filename RBV update int totalmillis = 120 * 1000; // 2 minutes timeout int grain = 25; long timer = 0, timer0 = System.currentTimeMillis(); while (isWriterBusy() && timer - timer0 < totalmillis) { Thread.sleep(grain); timer = System.currentTimeMillis(); } if (timer - timer0 >= totalmillis) { throw new TimeoutException( "It takes too long to write out data from EPICS Area Detector HDF buffer."); } if (scanRunning) { output.add(getFilePath(controller.getHDFFileName())); dataTree.addScanFileLink(getName(), "nxfile://" + output.get(0) + "#entry/instrument/detector/data"); } } } else { // cannot wait EPICS AD full file name update before collect next image - to support NDArray buffering String fileName = controller.getTiff().getFileName(); fileName = fileName.trim(); int counter = 0; if ((int) getCollectionTime() > 1) { int i = 0; // handle multiple images per data scan point. for (i = 0; i < getCollectionTime(); i++) { output.add(String.format(controller.getTiff().getFileTemplate(), absolutePath, fileName, i + scanpointindex)); } if (scanRunning) { dataTree.addFileNames(getName(), "scan point " + counter, output.toArray(new String[output.size()]), false, true); } scanpointindex = i + scanpointindex; counter += 1; } else { // single image per scan data point output.add(String.format(controller.getTiff().getFileTemplate(), absolutePath, fileName, scanpointindex)); if (scanRunning) { dataTree.addFileName(getName(), output.get(0)); } scanpointindex += 1; } } } catch (Exception e) { throw new DeviceException("readout failed to add scan file link to NeXus data file.", e); } // FileRegistrarHelper.registerFiles(output); if (LocalProperties.get("gda.data.scan.datawriter.dataFormat").matches("NexusDataWriter")) { // NeXus file format return dataTree; } // SRS file format return output.toArray(new String[output.size()]); }