Example usage for java.util ArrayList iterator

List of usage examples for java.util ArrayList iterator

Introduction

In this page you can find the example usage for java.util ArrayList iterator.

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

From source file:TypeConversionHelper.java

/**
 * Convenience method to convert a String containing numbers (separated by assorted
 * characters) into an int array. The separators can be ' '  '-'  ':'  '.'  ',' etc.
 * @param str The String/* ww w . ja  v a 2 s.  c  o  m*/
 * @return The int array
 */
private static int[] convertStringToIntArray(String str) {
    if (str == null) {
        return null;
    }

    int[] values = null;
    ArrayList list = new ArrayList();

    int start = -1;
    for (int i = 0; i < str.length(); i++) {
        if (start == -1 && Character.isDigit(str.charAt(i))) {
            start = i;
        }
        if (start != i && start >= 0) {
            if (!Character.isDigit(str.charAt(i))) {
                list.add(new Integer(str.substring(start, i)));
                start = -1;
            }
        }
    }

    if (list.size() > 0) {
        values = new int[list.size()];
        Iterator iter = list.iterator();
        int n = 0;
        while (iter.hasNext()) {
            values[n++] = ((Integer) iter.next()).intValue();
        }
    }
    return values;
}

From source file:buspathcontroller.JSONFileParser.java

