List of usage examples for java.util Stack pop
public synchronized E pop()
From source file:org.apache.struts2.components.Include.java
public static String getContextRelativePath(ServletRequest request, String relativePath) { String returnValue;/*from w w w. java 2 s .c o m*/ if (relativePath.startsWith("/")) { returnValue = relativePath; } else if (!(request instanceof HttpServletRequest)) { returnValue = relativePath; } else { HttpServletRequest hrequest = (HttpServletRequest) request; String uri = (String) request.getAttribute("javax.servlet.include.servlet_path"); if (uri == null) { uri = RequestUtils.getServletPath(hrequest); } returnValue = uri.substring(0, uri.lastIndexOf('/')) + '/' + relativePath; } // .. is illegal in an absolute path according to the Servlet Spec and will cause // known problems on Orion application servers. if (returnValue.indexOf("..") != -1) { Stack stack = new Stack(); StringTokenizer pathParts = new StringTokenizer(returnValue.replace('\\', '/'), "/"); while (pathParts.hasMoreTokens()) { String part = pathParts.nextToken(); if (!part.equals(".")) { if (part.equals("..")) { stack.pop(); } else { stack.push(part); } } } StringBuffer flatPathBuffer = new StringBuffer(); for (int i = 0; i < stack.size(); i++) { flatPathBuffer.append("/").append(stack.elementAt(i)); } returnValue = flatPathBuffer.toString(); } return returnValue; }
From source file:org.alfresco.service.cmr.calendar.CalendarTimezoneHelper.java
/** * Turns an iCal event into event + timezone parameters. * This is very closely tied to the SPP / VTI implementation, * and should be replaced with something more general. * Until then, it is deliberately not public. * // w ww . ja v a 2 s. co m * @param icalText iCal text for the event, and the TZ (prefixed) */ protected static Map<String, String> getICalParams(String icalText) { // Split the iCal file by lines String[] segregatedLines = icalText.split("\r\n"); if (segregatedLines.length == 1 && icalText.indexOf('\n') > 0) { segregatedLines = icalText.split("\n"); } // Perform a stack based parsing of it Map<String, String> result = new HashMap<String, String>(); int attendeeNum = 0; Stack<String> stack = new Stack<String>(); for (String line : segregatedLines) { String[] keyValue = icalLineKeyValue(line); if (keyValue.length >= 2) { if (keyValue[0].equals("BEGIN")) { stack.push(keyValue[1]); continue; } if (keyValue[0].equals("END")) { stack.pop(); continue; } if (!stack.isEmpty() && stack.peek().equals(ICAL_SECTION_EVENT)) { if (keyValue[0].contains(";")) { // Capture the extra details as suffix keys, they're sometimes needed int splitAt = keyValue[0].indexOf(';'); String mainKey = keyValue[0].substring(0, splitAt); if (splitAt < keyValue[0].length() - 2) { // Grab each ;k=v part and store as mainkey-k=v String[] extras = keyValue[0].substring(splitAt + 1).split(";"); for (String extra : extras) { splitAt = extra.indexOf('='); if (splitAt > -1 && !result.containsKey(mainKey + "-" + extra.substring(0, splitAt - 1))) { result.put(mainKey + "-" + extra.substring(0, splitAt - 1), extra.substring(splitAt + 1)); } } } // Use the main key for the core value keyValue[0] = mainKey; } if (keyValue[0].equals("ATTENDEE")) { keyValue[0] = keyValue[0] + attendeeNum; attendeeNum++; } if (!result.containsKey(keyValue[0])) { result.put(keyValue[0], keyValue[keyValue.length - 1]); } } if (!stack.isEmpty() && stack.peek().equals(ICAL_SECTION_TIMEZONE) && !result.containsKey("TZ-" + keyValue[0])) { // Store the top level timezone details with a TZ prefix result.put("TZ-" + keyValue[0], keyValue[keyValue.length - 1]); } if (stack.size() >= 2 && stack.get(stack.size() - 2).equals(ICAL_SECTION_TIMEZONE) && (stack.peek().equals(ICAL_SECTION_TZ_STANDARD) || stack.peek().equals(ICAL_SECTION_TZ_DAYLIGHT)) && !result.containsKey("TZ-" + stack.peek() + "-" + keyValue[0])) { // Store the timezone details with a TZ prefix + details type result.put("TZ-" + stack.peek() + "-" + keyValue[0], keyValue[keyValue.length - 1]); } } } return result; }
From source file:org.apache.hadoop.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);/*w w w . j ava2 s .c om*/ 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.isDirectory()) { stack.push(status.getPath()); } Assert.assertTrue(fs.exists(new Path( sourceBase + "/" + DistCpUtils.getRelativePath(new Path(targetBase), status.getPath())))); } } return true; }
From source file:org.apache.solr.handler.JsonLoader.java
static void addValToField(Stack stack, Object val, boolean inArray, JSONParser parser) throws IOException { Object obj = stack.peek();/*from w w w. j ava 2 s .c om*/ if (!(obj instanceof SolrInputField)) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "hymmm [" + parser.getPosition() + "]"); } SolrInputField f = inArray ? (SolrInputField) obj : (SolrInputField) stack.pop(); if (val == null) return; float boost = (f.getValue() == null) ? f.getBoost() : 1.0f; f.addValue(val, boost); }
From source file:org.apache.camel.util.FileUtil.java
/** * Compacts a path by stacking it and reducing <tt>..</tt> *///from www. j a v a 2 s .c om public static String compactPath(String path) { if (path == null) { return null; } // only normalize path if it contains .. as we want to avoid: path/../sub/../sub2 as this can leads to trouble if (path.indexOf("..") == -1) { return path; } // only normalize if contains a path separator if (path.indexOf(File.separator) == -1) { return path; } Stack<String> stack = new Stack<String>(); String separatorRegex = File.separator; if (FileUtil.isWindows()) { separatorRegex = "\\\\"; } String[] parts = path.split(separatorRegex); for (String part : parts) { if (part.equals("..") && !stack.isEmpty()) { // only pop if there is a previous path stack.pop(); } else { stack.push(part); } } // build path based on stack StringBuilder sb = new StringBuilder(); for (Iterator<String> it = stack.iterator(); it.hasNext();) { sb.append(it.next()); if (it.hasNext()) { sb.append(File.separator); } } return sb.toString(); }
From source file:opennlp.tools.parse_thicket.kernel_interface.BracesProcessor.java
public static boolean checkParentesis(String str) { if (str.isEmpty()) return true; Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < str.length(); i++) { char current = str.charAt(i); if (current == '{' || current == '(' || current == '[') { stack.push(current);//from w w w. ja va 2 s . co m } if (current == '}' || current == ')' || current == ']') { if (stack.isEmpty()) return false; char last = stack.peek(); if (current == '}' && (last == '{' || current == ')') && last == '(' || (current == ']' && last == '[')) stack.pop(); else return false; } } return stack.isEmpty(); }
From source file:opennlp.tools.parse_thicket.kernel_interface.BracesProcessor.java
public static boolean isBalanced(String s) { int count = 0; Stack<Character> stack = new Stack<Character>(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == L_PAREN) { stack.push(L_PAREN);//from ww w . j ava 2s.c o m count++; } else if (s.charAt(i) == L_BRACE) { stack.push(L_BRACE); count++; } else if (s.charAt(i) == L_BRACKET) { stack.push(L_BRACKET); count++; } else if (s.charAt(i) == R_PAREN) { if (stack.isEmpty()) return false; if (stack.pop() != L_PAREN) return false; } else if (s.charAt(i) == R_BRACE) { if (stack.isEmpty()) return false; if (stack.pop() != L_BRACE) return false; } else if (s.charAt(i) == R_BRACKET) { if (stack.isEmpty()) return false; if (stack.pop() != L_BRACKET) return false; } // ignore all other characters } return (stack.isEmpty()); }
From source file:edu.umn.cs.spatialHadoop.operations.ConvexHull.java
/** * Computes the convex hull of a set of points using a divide and conquer * in-memory algorithm. This function implements Andrew's modification to * the Graham scan algorithm.//from w w w . j av a 2 s .c o m * * @param points * @return */ public static <P extends Point> P[] convexHullInMemory(P[] points) { Stack<P> s1 = new Stack<P>(); Stack<P> s2 = new Stack<P>(); Arrays.sort(points); // Lower chain for (int i = 0; i < points.length; i++) { while (s1.size() > 1) { P p1 = s1.get(s1.size() - 2); P p2 = s1.get(s1.size() - 1); P p3 = points[i]; double crossProduct = (p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x); if (crossProduct <= 0) s1.pop(); else break; } s1.push(points[i]); } // Upper chain for (int i = points.length - 1; i >= 0; i--) { while (s2.size() > 1) { P p1 = s2.get(s2.size() - 2); P p2 = s2.get(s2.size() - 1); P p3 = points[i]; double crossProduct = (p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x); if (crossProduct <= 0) s2.pop(); else break; } s2.push(points[i]); } s1.pop(); s2.pop(); s1.addAll(s2); return s1.toArray((P[]) Array.newInstance(s1.firstElement().getClass(), s1.size())); }
From source file:com.linkedin.urls.PathNormalizer.java
License:asdf
/** * 1. Replaces "/./" with "/" recursively. * 2. "/blah/asdf/.." -> "/blah"/*w w w . ja v a2s . co m*/ * 3. "/blah/blah2/blah3/../../blah4" -> "/blah/blah4" * 4. "//" -> "/" * 5. Adds a slash at the end if there isn't one */ private static String sanitizeDotsAndSlashes(String path) { StringBuilder stringBuilder = new StringBuilder(path); Stack<Integer> slashIndexStack = new Stack<Integer>(); int index = 0; while (index < stringBuilder.length() - 1) { if (stringBuilder.charAt(index) == '/') { slashIndexStack.add(index); if (stringBuilder.charAt(index + 1) == '.') { if (index < stringBuilder.length() - 2 && stringBuilder.charAt(index + 2) == '.') { //If it looks like "/../" or ends with "/.." if (index < stringBuilder.length() - 3 && stringBuilder.charAt(index + 3) == '/' || index == stringBuilder.length() - 3) { boolean endOfPath = index == stringBuilder.length() - 3; slashIndexStack.pop(); int endIndex = index + 3; // backtrack so we can detect if this / is part of another replacement index = slashIndexStack.empty() ? -1 : slashIndexStack.pop() - 1; int startIndex = endOfPath ? index + 1 : index; stringBuilder.delete(startIndex + 1, endIndex); } } else if (index < stringBuilder.length() - 2 && stringBuilder.charAt(index + 2) == '/' || index == stringBuilder.length() - 2) { boolean endOfPath = index == stringBuilder.length() - 2; slashIndexStack.pop(); int startIndex = endOfPath ? index + 1 : index; stringBuilder.delete(startIndex, index + 2); // "/./" -> "/" index--; // backtrack so we can detect if this / is part of another replacement } } else if (stringBuilder.charAt(index + 1) == '/') { slashIndexStack.pop(); stringBuilder.deleteCharAt(index); index--; } } index++; } if (stringBuilder.length() == 0) { stringBuilder.append("/"); //Every path has at least a slash } return stringBuilder.toString(); }
From source file:com.espertech.esper.epl.parse.ExceptionConvertor.java
/** * Converts from a syntax error to a nice exception. * @param e is the syntax error/* w w w .jav a2 s . c om*/ * @param expression is the expression text * @param parser the parser that parsed the expression * @param addPleaseCheck indicates to add "please check" paraphrases * @return syntax exception */ public static UniformPair<String> convert(RecognitionException e, String expression, boolean addPleaseCheck, EsperEPL2GrammarParser parser) { if (expression.trim().length() == 0) { String message = "Unexpected " + END_OF_INPUT_TEXT; return new UniformPair<String>(message, expression); } Token t; Token tBeforeBefore = null; Token tBefore = null; Token tAfter = null; int tIndex = e.getOffendingToken() != null ? e.getOffendingToken().getTokenIndex() : Integer.MAX_VALUE; if (tIndex < parser.getTokenStream().size()) { t = parser.getTokenStream().get(tIndex); if ((tIndex + 1) < parser.getTokenStream().size()) { tAfter = parser.getTokenStream().get(tIndex + 1); } if (tIndex - 1 >= 0) { tBefore = parser.getTokenStream().get(tIndex - 1); } if (tIndex - 2 >= 0) { tBeforeBefore = parser.getTokenStream().get(tIndex - 2); } } else { if (parser.getTokenStream().size() >= 1) { tBeforeBefore = parser.getTokenStream().get(parser.getTokenStream().size() - 1); } if (parser.getTokenStream().size() >= 2) { tBefore = parser.getTokenStream().get(parser.getTokenStream().size() - 2); } t = parser.getTokenStream().get(parser.getTokenStream().size() - 1); } Token tEnd = null; if (parser.getTokenStream().size() > 0) { tEnd = parser.getTokenStream().get(parser.getTokenStream().size() - 1); } String positionInfo = getPositionInfo(t); String token = t.getType() == EsperEPL2GrammarParser.EOF ? "end-of-input" : "'" + t.getText() + "'"; Stack stack = parser.getParaphrases(); String check = ""; boolean isSelect = stack.size() == 1 && stack.get(0).equals("select clause"); if ((stack.size() > 0) && addPleaseCheck) { String delimiter = ""; StringBuilder checkList = new StringBuilder(); checkList.append(", please check the "); while (stack.size() != 0) { checkList.append(delimiter); checkList.append(stack.pop()); delimiter = " within the "; } check = checkList.toString(); } // check if token is a reserved keyword Set<String> keywords = parser.getKeywords(); boolean reservedKeyword = false; if (keywords.contains(token.toLowerCase())) { token += " (a reserved keyword)"; reservedKeyword = true; } else if (tAfter != null && keywords.contains("'" + tAfter.getText().toLowerCase() + "'")) { token += " ('" + tAfter.getText() + "' is a reserved keyword)"; reservedKeyword = true; } else { if ((tBefore != null) && (tAfter != null) && (keywords.contains("'" + tBefore.getText().toLowerCase() + "'")) && (keywords.contains("'" + tAfter.getText().toLowerCase() + "'"))) { token += " ('" + tBefore.getText() + "' and '" + tAfter.getText() + "' are a reserved keyword)"; reservedKeyword = true; } else if ((tBefore != null) && (keywords.contains("'" + tBefore.getText().toLowerCase() + "'"))) { token += " ('" + tBefore.getText() + "' is a reserved keyword)"; reservedKeyword = true; } else if (tEnd != null && keywords.contains("'" + tEnd.getText().toLowerCase() + "'")) { token += " ('" + tEnd.getText() + "' is a reserved keyword)"; reservedKeyword = true; } } // special handling for the select-clause "as" keyword, which is required if (isSelect && !reservedKeyword) { check += getSelectClauseAsText(tBeforeBefore, t); } String message = "Incorrect syntax near " + token + positionInfo + check; if (e instanceof NoViableAltException || e instanceof LexerNoViableAltException || checkForInputMismatchWithNoExpected(e)) { Token nvaeToken = e.getOffendingToken(); int nvaeTokenType = nvaeToken != null ? nvaeToken.getType() : EsperEPL2GrammarLexer.EOF; if (nvaeTokenType == EsperEPL2GrammarLexer.EOF) { if (token.equals(END_OF_INPUT_TEXT)) { message = "Unexpected " + END_OF_INPUT_TEXT + positionInfo + check; } else { if (ParseHelper.hasControlCharacters(expression)) { message = "Unrecognized control characters found in text" + positionInfo; } else { message = "Unexpected " + END_OF_INPUT_TEXT + " near " + token + positionInfo + check; } } } else { if (parser.getParserTokenParaphrases().get(nvaeTokenType) != null) { message = "Incorrect syntax near " + token + positionInfo + check; } else { // find next keyword in the next 3 tokens int currentIndex = tIndex + 1; while ((currentIndex > 0) && (currentIndex < parser.getTokenStream().size() - 1) && (currentIndex < tIndex + 3)) { Token next = parser.getTokenStream().get(currentIndex); currentIndex++; String quotedToken = "'" + next.getText() + "'"; if (parser.getKeywords().contains(quotedToken)) { check += " near reserved keyword '" + next.getText() + "'"; break; } } message = "Incorrect syntax near " + token + positionInfo + check; } } } else if (e instanceof InputMismatchException) { InputMismatchException mismatched = (InputMismatchException) e; String expected; if (mismatched.getExpectedTokens().size() > 1) { StringWriter writer = new StringWriter(); writer.append("any of the following tokens {"); String delimiter = ""; for (int i = 0; i < mismatched.getExpectedTokens().size(); i++) { writer.append(delimiter); if (i > 5) { writer.append("..."); writer.append(Integer.toString(mismatched.getExpectedTokens().size() - 5)); writer.append(" more"); break; } delimiter = ", "; writer.append(getTokenText(parser, mismatched.getExpectedTokens().get(i))); } writer.append("}"); expected = writer.toString(); } else { expected = getTokenText(parser, mismatched.getExpectedTokens().get(0)); } int offendingTokenType = mismatched.getOffendingToken().getType(); String unexpected = getTokenText(parser, offendingTokenType); String expecting = " expecting " + expected.trim() + " but found " + unexpected.trim(); message = "Incorrect syntax near " + token + expecting + positionInfo + check; } return new UniformPair<String>(message, expression); }