Example usage for java.util ListIterator next

List of usage examples for java.util ListIterator next

Introduction

In this page you can find the example usage for java.util ListIterator next.

Prototype

E next();

Source Link

Document

Returns the next element in the list and advances the cursor position.

Usage

From source file:com.frankdye.marvelgraphws2.MarvelGraphView.java

/**
 * Creates a new instance of SimpleGraphView
 */// w  w w.  j  a  v a2  s  . c o  m
public MarvelGraphView() {
    try {
        Path fFilePath;

        /**
         * Assumes UTF-8 encoding. JDK 7+.
         */
        String aFileName = "C:\\Users\\Frank Dye\\Desktop\\Programming Projects\\MarvelGraph\\data\\marvel_labeled_edges.tsv";
        fFilePath = Paths.get(aFileName);

        // New code
        // Read words from file and put into a simulated multimap
        Map<String, List<String>> map1 = new HashMap<String, List<String>>();
        Set<String> set1 = new HashSet<String>();

        Scanner scan1 = null;
        try {
            scan1 = new Scanner(fFilePath, ENCODING.name());
            while (scan1.hasNext()) {
                processLine(scan1.nextLine(), map1, set1);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // Creating an URL object.
        JSONObject newObj = new JSONObject();

        newObj.put("Heroes", set1);

        //Write out our set to a file
        PrintWriter fileWriter = null;
        try {
            fileWriter = new PrintWriter("heroes-json.txt", "UTF-8");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        fileWriter.println(newObj);
        fileWriter.close();

        System.out.println(newObj);

        // Close our scanner
        scan1.close();

        log("Done.");

        // Graph<V, E> where V is the type of the vertices
        // and E is the type of the edges
        g = new SparseMultigraph<String, String>();
        // Add some vertices. From above we defined these to be type Integer.

        for (String s : set1) {
            g.addVertex(s);
        }

        for (Entry<String, List<String>> entry : map1.entrySet()) {
            String issue = entry.getKey();
            ListIterator<String> heroes = entry.getValue().listIterator();
            String firstHero = heroes.next();
            while (heroes.hasNext()) {
                String secondHero = heroes.next();

                if (!g.containsEdge(issue)) {
                    g.addEdge(issue, firstHero, secondHero);
                }
            }
        }

        // Let's see what we have. Note the nice output from the
        // SparseMultigraph<V,E> toString() method
        // System.out.println("The graph g = " + g.toString());
        // Note that we can use the same nodes and edges in two different
        // graphs.
        DijkstraShortestPath alg = new DijkstraShortestPath(g, true);
        Map<String, Number> distMap = new HashMap<String, Number>();
        String n1 = "VOLSTAGG";
        String n4 = "ROM, SPACEKNIGHT";

        List<String> l = alg.getPath(n1, n4);
        distMap = alg.getDistanceMap(n1);
        System.out.println("The shortest unweighted path from " + n1 + " to " + n4 + " is:");
        System.out.println(l.toString());

        System.out.println("\nDistance Map: " + distMap.get(n4));
    } catch (JSONException ex) {
        Logger.getLogger(MarvelGraphView.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.apigee.sdk.apm.http.impl.client.cache.CacheEntryUpdater.java

private void removeCacheHeadersThatMatchResponse(List<Header> cacheEntryHeaderList, HttpResponse response) {
    for (Header responseHeader : response.getAllHeaders()) {
        ListIterator<Header> cacheEntryHeaderListIter = cacheEntryHeaderList.listIterator();

        while (cacheEntryHeaderListIter.hasNext()) {
            String cacheEntryHeaderName = cacheEntryHeaderListIter.next().getName();

            if (cacheEntryHeaderName.equals(responseHeader.getName())) {
                cacheEntryHeaderListIter.remove();
            }//from w  w  w .j a v a  2s .c om
        }
    }
}

From source file:edu.cornell.mannlib.vedit.controller.BaseEditController.java

public List<Option> getSortedList(HashMap<String, Option> hashMap, List<Option> optionList, VitroRequest vreq) {

    class ListComparator implements Comparator<String> {

        Collator collator;//from   w w w. j  a v a  2  s  .c  om

        public ListComparator(Collator collator) {
            this.collator = collator;
        }

        @Override
        public int compare(String str1, String str2) {
            return collator.compare(str1, str2);
        }

    }

    List<String> bodyVal = new ArrayList<String>();
    List<Option> options = new ArrayList<Option>();
    Iterator<Option> itr = optionList.iterator();
    while (itr.hasNext()) {
        Option option = itr.next();
        hashMap.put(option.getBody(), option);
        bodyVal.add(option.getBody());
    }

    Collections.sort(bodyVal, new ListComparator(vreq.getCollator()));
    ListIterator<String> itrStr = bodyVal.listIterator();
    while (itrStr.hasNext()) {
        options.add(hashMap.get(itrStr.next()));
    }
    return options;
}

From source file:brut.androlib.src.SmaliBuilder.java

private void buildFile(String fileName, DexBuilder dexBuilder) throws AndrolibException, IOException {
    File inFile = new File(mSmaliDir, fileName);
    InputStream inStream = new FileInputStream(inFile);

    if (fileName.endsWith(".smali")) {
        try {/*from   w  ww  . ja  va2  s  . co m*/
            if (!SmaliMod.assembleSmaliFile(inFile, dexBuilder, false, false)) {
                throw new AndrolibException("Could not smali file: " + fileName);
            }
        } catch (IOException | RecognitionException ex) {
            throw new AndrolibException(ex);
        }
        return;
    }
    if (!fileName.endsWith(".java")) {
        LOGGER.warning("Unknown file type, ignoring: " + inFile);
        return;
    }

    StringBuilder out = new StringBuilder();
    List<String> lines = IOUtils.readLines(inStream);

    if (!mDebug) {
        final String[] linesArray = lines.toArray(new String[0]);
        for (int i = 1; i < linesArray.length - 1; i++) {
            out.append(linesArray[i].split("//", 2)[1]).append('\n');
        }
    } else {
        lines.remove(lines.size() - 1);
        ListIterator<String> it = lines.listIterator(1);

        out.append(".source \"").append(inFile.getName()).append("\"\n");
        while (it.hasNext()) {
            String line = it.next().split("//", 2)[1].trim();
            if (line.isEmpty() || line.charAt(0) == '#' || line.startsWith(".source")) {
                continue;
            }
            if (line.startsWith(".method ")) {
                it.previous();
                DebugInjector.inject(it, out);
                continue;
            }

            out.append(line).append('\n');
        }
    }

    try {
        if (!SmaliMod.assembleSmaliFile(out.toString(), dexBuilder, false, false, inFile)) {
            throw new AndrolibException("Could not smali file: " + fileName);
        }
    } catch (IOException | RecognitionException ex) {
        throw new AndrolibException(ex);
    }
}

From source file:airbrake.Backtrace.java

private final List<String> filter(final List<String> backtrace) {
    final ListIterator<String> iterator = backtrace.listIterator();
    while (iterator.hasNext()) {
        String string = iterator.next();
        if (mustBeIgnored(string)) {
            continue;
        }/*  www  .  ja  v  a  2  s  .c o m*/
        if (notValidBacktrace(string)) {
            string = removeDobuleDot(string);
        }
        filteredBacktrace.add(string);
    }

    return filteredBacktrace;
}

From source file:net.relet.freimap.LinkInfo.java

public void setLinkProfile(LinkedList<LinkData> lp) {

    XYSeries data = new XYSeries("etx");
    XYSeries avail = new XYSeries("avail");
    XYSeriesCollection datac = new XYSeriesCollection(data);
    datac.addSeries(avail);/*from   w ww. jav  a2  s .co  m*/
    linkChart = ChartFactory.createXYLineChart("average link etx\r\naverage link availability", "time", "etx",
            datac, PlotOrientation.VERTICAL, false, false, false);
    sexupLayout(linkChart);

    long first = lp.getFirst().time, last = lp.getLast().time, lastClock = first, count = 0, //number of samplis in aggregation timespan
            maxCount = 0; //max idem
    long aggregate = (last - first) / CHART_WIDTH; //calculate aggregation timespan: divide available timespan in CHART_WIDTH equal chunks
    double sum = 0;

    /* ok, this ain't effective, we do it just to pre-calculate maxCount */
    ListIterator<LinkData> li = lp.listIterator();
    while (li.hasNext()) {
        LinkData ld = li.next();
        count++;
        if (ld.time - lastClock > aggregate) {
            if (maxCount < count)
                maxCount = count;
            lastClock = ld.time;
            count = 0;
        }
    }

    //reset for second iteration
    count = 0;
    lastClock = first;

    //iterate again
    li = lp.listIterator();
    while (li.hasNext()) {
        LinkData ld = li.next();

        sum += ld.quality;
        count++;

        if (aggregate == 0)
            aggregate = 1000;//dirty hack
        if (ld.time - lastClock > aggregate) {
            for (long i = lastClock; i < ld.time - aggregate; i += aggregate) {
                data.add(i * 1000, (i == lastClock) ? sum / count : Double.NaN);
                avail.add(i * 1000, (i == lastClock) ? ((double) count / maxCount) : 0);
            }

            count = 0;
            sum = 0;
            lastClock = ld.time;
        }
    }

    status = STATUS_AVAILABLE;
}

From source file:edu.harvard.i2b2.pm.util.PMUtil.java

public void convertToUppercaseStrings(List<String> list) {
    ListIterator<String> iterator = list.listIterator();

    while (iterator.hasNext()) {
        String color = iterator.next(); // get item                 
        iterator.set(color.toUpperCase()); // convert to upper case
    } // end while
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.json.GetEntitiesByVClass.java

@Override
protected JSONArray process() throws ServletException {
    log.debug("in getEntitiesByVClass()");
    String vclassURI = vreq.getParameter("vclassURI");
    WebappDaoFactory daos = vreq.getUnfilteredWebappDaoFactory();

    if (vclassURI == null) {
        throw new ServletException("getEntitiesByVClass(): no value for 'vclassURI' found in the HTTP request");
    }/*from   w  ww.j  a  v  a2 s.c om*/

    VClass vclass = daos.getVClassDao().getVClassByURI(vclassURI);
    if (vclass == null) {
        throw new ServletException("getEntitiesByVClass(): could not find vclass for uri '" + vclassURI + "'");
    }

    List<Individual> entsInVClass = daos.getIndividualDao().getIndividualsByVClass(vclass);
    if (entsInVClass == null) {
        throw new ServletException(
                "getEntitiesByVClass(): null List<Individual> retruned by getIndividualsByVClass() for "
                        + vclassURI);
    }
    int numberOfEntsInVClass = entsInVClass.size();

    List<Individual> entsToReturn = new ArrayList<Individual>(REPLY_SIZE);
    String requestHash = null;
    int count = 0;
    boolean more = false;
    /* we have a large number of items to send back so we need to stash the list in the session scope */
    if (entsInVClass.size() > REPLY_SIZE) {
        more = true;
        HttpSession session = vreq.getSession(true);
        requestHash = Integer.toString((vclassURI + System.currentTimeMillis()).hashCode());
        session.setAttribute(requestHash, entsInVClass);

        ListIterator<Individual> entsFromVclass = entsInVClass.listIterator();
        while (entsFromVclass.hasNext() && count < REPLY_SIZE) {
            entsToReturn.add(entsFromVclass.next());
            entsFromVclass.remove();
            count++;
        }
        if (log.isDebugEnabled()) {
            log.debug("getEntitiesByVClass(): Creating reply with continue token, found " + numberOfEntsInVClass
                    + " Individuals");
        }
    } else {
        if (log.isDebugEnabled())
            log.debug("getEntitiesByVClass(): sending " + numberOfEntsInVClass
                    + " Individuals without continue token");
        entsToReturn = entsInVClass;
        count = entsToReturn.size();
    }

    //put all the entities on the JSON array
    JSONArray ja = individualsToJson(entsToReturn);

    //put the responseGroup number on the end of the JSON array
    if (more) {
        try {
            JSONObject obj = new JSONObject();
            obj.put("resultGroup", "true");
            obj.put("size", count);
            obj.put("total", numberOfEntsInVClass);

            StringBuffer nextUrlStr = vreq.getRequestURL();
            nextUrlStr.append("?").append("getEntitiesByVClass").append("=1&").append("resultKey=")
                    .append(requestHash);
            obj.put("nextUrl", nextUrlStr.toString());

            ja.put(obj);
        } catch (JSONException je) {
            throw new ServletException("unable to create continuation as JSON: " + je.getMessage());
        }
    }

    log.debug("done with getEntitiesByVClass()");
    return ja;
}

From source file:com.adobe.acs.commons.httpcache.config.impl.GroupHttpCacheConfigExtension.java

@Activate
@Modified//  ww w. j  a  va  2 s .c  o  m
protected void activate(Map<String, Object> configs) {

    // User groups after removing empty strings.
    userGroups = new ArrayList(
            Arrays.asList(PropertiesUtil.toStringArray(configs.get(PROP_USER_GROUPS), new String[] {})));
    ListIterator<String> listIterator = userGroups.listIterator();
    while (listIterator.hasNext()) {
        String value = listIterator.next();
        if (StringUtils.isBlank(value)) {
            listIterator.remove();
        }
    }

    log.info("GroupHttpCacheConfigExtension activated/modified.");
}

From source file:de.htwg_konstanz.ebus.wholesaler.demo.ImportXML.java

@Override
public final String execute(final HttpServletRequest request, final HttpServletResponse response,
        final ArrayList<String> errorList) {
    // get the login bean from the session
    LoginBean loginBean = (LoginBean) request.getSession(true).getAttribute(PARAM_LOGIN_BEAN);

    // ensure that the user is logged in
    if (loginBean != null && loginBean.isLoggedIn()) {
        // ensure that the user is allowed to execute this action (authorization)
        // at this time the authorization is not fully implemented.
        // -> use the "Security.RESOURCE_ALL" constant which includes all resources.
        if (Security.getInstance().isUserAllowed(loginBean.getUser(), Security.RESOURCE_ALL,
                Security.ACTION_READ)) {
            response.setContentType("text/html;charset=UTF-8");
            /*--------------------------------------
             -- Start Import/*  w  w  w . j a v a 2s .  c  o m*/
             ----------------------------------------*/
            // Input Stream which has to be parsed
            InputStream is;
            // Check if the form was sended
            if (ServletFileUpload.isMultipartContent(request)) {
                try {
                    is = upload.upload(request);
                    // Server-Side check if a File was chosen or if it was an emty File
                    if (is == null) {
                        return "importxml.jsp?errormessage=File was empty!!!!!!! Or wrong file-type. only xml is allowed";
                    }

                    // Returns the valid XML document
                    ParseReportDTO report = xmlParser.validateTheXml(is);
                    org.w3c.dom.Document doc = report.getDoc();
                    if (doc == null) {
                        return "importxml.jsp?errormessage=" + report.getMessage();
                    }

                    System.out.println(doc);

                    // Reads the XML-File and saves the Products to the Database
                    ReportDTO returnval = saveProduct.readXML(doc);

                    // Writes the products which are already in database to the URL
                    String notimported = "";
                    if (returnval.getNotImported() != null) {
                        ListIterator<Integer> li = returnval.getNotImported().listIterator();
                        while (li.hasNext()) {
                            notimported = notimported + li.next() + ",";
                        }
                    }

                    if (returnval.getType()) {
                        return "importxml.jsp?infomessage=" + returnval.getMessage();
                    } else {
                        return "importxml.jsp?errormessage=" + returnval.getMessage() + "&notimported="
                                + notimported;
                    }
                    // XML File Validieeren
                } catch (FileUploadException | IOException | SAXException | ParserConfigurationException ex) {
                    Logger.getLogger(ImportXML.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            // Rendering the import page
            return "importxml.jsp";
        } else {
            // authorization failed -> show error message
            errorList.add("You are not allowed to perform this action!");
            // redirect to the welcome page
            return "welcome.jsp";
        }
    } else {
        // redirect to the login page
        return "login.jsp";
    }
}