List of usage examples for java.util Stack push
public E push(E item)
From source file:de.ipbhalle.metfrag.pubchem.PubChemWebService.java
/** * download directly over http because of server errors when downloading over pug soap * /*from w w w . j av a 2 s . com*/ * @author c-ruttkies * * @param mass * @param error * @param limit * @return */ public Vector<String> getHitsByMassHTTP(double mass, double error, int limit) { java.util.Stack<String> cids = new java.util.Stack<String>(); double minMass = mass - error; double maxMass = mass + error; String urlname = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi" + "?db=pccompound" + "&term=" + minMass + "[MIMASS]:" + maxMass + "[MIMASS]" + "&RetMax=" + limit; InputStream stream = getInputStreamFromURL(urlname); if (stream == null) return cids; try { BufferedReader breader = new BufferedReader(new InputStreamReader(stream)); String line = ""; while ((line = breader.readLine()) != null) { if (line.contains("<Id>") && line.contains("</Id>")) { cids.push(line.replaceAll("\\D", "").trim()); } } stream.close(); breader.close(); } catch (IOException e) { System.err.println("Error: Could not open result stream when using Pubchem HTTP mass search!"); System.err.println(urlname); return cids; } File tempFile = null; try { tempFile = File.createTempFile(getRandomString(20), ".sdf"); if (tempFile != null) tempFile.deleteOnExit(); } catch (IOException e) { System.err.println("Error: Could not open result stream when using Pubchem HTTP mass search!"); System.err.println(urlname); return cids; } try { boolean success = savingRetrievedHits(tempFile, cids); if (!success) return new Vector<String>(); } catch (AxisFault e) { System.err.println("Error: Could not open result stream when using Pubchem HTTP mass search!"); System.err.println(urlname); } return cids; }
From source file:com.bettervectordrawable.lib.graphics.drawable.VectorDrawable.java
private void inflateInternal(Resources res, XmlPullParser parser, AttributeSet attrs, Theme theme) throws XmlPullParserException, IOException { final VectorDrawableState state = mVectorState; final VPathRenderer pathRenderer = state.mVPathRenderer; boolean noPathTag = true; // Use a stack to help to build the group tree. // The top of the stack is always the current group. final Stack<VGroup> groupStack = new Stack<VGroup>(); groupStack.push(pathRenderer.mRootGroup); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { final String tagName = parser.getName(); final VGroup currentGroup = groupStack.peek(); if (SHAPE_PATH.equals(tagName)) { final VFullPath path = new VFullPath(); path.inflate(res, attrs, theme); currentGroup.mChildren.add(path); if (path.getPathName() != null) { pathRenderer.mVGTargetsMap.put(path.getPathName(), path); }//from w ww . j a v a 2 s. c om noPathTag = false; state.mChangingConfigurations |= path.mChangingConfigurations; } else if (SHAPE_CLIP_PATH.equals(tagName)) { final VClipPath path = new VClipPath(); path.inflate(res, attrs, theme); currentGroup.mChildren.add(path); if (path.getPathName() != null) { pathRenderer.mVGTargetsMap.put(path.getPathName(), path); } state.mChangingConfigurations |= path.mChangingConfigurations; } else if (SHAPE_GROUP.equals(tagName)) { VGroup newChildGroup = new VGroup(); newChildGroup.inflate(res, attrs, theme); currentGroup.mChildren.add(newChildGroup); groupStack.push(newChildGroup); if (newChildGroup.getGroupName() != null) { pathRenderer.mVGTargetsMap.put(newChildGroup.getGroupName(), newChildGroup); } state.mChangingConfigurations |= newChildGroup.mChangingConfigurations; } } else if (eventType == XmlPullParser.END_TAG) { final String tagName = parser.getName(); if (SHAPE_GROUP.equals(tagName)) { groupStack.pop(); } } eventType = parser.next(); } // Print the tree out for debug. if (DBG_VECTOR_DRAWABLE) { printGroupTree(pathRenderer.mRootGroup, 0); } if (noPathTag) { final StringBuffer tag = new StringBuffer(); if (tag.length() > 0) { tag.append(" or "); } tag.append(SHAPE_PATH); throw new XmlPullParserException("no " + tag + " defined"); } }
From source file:it.cnr.icar.eric.server.security.authorization.RegistryAttributeFinderModule.java
/** * Parses the attribute name from a URI rep of the Attribute id * If input is: "urn:oasis:names:tc:ebxml-regrep:3.0:rim:acp:resource:sourceObject:targetObject:objectType" * then return value will be a Stack with entries "sourceObject;targetObject;objectType". **//*from ww w . j a v a 2 s . c om*/ private Stack<String> getAttributeStackFromAttributeId(URI attributeId) { Stack<String> attrStack = new Stack<String>(); String attrIdStr = attributeId.toString(); String relevantSuffix = null; if (attrIdStr.startsWith(AuthorizationServiceImpl.RESOURCE_ATTRIBUTE_PREFIX)) { int startIndex = AuthorizationServiceImpl.RESOURCE_ATTRIBUTE_PREFIX.length(); int endIndex = attrIdStr.length(); relevantSuffix = attrIdStr.substring(startIndex, endIndex); } else if (attrIdStr.startsWith(AuthorizationServiceImpl.SUBJECT_ATTRIBUTE_ID)) { //Special case. We should get rid of use of XACML subject-id attribute from spec?? relevantSuffix = "id"; } else if (attrIdStr.startsWith(AuthorizationServiceImpl.ACTION_ATTRIBUTE_PREFIX)) { //Not clear what to do here but following will preserve old behavior which may not have been right always relevantSuffix = getAttributeFromAttributeId(attributeId); } //Now split into attributes and push them onto stack String[] attrs = relevantSuffix.split(":"); for (int i = attrs.length - 1; i >= 0; i--) { attrStack.push(attrs[i]); } return attrStack; }
From source file:com.madrobot.di.wizard.json.JSONSerializer.java
/** * Serialize a specific java object recursively. * /*from ww w . j a va 2s .c o m*/ * @param jsonObject * Object whose fields need to be set * * @param stack * Stack of {@link ClassInfo} - entity type under consideration * * @throws JSONException * If an exception occurs during parsing */ private void serializer(JSONObject jsonObject, final Stack<Object> stack) throws JSONException { Object userObject = stack.peek(); Class<?> userClass = userObject.getClass(); Field[] fields = userClass.getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); Class<?> classType = field.getType(); String jsonKeyName = getKeyName(field); try { String getMethodName = getGetMethodName(fieldName, classType); Method getMethod = userClass.getDeclaredMethod(getMethodName); Object returnValue = getMethod.invoke(userObject, new Object[] {}); if (Converter.isPseudoPrimitive(classType)) { Converter.storeValue(jsonObject, jsonKeyName, returnValue, field); } else if (Converter.isCollectionType(classType)) { JSONArray jsonArray = new JSONArray(); boolean canAdd = true; if (returnValue instanceof Collection) { Collection<?> userCollectionObj = (Collection<?>) returnValue; if (userCollectionObj.size() != 0) { Iterator<?> iterator = userCollectionObj.iterator(); while (iterator.hasNext()) { Object itemObject = iterator.next(); JSONObject object = new JSONObject(); stack.push(itemObject); serializer(object, stack); jsonArray.put(object); } } else if (field.isAnnotationPresent(ItemType.class)) { ItemType itemType = field.getAnnotation(ItemType.class); canAdd = itemType.canEmpty(); } if (canAdd) jsonObject.put(jsonKeyName, jsonArray); } else if (returnValue instanceof Map) { Map<?, ?> userMapObj = (Map<?, ?>) returnValue; JSONObject object = new JSONObject(userMapObj); jsonArray.put(object); jsonObject.put(jsonKeyName, jsonArray); } } else { stack.push(returnValue); JSONObject object = new JSONObject(); serializer(object, stack); jsonObject.put(jsonKeyName, object); } } catch (NoSuchMethodException e) { Log.e(TAG, e.getMessage()); } catch (IllegalAccessException e) { Log.e(TAG, e.getMessage()); } catch (InvocationTargetException e) { Log.e(TAG, e.getMessage()); } } }
From source file:com.udojava.evalex.Expression.java
/** * Evaluates the expression./*from w ww. ja v a 2 s. com*/ * * @return The result of the expression. */ public MyComplex eval() { Stack<LazyNumber> stack = new Stack<>(); for (final String token : getRPN()) { if (operators.containsKey(token)) { final LazyNumber v1 = stack.pop(); final LazyNumber v2 = stack.pop(); LazyNumber number = () -> operators.get(token).eval(v2.eval(), v1.eval()); stack.push(number); } else if (mainVars.getMap().containsKey(token)) { MyComplex v = mainVars.get(token); if (v.type == ValueType.ARRAY) { stack.push(() -> v); } else { PitDecimal bd = new PitDecimal(v.real, v.imaginary); bd.type = v.type; bd.setVarToken(token); stack.push(() -> bd); } } else if (functions.containsKey(token.toUpperCase(Locale.ROOT))) { LazyFunction f = functions.get(token.toUpperCase(Locale.ROOT)); ArrayList<LazyNumber> p = new ArrayList<>(!f.numParamsVaries() ? f.getNumParams() : 0); // pop parameters off the stack until we hit the start of // this function's parameter list while (!stack.isEmpty() && stack.peek() != PARAMS_START) { p.add(0, stack.pop()); } if (stack.peek() == PARAMS_START) { stack.pop(); } LazyNumber fResult = f.lazyEval(p); stack.push(fResult); } else if ("(".equals(token)) { stack.push(PARAMS_START); } else { MyComplex bd; if (token.endsWith("i")) { String str = token.substring(0, token.length() - 1); if (str.isEmpty()) str = "1"; bd = new MyComplex("0", str); } else { bd = new MyComplex(token); } MyComplex finalBd = bd; stack.push(() -> finalBd); // blank constant } } return stack.pop().eval(); }
From source file:com.qwazr.utils.WildcardMatcher.java
/** * Match the passed name with the current pattern * * @param name the string to test * @param caseSensitivity//from w w w. ja va 2s . c o m * @return true if the name match the pattern */ public boolean match(String name, IOCase caseSensitivity) { if (name == null && wcs == null) { return true; } if (name == null || wcs == null) { return false; } if (caseSensitivity == null) { caseSensitivity = IOCase.SENSITIVE; } int length = name.length(); boolean anyChars = false; int textIdx = 0; int wcsIdx = 0; Stack<int[]> backtrack = new Stack<int[]>(); // loop around a backtrack stack, to handle complex * matching do { if (backtrack.size() > 0) { int[] array = backtrack.pop(); wcsIdx = array[0]; textIdx = array[1]; anyChars = true; } // loop whilst tokens and text left to process while (wcsIdx < wcs.length) { if (wcs[wcsIdx].equals("?")) { // ? so move to next text char textIdx++; if (textIdx > length) { break; } anyChars = false; } else if (wcs[wcsIdx].equals("*")) { // set any chars status anyChars = true; if (wcsIdx == wcs.length - 1) { textIdx = length; } } else { // matching text token if (anyChars) { // any chars then try to locate text token textIdx = caseSensitivity.checkIndexOf(name, textIdx, wcs[wcsIdx]); if (textIdx == -1) { // token not found break; } int repeat = caseSensitivity.checkIndexOf(name, textIdx + 1, wcs[wcsIdx]); if (repeat >= 0) { backtrack.push(new int[] { wcsIdx, repeat }); } } else { // matching from current position if (!caseSensitivity.checkRegionMatches(name, textIdx, wcs[wcsIdx])) { // couldnt match token break; } } // matched text token, move text index to end of matched token textIdx += wcs[wcsIdx].length(); anyChars = false; } wcsIdx++; } // full match if (wcsIdx == wcs.length && textIdx == length) { return true; } } while (backtrack.size() > 0); return false; }
From source file:edu.umn.cs.spatialHadoop.core.RTree.java
/** * Searches the RTree starting from the given start position. This is either * a node number or offset of an element. If it's a node number, it performs * the search in the subtree rooted at this node. If it's an offset number, * it searches only the object found there. * It is assumed that the openQuery() has been called before this function * and that endQuery() will be called afterwards. * @param query_mbr// ww w. j a va 2 s . c o m * @param output * @param start - where to start searching * @param end - where to end searching. Only used when start is an offset of * an object. * @return * @throws IOException */ protected int search(Shape query_shape, ResultCollector<T> output, int start, int end) throws IOException { Rectangle query_mbr = query_shape.getMBR(); int resultSize = 0; // Special case for an empty tree if (height == 0) return 0; Stack<Integer> toBeSearched = new Stack<Integer>(); // Start from the given node toBeSearched.push(start); if (start >= nodeCount) { toBeSearched.push(end); } Rectangle node_mbr = new Rectangle(); // Holds one data line from tree data Text line = new Text2(); while (!toBeSearched.isEmpty()) { int searchNumber = toBeSearched.pop(); int mbrsToTest = searchNumber == 0 ? 1 : degree; if (searchNumber < nodeCount) { long nodeOffset = NodeSize * searchNumber; structure.seek(nodeOffset); int dataOffset = structure.readInt(); for (int i = 0; i < mbrsToTest; i++) { node_mbr.readFields(structure); int lastOffset = (searchNumber + i) == nodeCount - 1 ? treeSize : structure.readInt(); if (query_mbr.contains(node_mbr)) { // The node is full contained in the query range. // Save the time and do full scan for this node toBeSearched.push(dataOffset); // Checks if this node is the last node in its level // This can be easily detected because the next node in the level // order traversal will be the first node in the next level // which means it will have an offset less than this node if (lastOffset <= dataOffset) lastOffset = treeSize; toBeSearched.push(lastOffset); } else if (query_mbr.isIntersected(node_mbr)) { // Node partially overlaps with query. Go deep under this node if (searchNumber < nonLeafNodeCount) { // Search child nodes toBeSearched.push((searchNumber + i) * degree + 1); } else { // Search all elements in this node toBeSearched.push(dataOffset); // Checks if this node is the last node in its level // This can be easily detected because the next node in the level // order traversal will be the first node in the next level // which means it will have an offset less than this node if (lastOffset <= dataOffset) lastOffset = treeSize; toBeSearched.push(lastOffset); } } dataOffset = lastOffset; } } else { int firstOffset, lastOffset; // Search for data items (records) lastOffset = searchNumber; firstOffset = toBeSearched.pop(); data.seek(firstOffset + treeStartOffset); LineReader lineReader = new LineReader(data); while (firstOffset < lastOffset) { firstOffset += lineReader.readLine(line); stockObject.fromText(line); if (stockObject.isIntersected(query_shape)) { resultSize++; if (output != null) output.collect(stockObject); } } } } return resultSize; }
From source file:de.uni.bremen.monty.moco.ast.ASTBuilder.java
@Override public ASTNode visitListComprehension(ListComprehensionContext ctx) { Expression target = (Expression) visit(ctx.expression()); Position pos = position(ctx.getStart()); Stack<ResolvableIdentifier> identifiers = new Stack<>(); Stack<Expression> sources = new Stack<>(); Stack<Expression> filters = new Stack<>(); ResolvableIdentifier type = convertResolvableIdentifier(ctx.type()); tupleDeclarationFactory.checkTupleType(type); for (ListGeneratorContext genCtx : ctx.listGenerator()) { identifiers.push(new ResolvableIdentifier(getText(genCtx.Identifier()))); sources.push((Expression) visit(genCtx.expression())); if (genCtx.listFilter() != null) { filters.push((Expression) visit(genCtx.listFilter().expression())); } else {/*w ww . j a v a2s . co m*/ filters.push(null); } } // we start with the innermost block Block currentBlock = new Block(position(ctx.expression().getStart())); currentBlocks.push(currentBlock); currentGeneratorReturnType.push(type); currentBlock.addStatement(createYieldStatement(position(ctx.expression().getStart()), target)); currentGeneratorReturnType.pop(); for (int i = identifiers.size(); i > 0; i--) { Expression filter = filters.pop(); Expression source = sources.pop(); source = new MemberAccess(source.getPosition(), source, new FunctionCall(source.getPosition(), new ResolvableIdentifier("getIterator"), new ArrayList<Expression>())); ResolvableIdentifier ident = identifiers.pop(); if (filter != null) { Position filterPos = filter.getPosition(); Statement ifStm = new ConditionalStatement(filterPos, filter, currentBlock, new Block(filterPos)); currentBlocks.pop(); currentBlock = new Block(filterPos); currentBlocks.push(currentBlock); currentBlock.addStatement(ifStm); } currentBlocks.pop(); Block forBlock = new Block(source.getPosition()); // the block containing the for stm currentBlocks.push(forBlock); Statement forStm = (Statement) createForLoop(source.getPosition(), ident, source, currentBlock); currentBlock = forBlock; currentBlock.addStatement(forStm); } currentBlocks.pop(); // the current block is now the outermost for loop ClassDeclaration generator = (ClassDeclaration) createGenerator(pos, TmpIdentifierFactory.getUniqueIdentifier(), type, // new ResolvableIdentifier("Object"), new ArrayList<VariableDeclaration>(), new ArrayList<VariableDeclaration>(), new ArrayList<Expression>(), currentBlock); currentBlocks.peek().addDeclaration(generator); // return new instance return new WrappedFunctionCall(pos, new FunctionCall(pos, ResolvableIdentifier.convert(generator.getIdentifier()), new ArrayList<Expression>())); }
From source file:gdt.data.entity.ArchiveHandler.java
private void getTarEntries(TarArchiveEntry tarEntry, Stack<TarArchiveEntry> s, String root$) { if (tarEntry == null) return;// w w w. j a va2s.co m if (tarEntry.isDirectory()) { try { TarArchiveEntry[] tea = tarEntry.getDirectoryEntries(); if (tea != null) { for (TarArchiveEntry aTea : tea) { getTarEntries(aTea, s, root$); } } } catch (Exception e) { LOGGER.severe(":getTarEntities:" + e.toString()); } } else { String entryName$; entryName$ = tarEntry.getName().substring(root$.length()); tarEntry.setName(entryName$); s.push(tarEntry); } }
From source file:android.support.graphics.drawable.VectorDrawableCompat.java
private void inflateInternal(Resources res, XmlPullParser parser, AttributeSet attrs, Theme theme) throws XmlPullParserException, IOException { final VectorDrawableCompatState state = mVectorState; final VPathRenderer pathRenderer = state.mVPathRenderer; boolean noPathTag = true; // Use a stack to help to build the group tree. // The top of the stack is always the current group. final Stack<VGroup> groupStack = new Stack<VGroup>(); groupStack.push(pathRenderer.mRootGroup); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { final String tagName = parser.getName(); final VGroup currentGroup = groupStack.peek(); if (SHAPE_PATH.equals(tagName)) { final VFullPath path = new VFullPath(); path.inflate(res, attrs, theme, parser); currentGroup.mChildren.add(path); if (path.getPathName() != null) { pathRenderer.mVGTargetsMap.put(path.getPathName(), path); }// w w w. j av a 2s .com noPathTag = false; state.mChangingConfigurations |= path.mChangingConfigurations; } else if (SHAPE_CLIP_PATH.equals(tagName)) { final VClipPath path = new VClipPath(); path.inflate(res, attrs, theme, parser); currentGroup.mChildren.add(path); if (path.getPathName() != null) { pathRenderer.mVGTargetsMap.put(path.getPathName(), path); } state.mChangingConfigurations |= path.mChangingConfigurations; } else if (SHAPE_GROUP.equals(tagName)) { VGroup newChildGroup = new VGroup(); newChildGroup.inflate(res, attrs, theme, parser); currentGroup.mChildren.add(newChildGroup); groupStack.push(newChildGroup); if (newChildGroup.getGroupName() != null) { pathRenderer.mVGTargetsMap.put(newChildGroup.getGroupName(), newChildGroup); } state.mChangingConfigurations |= newChildGroup.mChangingConfigurations; } } else if (eventType == XmlPullParser.END_TAG) { final String tagName = parser.getName(); if (SHAPE_GROUP.equals(tagName)) { groupStack.pop(); } } eventType = parser.next(); } // Print the tree out for debug. if (DBG_VECTOR_DRAWABLE) { printGroupTree(pathRenderer.mRootGroup, 0); } if (noPathTag) { final StringBuffer tag = new StringBuffer(); if (tag.length() > 0) { tag.append(" or "); } tag.append(SHAPE_PATH); throw new XmlPullParserException("no " + tag + " defined"); } }