public void generateRouteStopsAndPath() {
    JSONParser parser = new JSONParser();
    ArrayList<String> routeList = new ArrayList<String>();
    try {/* www .  j  a va  2  s  .co m*/
        FileReader reader = new FileReader("/Users/Zhaowei/Desktop/BusPath/allRoutes.txt");
        BufferedReader br = new BufferedReader(reader);
        String line;
        while ((line = br.readLine()) != null) {
            String routeName = line.split(";")[1];
            routeList.add(routeName);
        }
        br.close();
        reader.close();

        Iterator<String> it = routeList.iterator();
        while (it.hasNext()) {
            String routeName = it.next();
            PrintWriter writer = new PrintWriter(
                    "/Users/Zhaowei/Desktop/BusPath/routeInfo/stops/" + routeName + ".txt");
            Object obj = parser.parse(
                    new FileReader("/Users/Zhaowei/Desktop/BusPath/RawJSON/route/" + routeName + ".json"));
            JSONObject jsonObject = (JSONObject) obj;
            JSONObject route = (JSONObject) jsonObject.get("route");
            JSONArray directions = (JSONArray) route.get("directions");
            for (int i = 0; i < directions.size(); i++) {
                JSONObject direction = (JSONObject) directions.get(i);
                writer.println(direction.get("direction"));
                JSONArray stops = (JSONArray) direction.get("stops");
                Iterator iter = stops.iterator();
                while (iter.hasNext()) {
                    JSONObject stop = (JSONObject) iter.next();
                    writer.println(stop.get("stopnumber") + ";" + stop.get("stoptitle") + ";"
                            + stop.get("stoplat") + ";" + stop.get("stoplng"));
                }
            }
            writer.close();
        }

    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:ca.sfu.federation.viewer.propertysheet.PointPropertySheet.java

/**
 * Build an Update Method user input panel.
 * @return Panel.//ww w.j av  a2  s .  co  m
 */
private JPanel buildUpdateMethodInputsPanel() {
    // init
    JPanel panel = new JPanel();
    // build panel
    InputTable inputTable = this.target.getInputTable();
    ArrayList keys = (ArrayList) inputTable.getInputKeys();
    if (keys.size() > 0) {
        panel.setLayout(new RiverLayout());
        boolean first = true;
        Iterator e = keys.iterator();
        while (e.hasNext()) {
            String key = (String) e.next();
            if (first) {
                panel.add("p left", new JLabel(key));
                panel.add("tab hfill", new InputTextField(inputTable, key));
                first = false;
            } else {
                panel.add("br", new JLabel(key));
                panel.add("tab hfill", new InputTextField(inputTable, key));
            }
        }
    }
    // clear the scrollpane, add the new panel, validate
    this.jspUpdateMethodInputs.removeAll();
    this.jspUpdateMethodInputs.add(panel, BorderLayout.CENTER);
    this.jspUpdateMethodInputs.validate();
    // return result
    return panel;
}

From source file:com.intel.hadoop.graphbuilder.demoapps.wikipedia.docwordgraph.WordCountGraphTokenizer.java

@Override
public Iterator<Vertex<StringType, StringType>> getVertices() {
    ArrayList<Vertex<StringType, StringType>> vlist = new ArrayList<Vertex<StringType, StringType>>(
            counts.size() + 1);/*from   www.j  a v  a2  s . c  o m*/
    vlist.add(new Vertex<StringType, StringType>(new StringType(id), new StringType(title)));
    Iterator<String> iter = counts.keySet().iterator();
    while (iter.hasNext()) {
        vlist.add(new Vertex<StringType, StringType>(new StringType(iter.next()), new StringType()));
    }
    return vlist.iterator();
}

From source file:it.cnr.icar.eric.server.cms.CanonicalXMLValidationService.java

public ServiceOutput invoke(ServerRequestContext context, ServiceInput input, ServiceType service,
        InvocationController invocationController, UserType user) throws RegistryException {

    ServerRequestContext outputContext = context;

    try {/*from  w  ww  .  java 2 s  . c  o m*/
        //ExtrinsicObjectType eo = (ExtrinsicObjectType)input.getRegistryObject();
        //RepositoryItem repositoryItem = input.getRepositoryItem();
        //DataHandler dh = repositoryItem.getDataHandler();
        InputSource inputSource = null;

        //registryObject MUST be ExrinsicObject or ExternalLink of objectType WSDL
        ExtrinsicObjectType ebExtrinsicObjectType = null;
        ExternalLinkType ebExternalLinkType = null;
        RegistryObjectType ebRegistryObjectType = input.getRegistryObject();
        if (ebRegistryObjectType instanceof ExtrinsicObjectType) {
            ebExtrinsicObjectType = (ExtrinsicObjectType) ebRegistryObjectType;
            RepositoryItem repositoryItem = input.getRepositoryItem();
            if (repositoryItem == null) {
                // Section 8.10 of the [ebRS] spec specifies that the RI
                // is optional. Log message and return
                log.info(ServerResourceBundle.getInstance().getString("message.noRepositoryItemIncluded",
                        new String[] { ebRegistryObjectType.getId() }));
                ServiceOutput so = new ServiceOutput();
                so.setOutput(outputContext);
                return so;
            }
            inputSource = new InputSource(repositoryItem.getDataHandler().getInputStream());
        } else if (ebRegistryObjectType instanceof ExternalLinkType) {
            ebExternalLinkType = (ExternalLinkType) ebRegistryObjectType;
            String urlStr = ebExternalLinkType.getExternalURI();
            urlStr = Utility.absolutize(Utility.getFileOrURLName(urlStr));
            URL url = new URL(urlStr);
            InputStream is = url.openStream();
            inputSource = new InputSource(is);
        } else {
            throw new ValidationException("RegistryObject not ExtrinsicObject or ExternalLink");
        }

        StreamSource schematronInvControlFileSrc = rm.getAsStreamSource(invocationController.getEoId());
        //Commenting out caching until we figure out how to reinit the stream position at begining
        //Currently if we cache then subsequent uses result in error: "Could not compile stylesheet"
        // The schematron XSLT file is expected to be stable and change infrequently. So, cache it.
        //if (schematronXSLTFileSrc == null) {
        schematronXSLTFileSrc = new StreamSource(this.getClass().getClassLoader()
                .getResourceAsStream("it/cnr/icar/eric/server/cms/conf/skeleton1-5.xsl"));
        //}

        if (log.isDebugEnabled()) {
            dumpStream(schematronInvControlFileSrc);
            dumpStream(schematronXSLTFileSrc);
        }

        // Use the Schematron Invocation Control File and Schematron XSLT to
        // create the XSLT Invocation Control File
        File xsltInvocationControlFile = File.createTempFile("InvocationControlFile_WSDLValidation", ".xslt");
        xsltInvocationControlFile.deleteOnExit();
        StreamResult xsltInvocationControlFileSR = new StreamResult(xsltInvocationControlFile);

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer(schematronXSLTFileSrc);

        configureTransformer(transformer);

        // This call creates the XSLT Invocation Control File using
        // schematron invocation control file and schematron xslt files
        transformer.transform(schematronInvControlFileSrc, xsltInvocationControlFileSR);

        // Use generated XSLT Invocation Control File to validate the WSDL file(s)
        StreamSource xsltInvocationControlFileSrc = new StreamSource(xsltInvocationControlFile);
        transformer = tFactory.newTransformer(xsltInvocationControlFileSrc);

        configureTransformer(transformer);

        //Set respository item as parameter
        transformer.setParameter("repositoryItem", input.getRegistryObject().getId());

        if ((ebExtrinsicObjectType != null)
                && (ebExtrinsicObjectType.getMimeType().equalsIgnoreCase("application/zip"))) {
            ArrayList<File> files = Utility.unZip(TMP_DIR, inputSource.getByteStream());

            //Now iterate and create ExtrinsicObject - Repository Item pair for each unzipped file
            Iterator<File> iter = files.iterator();
            while (iter.hasNext()) {
                File file = iter.next();
                @SuppressWarnings("resource")
                BufferedReader br = new BufferedReader(new FileReader(file));
                StringBuffer sb = new StringBuffer();
                while (br.ready()) {
                    sb.append(br.readLine());
                }
                StringReader reader = new StringReader(sb.toString());
                StreamSource inputSrc = new StreamSource(reader);
                validateXMLFile(inputSrc, transformer);
            }
        } else {
            //Following will fail if there are unresolved imports in the WSDL
            StreamSource inputSrc = new StreamSource(inputSource.getByteStream());
            //dumpStream(inputSrc);
            //inputSrc = new StreamSource(inputSource.getByteStream());
            validateXMLFile(inputSrc, transformer);
        }
    } catch (ValidationException e) {
        if (outputContext != context) {
            outputContext.rollback();
        }
        log.error(ServerResourceBundle.getInstance().getString("message.errorValidatingXML"), e);
        throw e;
    } catch (Exception e) {
        if (outputContext != context) {
            outputContext.rollback();
        }
        log.error(ServerResourceBundle.getInstance().getString("message.errorValidatingXML"), e);
        throw new RegistryException(e);
    }

    ServiceOutput so = new ServiceOutput();
    so.setOutput(outputContext);

    if (outputContext != context) {
        outputContext.commit();
    }

    return so;
}

From source file:com.projity.reports.view.ReportView.java

private void makeViewer() throws JRException {
    if (!dirty)/*from  w ww  .  j  a  va  2 s  .  c  o m*/
        return;

    documentFrame.showWaitCursor(true);

    if (cache != null) { // remove old listener
        cache.removeNodeModelListener(this);
    }

    DataSource dataSource;

    SpreadSheetFieldArray fa = null;
    if (fieldArray != null) {
        fa = (SpreadSheetFieldArray) fieldArray.clone();
        CollectionUtils.filter(fa, new Predicate() {
            public boolean evaluate(Object arg0) {
                return !((Field) arg0).isGraphical(); // get rid of fields that can't be shown
            }
        });
    }
    JasperReport report = ReportUtil.getReport(reportDefinition, coord.getProjectTimeIterator(), fa);

    viewName = DataSourceProvider.getViewName(report);
    //System.out.println("viewName="+viewName);
    documentFrame.setComboBoxesViewName(viewName);

    NodeModel model = null;
    PredicatedNodeFilterIterator iterator;
    if (viewName == DataSourceProvider.REPORT_VIEW) { // special case to just use project
        cache = null;
        ArrayList list = new ArrayList();
        list.add(project);
        iterator = GeneralFilteredIterator.instance(list.iterator());
    } else {
        model = updateCacheForView(viewName);
        if (cache == null) {
            iterator = GeneralFilteredIterator.instance(model.iterator());
            //for (Iterator i=GeneralFilteredIterator.instance(model.iterator());i.hasNext();) System.out.println("Report model iterator: "+i.next());
        } else {
            iterator = GeneralFilteredIterator.instance(cache.getIterator());
            //for (Iterator i=GeneralFilteredIterator.instance(cache.getIterator());i.hasNext();) System.out.println("Report cache iterator: "+i.next());
        }
    }
    dataSource = DataSourceProvider.createDataSource(report, project, iterator, model);

    // projet name is used as report's title
    // and passed as a parameter
    HashMap params = new HashMap();
    params.put("projectName", project.getName()); //$NON-NLS-1$

    JasperPrint jasperPrint = JasperFillManager.fillReport(report, params, dataSource);
    if (viewer != null) {
        viewer.changeReport(jasperPrint);
    } else {
        viewer = new ReportViewer(jasperPrint);
        add(viewer, BorderLayout.CENTER);
    }
    // add new listener
    if (cache != null) {
        cache.addNodeModelListener(this);
    }
    dirty = false;

    documentFrame.showWaitCursor(false);

}

From source file:org.toobsframework.pres.component.dataprovider.impl.DataProviderReflectImpl.java

public Collection searchIndex(String returnType, String objectDao, String searchCriteria, String searchMethod,
        String permissionAction, Map params, Map outParams) throws ObjectCreationException {
    ArrayList retObjects = new ArrayList();

    // Get Object
    params.put("dao", ParameterUtil.resolveParam(null, objectDao, params));
    params.put("searchMethod", searchMethod);
    params.put("searchCriteria", searchCriteria);
    params.put("permissionAction", permissionAction);
    params.put("returnType", returnType);
    if (params.get("personId") == null) {
        params.put("personId", PlatformConstants.PERSON_ID_NO_PERSON);
    }/*  w ww .  j a  v a  2  s .c  o  m*/
    try {
        // Get Object
        ArrayList objects = null;// =  (ArrayList) this.getScriptManager().runScript("searchIndex", objectDao, params, outParams);
        if (objects != null) {
            //Massage Objects.
            Iterator it = objects.iterator();
            while (it.hasNext()) {
                DataProviderObjectImpl dsObj = new DataProviderObjectImpl();
                dsObj.setValueObject(it.next());
                retObjects.add(dsObj);
            }
        }
    } catch (Exception e) {
        throw new ObjectCreationException("Error searching for objects.", e);
    }

    return retObjects;
}

From source file:com.intel.hadoop.graphbuilder.demoapps.wikipedia.docwordgraph.WordCountGraphTokenizer.java

@Override
public Iterator<Edge<StringType, StringType>> getEdges() {
    if (counts.isEmpty())
        return EmptyIterator.INSTANCE;

    ArrayList<Edge<StringType, StringType>> elist = new ArrayList<Edge<StringType, StringType>>(counts.size());
    Iterator<Entry<String, Integer>> iter = counts.entrySet().iterator();
    while (iter.hasNext()) {
        Entry<String, Integer> e = iter.next();
        elist.add(new Edge<StringType, StringType>(new StringType(id), new StringType(e.getKey()),
                new StringType(e.getValue().toString())));
    }/*from  w w w.  ja  v  a  2s.  com*/
    return elist.iterator();
}

From source file:edu.unibonn.kmeans.mapreduce.plotting.TimeSeriesPlotter_KMeans.java

private XYDataset createDataset(ArrayList<Cluster_KMeans> clusters, LocalDateTime from) {
    final TimeSeriesCollection dataset = new TimeSeriesCollection();

    //      for (int i = 0; i < clusters.size(); i++)
    //      {/*from ww w. j  ava 2 s.c  om*/
    //         Cluster_KMeans current_cluster = clusters.get(i);   
    //         double[] center_of_mass = current_cluster.getCenter_of_mass();
    //         
    //         final TimeSeries s1 = new TimeSeries("Cluster_"+current_cluster.getCluster_id(), Hour.class);
    //
    //         for (int j = 0; j < 24; j++)
    //         {
    //            s1.add(new Hour( j, from.getDayOfMonth(), from.getMonthValue(), from.getYear() ), center_of_mass[j]);
    //         }
    //         
    //         dataset.addSeries(s1);
    //      }

    for (int i = 0; i < clusters.size(); i++) {
        Cluster_KMeans current_cluster = clusters.get(i);
        ArrayList<Day_24d> member_time_series = current_cluster.getMembership();

        for (Iterator iterator = member_time_series.iterator(); iterator.hasNext();) {
            final TimeSeries s1 = new TimeSeries("Cluster_" + current_cluster.getCluster_id(), Hour.class);

            Day_24d current_series = (Day_24d) iterator.next();

            for (int j = 0; j < 24; j++) {
                s1.add(new Hour(j, from.getDayOfMonth(), from.getMonthValue(), from.getYear()),
                        current_series.getMeasurement(j));
            }

            dataset.addSeries(s1);
        }
    }

    dataset.setDomainIsPointsInTime(true);

    return dataset;
}

From source file:de.mprengemann.intellij.plugin.androidicons.dialogs.AndroidBatchScaleImporter.java

private void initRenderers() {
    final DefaultTableCellRenderer fileCellRenderer = new DefaultTableCellRenderer() {
        @Override/*from   ww w. j a va 2 s  . co  m*/
        protected void setValue(Object o) {
            File file = (File) o;
            if (file == null) {
                setText("");
                return;
            }
            if (file.isDirectory()) {
                setText(file.getAbsolutePath());
            } else {
                setText(FilenameUtils.removeExtension(file.getName()));
            }
        }
    };
    fileCellRenderer.setHorizontalTextPosition(DefaultTableCellRenderer.TRAILING);
    table.setDefaultRenderer(File.class, fileCellRenderer);
    table.setDefaultRenderer(ArrayList.class, new DefaultTableCellRenderer() {
        @Override
        protected void setValue(Object o) {
            if (o == null) {
                setText("");
            } else {
                ArrayList list = (ArrayList) o;
                Collections.sort(list);
                StringBuilder buffer = new StringBuilder();
                Iterator iterator = list.iterator();
                while (iterator.hasNext()) {
                    Object val = iterator.next();
                    buffer.append(val.toString());
                    if (iterator.hasNext()) {
                        buffer.append(", ");
                    }
                }
                setText(buffer.toString());
            }
        }
    });
}