List of usage examples for java.util Stack Stack
public Stack()
From source file:org.pgptool.gui.encryption.implpgp.KeyFilesOperationsPgpImpl.java
@Override public void exportPrivateKey(Key key, String targetFilePathname) { Preconditions.checkArgument(key != null && key.getKeyData() != null && key.getKeyInfo() != null, "Key must be providedand fully described"); KeyDataPgp keyDataPgp = KeyDataPgp.get(key); Preconditions.checkArgument(keyDataPgp.getSecretKeyRing() != null, "KeyPair key wasn't provided"); Preconditions.checkArgument(StringUtils.hasText(targetFilePathname), "targetFilePathname must be provided"); Stack<OutputStream> os = new Stack<>(); try {// w w w. ja v a 2s. c o m os.push(new FileOutputStream(targetFilePathname)); if ("asc".equalsIgnoreCase(FilenameUtils.getExtension(targetFilePathname))) { os.push(new ArmoredOutputStream(os.peek())); } keyDataPgp.getSecretKeyRing().encode(os.peek()); if (keyDataPgp.getPublicKeyRing() != null) { keyDataPgp.getPublicKeyRing().encode(os.peek()); } } catch (Throwable t) { throw new RuntimeException( "Failed to export private key " + key.getKeyInfo().getUser() + " to " + targetFilePathname, t); } finally { while (!os.isEmpty()) { IoStreamUtils.safeClose(os.pop()); } } }
From source file:hugonicolau.openbrailleinput.wordcorrection.mafsa.MAFSA.java
public Set<SuggestionResult> searchMSD(String transWord, int maxCost, float insertionCost, float substitutionCost, float omissionCost, Distance distance) { // build first row List<Float> row = range(transWord.length() + 1); // results/*w w w. j av a2s . c o m*/ Set<SuggestionResult> results = new HashSet<SuggestionResult>(); // iteratively (to prevent stack overflow) search each branch of the graph // a stack of paths to traverse. This prevents the StackOverflowException. Stack<StackLevenshteinEntry> stack = new Stack<StackLevenshteinEntry>(); for (Iterator<Long> iter = childIterator(nodes[0]); iter.hasNext();) { long child = iter.next(); char c = getChar(child); StackLevenshteinEntry entry = new StackLevenshteinEntry(child, transWord.toUpperCase().toCharArray(), String.valueOf(c), row); stack.push(entry); } // thread to control time to search for suggestions mAreTimeAvailable = true; mTimerTask = new TimerTask() { @Override public void run() { //Log.v(BrailleSpellCheckerService.TAG, "Search Interrupted!"); mAreTimeAvailable = false; } }; mTimer = new Timer(); mTimer.schedule(mTimerTask, 500); //500 ms to find all suggestions while (!stack.empty() && mAreTimeAvailable) { StackLevenshteinEntry entry = stack.pop(); List<Float> previousRow = entry.previousRow; int columns = entry.chars.length + 1; List<Float> currentRow = new LinkedList<Float>(); currentRow.add(previousRow.get(0) + omissionCost); // build one row for the letter, with a column for each letter in the target word, // plus one for the empty string at column 0 for (int column = 1; column < columns; column++) { // cost * braille_distance float insertCost = currentRow.get(column - 1) + insertionCost;// * //getInsertionDistance(entry.chars, column-1, getChar(entry.node)); float omitCost = previousRow.get(column) + omissionCost; float substituteCost = previousRow.get(column - 1); if (entry.chars[column - 1] != getChar(entry.node)) substituteCost += substitutionCost * distance.getDistance(entry.chars[column - 1], getChar(entry.node)); currentRow.add(Math.min(insertCost, Math.min(omitCost, substituteCost))); } // if last entry in the row indicates the optimal cost is less than the maximum cost, // and there is a word in this node, then add it. int last = currentRow.size() - 1; if (currentRow.get(last) <= maxCost && canTerminate(entry.node)) { results.add(new SuggestionResult(entry.subword, currentRow.get(last))); } // if any entries in the row are less than the maximum cost, then iteratively search each branch if (min(currentRow) <= maxCost) { for (Iterator<Long> iter = childIterator(entry.node); iter.hasNext();) { // get child long child = iter.next(); // build subword StackLevenshteinEntry nextEntry = new StackLevenshteinEntry(child, entry.chars, entry.subword + getChar(child), currentRow); // search that branch stack.push(nextEntry); } } } mTimer.cancel(); // return list of results return results; }
From source file:com.webcohesion.ofx4j.io.nanoxml.TestNanoXMLOFXReader.java
/** * tests whitespace before and after/* w w w. ja v a 2 s . c o m*/ */ public void testWhitespaceBeforeAndAfter() throws Exception { NanoXMLOFXReader reader = new NanoXMLOFXReader(); final Map<String, List<String>> headers = new HashMap<String, List<String>>(); final Stack<Map<String, List<Object>>> aggregateStack = new Stack<Map<String, List<Object>>>(); TreeMap<String, List<Object>> root = new TreeMap<String, List<Object>>(); aggregateStack.push(root); reader.setContentHandler(getNewDefaultHandler(headers, aggregateStack)); reader.parse(TestNanoXMLOFXReader.class.getResourceAsStream("whitespace-example.ofx")); assertEquals(9, headers.size()); assertEquals(1, aggregateStack.size()); assertSame(root, aggregateStack.pop()); TreeMap<String, List<Object>> OFX = (TreeMap<String, List<Object>>) root.remove("OFX").get(0); assertNotNull(OFX); assertEquals("E", OFX.remove("S").get(0)); assertTrue(OFX.isEmpty()); assertTrue(root.isEmpty()); }
From source file:com.amalto.webapp.core.util.Util.java
public static WSWhereItem makeWhereItem(List<WSWhereItem> conditions) { List<Object> conds = new ArrayList<Object>(); for (int i = 0; i < conditions.size(); i++) { WSWhereItem item = conditions.get(i); conds.add(item);/*from w w w .j a va 2s . c o m*/ if (i < conditions.size() - 1) { WSStringPredicate predicate = item.getWhereCondition().getStringPredicate(); switch (predicate) { case NOT: case EXACTLY: case STRICTAND: case NONE: predicate = WSStringPredicate.AND; break; } conds.add(predicate); } } Stack<WSStringPredicate> stackOp = new Stack<WSStringPredicate>(); List<Object> rpn = new ArrayList<Object>(); for (Object item : conds) { if (item instanceof WSWhereItem) { rpn.add(item); } else { WSStringPredicate predicate = (WSStringPredicate) item; while (!stackOp.isEmpty()) { rpn.add(stackOp.pop()); } stackOp.push(predicate); } } while (!stackOp.isEmpty()) { rpn.add(stackOp.pop()); } Stack<WSWhereItem> whereStack = new Stack<WSWhereItem>(); for (Object o : rpn) { if (o instanceof WSWhereItem) { whereStack.push((WSWhereItem) o); } else if (o instanceof WSStringPredicate) { if (WSStringPredicate.OR.equals(o)) { WSWhereItem item1 = whereStack.pop(); WSWhereItem item2 = whereStack.pop(); WSWhereOr or = new WSWhereOr(new WSWhereItem[] { item2, item1 }); whereStack.push(new WSWhereItem(null, null, or)); } else if (WSStringPredicate.AND.equals(o)) { WSWhereItem item1 = whereStack.pop(); WSWhereItem item2 = whereStack.pop(); WSWhereAnd and = new WSWhereAnd(new WSWhereItem[] { item2, item1 }); whereStack.push(new WSWhereItem(null, and, null)); } } } return whereStack.pop(); }
From source file:ch.randelshofer.cubetwister.HTMLExporter.java
private void init() throws IOException { // Initialize the progress observer // -------------------------------- p.setMaximum(countHTMLTemplates(p) + 1); p.setIndeterminate(false);// w w w . ja v a2s.c o m // Determine which virtual cube kinds need to be exported virtualCubeKinds = new HashSet<CubeKind>(); for (EntityModel node : model.getCubes().getChildren()) { CubeModel cm = (CubeModel) node; virtualCubeKinds.add(cm.getKind()); } playerCubeKinds = new HashSet<CubeKind>(); for (EntityModel node : model.getCubes().getChildren()) { ScriptModel sm = (ScriptModel) node; playerCubeKinds.add(sm.getCubeModel().getKind()); } // Create unique ID's for all objects // ---------------------------------- ids = new HashMap<EntityModel, String>(); // Holds all used ID's. To prevent name collisions on // file systems, which are not case sensitive, we store // only lower-case ID's in this set. HashSet<String> usedIDs = new HashSet<String>(); for (EntityModel node : model.getRoot().preorderIterable()) { if (node instanceof InfoModel) { InfoModel im = (InfoModel) node; String baseId = toID(im.getName()); String id = baseId; for (int i = 1; usedIDs.contains(id.toLowerCase()); i++) { id = baseId + "_" + i; } usedIDs.add(id.toLowerCase()); ids.put(im, id); } } // Create top level of data on placeholder stack stack = new Stack<StackEntry>(); StackEntry entry = new StackEntry(); stack.push(entry); // Put labels DataMap data = entry.data; data.put("software.title", "CubeTwister"); data.put("software.copyright", "Copyright by Werner Randelshofer. All Rights Reserved."); data.put("software.version", Main.getVersion()); data.put("cubes.title", "Cubes"); data.put("notations.title", "Notations"); data.put("scripts.title", "Scripts"); data.put("notes.title", "Notes"); // Put information about the document data.put("document.name", documentName); data.put("document.copyright", "Copyright by Werner Randelshofer. All Rights Reserved."); data.put("cube.count", model.getCubes().getChildCount()); data.put("notation.count", model.getNotations().getChildCount()); data.put("script.count", model.getScripts().getChildCount()); data.put("note.count", model.getTexts().getChildCount()); // Push default cube and default notation on the placeholder Stack putCubeData(model.getDefaultCube(), ""); putNotationData(model.getDefaultNotation(model.getDefaultCube().getLayerCount()), ""); }
From source file:dev.memento.MainActivity.java
/** Called when the activity is first created. */ @Override// www .j av a2 s. c om public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUserPressedBack = false; setContentView(R.layout.activity_main); mUserAgent = getApplicationContext().getText(R.string.user_agent).toString(); mWebHistory = new Stack<ExWebHistoryItem>(); // Set the date and time format SimpleDateTime.mDateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext()); SimpleDateTime.mTimeFormat = android.text.format.DateFormat.getTimeFormat(getApplicationContext()); // Holds all the timemaps for the web page being viewed mTimeMaps = new HashSet<TimeMap>(); // Set the current date mToday = new SimpleDateTime(); mCurrentUrl = getApplicationContext().getText(R.string.homepage).toString(); mOriginalUrl = mCurrentUrl; mDateChosen = mToday; mDateDisplayed = mToday; mMementos = new MementoList(); // Add some favicons of web archives used by proxy server mFavicons = new HashMap<String, Bitmap>(); mFavicons.put("ia", BitmapFactory.decodeResource(getResources(), R.drawable.ia_favicon)); mFavicons.put("webcite", BitmapFactory.decodeResource(getResources(), R.drawable.webcite_favicon)); mFavicons.put("national-archives", BitmapFactory.decodeResource(getResources(), R.drawable.national_archives_favicon)); initUI(); }
From source file:com.unboundid.scim.sdk.FilterParser.java
/** * Read a filter expression./* www . j a va2s .c om*/ * * @return The SCIM filter. */ private SCIMFilter readFilter() { final Stack<Node> expressionStack = new Stack<Node>(); // Employ the shunting-yard algorithm to parse into reverse polish notation, // where the operands are filter components and the operators are the // logical AND and OR operators. This algorithm ensures that operator // precedence and parentheses are respected. final List<Node> reversePolish = new ArrayList<Node>(); for (String word = readWord(); word != null; word = readWord()) { if (word.equalsIgnoreCase("and") || word.equalsIgnoreCase("or")) { final OperatorNode currentOperator; if (word.equalsIgnoreCase("and")) { currentOperator = new OperatorNode(SCIMFilterType.AND, markPos); } else { currentOperator = new OperatorNode(SCIMFilterType.OR, markPos); } while (!expressionStack.empty() && (expressionStack.peek() instanceof OperatorNode)) { final OperatorNode previousOperator = (OperatorNode) expressionStack.peek(); if (previousOperator.getPrecedence() < currentOperator.getPrecedence()) { break; } reversePolish.add(expressionStack.pop()); } expressionStack.push(currentOperator); } else if (word.equals("(")) { expressionStack.push(new LeftParenthesisNode(markPos)); } else if (word.equals(")")) { while (!expressionStack.empty() && !(expressionStack.peek() instanceof LeftParenthesisNode)) { reversePolish.add(expressionStack.pop()); } if (expressionStack.empty()) { final String msg = String.format( "No opening parenthesis matching closing " + "parenthesis at position %d", markPos); throw new IllegalArgumentException(msg); } expressionStack.pop(); } else { rewind(); final int pos = currentPos; final SCIMFilter filterComponent = readFilterComponent(); reversePolish.add(new FilterNode(filterComponent, pos)); } } while (!expressionStack.empty()) { final Node node = expressionStack.pop(); if (node instanceof LeftParenthesisNode) { final String msg = String.format( "No closing parenthesis matching opening " + "parenthesis at position %d", node.getPos()); throw new IllegalArgumentException(msg); } reversePolish.add(node); } // Evaluate the reverse polish notation to create a single complex filter. final Stack<FilterNode> filterStack = new Stack<FilterNode>(); for (final Node node : reversePolish) { if (node instanceof OperatorNode) { final FilterNode rightOperand = filterStack.pop(); final FilterNode leftOperand = filterStack.pop(); final OperatorNode operatorNode = (OperatorNode) node; if (operatorNode.getFilterType().equals(SCIMFilterType.AND)) { final SCIMFilter filter = SCIMFilter.createAndFilter( Arrays.asList(leftOperand.getFilterComponent(), rightOperand.getFilterComponent())); filterStack.push(new FilterNode(filter, leftOperand.getPos())); } else { final SCIMFilter filter = SCIMFilter.createOrFilter( Arrays.asList(leftOperand.getFilterComponent(), rightOperand.getFilterComponent())); filterStack.push(new FilterNode(filter, leftOperand.getPos())); } } else { filterStack.push((FilterNode) node); } } if (filterStack.size() == 0) { final String msg = String.format("Empty filter expression"); throw new IllegalArgumentException(msg); } else if (filterStack.size() > 1) { final String msg = String.format("Unexpected characters at position %d", expressionStack.get(1).pos); throw new IllegalArgumentException(msg); } return filterStack.get(0).filterComponent; }
From source file:au.edu.usq.fascinator.harvester.ice2.Ice2Harvester.java
@Override public void init() throws HarvesterException { // Init stats objectsCreated = 0;/* w w w. jav a2 s .co m*/ filesProcessed = 0; // Caching area for html marshalling String tempPath = System.getProperty("java.io.tmpdir"); tempDir = new File(tempPath, "ice2Harvest"); if (!tempDir.exists()) { tempDir.mkdir(); } // Base directory of harvested content baseDir = new File(getJsonConfig().getString(".", "harvester", "ice2-harvester", "baseDir")); // File to ignore inside directory ignoreFilter = new IgnoreFilter(getJsonConfig() .getString(DEFAULT_IGNORE_PATTERNS, "harvester", "ice2-harvester", "ignoreFilter").split("\\|")); // Course to specifically look for String courseList = getJsonConfig().getString(null, "harvester", "ice2-harvester", "targetCourses"); if (courseList != null && !courseList.isEmpty()) { targetCourses = Arrays.asList(StringUtils.split(courseList, ',')); } // Courses we are ignoring courseList = getJsonConfig().getString(null, "harvester", "ice2-harvester", "ignoreCourses"); if (courseList != null && !courseList.isEmpty()) { ignoreCourses = Arrays.asList(StringUtils.split(courseList, ',')); } // Harvest completely into storage or harvest a link back to disk? link = getJsonConfig().getBoolean(false, "harvester", "ice2-harvester", "link"); // If the testRun flag is on, we're not really harvesting testRun = getJsonConfig().getBoolean(false, "harvester", "ice2-harvester", "testRun"); // Directory traversal variables currentDir = baseDir; subDirs = new Stack<File>(); iceDirs = new Stack<File>(); iceMetadata = new Stack<File>(); hasMore = true; // Files, directories and objects for preparing packages packageDir = FascinatorHome.getPathFile("packages"); if (!packageDir.exists()) { packageDir.mkdirs(); } workflowsDir = FascinatorHome.getPathFile("harvest/workflows"); if (!workflowsDir.exists()) { workflowsDir.mkdirs(); } try { File configFile = getFile(workflowsDir, "packaging-config.json"); File rulesFile = getFile(workflowsDir, "packaging-rules.py"); pkgConfig = StorageUtils.storeFile(getStorage(), configFile); pkgRules = StorageUtils.storeFile(getStorage(), rulesFile); } catch (Exception ex) { throw new HarvesterException(ex); } // Python scripting python = new PythonInterpreter(); iceManifestLib = null; }
From source file:net.bulletin.pdi.xero.step.XeroGetStep.java
private Stack<String> getContainerElementsStack(XeroGetStepMeta meta) throws KettleException { Stack<String> result = new Stack<String>(); String ce = StringUtils.trimToEmpty(meta.getContainerElements()); while (ce.startsWith("/")) { ce = ce.substring(1);/*from w w w .j av a2s . c om*/ } if (StringUtils.isNotBlank(ce)) { if (!PATTERN_CONTAINERELEMENTS.matcher(ce).matches()) { throw new KettleException("malformed container elements; " + ce); } Collections.addAll(result, ce.split("/")); } return result; }
From source file:app.web.Application2ITCase.java
public Stack<URL> toLocationStack(Stack<Action> actionStack) { Stack<URL> locationStack = new Stack<URL>(); for (Action action : actionStack) { if (action.getType() == Action.ActionType.OPEN || action.getType() == Action.ActionType.CLICK_NEW_PAGE) { locationStack.push(toLocationPath(action.getValue())); }// w w w .j a v a 2s. c o m } return locationStack; }