List of usage examples for java.util Stack Stack
public Stack()
From source file:cz.incad.kramerius.rest.api.k5.client.search.SearchResource.java
public static JSONObject changeJSONResult(String rawString, String context, List<JSONDecorator> decs) throws UnsupportedEncodingException, JSONException { //List<JSONDecorator> decs = this.jsonDecoratorAggregates.getDecorators(); List<JSONArray> docsArrays = new ArrayList<JSONArray>(); JSONObject resultJSONObject = new JSONObject(rawString); Stack<JSONObject> prcStack = new Stack<JSONObject>(); prcStack.push(resultJSONObject);/*from w w w .java2s .c om*/ while (!prcStack.isEmpty()) { JSONObject popped = prcStack.pop(); //Iterator keys = popped.keys(); for (Iterator keys = popped.keys(); keys.hasNext();) { Object kobj = (Object) keys.next(); String key = (String) kobj; Object obj = popped.get(key); boolean docsKey = key.equals("docs"); if (docsKey && (obj instanceof JSONArray)) { docsArrays.add((JSONArray) obj); } if (obj instanceof JSONObject) { prcStack.push((JSONObject) obj); } if (obj instanceof JSONArray) { JSONArray arr = (JSONArray) obj; for (int i = 0, ll = arr.length(); i < ll; i++) { Object arrObj = arr.get(i); if (arrObj instanceof JSONObject) { prcStack.push((JSONObject) arrObj); } } } } } for (JSONArray docs : docsArrays) { for (int i = 0, ll = docs.length(); i < ll; i++) { JSONObject docJSON = (JSONObject) docs.get(i); // check master pid changeMasterPidInJSON(docJSON); // fiter protected fields filterFieldsInJSON(docJSON); // decorators decorators(context, decs, docJSON); // replace pids replacePidsInJSON(docJSON); } } return resultJSONObject; }
From source file:com.mmnaseri.dragonfly.data.impl.DefaultDataAccess.java
public DefaultDataAccess(DataAccessSession session, EntityContext entityContext, EntityHandlerContext entityHandlerContext, boolean autoInitialize) { this.session = session; this.entityContext = entityContext; this.entityHandlerContext = entityHandlerContext; this.beanInitializer = new ConstructorBeanInitializer(); this.metadataCollector = new ColumnMappingMetadataCollector(); this.eventHandler = new CompositeDataAccessEventHandler(); this.initializationContext = new ThreadLocalEntityInitializationContext(this); this.rowHandler = new DefaultRowHandler(); this.mapCreator = new DefaultEntityMapCreator(); try {/*www.j a v a2 s . c om*/ this.entityCreator = new DefaultMapEntityCreator(); } catch (RegistryException e) { throw new DataAccessSessionInitializationError("Failed to initialize the map-to-entity converter", e); } this.saveQueue = new ThreadLocal<Map<Object, Object>>() { @Override protected Map<Object, Object> initialValue() { return new HashMap<Object, Object>(); } }; this.deleteQueue = new ThreadLocal<Set<Object>>() { @Override protected Set<Object> initialValue() { return new HashSet<Object>(); } }; this.deleteAllStatements = new ThreadLocal<Map<Class<?>, Map<Statements.Manipulation, Set<Statement>>>>() { @Override protected Map<Class<?>, Map<Statements.Manipulation, Set<Statement>>> initialValue() { return new HashMap<Class<?>, Map<Statements.Manipulation, Set<Statement>>>(); } }; this.batchOperation = new ThreadLocal<List<BatchOperationDescriptor>>(); this.batch = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; this.entityContext.initialize(this); this.statementPreparator = new DefaultStatementPreparator(false); this.deferredKeys = new ThreadLocal<List<Object>>() { @Override protected List<Object> initialValue() { return new ArrayList<Object>(); } }; this.deferredSaveQueue = new ThreadLocal<Set<Object>>() { @Override protected Set<Object> initialValue() { return new HashSet<Object>(); } }; this.saveQueueLock = new ThreadLocal<Long>() { @Override protected Long initialValue() { return 0L; } }; this.localCounts = new ThreadLocal<Set<LocalOperationResult>>() { @Override protected Set<LocalOperationResult> initialValue() { return new HashSet<LocalOperationResult>(); } }; this.localStatements = new ThreadLocal<Stack<PreparedStatement>>() { @Override protected Stack<PreparedStatement> initialValue() { return new Stack<PreparedStatement>(); } }; if (autoInitialize) { log.info("Automatically initializing the session"); synchronized (this.session) { if (!this.session.isInitialized()) { this.session.initialize(); this.session.markInitialized(); } } } }
From source file:HtmlEncoder.java
/** * Do "smart" encodging on a string. This means that valid HTML entities and tags, * Helma macros and HTML comments are passed through unescaped, while * other occurrences of '<', '>' and '&' are encoded to HTML entities. * * @param str the string to encode//from w w w . j ava 2 s . c o m * @param ret the string buffer to encode to * @param paragraphs if true use p tags for paragraphs, otherwise just use br's * @param allowedTags a set containing the names of allowed tags as strings. All other * tags will be escaped */ public final static void encode(String str, StringBuffer ret, boolean paragraphs, Set allowedTags) { if (str == null) { return; } int l = str.length(); // where to insert the <p> tag in case we want to create a paragraph later on int paragraphStart = ret.length(); // what kind of element/text are we leaving and entering? // this is one of TEXT|SEMIBLOCK|BLOCK|INTERNAL // depending on this information, we decide whether and how to insert // paragraphs and line breaks. "entering" a tag means we're at the '<' // and exiting means we're at the '>', not that it's a start or close tag. byte entering = TEXT; byte exiting = TEXT; Stack openTags = new Stack(); // are we currently within a < and a > that consitute some kind of tag? // we use tag balancing to know whether we are inside a tag (and should // pass things through unchanged) or outside (and should encode stuff). boolean insideTag = false; // are we inside an HTML tag? boolean insideHtmlTag = false; boolean insideCloseTag = false; byte htmlTagMode = TAG_NAME; // if we are inside a <code> tag, we encode everything to make // documentation work easier boolean insideCodeTag = false; boolean insidePreTag = false; // are we within a Helma <% macro %> tag? We treat macro tags and // comments specially, since we can't rely on tag balancing // to know when we leave a macro tag or comment. boolean insideMacroTag = false; // are we inside an HTML comment? boolean insideComment = false; // the quotation mark we are in within an HTML or Macro tag, if any char htmlQuoteChar = '\u0000'; char macroQuoteChar = '\u0000'; // number of newlines met since the last non-whitespace character int linebreaks = 0; // did we meet a backslash escape? boolean escape = false; boolean triggerBreak = false; for (int i = 0; i < l; i++) { char c = str.charAt(i); // step one: check if this is the beginning of an HTML tag, comment or // Helma macro. if (c == '<') { if (i < (l - 2)) { if (!insideMacroTag && ('%' == str.charAt(i + 1))) { // this is the beginning of a Helma macro tag if (!insideCodeTag) { insideMacroTag = insideTag = true; macroQuoteChar = '\u0000'; } } else if (('!' == str.charAt(i + 1)) && ('-' == str.charAt(i + 2))) { // the beginning of an HTML comment? if (!insideCodeTag) { insideComment = insideTag = ((i < (l - 3)) && ('-' == str.charAt(i + 3))); } } else if (!insideTag) { // check if this is a HTML tag. insideCloseTag = ('/' == str.charAt(i + 1)); int tagStart = insideCloseTag ? (i + 2) : (i + 1); int j = tagStart; while ((j < l) && Character.isLetterOrDigit(str.charAt(j))) j++; if ((j > tagStart) && (j < l)) { String tagName = str.substring(tagStart, j).toLowerCase(); if ("code".equals(tagName) && insideCloseTag && insideCodeTag) { insideCodeTag = false; } if (((allowedTags == null) || allowedTags.contains(tagName)) && allTags.contains(tagName) && !insideCodeTag) { insideHtmlTag = insideTag = true; htmlQuoteChar = '\u0000'; htmlTagMode = TAG_NAME; exiting = entering; entering = TEXT; if (internalTags.contains(tagName)) { entering = INTERNAL; } else if (blockTags.contains(tagName)) { entering = BLOCK; } else if (semiBlockTags.contains(tagName)) { entering = paragraphs ? BLOCK : SEMIBLOCK; } if (entering > 0) { triggerBreak = !insidePreTag; } if (insideCloseTag) { int t = openTags.search(tagName); if (t == -1) { i = j; insideHtmlTag = insideTag = false; continue; } else if (t > 1) { for (int k = 1; k < t; k++) { Object tag = openTags.pop(); if (!emptyTags.contains(tag)) { ret.append("</"); ret.append(tag); ret.append(">"); } } } openTags.pop(); } else { openTags.push(tagName); } if ("code".equals(tagName) && !insideCloseTag) { insideCodeTag = true; } if ("pre".equals(tagName)) { insidePreTag = !insideCloseTag; } } } } } // if (i < l-2) } if ((triggerBreak || linebreaks > 0) && !Character.isWhitespace(c)) { if (!insideTag) { exiting = entering; entering = TEXT; if (exiting >= SEMIBLOCK) { paragraphStart = ret.length(); } } if (entering != INTERNAL && exiting != INTERNAL) { int swallowBreaks = 0; if (paragraphs && (entering != BLOCK || exiting != BLOCK) && (exiting < BLOCK) && (linebreaks > 1) && paragraphStart < ret.length()) { ret.insert(paragraphStart, "<p>"); ret.append("</p>"); swallowBreaks = 2; } // treat entering a SEMIBLOCK as entering a TEXT int _entering = entering == SEMIBLOCK ? TEXT : entering; for (int k = linebreaks - 1; k >= 0; k--) { if (k >= swallowBreaks && k >= _entering && k >= exiting) { ret.append("<br />"); } ret.append(newLine); } if (exiting >= SEMIBLOCK || linebreaks > 1) { paragraphStart = ret.length(); } } linebreaks = 0; triggerBreak = false; } switch (c) { case '<': if (insideTag) { ret.append('<'); } else { ret.append("<"); } break; case '&': // check if this is an HTML entity already, // in which case we pass it though unchanged if ((i < (l - 3)) && !insideCodeTag) { // is this a numeric entity? if (str.charAt(i + 1) == '#') { int j = i + 2; while ((j < l) && Character.isDigit(str.charAt(j))) j++; if ((j < l) && (str.charAt(j) == ';')) { ret.append("&"); break; } } else { int j = i + 1; while ((j < l) && Character.isLetterOrDigit(str.charAt(j))) j++; if ((j < l) && (str.charAt(j) == ';')) { ret.append("&"); break; } } } // we didn't reach a break, so encode the ampersand as HTML entity ret.append("&"); break; case '\\': ret.append(c); if (insideTag && !insideComment) { escape = !escape; } break; case '"': case '\'': ret.append(c); if (!insideComment) { // check if the quote is escaped if (insideMacroTag) { if (escape) { escape = false; } else if (macroQuoteChar == c) { macroQuoteChar = '\u0000'; } else if (macroQuoteChar == '\u0000') { macroQuoteChar = c; } } else if (insideHtmlTag) { if (escape) { escape = false; } else if (htmlQuoteChar == c) { htmlQuoteChar = '\u0000'; htmlTagMode = TAG_SPACE; } else if (htmlQuoteChar == '\u0000') { htmlQuoteChar = c; } } } break; case '\n': if (insideTag || insidePreTag) { ret.append('\n'); } else { linebreaks++; } break; case '\r': if (insideTag || insidePreTag) { ret.append('\r'); } break; case '>': // For Helma macro tags and comments, we overrule tag balancing, // i.e. we don't require that '<' and '>' be balanced within // macros and comments. Rather, we check for the matching closing tag. if (insideComment) { ret.append('>'); insideComment = !((str.charAt(i - 2) == '-') && (str.charAt(i - 1) == '-')); } else if (insideMacroTag) { ret.append('>'); insideMacroTag = !((str.charAt(i - 1) == '%') && (macroQuoteChar == '\u0000')); } else if (insideHtmlTag) { ret.append('>'); // only leave HTML tag if quotation marks are balanced // within that tag. insideHtmlTag = htmlQuoteChar != '\u0000'; // Check if this is an empty tag so we don't generate an // additional </close> tag. if (str.charAt(i - 1) == '/') { // this is to avoid misinterpreting tags like // <a href=http://foo/> as empty if (htmlTagMode != TAG_ATT_VAL && htmlTagMode != TAG_ATT_NAME) { openTags.pop(); } } exiting = entering; if (exiting > 0) { triggerBreak = !insidePreTag; } } else { ret.append(">"); } // check if we still are inside any kind of tag insideTag = insideComment || insideMacroTag || insideHtmlTag; insideCloseTag = insideTag; break; default: if (insideHtmlTag && !insideCloseTag) { switch (htmlTagMode) { case TAG_NAME: if (!Character.isLetterOrDigit(c)) { htmlTagMode = TAG_SPACE; } break; case TAG_SPACE: if (Character.isLetterOrDigit(c)) { htmlTagMode = TAG_ATT_NAME; } break; case TAG_ATT_NAME: if (c == '=') { htmlTagMode = TAG_ATT_VAL; } else if (c == ' ') { htmlTagMode = TAG_SPACE; } break; case TAG_ATT_VAL: if (Character.isWhitespace(c) && htmlQuoteChar == '\u0000') { htmlTagMode = TAG_SPACE; } break; } } if (c < 128) { ret.append(c); } else if ((c >= 128) && (c < 256)) { ret.append(transform[c - 128]); } else { ret.append("&#"); ret.append((int) c); ret.append(";"); } escape = false; } } // if tags were opened but not closed, close them. int o = openTags.size(); if (o > 0) { for (int k = 0; k < o; k++) { Object tag = openTags.pop(); if (!emptyTags.contains(tag)) { ret.append("</"); ret.append(tag); ret.append(">"); } } } // add remaining newlines we may have collected int swallowBreaks = 0; if (paragraphs && entering < BLOCK) { ret.insert(paragraphStart, "<p>"); ret.append("</p>"); swallowBreaks = 2; } if (linebreaks > 0) { for (int i = linebreaks - 1; i >= 0; i--) { if (i >= swallowBreaks && i > exiting) { ret.append("<br />"); } ret.append(newLine); } } }
From source file:com.amazonaws.services.kinesis.scaling.StreamScaler.java
private ScalingOperationReport scaleStream(String streamName, String shardId, int targetShards, int operationsMade, int shardsCompleted, long startTime, Integer minShards, Integer maxShards) throws Exception { Stack<ShardHashInfo> shardStack = new Stack<>(); shardStack.add(StreamScalingUtils.getOpenShard(this.kinesisClient, streamName, shardId)); LOG.info(String.format("Scaling Shard %s:%s into %s Shards", streamName, shardId, targetShards)); return scaleStream(streamName, 1, targetShards, operationsMade, shardsCompleted, startTime, shardStack, minShards, maxShards);//from w w w . jav a 2s.com }
From source file:fr.inria.oak.paxquery.common.xml.navigation.NavigationTreePattern.java
/** * Same as {@link #renumberNodes()}, but it starts the numbering from the localCounter. * //from ww w . j av a2 s .com * @author Konstantinos KARANASOS */ public void renumberNodes(int localCounter) { Stack<NavigationTreePatternNode> st = new Stack<NavigationTreePatternNode>(); st.push(this.root); while (!st.empty()) { NavigationTreePatternNode pn = st.pop(); if (pn.getNodeCode() == -1) { // nothing //Parameters.logger.debug("-1 node! Left unchanged"); } else { pn.setNodeCode(localCounter); localCounter++; } Iterator<NavigationTreePatternEdge> ie = pn.getEdges().iterator(); while (ie.hasNext()) { st.push(ie.next().n2); } } }
From source file:jp.terasoluna.fw.batch.util.BatchUtil.java
/** * ??/*from ww w . j ava2s . c o m*/ * @param tranMap * @param statMap * @param log */ public static void commitTransactions(Map<?, ?> tranMap, Map<String, TransactionStatus> statMap, Log log) { Set<Entry<String, TransactionStatus>> statSet = statMap.entrySet(); if (statSet.isEmpty()) { return; } Stack<Entry<String, TransactionStatus>> stack = new Stack<Entry<String, TransactionStatus>>(); for (Entry<String, TransactionStatus> stat : statSet) { stack.push(stat); } while (!stack.isEmpty()) { // ??? Entry<String, TransactionStatus> statEntry = stack.pop(); String key = statEntry.getKey(); TransactionStatus trnStat = statEntry.getValue(); if (trnStat == null) { continue; } // ??? Object ptmObj = tranMap.get(key); if (ptmObj == null || !(ptmObj instanceof PlatformTransactionManager)) { continue; } PlatformTransactionManager ptm = (PlatformTransactionManager) ptmObj; if (log != null && log.isDebugEnabled()) { logDebug(log, LogId.DAL025038, trnStat); } // ptm.commit(trnStat); } }
From source file:com.datatorrent.stram.plan.physical.PhysicalPlan.java
/** * * @param dag/*w w w . j av a2 s. c om*/ * @param ctx */ public PhysicalPlan(LogicalPlan dag, PlanContext ctx) { this.dag = dag; this.ctx = ctx; this.maxContainers = Math.max(dag.getMaxContainerCount(), 1); LOG.debug("Max containers: {}", this.maxContainers); Stack<OperatorMeta> pendingNodes = new Stack<OperatorMeta>(); // Add logging operators for streams if not added already updatePersistOperatorStreamCodec(dag); for (OperatorMeta n : dag.getAllOperators()) { pendingNodes.push(n); } while (!pendingNodes.isEmpty()) { OperatorMeta n = pendingNodes.pop(); if (this.logicalToPTOperator.containsKey(n)) { // already processed as upstream dependency continue; } boolean upstreamDeployed = true; for (Map.Entry<InputPortMeta, StreamMeta> entry : n.getInputStreams().entrySet()) { StreamMeta s = entry.getValue(); boolean delay = entry.getKey().getValue(LogicalPlan.IS_CONNECTED_TO_DELAY_OPERATOR); // skip delay sources since it's going to be handled as downstream if (!delay && s.getSource() != null && !this.logicalToPTOperator.containsKey(s.getSource().getOperatorMeta())) { pendingNodes.push(n); pendingNodes.push(s.getSource().getOperatorMeta()); upstreamDeployed = false; break; } } if (upstreamDeployed) { addLogicalOperator(n); } } updatePartitionsInfoForPersistOperator(dag); // assign operators to containers int groupCount = 0; Set<PTOperator> deployOperators = Sets.newHashSet(); for (Map.Entry<OperatorMeta, PMapping> e : logicalToPTOperator.entrySet()) { for (PTOperator oper : e.getValue().getAllOperators()) { if (oper.container == null) { PTContainer container = getContainer((groupCount++) % maxContainers); if (!container.operators.isEmpty()) { LOG.warn( "Operator {} shares container without locality contraint due to insufficient resources.", oper); } Set<PTOperator> inlineSet = oper.getGrouping(Locality.CONTAINER_LOCAL).getOperatorSet(); if (!inlineSet.isEmpty()) { // process inline operators for (PTOperator inlineOper : inlineSet) { setContainer(inlineOper, container); } } else { setContainer(oper, container); } deployOperators.addAll(container.operators); } } } for (PTContainer container : containers) { updateContainerMemoryWithBufferServer(container); container.setRequiredVCores(getVCores(container.getOperators())); } for (Map.Entry<PTOperator, Operator> operEntry : this.newOpers.entrySet()) { initCheckpoint(operEntry.getKey(), operEntry.getValue(), Checkpoint.INITIAL_CHECKPOINT); } // request initial deployment ctx.deploy(Collections.<PTContainer>emptySet(), Collections.<PTOperator>emptySet(), Sets.newHashSet(containers), deployOperators); this.newOpers.clear(); this.deployOpers.clear(); this.undeployOpers.clear(); }
From source file:alluxio.job.move.MoveDefinition.java
/** * @param source an Alluxio URI//from www. ja v a 2 s . co m * @param fileSystem the Alluxio file system * @return whether the URI is a file or a directory which contains files (including recursively) * @throws Exception if an unexpected exception occurs */ private static boolean hasFiles(AlluxioURI source, FileSystem fileSystem) throws Exception { Stack<AlluxioURI> dirsToCheck = new Stack<>(); dirsToCheck.add(source); while (!dirsToCheck.isEmpty()) { try { for (URIStatus status : fileSystem.listStatus(dirsToCheck.pop())) { if (!status.isFolder()) { return true; } dirsToCheck.push(new AlluxioURI(status.getPath())); } } catch (FileDoesNotExistException e) { // This probably means another worker has deleted the directory already, so we can probably // return false here. To be safe though, we will fall through and complete the search. } } return false; }
From source file:com.qq.tars.maven.gensrc.TarsBuildMojo.java
private void collect(final DependencyNode root, final Set<Artifact> artifacts) { Stack<DependencyNode> stack = new Stack<DependencyNode>(); stack.push(root);/* w w w .j a v a2s .c o m*/ while (!stack.isEmpty()) { DependencyNode node = stack.pop(); if (node.getState() == DependencyNode.INCLUDED) { final Artifact artifact = node.getArtifact(); if (includedScope(artifact.getScope())) { getLog().info("Adding Artefact: " + artifact.toString()); artifacts.add(artifact); // check children if (!node.getChildren().isEmpty()) { stack.addAll(node.getChildren()); } } } } }
From source file:com.abstratt.mdd.internal.frontend.textuml.TextUMLCompiler.java
/** * Given a position in a compilation unit, finds the contextual namespace. * // w w w.j a v a2 s . c o m * @param toParse source of compilation unit * @param line line number, starting from 1 * @param col column number, starting from 1 * @return the name of the contextual namespace */ public String findNamespace(String toParse, final int line, final int col) { Token token = findTokenAt(toParse, line, col, false, true); if (token == null) return null; final Stack<String> segments = new Stack<String>(); for (Node current = token; current != null; current = current.parent()) { current.apply(new AnalysisAdapter() { @Override public void caseAStart(AStart node) { segments.push(TextUMLCore.getSourceMiner().getQualifiedIdentifier( ((APackageHeading) node.getPackageHeading()).getQualifiedIdentifier())); } public void caseASubNamespace(ASubNamespace node) { segments.push(TextUMLCore.getSourceMiner() .getQualifiedIdentifier(((APackageHeading) node.getPackageHeading()))); } @Override public void caseAClassDef(AClassDef node) { segments.push(((AClassHeader) node.getClassHeader()).getIdentifier().getText()); } @Override public void caseAStereotypeDef(AStereotypeDef node) { segments.push(((AStereotypeDefHeader) node.getStereotypeDefHeader()).getIdentifier().getText()); } @Override public void caseAAssociationDef(AAssociationDef node) { final String associationName = ((AAssociationHeader) node.getAssociationHeader()) .getIdentifier().getText(); if (associationName.length() > 0) segments.push(associationName); } }); } if (segments.isEmpty()) return null; StringBuffer result = new StringBuffer(); while (!segments.isEmpty()) { result.append(segments.pop()); result.append(NamedElement.SEPARATOR); } result.delete((result.length() - NamedElement.SEPARATOR.length()), result.length()); return result.toString(); }