List of usage examples for java.util Stack Stack
public Stack()
From source file:com.inmobi.conduit.distcp.tools.util.TestDistCpUtils.java
public static boolean checkIfFoldersAreInSync(FileSystem fs, String targetBase, String sourceBase) throws IOException { Path base = new Path(targetBase); Stack<Path> stack = new Stack<Path>(); stack.push(base);//from w ww . ja v a2 s .com while (!stack.isEmpty()) { Path file = stack.pop(); if (!fs.exists(file)) continue; FileStatus[] fStatus = fs.listStatus(file); if (fStatus == null || fStatus.length == 0) continue; for (FileStatus status : fStatus) { if (status.isDir()) { stack.push(status.getPath()); } Assert.assertTrue(fs.exists(new Path( sourceBase + "/" + DistCpUtils.getRelativePath(new Path(targetBase), status.getPath())))); } } return true; }
From source file:nz.co.senanque.workflow.WorkflowManagerAbstract.java
@Transactional public List<Audit> findHandlerTasks(ProcessInstance processInstance) { Stack<Audit> ret = new Stack<Audit>(); for (Audit audit : processInstance.getAudits()) { if (audit.isHandler() && audit.getStatus() != null) { ret.push(audit);//from www .j av a 2 s . c om } } return ret; }
From source file:com.webcohesion.ofx4j.io.nanoxml.TestNanoXMLOFXReader.java
/** * tests using sax to parse an OFX doc.//www. j a v a2 s . c o m */ public void testSimpleVersion1() 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("simple.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); TreeMap<String, List<Object>> SIGNONMSGSRSV1 = (TreeMap<String, List<Object>>) OFX.remove("SIGNONMSGSRSV1") .get(0); assertNotNull(SIGNONMSGSRSV1); TreeMap<String, List<Object>> SONRS = (TreeMap<String, List<Object>>) SIGNONMSGSRSV1.remove("SONRS").get(0); assertNotNull(SONRS); TreeMap<String, List<Object>> STATUS = (TreeMap<String, List<Object>>) SONRS.remove("STATUS").get(0); assertNotNull(STATUS); assertEquals("0", STATUS.remove("CODE").get(0).toString().trim()); assertEquals("INFO", STATUS.remove("SEVERITY").get(0).toString().trim()); assertTrue(STATUS.isEmpty()); assertEquals("20071015021529.000[-8:PST]", SONRS.remove("DTSERVER").get(0).toString().trim()); assertEquals("ENG", SONRS.remove("LANGUAGE").get(0).toString().trim()); assertEquals("19900101000000", SONRS.remove("DTACCTUP").get(0).toString().trim()); assertTrue(SONRS.isEmpty()); assertTrue(SIGNONMSGSRSV1.isEmpty()); assertTrue(OFX.isEmpty()); assertTrue(root.isEmpty()); }
From source file:edu.umd.gorden2.BooleanRetrievalHBase.java
/** * Runs this tool./*from ww w .j a v a 2 s . c o m*/ */ @SuppressWarnings({ "static-access" }) public int run(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INDEX)); options.addOption( OptionBuilder.withArgName("path").hasArg().withDescription("output path").create(COLLECTION)); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(INDEX) || !cmdline.hasOption(COLLECTION)) { System.out.println("args: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); //formatter.printHelp(LookupPostings.class.getName(), options); ToolRunner.printGenericCommandUsage(System.out); System.exit(-1); } String indexPath = cmdline.getOptionValue(INDEX); String collectionPath = cmdline.getOptionValue(COLLECTION); if (collectionPath.endsWith(".gz")) { System.out.println("gzipped collection is not seekable: use compressed version!"); System.exit(-1); } Configuration conf = getConf(); conf.addResource(new Path("/etc/hbase/conf/hbase-site.xml")); Configuration hbaseConfig = HBaseConfiguration.create(conf); HConnection hbaseConnection = HConnectionManager.createConnection(hbaseConfig); table = hbaseConnection.getTable(indexPath); FileSystem fs = FileSystem.get(conf); collection = fs.open(new Path(collectionPath)); stack = new Stack<Set<Integer>>(); //initialize(indexPath, collectionPath, fs); String[] queries = { "outrageous fortune AND", "white rose AND", "means deceit AND", "white red OR rose AND pluck AND", "unhappy outrageous OR good your AND OR fortune AND" }; for (String q : queries) { System.out.println("Query: " + q); runQuery(q); System.out.println(""); } return 1; }
From source file:com.rabbitmq.client.test.performance.ScalabilityTest.java
public Results run() throws Exception { Connection con = new ConnectionFactory() { {/*from w w w . j av a 2s . c om*/ setHost(params.host); setPort(params.port); } }.newConnection(); Channel channel = con.createChannel(); Results r = new Results(params.maxBindingExp); for (int y = 0; y < params.maxBindingExp; y++) { final int maxBindings = pow(params.base, y); String[] routingKeys = new String[maxBindings]; for (int b = 0; b < maxBindings; b++) { routingKeys[b] = UUID.randomUUID().toString(); } Stack<String> queues = new Stack<String>(); int maxQueueExp = Math.min(params.maxQueueExp, params.maxExp - y); System.out.println("---------------------------------"); System.out.println("| bindings = " + maxBindings + ", messages = " + params.messageCount); System.out.println("| Routing"); int q = 0; // create queues & bindings, time routing Measurements creation = new CreationMeasurements(maxQueueExp); float routingTimes[] = new float[maxQueueExp]; for (int x = 0; x < maxQueueExp; x++) { final int maxQueues = pow(params.base, x); for (; q < maxQueues; q++) { AMQP.Queue.DeclareOk ok = channel.queueDeclare(); queues.push(ok.getQueue()); for (int b = 0; b < maxBindings; b++) { channel.queueBind(ok.getQueue(), "amq.direct", routingKeys[b]); } } creation.addDataPoint(x); float routingTime = timeRouting(channel, routingKeys); routingTimes[x] = routingTime; printTime(params.base, x, routingTime); } r.routingTimes[y] = routingTimes; float[] creationTimes = creation.analyse(params.base); r.creationTimes[y] = creationTimes; System.out.println("| Creating"); printTimes(params.base, creationTimes); // delete queues & bindings Measurements deletion = new DeletionMeasurements(maxQueueExp); for (int x = maxQueueExp - 1; x >= 0; x--) { final int maxQueues = (x == 0) ? 0 : pow(params.base, x - 1); for (; q > maxQueues; q--) { channel.queueDelete(queues.pop()); } deletion.addDataPoint(x); } float[] deletionTimes = deletion.analyse(params.base); r.deletionTimes[y] = deletionTimes; System.out.println("| Deleting"); printTimes(params.base, deletionTimes); } channel.close(); con.close(); return r; }
From source file:net.dv8tion.jda.core.entities.impl.MessageImpl.java
@Override public synchronized String getStrippedContent() { if (strippedContent == null) { String tmp = getContent(); //all the formatting keys to keep track of String[] keys = new String[] { "*", "_", "`", "~~" }; //find all tokens (formatting strings described above) TreeSet<FormatToken> tokens = new TreeSet<>((t1, t2) -> Integer.compare(t1.start, t2.start)); for (String key : keys) { Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(tmp); while (matcher.find()) { tokens.add(new FormatToken(key, matcher.start())); }//from www. j a v a 2 s .c o m } //iterate over all tokens, find all matching pairs, and add them to the list toRemove Stack<FormatToken> stack = new Stack<>(); List<FormatToken> toRemove = new ArrayList<>(); boolean inBlock = false; for (FormatToken token : tokens) { if (stack.empty() || !stack.peek().format.equals(token.format) || stack.peek().start + token.format.length() == token.start) { //we are at opening tag if (!inBlock) { //we are outside of block -> handle normally if (token.format.equals("`")) { //block start... invalidate all previous tags stack.clear(); inBlock = true; } stack.push(token); } else if (token.format.equals("`")) { //we are inside of a block -> handle only block tag stack.push(token); } } else if (!stack.empty()) { //we found a matching close-tag toRemove.add(stack.pop()); toRemove.add(token); if (token.format.equals("`") && stack.empty()) { //close tag closed the block inBlock = false; } } } //sort tags to remove by their start-index and iteratively build the remaining string Collections.sort(toRemove, (t1, t2) -> Integer.compare(t1.start, t2.start)); StringBuilder out = new StringBuilder(); int currIndex = 0; for (FormatToken formatToken : toRemove) { if (currIndex < formatToken.start) { out.append(tmp.substring(currIndex, formatToken.start)); } currIndex = formatToken.start + formatToken.format.length(); } if (currIndex < tmp.length()) { out.append(tmp.substring(currIndex)); } //return the stripped text, escape all remaining formatting characters (did not have matching open/close before or were left/right of block strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~"); } return strippedContent; }
From source file:org.springjutsu.validation.rules.ValidationRulesContainer.java
/** * Copy rules from parent classes into child classes. *//*from www . j av a 2 s. c o m*/ @SuppressWarnings("unchecked") protected void initInheritance() { Set<Class<?>> inheritanceChecked = new HashSet<Class<?>>(); for (ValidationEntity entity : validationEntityMap.values()) { Stack<Class<?>> classStack = new Stack<Class<?>>(); classStack.push(entity.getValidationClass()); for (Class<?> clazz = entity.getValidationClass().getSuperclass(); clazz != null && clazz != Object.class; clazz = clazz.getSuperclass()) { classStack.push(clazz); } Set<ValidationRule> inheritableRules = new ListOrderedSet(); Set<ValidationTemplateReference> inheritableTemplateReferences = new ListOrderedSet(); Set<ValidationContext> inheritableContexts = new ListOrderedSet(); Set<String> inheritableExclusionPaths = new HashSet<String>(); Set<String> inheritableInclusionPaths = new HashSet<String>(); while (!classStack.isEmpty()) { Class<?> clazz = classStack.pop(); if (supportsClass(clazz) && !inheritanceChecked.contains(clazz)) { validationEntityMap.get(clazz).getRules().addAll(inheritableRules); validationEntityMap.get(clazz).getValidationContexts().addAll(inheritableContexts); validationEntityMap.get(clazz).getExcludedPaths().addAll(inheritableExclusionPaths); validationEntityMap.get(clazz).getIncludedPaths().addAll(inheritableInclusionPaths); validationEntityMap.get(clazz).getTemplateReferences().addAll(inheritableTemplateReferences); } if (hasRulesForClass(clazz)) { inheritableRules.addAll(validationEntityMap.get(clazz).getRules()); } if (supportsClass(clazz)) { inheritableContexts.addAll(validationEntityMap.get(clazz).getValidationContexts()); inheritableExclusionPaths.addAll(validationEntityMap.get(clazz).getExcludedPaths()); inheritableInclusionPaths.addAll(validationEntityMap.get(clazz).getIncludedPaths()); } inheritanceChecked.add(clazz); } } }
From source file:hugonicolau.openbrailleinput.wordcorrection.mafsa.MAFSA.java
public String[] searchPrefix(String prefix) { Set<String> results = new HashSet<String>(); if ((prefix == null) || (prefix.length() < 2)) return results.toArray(new String[results.size()]); char[] letters = prefix.toUpperCase().toCharArray(); long ptr = nodes[0]; for (char c : letters) { ptr = findChild(ptr, c);//from ww w.j a v a2s . c o m if (-1 == ptr) return results.toArray(new String[results.size()]); } // iteratively (to prevent stack overflow) search each branch of the graph Stack<StackEntry> stack = new Stack<StackEntry>(); // a stack of paths to traverse. This prevents the StackOverflowException. stack.push(new StackEntry(ptr, prefix.toUpperCase().toCharArray(), "")); while (!stack.empty()) { StackEntry entry = stack.pop(); // if current node is a valid word if (canTerminate(entry.node)) { results.add(String.valueOf(entry.chars) + entry.subword); } for (Iterator<Long> iter = childIterator(entry.node); iter.hasNext();) { long child = iter.next(); stack.push(new StackEntry(child, entry.chars, entry.subword + getChar(child))); } } return results.toArray(new String[results.size()]); }
From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.ServletHolder.java
public void start() throws Exception { _unavailable = 0;/*from www .j a v a 2s . com*/ super.start(); if (!javax.servlet.Servlet.class.isAssignableFrom(_class)) { Exception ex = new IllegalStateException("Servlet " + _class + " is not a javax.servlet.Servlet"); super.stop(); throw ex; } _config = new Config(); if (_runAs != null) _realm = _httpHandler.getHttpContext().getRealm(); if (javax.servlet.SingleThreadModel.class.isAssignableFrom(_class)) _servlets = new Stack(); if (_initOnStartup) { _servlet = (Servlet) newInstance(); try { initServlet(_servlet, _config); } catch (Throwable e) { _servlet = null; _config = null; if (e instanceof Exception) throw (Exception) e; else if (e instanceof Error) throw (Error) e; else throw new ServletException(e); } } }
From source file:org.pgptool.gui.encryption.implpgp.KeyFilesOperationsPgpImpl.java
@Override public void exportPublicKey(Key key, String targetFilePathname) { Preconditions.checkArgument(key != null && key.getKeyData() != null && key.getKeyInfo() != null, "Key must be providedand fully described"); Preconditions.checkArgument(StringUtils.hasText(targetFilePathname), "targetFilePathname must be provided"); Stack<OutputStream> os = new Stack<>(); try {// www .ja v a2 s .c o m os.push(new FileOutputStream(targetFilePathname)); if ("asc".equalsIgnoreCase(FilenameUtils.getExtension(targetFilePathname))) { os.push(new ArmoredOutputStream(os.peek())); } KeyDataPgp keyDataPgp = KeyDataPgp.get(key); if (keyDataPgp.getPublicKeyRing() != null) { keyDataPgp.getPublicKeyRing().encode(os.peek()); } else { keyDataPgp.getSecretKeyRing().getPublicKey().encode(os.peek()); } } catch (Throwable t) { throw new RuntimeException( "Failed to export public key " + key.getKeyInfo().getUser() + " to " + targetFilePathname, t); } finally { while (!os.isEmpty()) { IoStreamUtils.safeClose(os.pop()); } } }