List of usage examples for java.util ListIterator previous
E previous();
From source file:org.rifidi.emulator.reader.thingmagic.commandobjects.FetchCommand.java
public FetchCommand(String command, ThingMagicReaderSharedResources tmsr) throws CommandCreationException { // TODO Auto-generated constructor stub this.command = command; this.tmsr = tmsr; this.tmsr = tmsr; this.command = command; List<String> tokens = new ArrayList<String>(); /*/*from w w w . j av a 2s .c o m*/ * This regex looks for a Word, or a series of spaces on either side of * any single comparison operator or comma, or a single parentheses * (opening or closing). At the last ... any dangling spaces not * attached to the above groups and then anything else as a single * group. * * This makes it really easy to parse the command string as it becomes * really predictable tokens. */ Pattern tokenizer = Pattern.compile( // anything less... "[^\\s\\w,]+|" + // groups we are looking for... "\\w+|" + "\\s*,\\s*|" + "\\s?+", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher tokenFinder = tokenizer.matcher(command.toLowerCase().trim()); while (tokenFinder.find()) { String temp = tokenFinder.group(); /* * no need to add empty strings at tokens. */ // TODO: Figure out why we are getting empty stings as tokens. if (temp.equals("")) continue; tokens.add(temp); } ListIterator<String> tokenIterator = tokens.listIterator(); String token = tokenIterator.next(); if (!token.equals("fetch")) throw new CommandCreationException("Error 0100: syntax error at '" + token + "'"); try { token = tokenIterator.next(); if (!token.matches(WHITE_SPACE)) throw new CommandCreationException("Error 0100: syntax error at '" + token + "'"); do { token = tokenIterator.next(); if (!token.matches(A_WORD)) { throw new CommandCreationException("Error 0100: syntax error at '" + token + "'"); } if (!tmsr.getCursorCommandRegistry().containsKey(token)) { throw new CommandCreationException("Error 0100: Cursor does not exist"); } fetchList.add(token); if (!tokenIterator.hasNext()) { break; } token = tokenIterator.next(); if (!token.matches(COMMA_WITH_WS)) { tokenIterator.previous(); break; } } while (true); // check if the command correctly ends in a semicolon if (tokenIterator.hasNext()) { token = tokenIterator.next(); if (token.matches(WHITE_SPACE)) { token = tokenIterator.next(); } if (!token.equals(";")) { throw new CommandCreationException("Error 0100: syntax error at '" + token + "'"); } } else { throw new CommandCreationException("Error 0100: syntax error at '\n'"); } } catch (NoSuchElementException e) { /* * if we get here... we run out of tokens prematurely... Our job now * is to walk backwards to find the last non space tokens and throw * an exception saying that there is an syntax error at that point. */ /* * look for the last offending command block that is not a series of * whitespaces. */ token = tokenIterator.previous(); while (token.matches(WHITE_SPACE)) { token = tokenIterator.previous(); } logger.debug("Premature end of token list detected."); throw new CommandCreationException("Error 0100: syntax error at '" + token + "'"); } }
From source file:pku.sei.checkedcoverage.tracer.instrumentation.PauseTracingInstrumenter.java
@SuppressWarnings("unchecked") public void transformMethod(final MethodNode method, final ListIterator<MethodNode> methodIt, final String className) { if ((method.access & ACC_ABSTRACT) != 0 || (method.access & ACC_NATIVE) != 0) return;//from w w w . j a v a 2 s.c om int tracerLocalVarIndex = (method.access & Opcodes.ACC_STATIC) == 0 ? 1 : 0; for (final Type t : Type.getArgumentTypes(method.desc)) tracerLocalVarIndex += t.getSize(); // increment number of local variables by one (for the threadtracer) ++method.maxLocals; // and increment all local variable indexes after the new one by one for (final Object o : method.localVariables) { final LocalVariableNode localVar = (LocalVariableNode) o; if (localVar.index >= tracerLocalVarIndex) ++localVar.index; } final LabelNode l0 = new LabelNode(); final LabelNode l1 = new LabelNode(); final ListIterator<AbstractInsnNode> insnIt = method.instructions.iterator(); insnIt.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(Tracer.class), "getInstance", "()L" + Type.getInternalName(Tracer.class) + ";")); insnIt.add(new MethodInsnNode(INVOKEVIRTUAL, Type.getInternalName(Tracer.class), "getThreadTracer", "()L" + Type.getInternalName(ThreadTracer.class) + ";")); insnIt.add(new InsnNode(DUP)); insnIt.add(new VarInsnNode(ASTORE, tracerLocalVarIndex)); insnIt.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(ThreadTracer.class), "pauseTracing", "()V")); insnIt.add(l0); while (insnIt.hasNext()) { final AbstractInsnNode insn = insnIt.next(); switch (insn.getType()) { case AbstractInsnNode.INSN: switch (insn.getOpcode()) { case IRETURN: case LRETURN: case FRETURN: case DRETURN: case ARETURN: case RETURN: insnIt.previous(); insnIt.add(new VarInsnNode(ALOAD, tracerLocalVarIndex)); insnIt.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(ThreadTracer.class), "resumeTracing", "()V")); insnIt.next(); } break; case AbstractInsnNode.IINC_INSN: if (((IincInsnNode) insn).var >= tracerLocalVarIndex) ++((IincInsnNode) insn).var; break; case AbstractInsnNode.VAR_INSN: if (((VarInsnNode) insn).var >= tracerLocalVarIndex) ++((VarInsnNode) insn).var; break; default: break; } } method.instructions.add(l1); method.instructions.add(new VarInsnNode(ALOAD, tracerLocalVarIndex)); method.instructions.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(ThreadTracer.class), "resumeTracing", "()V")); method.instructions.add(new InsnNode(ATHROW)); method.tryCatchBlocks.add(new TryCatchBlockNode(l0, l1, l1, null)); // finally: create a copy of the method that gets the ThreadTracer as argument if (!"<clinit>".equals(method.name) && this.tracer.wasRedefined(className)) { final Type[] oldMethodArguments = Type.getArgumentTypes(method.desc); final Type[] newMethodArguments = Arrays.copyOf(oldMethodArguments, oldMethodArguments.length + 1); newMethodArguments[oldMethodArguments.length] = Type.getType(ThreadTracer.class); final String newMethodDesc = Type.getMethodDescriptor(Type.getReturnType(method.desc), newMethodArguments); final MethodNode newMethod = new MethodNode(method.access, method.name, newMethodDesc, method.signature, (String[]) method.exceptions.toArray(new String[method.exceptions.size()])); methodIt.add(newMethod); final Map<LabelNode, LabelNode> newMethodLabels = LazyMap.decorate(new HashMap<LabelNode, LabelNode>(), new Factory() { public Object create() { return new LabelNode(); } }); // copy the local variables information to the new method for (final Object o : method.localVariables) { final LocalVariableNode lv = (LocalVariableNode) o; newMethod.localVariables.add(new LocalVariableNode(lv.name, lv.desc, lv.signature, newMethodLabels.get(lv.start), newMethodLabels.get(lv.end), lv.index)); } newMethod.maxLocals = method.maxLocals; newMethod.maxStack = method.maxStack; // copy the try-catch-blocks for (final Object o : method.tryCatchBlocks) { final TryCatchBlockNode tcb = (TryCatchBlockNode) o; newMethod.tryCatchBlocks.add(new TryCatchBlockNode(newMethodLabels.get(tcb.start), newMethodLabels.get(tcb.end), newMethodLabels.get(tcb.handler), tcb.type)); } // skip the first 4 instructions, replace them with this: newMethod.instructions.add(new VarInsnNode(ALOAD, tracerLocalVarIndex)); final Iterator<AbstractInsnNode> oldInsnIt = method.instructions.iterator(4); // and add all the other instructions while (oldInsnIt.hasNext()) { final AbstractInsnNode insn = oldInsnIt.next(); newMethod.instructions.add(insn.clone(newMethodLabels)); } } }
From source file:de.unisb.cs.st.javaslicer.tracer.instrumentation.PauseTracingInstrumenter.java
@SuppressWarnings("unchecked") public void transformMethod(final MethodNode method, final ListIterator<MethodNode> methodIt, final String className) { if ((method.access & ACC_ABSTRACT) != 0 || (method.access & ACC_NATIVE) != 0) return;/*from ww w.java2 s . c o m*/ int tracerLocalVarIndex = (method.access & Opcodes.ACC_STATIC) == 0 ? 1 : 0; for (final Type t : Type.getArgumentTypes(method.desc)) tracerLocalVarIndex += t.getSize(); // increment number of local variables by one (for the threadtracer) ++method.maxLocals; // and increment all local variable indexes after the new one by one for (final Object o : method.localVariables) { final LocalVariableNode localVar = (LocalVariableNode) o; if (localVar.index >= tracerLocalVarIndex) ++localVar.index; } final LabelNode l0 = new LabelNode(); final LabelNode l1 = new LabelNode(); final ListIterator<AbstractInsnNode> insnIt = method.instructions.iterator(); insnIt.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(Tracer.class), "getInstance", "()L" + Type.getInternalName(Tracer.class) + ";")); insnIt.add(new MethodInsnNode(INVOKEVIRTUAL, Type.getInternalName(Tracer.class), "getThreadTracer", "()L" + Type.getInternalName(ThreadTracer.class) + ";")); insnIt.add(new InsnNode(DUP)); insnIt.add(new VarInsnNode(ASTORE, tracerLocalVarIndex)); insnIt.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(ThreadTracer.class), "pauseTracing", "()V")); insnIt.add(l0); while (insnIt.hasNext()) { final AbstractInsnNode insn = insnIt.next(); switch (insn.getType()) { case AbstractInsnNode.INSN: switch (insn.getOpcode()) { case IRETURN: case LRETURN: case FRETURN: case DRETURN: case ARETURN: case RETURN: insnIt.previous(); insnIt.add(new VarInsnNode(ALOAD, tracerLocalVarIndex)); insnIt.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(ThreadTracer.class), "resumeTracing", "()V")); insnIt.next(); } break; case AbstractInsnNode.IINC_INSN: if (((IincInsnNode) insn).var >= tracerLocalVarIndex) ++((IincInsnNode) insn).var; break; case AbstractInsnNode.VAR_INSN: if (((VarInsnNode) insn).var >= tracerLocalVarIndex) ++((VarInsnNode) insn).var; break; default: break; } } method.instructions.add(l1); method.instructions.add(new VarInsnNode(ALOAD, tracerLocalVarIndex)); method.instructions.add(new MethodInsnNode(INVOKEINTERFACE, Type.getInternalName(ThreadTracer.class), "resumeTracing", "()V")); method.instructions.add(new InsnNode(ATHROW)); method.tryCatchBlocks.add(new TryCatchBlockNode(l0, l1, l1, null)); // finally: create a copy of the method that gets the ThreadTracer as argument if (!"<clinit>".equals(method.name) && this.tracer.wasRedefined(className)) { final Type[] oldMethodArguments = Type.getArgumentTypes(method.desc); final Type[] newMethodArguments = Arrays.copyOf(oldMethodArguments, oldMethodArguments.length + 1); newMethodArguments[oldMethodArguments.length] = Type.getType(ThreadTracer.class); final String newMethodDesc = Type.getMethodDescriptor(Type.getReturnType(method.desc), newMethodArguments); final MethodNode newMethod = new MethodNode(method.access, method.name, newMethodDesc, method.signature, (String[]) method.exceptions.toArray(new String[method.exceptions.size()])); methodIt.add(newMethod); final Map<LabelNode, LabelNode> newMethodLabels = LazyMap.decorate(new HashMap<LabelNode, LabelNode>(), new Factory() { @Override public Object create() { return new LabelNode(); } }); // copy the local variables information to the new method for (final Object o : method.localVariables) { final LocalVariableNode lv = (LocalVariableNode) o; newMethod.localVariables.add(new LocalVariableNode(lv.name, lv.desc, lv.signature, newMethodLabels.get(lv.start), newMethodLabels.get(lv.end), lv.index)); } newMethod.maxLocals = method.maxLocals; newMethod.maxStack = method.maxStack; // copy the try-catch-blocks for (final Object o : method.tryCatchBlocks) { final TryCatchBlockNode tcb = (TryCatchBlockNode) o; newMethod.tryCatchBlocks.add(new TryCatchBlockNode(newMethodLabels.get(tcb.start), newMethodLabels.get(tcb.end), newMethodLabels.get(tcb.handler), tcb.type)); } // skip the first 4 instructions, replace them with this: newMethod.instructions.add(new VarInsnNode(ALOAD, tracerLocalVarIndex)); final Iterator<AbstractInsnNode> oldInsnIt = method.instructions.iterator(4); // and add all the other instructions while (oldInsnIt.hasNext()) { final AbstractInsnNode insn = oldInsnIt.next(); newMethod.instructions.add(insn.clone(newMethodLabels)); } } }
From source file:org.eredlab.g4.ccl.net.ftp.parser.VMSVersioningFTPEntryParser.java
/** * Implement hook provided for those implementers (such as * VMSVersioningFTPEntryParser, and possibly others) which return * multiple files with the same name to remove the duplicates .. * * @param original Original list//from www. j a v a 2s.co m * * @return Original list purged of duplicates */ public List preParse(List original) { original = super.preParse(original); HashMap existingEntries = new HashMap(); ListIterator iter = original.listIterator(); while (iter.hasNext()) { String entry = ((String) iter.next()).trim(); MatchResult result = null; if (_preparse_matcher_.matches(entry, _preparse_pattern_)) { result = _preparse_matcher_.getMatch(); String name = result.group(1); String version = result.group(2); NameVersion nv = new NameVersion(name, version); NameVersion existing = (NameVersion) existingEntries.get(name); if (null != existing) { if (nv.versionNumber < existing.versionNumber) { iter.remove(); // removal removes from original list. continue; } } existingEntries.put(name, nv); } } // we've now removed all entries less than with less than the largest // version number for each name that were listed after the largest. // we now must remove those with smaller than the largest version number // for each name that were found before the largest while (iter.hasPrevious()) { String entry = ((String) iter.previous()).trim(); MatchResult result = null; if (_preparse_matcher_.matches(entry, _preparse_pattern_)) { result = _preparse_matcher_.getMatch(); String name = result.group(1); String version = result.group(2); NameVersion nv = new NameVersion(name, version); NameVersion existing = (NameVersion) existingEntries.get(name); if (null != existing) { if (nv.versionNumber < existing.versionNumber) { iter.remove(); // removal removes from original list. } } } } return original; }
From source file:net.rptools.tokentool.controller.TokenTool_Controller.java
public void updateOverlayTreeViewRecentFolder(boolean selectMostRecent) { if (lastSelectedItem != null) updateRecentOverlayTreeItems(lastSelectedItem.getValue()); // Update Recent Overlay List if (!recentOverlayTreeItems.isEmpty()) { // Remember current selection (adding/removing tree items messes with the selection model) // int selectedItem = overlayTreeView.getSelectionModel().getSelectedIndex(); overlayTreeView.getSelectionModel().clearSelection(); // Clear current folder recentFolder.getChildren().clear(); // Add recent list to recentFolder in reverse order so most recent is at the top ListIterator<Entry<Path, TreeItem<Path>>> iter = new ArrayList<>(recentOverlayTreeItems.entrySet()) .listIterator(recentOverlayTreeItems.size()); while (iter.hasPrevious()) recentFolder.getChildren().add(iter.previous().getValue()); if (overlayTreeView.getRoot().getChildren().indexOf(recentFolder) == -1) { overlayTreeView.getRoot().getChildren().add(recentFolder); } else {/*from w ww . j a va2 s .co m*/ overlayTreeView.getRoot().getChildren().remove(recentFolder); overlayTreeView.getRoot().getChildren().add(recentFolder); } // Auto expand recent folder... recentFolder.setExpanded(true); addPseudoClassToLeafs(overlayTreeView); // Set the selected index back to what it was unless... if (selectMostRecent) { overlayTreeView.getSelectionModel().select(recentFolder.getChildren().get(0)); } else { // overlayTreeView.getSelectionModel().clearAndSelect(selectedItem); } } }
From source file:com.epam.catgenome.manager.gene.GffManager.java
private void loadExonsBackwards(int centerPosition, int viewPortSize, Chromosome chromosome, int intronLength, int featuresStart, final IntervalTree<Block> intervalTree, final AbstractFeatureReader<GeneFeature, LineIterator> featureReader) throws IOException { int totalLength = 0; // check if some of exons, got by forward lookup are good for backwards Iterator<IntervalTree.Node<Block>> nodeIterator = intervalTree.overlappers(featuresStart, centerPosition); while (nodeIterator.hasNext()) { Block exon = nodeIterator.next().getValue(); totalLength += calculateExonLength(exon, centerPosition, false); }//from w ww . j a va 2 s .c o m int i = 0; boolean lastChunk = false; while (totalLength < viewPortSize / 2) { if (lastChunk) { break; } int firstIndex = centerPosition - EXON_SEARCH_CHUNK_SIZE * (i + 1); final int lastIndex = centerPosition - 1 - EXON_SEARCH_CHUNK_SIZE * i; if (firstIndex < featuresStart) { firstIndex = featuresStart; lastChunk = true; // this is the last chunk to be traversed } CloseableIterator<GeneFeature> iterator = Utils.query(featureReader, chromosome, firstIndex, lastIndex); // instead traversing the whole file, read it by small chunks, 100000 bps // long. Hopefully, the desired window will be covered by first/second chunk if (iterator.hasNext()) { List<GeneFeature> featuresChunk = iterator.toList(); ListIterator<GeneFeature> listIterator = featuresChunk.listIterator(featuresChunk.size() - 1); while (listIterator.hasPrevious() && totalLength < viewPortSize / 2) { GeneFeature feature = listIterator.previous(); totalLength = processExon(intervalTree, totalLength, feature, intronLength, centerPosition, false); } } i++; } }
From source file:de.unisb.cs.st.javaslicer.tracer.instrumentation.TracingMethodInstrumenter.java
private boolean followedByJumpLabel(final ListIterator<AbstractInsnNode> iterator) { if (!iterator.hasNext()) return false; final AbstractInsnNode nextInsn = iterator.next(); iterator.previous(); for (AbstractInsnNode insn = nextInsn; insn != null; insn = insn.getNext()) { if (insn instanceof LabelNode && this.jumpTargetLabels.contains(insn)) return true; if (!(insn instanceof FrameNode || insn instanceof LineNumberNode)) break; }//from ww w .ja v a 2s . com return false; }
From source file:com.projity.pm.graphic.frames.DocumentFrame.java
/** * sees if currently selected row belongs to main project. used to see if can insert a subproject. subprojects can * only be inserted into master project//from w w w .j a va 2 s . co m * @return */ public boolean isCurrentRowInMainProject() { CommonSpreadSheet spreadSheet = getTopSpreadSheet(); if (spreadSheet == null) return true; int row = spreadSheet.getCurrentRow(); if (row == -1) return true; Node current = spreadSheet.getCurrentRowNode(); SpreadSheetModel model = (SpreadSheetModel) spreadSheet.getModel(); LinkedList previousNodes = model.getPreviousVisibleNodesFromRow(row); if (previousNodes == null) return true; previousNodes.add(current); // treat current node first since going backwards ListIterator i = previousNodes.listIterator(previousNodes.size()); while (i.hasPrevious()) { Object o = ((Node) i.previous()).getImpl(); if (o instanceof Task) { if (((Task) o).isInSubproject()) return false; return project == ((Task) o).getOwningProject(); } } return true; }
From source file:de.fosd.jdime.matcher.cost_model.CostModelMatcher.java
/** * Finds the lowest pair of (possibly different) ancestors of <code>a</code> and <code>b</code> that are part of the * same sibling group./* w w w .jav a2 s. co m*/ * * @param a * the first <code>Artifact</code> * @param b * the second <code>Artifact</code> * @param matchings * the current <code>CMMatching</code> * @param parameters * the <code>CMParameters</code> to use * @return the ancestor of the first <code>Artifact</code> in the first position, that of the second in the second * position */ private Tuple<T, T> lca(T a, T b, CMMatchings<T> matchings, CMParameters<T> parameters) { return parameters.lcaCache.computeIfAbsent(Tuple.of(a, b), ab -> { Tuple<T, T> ba = Tuple.of(b, a); if (parameters.lcaCache.containsKey(ba)) { Tuple<T, T> baLCS = parameters.lcaCache.get(ba); return Tuple.of(baLCS.y, baLCS.x); } if (siblings(a, matchings, parameters).contains(b)) { return ab; } List<T> aPath = pathToRoot(a); List<T> bPath = pathToRoot(b); ListIterator<T> aIt = aPath.listIterator(aPath.size()); ListIterator<T> bIt = bPath.listIterator(bPath.size()); T l, r; do { l = aIt.previous(); r = bIt.previous(); } while (l == r && (aIt.hasPrevious() && bIt.hasPrevious())); return Tuple.of(l, r); }); }
From source file:com.qspin.qtaste.testsuite.impl.JythonTestScript.java
private void dumpScriptPythonStackDetails(TestResult result, Throwable error) { StringBuilder stackTrace = new StringBuilder(); // get stacktrace from PyException traceback, because easier and line number is not always correct in Java stack trace if (error instanceof PyException) { List<PyFrame> stacktrace = new ArrayList<>(); PyTraceback previousTraceback = null; PyTraceback traceback = ((PyException) error).traceback; while (traceback != null && traceback != previousTraceback) { PyFrame frame = traceback.tb_frame; String fileName;/*from w w w .j a va 2s . c om*/ String function; if (frame != null && frame.f_code != null && (fileName = frame.f_code.co_filename) != null && (function = frame.f_code.co_name) != null) { // skip execfile() call in the embedded jython, doStep() and doSteps() functions, // private __invokexxx() methods of the __TestAPIWrapper class, // private __checkPresent() method of a test API wrapper class, // user_line() method of the __ScriptDebugger class and a function of the debugger if ((!fileName.equals("embedded_jython") || (!function.equals("<module>") && !function.equals("doStep") && !function.equals("doSteps") && !function.startsWith("_TestAPIWrapper__invoke") && !function.endsWith("__checkPresent") && !function.equals("user_line"))) && !fileName.endsWith(File.separator + "bdb.py")) { stacktrace.add(frame); } } previousTraceback = traceback; traceback = (PyTraceback) traceback.tb_next; } // extract all necessary details from stacktrace from last frame to first one boolean stackLastDataExtracted = false; ListIterator<PyFrame> frameIterator = stacktrace.listIterator(stacktrace.size()); while (frameIterator.hasPrevious()) { PyFrame frame = frameIterator.previous(); String fileName = frame.f_code.co_filename; String function = frame.f_code.co_name; int lineNumber = frame.f_lineno; // convert absolute path to relative path Path filePath = Paths.get(fileName); if (filePath.isAbsolute()) { filePath = Paths.get("").toAbsolutePath().relativize(filePath); } // normalize path fileName = filePath.normalize().toString(); if (function.equals("<module>")) { stackTrace.append("at file ").append(fileName).append(" line ").append(lineNumber).append('\n'); } else if (!function.equals("importTestScript")) { stackTrace.append("function ").append(function); if (!fileName.equals("embedded_jython") && !fileName.equals("JythonTestScript.java")) { stackTrace.append(" at file ").append(fileName).append(" line ").append(lineNumber); } stackTrace.append('\n'); } if (!stackLastDataExtracted && !fileName.equals("embedded_jython") && !fileName.equals("JythonTestScript.java")) { stackLastDataExtracted = true; result.setFailedLineNumber(lineNumber); result.setFailedFunctionId(function); } result.addStackTraceElement(new StackTraceElement("", function, fileName, lineNumber)); } } result.setStackTrace(stackTrace.toString().trim()); }