List of usage examples for java.util ArrayList trimToSize
public void trimToSize()
From source file:org.openestate.is24.restapi.utils.RandomRealEstateFactory.java
/** * Create a {@link EnergySourcesEnev2014}, that contains random * {@link EnergySourceEnev2014} values./*w w w . j a va 2 s. c o m*/ * * @return * randomly filled {@link EnergySourcesEnev2014} object */ public EnergySourcesEnev2014 createRandomEnergySourcesEnev2014() { EnergySourcesEnev2014 output = commonFactory.createEnergySourcesEnev2014(); ArrayList<EnergySourceEnev2014> pool = new ArrayList<EnergySourceEnev2014>(); pool.addAll(Arrays.asList(EnergySourceEnev2014.values())); int limit = getRandomInt(pool.size()) + 1; int i = 0; while (i < limit && !pool.isEmpty()) { int pos = getRandomInt(pool.size()); EnergySourceEnev2014 source = pool.remove(pos); if (!EnergySourceEnev2014.NO_INFORMATION.equals(source)) { output.getEnergySourceEnev2014().add(source); i++; } pool.trimToSize(); } return output; }
From source file:org.openestate.is24.restapi.utils.RandomRealEstateFactory.java
/** * Create a {@link SiteRecommendedUseTypes}, that contains random * {@link SiteRecommendedUseType} values. * * @return/* www. jav a2 s . c om*/ * randomly filled {@link SiteRecommendedUseTypes} object */ public SiteRecommendedUseTypes createRandomSiteRecommendedUseTypes() { SiteRecommendedUseTypes output = commonFactory.createSiteRecommendedUseTypes(); ArrayList<SiteRecommendedUseType> pool = new ArrayList<SiteRecommendedUseType>(); pool.addAll(Arrays.asList(SiteRecommendedUseType.values())); int limit = getRandomInt(pool.size()) + 1; int i = 0; while (i < limit && !pool.isEmpty()) { int pos = getRandomInt(pool.size()); SiteRecommendedUseType use = pool.remove(pos); if (!SiteRecommendedUseType.NO_INFORMATION.equals(use)) { output.getSiteRecommendedUseType().add(use); i++; } pool.trimToSize(); } return output; }
From source file:org.openestate.is24.restapi.utils.RandomRealEstateFactory.java
/** * Create a {@link SiteRecommendedUseForTradeTypes}, that contains random * {@link SiteRecommendedUseForTradeType} values. * * @return//from w w w. j av a 2s . c o m * randomly filled {@link SiteRecommendedUseForTradeTypes} object */ public SiteRecommendedUseForTradeTypes createRandomSiteRecommendedUseForTradeTypes() { SiteRecommendedUseForTradeTypes output = commonFactory.createSiteRecommendedUseForTradeTypes(); ArrayList<SiteRecommendedUseForTradeType> pool = new ArrayList<SiteRecommendedUseForTradeType>(); pool.addAll(Arrays.asList(SiteRecommendedUseForTradeType.values())); int limit = getRandomInt(pool.size()) + 1; int i = 0; while (i < limit && !pool.isEmpty()) { int pos = getRandomInt(pool.size()); SiteRecommendedUseForTradeType use = pool.remove(pos); if (!SiteRecommendedUseForTradeType.NO_INFORMATION.equals(use)) { output.getSiteRecommendedUseForTradeType().add(use); i++; } pool.trimToSize(); } return output; }
From source file:edu.ucla.stat.SOCR.chart.ChartGenerator_JTable.java
/** * */// ww w . ja v a 2s . co m private void setArrayFromTable(int numberOfSeries, int[][] pairs) { int independentVarLength = numberOfSeries; int dependentVarLength = numberOfSeries; int[] independentVar = new int[independentVarLength]; int[] dependentVar = new int[dependentVarLength]; dependentHeaders = new String[dependentVarLength]; independentHeaders = new String[independentVarLength]; //independentVars store the column index for indep int indep, dep; for (int i = 0; i < numberOfSeries; i++) { //System.out.println("indep=pairs["+i+"][0]="+pairs[i][0]); //System.out.println("dep=pairs["+i+"][1]="+pairs[i][1]); indep = pairs[i][0]; //x, value(pie) dep = pairs[i][1]; //y, name(pie) independentHeaders[i] = columnModel.getColumn(indep).getHeaderValue().toString().trim(); independentVar[i] = indep; dependentHeaders[i] = columnModel.getColumn(dep).getHeaderValue().toString().trim(); dependentVar[i] = dep; } int xLength = 0; int yLength = 0; String cellValue = null; ArrayList<String> xList = new ArrayList<String>(); ArrayList<String> yList = new ArrayList<String>(); try { //dependent Y yLength = dataTable.getRowCount(); depValues = new String[yLength][dependentVarLength]; indepValues = new String[yLength][independentVarLength]; //dependent Y for (int index2 = 0; index2 < dependentVarLength; index2++) { yList = new ArrayList<String>(); for (int k = 0; k < dataTable.getRowCount(); k++) { try { cellValue = ((String) dataTable.getValueAt(k, dependentVar[index2])).trim(); if (cellValue != null && !cellValue.equals("")) { yList.add(cellValue); } else { continue; // to the next for } } catch (Exception e) { //System.out.println("Exception: "+e); } } yList.trimToSize(); for (int i = 0; i < yList.size(); i++) { depValues[i][index2] = (String) yList.get(i); //System.out.println("depValues["+i+"]["+index2+"]="+depValues[i][index2]); } } xyLength = yList.size(); ; //independents for (int index2 = 0; index2 < independentVarLength; index2++) { xList = new ArrayList<String>(); for (int k = 0; k < dataTable.getRowCount(); k++) { try { cellValue = ((String) dataTable.getValueAt(k, independentVar[index2])).trim(); if (cellValue != null && !cellValue.equals("")) { xList.add(cellValue); } else { continue; // to the next for } } catch (Exception e) { //System.out.println("Exception: " + e ); } } xList.trimToSize(); for (int i = 0; i < xList.size(); i++) { indepValues[i][index2] = (String) xList.get(i); //System.out.println("indepValues["+i+"]["+index2+"]="+indepValues[i][index2]); } } } catch (Exception e) { System.out.println("Exception In outer catch: " + e); } }
From source file:org.zaproxy.zap.extension.websocket.db.TableWebSocket.java
/** * @param rs//from w w w .j av a 2s .co m * @param interpretLiteralBytes * @param payloadLength * @return * @throws HttpMalformedHeaderException * @throws SQLException * @throws DatabaseException */ private List<WebSocketMessageDTO> buildMessageDTOs(ResultSet rs, boolean interpretLiteralBytes, int payloadLength) throws SQLException, DatabaseException { ArrayList<WebSocketMessageDTO> messages = new ArrayList<>(); try { while (rs.next()) { WebSocketMessageDTO message; int channelId = rs.getInt("channel_id"); WebSocketChannelDTO channel = getChannel(channelId); if (rs.getInt("fuzz_id") != 0) { WebSocketFuzzMessageDTO fuzzMessage = new WebSocketFuzzMessageDTO(channel); fuzzMessage.fuzzId = rs.getInt("fuzz_id"); fuzzMessage.state = WebSocketFuzzMessageDTO.State.valueOf(rs.getString("state")); fuzzMessage.fuzz = rs.getString("fuzz"); message = fuzzMessage; } else { message = new WebSocketMessageDTO(channel); } message.id = rs.getInt("message_id"); message.setTime(rs.getTimestamp("timestamp")); message.opcode = rs.getInt("opcode"); message.readableOpcode = WebSocketMessage.opcode2string(message.opcode); // read payload if (message.opcode == WebSocketMessage.OPCODE_BINARY) { if (payloadLength == -1) { // load all bytes message.payload = rs.getBytes("payload_bytes"); } else { Blob blob = rs.getBlob("payload_bytes"); int length = Math.min(payloadLength, (int) blob.length()); message.payload = blob.getBytes(1, length); blob.free(); } if (message.payload == null) { message.payload = new byte[0]; } } else { if (payloadLength == -1) { // load all characters message.payload = rs.getString("payload_utf8"); } else { Clob clob = rs.getClob("payload_utf8"); int length = Math.min(payloadLength, (int) clob.length()); message.payload = clob.getSubString(1, length); clob.free(); } if (message.payload == null) { message.payload = ""; } } message.isOutgoing = rs.getBoolean("is_outgoing"); message.payloadLength = rs.getInt("payload_length"); messages.add(message); } } finally { rs.close(); } messages.trimToSize(); return messages; }
From source file:trendanalisis.main.tools.weka.CoreWekaTFIDF.java
/** * determines the dictionary./*from w w w . j av a 2 s.c o m*/ */ private void determineDictionary() { // Operate on a per-class basis if class attribute is set int classInd = getInputFormat().classIndex(); int values = 1; if (!m_doNotOperateOnPerClassBasis && (classInd != -1)) { values = getInputFormat().attribute(classInd).numValues(); } // TreeMap dictionaryArr [] = new TreeMap[values]; @SuppressWarnings("unchecked") TreeMap<String, Count>[] dictionaryArr = new TreeMap[values]; for (int i = 0; i < values; i++) { dictionaryArr[i] = new TreeMap<String, Count>(); } // Make sure we know which fields to convert determineSelectedRange(); // Tokenize all training text into an orderedMap of "words". long pruneRate = Math.round((m_PeriodicPruningRate / 100.0) * getInputFormat().numInstances()); for (int i = 0; i < getInputFormat().numInstances(); i++) { Instance instance = getInputFormat().instance(i); int vInd = 0; if (!m_doNotOperateOnPerClassBasis && (classInd != -1)) { vInd = (int) instance.classValue(); } // Iterate through all relevant string attributes of the current instance Hashtable<String, Integer> h = new Hashtable<String, Integer>(); for (int j = 0; j < instance.numAttributes(); j++) { if (m_SelectedRange.isInRange(j) && (instance.isMissing(j) == false)) { // Get tokenizer m_Tokenizer.tokenize(instance.stringValue(j)); // Iterate through tokens, perform stemming, and remove stopwords // (if required) while (m_Tokenizer.hasMoreElements()) { String word = m_Tokenizer.nextElement().intern(); if (this.m_lowerCaseTokens == true) { word = word.toLowerCase(); } word = m_Stemmer.stem(word); if (m_StopwordsHandler.isStopword(word)) { continue; } if (!(h.containsKey(word))) { h.put(word, new Integer(0)); } Count count = dictionaryArr[vInd].get(word); if (count == null) { dictionaryArr[vInd].put(word, new Count(1)); } else { count.count++; } } } } // updating the docCount for the words that have occurred in this // instance(document). Enumeration<String> e = h.keys(); while (e.hasMoreElements()) { String word = e.nextElement(); Count c = dictionaryArr[vInd].get(word); if (c != null) { c.docCount++; } else { System.err.println( "Warning: A word should definitely be in the " + "dictionary.Please check the code"); } } if (pruneRate > 0) { if (i % pruneRate == 0 && i > 0) { for (int z = 0; z < values; z++) { ArrayList<String> d = new ArrayList<String>(1000); Iterator<String> it = dictionaryArr[z].keySet().iterator(); while (it.hasNext()) { String word = it.next(); Count count = dictionaryArr[z].get(word); if (count.count <= 1) { d.add(word); } } Iterator<String> iter = d.iterator(); while (iter.hasNext()) { String word = iter.next(); dictionaryArr[z].remove(word); } } } } } // Figure out the minimum required word frequency int totalsize = 0; int prune[] = new int[values]; for (int z = 0; z < values; z++) { totalsize += dictionaryArr[z].size(); int array[] = new int[dictionaryArr[z].size()]; int pos = 0; Iterator<String> it = dictionaryArr[z].keySet().iterator(); while (it.hasNext()) { String word = it.next(); Count count = dictionaryArr[z].get(word); array[pos] = count.count; pos++; } // sort the array sortArray(array); if (array.length < m_WordsToKeep) { // if there aren't enough words, set the threshold to // minFreq prune[z] = m_minTermFreq; } else { // otherwise set it to be at least minFreq prune[z] = Math.max(m_minTermFreq, array[array.length - m_WordsToKeep]); } } // Convert the dictionary into an attribute index // and create one attribute per word ArrayList<Attribute> attributes = new ArrayList<Attribute>(totalsize + getInputFormat().numAttributes()); // Add the non-converted attributes int classIndex = -1; for (int i = 0; i < getInputFormat().numAttributes(); i++) { if (!m_SelectedRange.isInRange(i)) { if (getInputFormat().classIndex() == i) { classIndex = attributes.size(); } attributes.add((Attribute) getInputFormat().attribute(i).copy()); } } // Add the word vector attributes (eliminating duplicates // that occur in multiple classes) TreeMap<String, Integer> newDictionary = new TreeMap<String, Integer>(); int index = attributes.size(); for (int z = 0; z < values; z++) { Iterator<String> it = dictionaryArr[z].keySet().iterator(); while (it.hasNext()) { String word = it.next(); Count count = dictionaryArr[z].get(word); if (count.count >= prune[z]) { if (newDictionary.get(word) == null) { newDictionary.put(word, new Integer(index++)); attributes.add(new Attribute(m_Prefix + word)); } } } } // Compute document frequencies global_tf = new double[attributes.size()]; df_prob = new double[attributes.size()]; m_DocsCounts = new int[attributes.size()]; IG = new double[attributes.size()]; Iterator<String> it = newDictionary.keySet().iterator(); while (it.hasNext()) { String word = it.next(); int idx = newDictionary.get(word).intValue(); int docsCount = 0; for (int j = 0; j < values; j++) { Count c = dictionaryArr[j].get(word); if (c != null) { docsCount += c.docCount; } } m_DocsCounts[idx] = docsCount; } // Trim vector and set instance variables attributes.trimToSize(); m_Dictionary = newDictionary; m_NumInstances = getInputFormat().numInstances(); // Set the filter's output format Instances outputFormat = new Instances(getInputFormat().relationName(), attributes, 0); outputFormat.setClassIndex(classIndex); setOutputFormat(outputFormat); }
From source file:com.silverwrist.venice.sidebox.SideboxManager.java
public List getSideboxes(Request req, String context_namespace, String context_name, Object context_param) throws DynamoException { // Start by getting the current user object. SessionInfoProvider sip = (SessionInfoProvider) (req.queryService(SessionInfoProvider.class)); SessionInfo si = sip.getSessionInfo(); DynamoUser user = (DynamoUser) (si.getObject(SessionInfoParams.NAMESPACE, SessionInfoParams.ATTR_USER)); if (logger.isDebugEnabled()) logger.debug("Retrieving sidebox list for user: " + user.getName()); // Get the IDs of all the sideboxes. int[] ids = m_ops.getSideboxIDList(user.getUID(), m_ns_cache.namespaceNameToId(context_namespace), context_name, context_param); if (logger.isDebugEnabled()) logger.debug("Returned " + ids.length + " sideboxes"); if (ids.length == 0) return Collections.EMPTY_LIST; // Create the return list. ArrayList rc = new ArrayList(ids.length); for (int i = 0; i < ids.length; i++) { // get the key to use for mapping if (logger.isDebugEnabled()) logger.debug("Creating sidebox #" + ids[i]); Integer key = new Integer(ids[i]); SideboxFactory fact = null;/*from w w w. j av a 2 s. c o m*/ synchronized (this) { // Look up the sidebox identity. PropertyKey name_key = null; // look up the type in our map first name_key = (PropertyKey) (m_id_to_name.get(key)); if (name_key == null) { // go down to the database and get it name_key = m_ops.getSideboxIdentity(ids[i]); m_id_to_name.put(key, name_key); } // end if if (logger.isDebugEnabled()) logger.debug("Sidebox name: " + name_key); // Now try and look up the factory. fact = (SideboxFactory) (m_pk_to_fact.get(name_key)); if (fact == null) { // need to go create the factory PropertyKey type_key = null; // look up the type in our map first type_key = (PropertyKey) (m_id_to_type.get(key)); if (type_key == null) { // go down to the database and get it type_key = m_ops.getSideboxType(ids[i]); m_id_to_type.put(key, type_key); } // end if if (logger.isDebugEnabled()) logger.debug("Sidebox type: " + type_key); // Convert the type key to a QualifiedNameKey and look for a SideboxTypeFactory to use. QualifiedNameKey type_qn = new QualifiedNameKey( m_ns_cache.namespaceIdToName(type_key.getNamespaceID()), type_key.getName()); SideboxTypeFactory typefact = (SideboxTypeFactory) (m_qnk_to_tf.get(type_qn)); if (typefact == null) typefact = (SideboxTypeFactory) (m_ns_to_tf.get(type_qn.getNamespace())); if (typefact == null) { // no type factory found for this sidebox type - throw an error SideboxException se = new SideboxException(SideboxManager.class, "SideboxMessages", "no.sbtype"); se.setParameter(0, type_qn.getNamespace()); se.setParameter(1, type_qn.getName()); throw se; } // end if if (logger.isDebugEnabled()) logger.debug("Type factory is of class: " + typefact.getClass().getName()); // Now create the sidebox factory. fact = typefact.createFactory(type_qn.getNamespace(), type_qn.getName(), m_ns_cache.namespaceIdToName(name_key.getNamespaceID()), name_key.getName(), new InitProps(ids[i])); m_pk_to_fact.put(name_key, fact); } // end if (no factory there) } // end synchronized block if (logger.isDebugEnabled()) logger.debug("Factory is of class: " + fact.getClass().getName()); // Use the factory to create the sidebox. Sidebox sbox = fact.createSidebox(req); if (sbox != null) rc.add(sbox); } // end for if (logger.isDebugEnabled()) logger.debug("Final sidebox list has " + rc.size() + " element(s)"); if (rc.isEmpty()) return Collections.EMPTY_LIST; rc.trimToSize(); return Collections.unmodifiableList(rc); }
From source file:org.cruk.genologics.api.impl.GenologicsAPIImpl.java
/** * Perform a list operation for obtaining links to entities using a specific * batch fetch class. These lists may be a simple "list all in system" call * or from a "find" operation./*from w w w . j av a2s. com*/ * * <p> * Deals with the pagination mechanism employed by the API to bring * back the required number of links regardless of the number of "pages" * the API returns them in. * </p> * * @param uri The URI to use for the list. * @param entityClass The type of entities required (or rather links to such entities). * @param batchClass The type of object to use for fetching the links. * @param number The maximum number of entities required. Calling code should * use {@code Integer.MAX_VALUE} to return all. * * @param <E> The type of the entity. * @param <BH> The type of the batch fetch object that holds the list of links * to these entities. * * @return A list of links to the entities found. * * @throws IllegalArgumentException if {@code entityClass} is annotated to be * a part of another entity (its {@code primaryEntity} attribute is set). */ private <E extends Locatable, BH extends Batch<? extends LimsLink<E>>> List<LimsLink<E>> doList(String uri, Class<E> entityClass, Class<BH> batchClass, int number) { GenologicsEntity entityAnno = checkEntityAnnotated(entityClass); String entityClassName = getShortClassName(entityClass); if (entityAnno.primaryEntity() != void.class) { String primaryName = getShortClassName(entityAnno.primaryEntity()); throw new IllegalArgumentException( "Cannot list all " + entityClassName + "s as they are part of " + primaryName + ". " + "A " + primaryName + " should supply a list of its relevant " + entityClassName + "s."); } ArrayList<LimsLink<E>> allLinks = new ArrayList<LimsLink<E>>(1024); // Note that it is important here to prevent the Spring escaping system // from encoding subsequent page URIs and turning, for example, plus signs // into %2B escaped characters. So for subsequent pages, take the URI // as given from the response. URI nextPageUri = null; do { ResponseEntity<BH> response; if (nextPageUri == null) { logger.debug("Fetching first batch of {} links from {}", entityClassName, uri); // First page response = restClient.getForEntity(uri, batchClass); } else { logger.debug("Fetching further batch of {} links from {}", entityClassName, nextPageUri); // Later batches. response = restClient.getForEntity(nextPageUri, batchClass); } BH batch = response.getBody(); Iterator<? extends LimsLink<E>> iter = batch.iterator(); int toAdd = Math.min(batch.getSize(), number - allLinks.size()); allLinks.ensureCapacity(allLinks.size() + toAdd); for (; iter.hasNext() && toAdd > 0; toAdd--) { allLinks.add(iter.next()); } nextPageUri = null; if (PaginatedBatch.class.isAssignableFrom(batchClass)) { PaginatedBatch<?> paginatedBatch = (PaginatedBatch<?>) batch; if (paginatedBatch.getNextPage() != null) { nextPageUri = paginatedBatch.getNextPage().getUri(); } } } while (nextPageUri != null && allLinks.size() < number); allLinks.trimToSize(); return allLinks; }
From source file:org.getobjects.eoaccess.EOAdaptorChannel.java
/** * Executes the SQL string and returns a Map containing the results of the * SQL./*from ww w . j a va 2 s . com*/ * <p> * If the SQL string is empty, an error is set and null is returned. * * @return null on error (check lastException), or the fetch results */ public List<Map<String, Object>> performSQL(final String _sql, final EOAttribute[] _optAttrs) { if (_sql == null || _sql.length() == 0) { log.error("performSQL caller gave us no SQL ..."); this.lastException = new Exception("got no SQL to perform!"); return null; } this.lastException = null; /* acquire DB resources */ final Statement stmt = this._createStatement(); if (stmt == null) return null; /* perform query */ ArrayList<Map<String, Object>> records = null; ResultSet rs = null; try { if (sqllog.isInfoEnabled()) sqllog.info(_sql); rs = stmt.executeQuery(_sql); SQLWarning warning = rs.getWarnings(); if (warning != null) { // TBD: find out when this happens log.warn("detected SQL warning: " + warning); } /* Collect meta data, calling meta inside fetches is rather expensive, * even though the PG JDBC adaptor also has some cache. */ final ResultSetMetaData meta = rs.getMetaData(); final int columnCount = meta.getColumnCount(); final String[] colNames = new String[columnCount]; final int[] colHashes = new int[columnCount]; final int[] colTypes = new int[columnCount]; for (int i = 1; i <= columnCount; i++) { if (_optAttrs != null) colNames[i - 1] = _optAttrs[i - 1].columnName(); else colNames[i - 1] = meta.getColumnName(i); colHashes[i - 1] = colNames[i - 1].hashCode(); colTypes[i - 1] = meta.getColumnType(i); } /* loop over results and convert them to records */ records = new ArrayList<Map<String, Object>>(128); while (rs.next()) { EORecordMap record = new EORecordMap(colNames, colHashes); boolean ok = this.fillRecordMapFromResultSet(record, rs, colNames, colTypes); if (ok) records.add(record); } } catch (SQLException e) { /* * SQLState: * 42601 - PostgreSQL for invalid SQL, like "SELECT *" or "IN ()" * 42804 - PostgreSQL for * IN types character varying and integer cannot be matched * 42P01 - PostgreSQL: relation 'notes' does not exist * 42703 - PostgreSQL: column "lastname" does not exist */ this.lastException = e; /* Note: if we already fetched records, we actually return them ... */ if (records != null && records.size() == 0) { records = null; if (log.isInfoEnabled()) { log.info("could not execute SQL statement (state=" + e.getSQLState() + "): " + _sql, e); } // System.err.println("STATE: " + e.getSQLState()); } else { log.warn("could not execute SQL statement (state=" + e.getSQLState() + "): " + _sql, e); } } finally { // TODO: we might also want to close our channel if the tear down was not // clean this._releaseResources(stmt, rs); } if (sqllog.isDebugEnabled()) sqllog.debug(" GOT RESULTS: " + records); /* compact array */ if (records != null) records.trimToSize(); return records; }
From source file:winnipegtransit.TransitConnection.java
private static void buildScheduleInfo(String stopNo) throws IOException, org.json.JSONException, NullPointerException, MalformedURLException { //storage variables used for storing information during processing String name = null;//from ww w. j av a 2s .c o m Object unknownType; Object anotherUnknownType; JSONArray routeScheduleArray; JSONObject routeScheduleObject; JSONObject routeInfo = null; JSONObject allSchedules; JSONObject bus; JSONObject singleRoute; ArrayList<BusArrival> arrivals; ArrayList<ScheduleItem> scheduleItems; String arrival; String busName; String routeName; Date arrivalTime; JSONObject stop; JSONObject geo; JSONArray schedules; URL stopScheduleInfoURL; JSONObject scheduleInfo; StopInfo stopInfo; //build the URL object for the information that we need to retrieve, patching in the stop number passed in //as a parameter stopScheduleInfoURL = new URL( WT_URL + "stops/" + stopNo + "/schedule.json?max-results-per-route=3&" + API_KEY); //retreve the schedule JSON string from the web using the retrieveFromWeb method scheduleInfo = retrieveFromWeb(stopScheduleInfoURL); //get a JSON object containting the stop information stop = scheduleInfo.getJSONObject("stop-schedule").getJSONObject("stop"); //create a JSON Object containing the geographic information geo = stop.getJSONObject("centre").getJSONObject("geographic"); //retrieve specific stop information from the stop and geo JSON objects. String stopName = stop.getString("name"); String latitude = geo.getString("latitude"); String longitude = geo.getString("longitude"); //create a stopInfo object from the name, lattitude and longitude //will be built into a Schedule object further into the class stopInfo = new StopInfo(stopName, latitude, longitude); //get a JSON Object containging the route schedule information for the stop allSchedules = scheduleInfo.getJSONObject("stop-schedule").getJSONObject("route-schedules"); //in order to determine if the route schedule information is stored in an Object or an Array //get the route schedule object and place it into a generic Object. //then test to see if it is an instance of a JSONArray or JSONObject and take appropriate //action unknownType = allSchedules.get("route-schedule"); //if it is a JSONObject, then no array is present and cannot be iterated. if (unknownType instanceof JSONObject) { //cast the unknownType into a JSONObject routeScheduleObject = (JSONObject) unknownType; //get the route info into another object routeInfo = routeScheduleObject.getJSONObject("route"); //extract the name fro the routeInfo object name = routeInfo.getString("name"); //get the single route stop information from the routeSchedue object. singleRoute = routeScheduleObject.getJSONObject("scheduled-stops"); //get the array containing the scheduled stop information routeScheduleArray = singleRoute.getJSONArray("scheduled-stop"); //create a new scheduleItem array list scheduleItems = new ArrayList<ScheduleItem>(); //create a new BusArrival array list arrivals = new ArrayList<BusArrival>(); //for every item in the routeSchedule array for (int j = 0; j < routeScheduleArray.length(); j++) { //extract the bus object from the array at the current position bus = routeScheduleArray.getJSONObject(j); //and then store the bus name in a variable busName = bus.getJSONObject("variant").getString("name"); //then get the time information for the current bus. try { //there are cases where a bus only has a departure time, and not an arrival time. I let the JSONException handle //these cases. arrival = bus.getJSONObject("times").getJSONObject("arrival").getString("estimated"); } catch (JSONException jex) { arrival = bus.getJSONObject("times").getJSONObject("departure").getString("estimated"); } //convert the arrival time string into a date object arrivalTime = javax.xml.bind.DatatypeConverter.parseDateTime(arrival).getTime(); //add a BusArrival object to the arrivals Array List arrivals.add(new BusArrival(busName, arrivalTime)); } //when all arrivals are processed, add a new schedule item to the scheduleItems array list //there will only be one item. I might change this around later. scheduleItems.add(new ScheduleItem(name, arrivals)); //create the new schedule item sc = new Schedule(scheduleItems, stopInfo, stopFeats); } //if its a JSONArray else if (unknownType instanceof JSONArray) { //cast the generic object into a JSONArray object routeScheduleArray = (JSONArray) unknownType; //only gets the first route. routeInfo = routeScheduleArray.getJSONObject(1).getJSONObject("route"); //create a new ScheduleItem array list scheduleItems = new ArrayList<ScheduleItem>(); //for every item in the route schedule array for (int i = 0; i < routeScheduleArray.length(); i++) { //we need to again test to see if the item retrieved is an Array or an Object anotherUnknownType = routeScheduleArray.getJSONObject(i).getJSONObject("scheduled-stops") .get("scheduled-stop"); //if its an object if (anotherUnknownType instanceof JSONObject) { //cast the generic object into a JSONObject routeScheduleObject = (JSONObject) anotherUnknownType; //extract the current route's name routeName = routeScheduleArray.getJSONObject(i).getJSONObject("route").getString("name"); //create a new BusArrival array list arrivals = new ArrayList<BusArrival>(); //extract the bus name and arrival time from the routeScheduleObject busName = routeScheduleObject.getJSONObject("variant").getString("name"); arrival = routeScheduleObject.getJSONObject("times").getJSONObject("arrival") .getString("estimated"); arrivalTime = javax.xml.bind.DatatypeConverter.parseDateTime(arrival).getTime(); //add a new BusArrival to the arrivals array list arrivals.add(new BusArrival(busName, arrivalTime)); //trim it down to its actual size arrivals.trimToSize(); //add a new scheduleItem using the route name and arrivals array list scheduleItems.add(new ScheduleItem(routeName, arrivals)); } //however, if it is an Array else { //get the scheduled stops from the scheduled-stop array schedules = routeScheduleArray.getJSONObject(i).getJSONObject("scheduled-stops") .getJSONArray("scheduled-stop"); //extract the routes name routeName = routeScheduleArray.getJSONObject(i).getJSONObject("route").getString("name"); //create a new arrayList of BusArrival objects arrivals = new ArrayList<BusArrival>(); //for every item in the schedules array for (int j = 0; j < schedules.length(); j++) { //get the current bus object bus = schedules.getJSONObject(j); //and the bus name busName = bus.getJSONObject("variant").getString("name"); //gets set three times. thats ok. //get the busses arrival time try { //there are cases where a bus only has a departure time, and not an arrival time. I let the JSONException handle //these cases. arrival = bus.getJSONObject("times").getJSONObject("arrival").getString("estimated"); } catch (JSONException jex) { arrival = bus.getJSONObject("times").getJSONObject("departure").getString("estimated"); } //parse the arrival time into a date object arrivalTime = javax.xml.bind.DatatypeConverter.parseDateTime(arrival).getTime(); //add a new BusArrival object to the arrivals Array list arrivals.add(new BusArrival(busName, arrivalTime)); } //when all schedule items are processed arrivals.trimToSize(); //add a new schedule item using the route name and arrivals array list scheduleItems.add(new ScheduleItem(routeName, arrivals)); } } //trim the schedule items array list scheduleItems.trimToSize(); //build a new Schedule object using the scheduleItems Array list, stopInformation object, //and stopFeatures Array List sc = new Schedule(scheduleItems, stopInfo, stopFeats); } }