List of usage examples for java.util ListIterator hasNext
boolean hasNext();
From source file:com.xtivia.training.BookPortlet.java
@ProcessAction(name = "editBookAction") public void editBookAction(ActionRequest actionRequest, ActionResponse actionResponse) { String isbn = actionRequest.getParameter("isbn"); ArrayList<String> errors = new ArrayList<String>(); Book bookEdit = ActionUtil.getFormRequest(actionRequest); boolean validate = ValidateBook.validateBook(bookEdit, errors); Book fromArray = null;/*from w w w. j av a 2 s. com*/ if (validate) { ListIterator iterator = books.listIterator(); while (iterator.hasNext()) { Book book = (Book) iterator.next(); String isbns = book.getIsbnNumber() + ""; if (isbn.equals(isbns)) { iterator.remove(); } } books.add(bookEdit); actionRequest.setAttribute("book", bookEdit); actionResponse.setRenderParameter(MYACTION_PARAM, bookJSP); } else { for (String error : errors) { SessionErrors.add(actionRequest, error); } SessionErrors.add(actionRequest, "error-saving-book"); actionResponse.setRenderParameter(MYACTION_PARAM, addJSP); actionRequest.setAttribute("book", bookEdit); actionRequest.setAttribute("edit", "edit"); } }
From source file:com.amazonaws.services.kinesis.clientlibrary.lib.worker.ProcessTask.java
/** * Scans a list of records to filter out records up to and including the most recent checkpoint value and to get * the greatest extended sequence number from the retained records. Also emits metrics about the records. * * @param scope metrics scope to emit metrics into * @param records list of records to scan and change in-place as needed * @param lastCheckpointValue the most recent checkpoint value * @param lastLargestPermittedCheckpointValue previous largest permitted checkpoint value * @return the largest extended sequence number among the retained records *///from ww w . j av a 2 s . c o m private ExtendedSequenceNumber filterAndGetMaxExtendedSequenceNumber(IMetricsScope scope, List<Record> records, final ExtendedSequenceNumber lastCheckpointValue, final ExtendedSequenceNumber lastLargestPermittedCheckpointValue) { ExtendedSequenceNumber largestExtendedSequenceNumber = lastLargestPermittedCheckpointValue; ListIterator<Record> recordIterator = records.listIterator(); while (recordIterator.hasNext()) { Record record = recordIterator.next(); ExtendedSequenceNumber extendedSequenceNumber = new ExtendedSequenceNumber(record.getSequenceNumber(), record instanceof UserRecord ? ((UserRecord) record).getSubSequenceNumber() : null); if (extendedSequenceNumber.compareTo(lastCheckpointValue) <= 0) { recordIterator.remove(); LOG.debug("removing record with ESN " + extendedSequenceNumber + " because the ESN is <= checkpoint (" + lastCheckpointValue + ")"); continue; } if (largestExtendedSequenceNumber == null || largestExtendedSequenceNumber.compareTo(extendedSequenceNumber) < 0) { largestExtendedSequenceNumber = extendedSequenceNumber; } scope.addData(DATA_BYTES_PROCESSED_METRIC, record.getData().limit(), StandardUnit.Bytes, MetricsLevel.SUMMARY); } return largestExtendedSequenceNumber; }
From source file:com.frankdye.marvelgraphws2.MarvelGraphView.java
/** * Creates a new instance of SimpleGraphView *//*from w w w . j a va 2s . 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:vteaexploration.plotgatetools.gates.PolygonGate.java
@Override public Path2D createPath2D() { Point2D p;//www. j a v a 2 s . c o m Path2D.Double polygon = new Path2D.Double(); ListIterator<Point2D.Double> itr = vertices.listIterator(); p = (Point2D) vertices.get(0); polygon.moveTo(p.getX(), p.getY()); while (itr.hasNext()) { p = (Point2D) itr.next(); polygon.lineTo(p.getX(), p.getY()); } polygon.closePath(); return polygon; }
From source file:org.powertac.officecomplexcustomer.persons.Person.java
/** * This function fills out the vector containing the days that the person is * going to be sick. When a person is sick he stays in bed. * //from w w w . java 2s.c o m * @param mean * @param dev * @param gen * @return */ Vector<Integer> createSicknessVector(double mean, double dev) { // Create auxiliary variables int days = (int) (dev * gen.nextGaussian() + mean); Vector<Integer> v = new Vector<Integer>(days); for (int i = 0; i < days; i++) { int x = gen.nextInt( OfficeComplexConstants.DAYS_OF_COMPETITION + OfficeComplexConstants.DAYS_OF_BOOTSTRAP) + 1; ListIterator<Integer> iter = v.listIterator(); while (iter.hasNext()) { int temp = (int) iter.next(); if (x == temp) { x = x + 1; iter = v.listIterator(); } } v.add(x); } java.util.Collections.sort(v); return v; }
From source file:com.predic8.membrane.core.interceptor.rewrite.RewriteInterceptor.java
@Override public Outcome handleRequest(Exchange exc) throws Exception { logMappings();/*ww w . j av a2 s. co m*/ ListIterator<String> it = exc.getDestinations().listIterator(); while (it.hasNext()) { String dest = it.next(); String pathQuery = URLUtil.getPathQuery(router.getUriFactory(), dest); int pathBegin = -1; int authorityBegin = dest.indexOf("//"); if (authorityBegin != -1) pathBegin = dest.indexOf("/", authorityBegin + 2); String schemaHostPort = pathBegin == -1 ? null : dest.substring(0, pathBegin); log.debug("pathQuery: " + pathQuery); log.debug("schemaHostPort: " + schemaHostPort); Mapping mapping = findFirstMatchingRegEx(pathQuery); if (mapping == null) continue; Type do_ = mapping.getDo(); log.debug("match found: " + mapping.from); log.debug("replacing with: " + mapping.to); log.debug("for type: " + do_); String newDest = replace(pathQuery, mapping); if (do_ == Type.REDIRECT_PERMANENT || do_ == Type.REDIRECT_TEMPORARY) { exc.setResponse(Response.redirect(newDest, do_ == Type.REDIRECT_PERMANENT).build()); return Outcome.RETURN; } if (!newDest.contains("://") && schemaHostPort != null) { // prepend schema, host and port from original uri newDest = schemaHostPort + newDest; } it.set(newDest); } Mapping mapping = findFirstMatchingRegEx(exc.getRequest().getUri()); if (mapping != null && mapping.do_ == Type.REWRITE) { String newDest = replace(exc.getRequest().getUri(), mapping); if (newDest.contains("://")) { newDest = URLUtil.getPathQuery(router.getUriFactory(), newDest); } exc.getRequest().setUri(newDest); } return Outcome.CONTINUE; }
From source file:com.qualogy.qafe.presentation.EventHandlerImpl.java
private Collection<BuiltInFunction> handleEventItems(List<EventItem> eventItems, ApplicationContext context, Event event, DataIdentifier dataId, EventData eventData) throws ExternalException { Collection<BuiltInFunction> builtInList = new ArrayList<BuiltInFunction>(); if (eventItems != null) { ListIterator<EventItem> itrEventItem = eventItems.listIterator(); while (itrEventItem.hasNext()) { EventItem eventItem = itrEventItem.next(); try { boolean stopProcessing = EventItemExecutor.getInstance().execute(eventItem, context, event, eventData, builtInList, this, dataId); if (stopProcessing) { break; }/* w w w .j a va 2s.co m*/ } catch (ReturnBuiltInException e) { break; } catch (ExternalException e) { ErrorResult errorResult = EventErrorProcessor.processError(itrEventItem, eventItem, context, dataId, e, eventData); boolean rethrow = (errorResult.getExternalException() != null); if (rethrow) { throw errorResult.getExternalException(); } else if (errorResult.hasItems()) { List<EventItem> exceptionHandlingEventItems = new ArrayList<EventItem>(); for (Item item : errorResult.getItems()) { if (item instanceof EventItem) { exceptionHandlingEventItems.add((EventItem) item); } } Collection<BuiltInFunction> exceptionHandlingBuiltInList = handleEventItems( exceptionHandlingEventItems, context, event, dataId, eventData); builtInList.addAll(exceptionHandlingBuiltInList); } } } } return builtInList; }
From source file:gov.nih.nci.ncicb.cadsr.contexttree.CDEBrowserTree.java
public DefaultMutableTreeNode buildTree(Hashtable treeParams) throws Exception { DefaultMutableTreeNode tree = null; BaseTreeNode baseNode = null;/*from w ww . ja va 2s . c o m*/ //TimeUtils.recordStartTime("Tree"); try { log.info("Tree Start " + TimeUtils.getEasternTime()); baseNode = new BaseTreeNode(treeParams); CDEBrowserTreeCache cache = CDEBrowserTreeCache.getAnInstance(); cache.init(baseNode, treeParams); WebNode contexts = new WebNode(cache.getIdGen().getNewId(), "caDSR Contexts", "javascript:" + baseNode.getJsFunctionName() + "('P_PARAM_TYPE=P_PARAM_TYPE&P_IDSEQ=P_IDSEQ&" + baseNode.getExtraURLParameters() + "')"); tree = new DefaultMutableTreeNode(contexts); List allContexts = cache.getAllContextHolders(); if (allContexts == null) return tree; ListIterator contextIt = allContexts.listIterator(); while (contextIt.hasNext()) { ContextHolder currContextHolder = (ContextHolder) contextIt.next(); Context currContext = currContextHolder.getContext(); DefaultMutableTreeNode contextNode = currContextHolder.getNode(); //Adding data template nodes DefaultMutableTreeNode tmpLabelNode; DefaultMutableTreeNode otherTempNodes; if (Context.CTEP.equals(currContext.getName())) { cache.initCtepInfo(baseNode, currContext); tmpLabelNode = new DefaultMutableTreeNode( new WebNode(cache.getIdGen().getNewId(), "Protocol Form Templates")); List ctepNodes = cache.getAllTemplatesForCtep(); tmpLabelNode.add((DefaultMutableTreeNode) ctepNodes.get(0)); tmpLabelNode.add((DefaultMutableTreeNode) ctepNodes.get(1)); contextNode.add(tmpLabelNode); log.info("CTEP Templates End " + TimeUtils.getEasternTime()); } else { log.info("Other Templates Start " + TimeUtils.getEasternTime()); otherTempNodes = cache.getTemplateNodes(currContext.getConteIdseq()); if (otherTempNodes != null) { contextNode.add(otherTempNodes); } log.info("Other Templates End " + TimeUtils.getEasternTime()); } //Adding classification nodes long startingTime = System.currentTimeMillis(); log.info("Classification Start " + TimeUtils.getEasternTime()); DefaultMutableTreeNode csNode = cache.getClassificationNodes(currContext.getConteIdseq()); if (csNode != null) contextNode.add(csNode); long timeElsp = System.currentTimeMillis() - startingTime; log.info("Classification Took " + timeElsp); //End Adding Classification Node //Adding protocols nodes //Filtering CTEP context in data element search tree log.info("Proto forms Start " + TimeUtils.getEasternTime()); /** Remove to TT 1892 if ((!currContext.getName().equals(Context.CTEP) && treeType.equals(TreeConstants.DE_SEARCH_TREE)) //Publish Change order || (baseNode.isCTEPUser().equals("Yes") && treeType.equals(TreeConstants.DE_SEARCH_TREE)) || (treeType.equals(TreeConstants.FORM_SEARCH_TREE))) { if ((currContext.getName().equals( Context.CTEP) && baseNode.isCTEPUser().equals("Yes")) || (!currContext.getName().equals(Context.CTEP))) { **/ List protoNodes = cache.getProtocolNodes(currContext.getConteIdseq()); /** for release 3.0.1, forms without protocol is not displayed, uncomment this * code to display them DefaultMutableTreeNode noProtocolFormNode = cache.getProtocolFormNodeWithNoProtocol(currContext.getConteIdseq()); */ DefaultMutableTreeNode protocolFormsLabelNode = null; /** for release 3.0.1, forms without protocol is not displayed, uncomment this * code to display them if ((protoNodes != null && !protoNodes.isEmpty()) || noProtocolFormNode != null ) { */ if ((protoNodes != null && !protoNodes.isEmpty())) { protocolFormsLabelNode = new DefaultMutableTreeNode( new WebNode(cache.getIdGen().getNewId(), "Protocol Forms")); /** for release 3.0.1, forms without protocol is not displayed, uncomment this * code to display them // Add form with no protocol if (noProtocolFormNode != null ) { protocolFormsLabelNode.add(noProtocolFormNode); } */ // Add form with protocol if (protoNodes != null && !protoNodes.isEmpty()) { Iterator tmpIter = protoNodes.iterator(); while (tmpIter.hasNext()) { protocolFormsLabelNode.add((DefaultMutableTreeNode) tmpIter.next()); } } contextNode.add(protocolFormsLabelNode); } /** } TT 1892 }**/ log.info("Proto forms End " + TimeUtils.getEasternTime()); //End Add Protocol Nodes //Display Catalog //Get Publishing Node info log.info("Publish strat " + TimeUtils.getEasternTime()); DefaultMutableTreeNode publishNode = cache.getPublishNode(currContext); if (publishNode != null) contextNode.add(publishNode); log.info("Publish end " + TimeUtils.getEasternTime()); //End Catalog tree.add(contextNode); } log.info("Tree End " + TimeUtils.getEasternTime()); } catch (Exception ex) { ex.printStackTrace(); throw ex; } return tree; }
From source file:name.livitski.tools.springlet.Launcher.java
/** * Configures the manager using command-line arguments. * The arguments are checked in their command line sequence. * If an argument begins with {@link Command#COMMAND_PREFIX}, * its part that follows it is treated as a (long) command's name. * If an argument begins with {@link Command#SWITCH_PREFIX}, * the following character(s) are treated as a switch. * The name or switch extracted this way, prepended with * a bean name prefix for a {@link #BEAN_NAME_PREFIX_COMMAND command} * or a {@link #BEAN_NAME_PREFIX_SWITCH switch}, becomes the name * of a bean to look up in the framework's * {@link #MAIN_BEAN_CONFIG_FILE configuration file(s)}. * The bean that handles a command must extend the * {@link Command} class. Once a suitable bean is found, * it is called to act upon the command or switch and process * any additional arguments associated with it. * If no bean can be found or the argument is not prefixed * properly, it is considered unclaimed. You may configure a * special subclass of {@link Command} to process such arguments * by placing a bean named {@link #BEAN_NAME_DEFAULT_HANDLER} on * the configuration. If there is no such bean configured, or when * any {@link Command} bean throws an exception while processing * a command, a command line error is reported and the application * quits./*w w w . j a va 2 s. c o m*/ * @param args the command line * @return this manager object */ public Launcher withArguments(String[] args) { configureDefaultLogging(); final Log log = log(); ListIterator<String> iargs = Arrays.asList(args).listIterator(); while (iargs.hasNext()) { String arg = iargs.next(); String prefix = null; String beanPrefix = null; Command cmd = null; if (arg.startsWith(Command.COMMAND_PREFIX)) prefix = Command.COMMAND_PREFIX; else if (arg.startsWith(Command.SWITCH_PREFIX)) prefix = Command.SWITCH_PREFIX; if (null != prefix) { arg = arg.substring(prefix.length()); beanPrefix = Command.SWITCH_PREFIX == prefix ? BEAN_NAME_PREFIX_SWITCH : BEAN_NAME_PREFIX_COMMAND; try { cmd = getBeanFactory().getBean(beanPrefix + arg, Command.class); } catch (NoSuchBeanDefinitionException noBean) { log.debug("Could not find a handler for command-line argument " + prefix + arg, noBean); } } if (null == cmd) { iargs.previous(); try { cmd = getBeanFactory().getBean(BEAN_NAME_DEFAULT_HANDLER, Command.class); } catch (RuntimeException ex) { log.error("Unknown command line argument: " + (null != prefix ? prefix : "") + arg, ex); status = STATUS_COMMAND_PARSING_FAILURE; break; } } try { cmd.process(iargs); } catch (SkipApplicationRunRequest skip) { if (log.isTraceEnabled()) log.trace("Handler for argument " + (null != prefix ? prefix : "") + arg + " requested to skip the application run", skip); status = STATUS_RUN_SKIPPED; break; } catch (RuntimeException err) { log.error("Invalid command line argument(s) near " + (null != prefix ? prefix : "") + arg + ": " + err.getMessage(), err); status = STATUS_COMMAND_PARSING_FAILURE; break; } catch (ApplicationBeanException err) { log.error("Error processing command line argument " + (null != prefix ? prefix : "") + arg + ": " + err.getMessage(), err); try { err.updateBeanStatus(); } catch (RuntimeException noStatus) { final ApplicationBean appBean = err.getApplicationBean(); log.warn("Could not obtain status code" + (null != appBean ? " from " + appBean : ""), noStatus); status = STATUS_INTERNAL_ERROR; } break; } } return this; }
From source file:org.socraticgrid.codeconversion.matchers.MapMatch.java
/** * Initialize the map from the inputstream. * * @param is/* ww w. ja v a 2 s. c o m*/ * * @throws InitializationException */ protected void load(InputStream is) throws InitializationException { try { JAXBContext jaxbContext = JAXBContext .newInstance(org.socraticgrid.codeconversion.matchers.xml.ObjectFactory.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); org.socraticgrid.codeconversion.matchers.xml.MapMatch xmlMap = (org.socraticgrid.codeconversion.matchers.xml.MapMatch) jaxbUnmarshaller .unmarshal(is); Iterator<TargetSystem> itr = xmlMap.getTargetSystem().iterator(); while (itr.hasNext()) { TargetSystem ts = itr.next(); // Update contract.addTargetSystem(ts.getTargetSystemCode()); TargetSystemCodeMap tsm = new TargetSystemCodeMap(); tsMap.put(ts.getTargetSystemCode(), tsm); ListIterator<SourceCoding> sItr = ts.getSourceCoding().listIterator(); while (sItr.hasNext()) { SourceCoding sc = sItr.next(); CodeReference cd = new CodeReference(ts.getTargetSystemCode(), sc.getTargetCode(), sc.getTargetName()); SearchMapping sm = new SearchMapping(sc.getSystem(), sc.getCode()); tsm.SrchMap.put(sm, cd); } } } catch (JAXBException exp) { throw new InitializationException("MapMap, Error parsing code map", exp); } }