List of usage examples for java.util Stack push
public E push(E item)
From source file:com.linuxbox.enkive.message.MessageImpl.java
/** * @throws IOException//from ww w . j a va2 s. c om * @throws MimeIOException * @throws MimeException * @throws CannotTransferMessageContentException * * @param InputStream * in An InputStream of the message to be parsed * * Constructs a com.linuxbox.enkive.message object from a raw * email message InputStream * @throws BadMessageException */ public void ConstructMessage(InputStream in) throws IOException, CannotTransferMessageContentException, BadMessageException { Stack<MultiPartHeader> headerStack = new Stack<MultiPartHeader>(); MultiPartHeader mp; StringBuilder headers = new StringBuilder(); boolean messageHeadersParsed = false; boolean isMultiPart = false; // TODO Get line ending from message final String lineEnding = "\r\n"; final MessageStreamParser stream = new MessageStreamParser(config); stream.setRecursionMode(RecursionMode.M_NO_RECURSE); stream.parse(in); try { for (EntityState state = stream.getState(); state != EntityState.T_END_OF_STREAM; state = stream .next()) { switch (state) { // At the start of a header section we want to reset the local // header variable since we only want to store the headers // for the section currently being parsed case T_START_HEADER: headers = new StringBuilder(); break; // Append each header field to the local header variable case T_FIELD: headers.append(stream.getField()); headers.append(lineEnding); break; // If we haven't set the message headers set them and // clear the variable so they don't get stored in a // ContentHeader object case T_END_HEADER: if (!messageHeadersParsed) { setOriginalHeaders(headers.toString()); messageHeadersParsed = true; headers = new StringBuilder(); } break; // If we have a multipart message, create a new object, // grab the information we need and push it on the stack case T_START_MULTIPART: isMultiPart = true; mp = new MultiPartHeaderImpl(); mp.setBoundary(stream.getBodyDescriptor().getBoundary()); mp.setOriginalHeaders(headers.toString()); mp.setLineEnding(lineEnding); headerStack.push(mp); break; // If there's a preamble, get the multipartheader off // the top of the stack, set it, and push back on the stack case T_PREAMBLE: BufferedReader reader = new BufferedReader(stream.getReader()); String tempString; String preamble = ""; while ((tempString = reader.readLine()) != null) { preamble += tempString + lineEnding; } mp = headerStack.pop(); mp.setPreamble(preamble); headerStack.push(mp); break; // If there's an epilogue, get the multipartheader off // the top of the stack, set it, and push back on the stack case T_EPILOGUE: BufferedReader epilogueReader = new BufferedReader(stream.getReader()); String tempEpilogueString; String epilogue = ""; while ((tempEpilogueString = epilogueReader.readLine()) != null) { epilogue += tempEpilogueString + lineEnding; } mp = headerStack.pop(); mp.setEpilogue(epilogue); headerStack.push(mp); break; // Create a new singlepartheader, set the headers, // set the content_data case T_BODY: SinglePartHeader single = new SinglePartHeaderImpl(); final String transferEncoding = stream.getBodyDescriptor().getTransferEncoding(); EncodedContentDataImpl cd = new EncodedContentDataImpl(transferEncoding); cd.setBinaryContent(stream.getInputStream()); single.setContentTransferEncoding(transferEncoding); single.setOriginalHeaders(headers.toString()); single.parseHeaders(headers.toString(), config); single.setEncodedContentData(cd); single.setLineEnding(lineEnding); // If we're working with a multipart message, // pop, add the singlepartheader, and push. // Otherwise just set the singlepartheader if (isMultiPart) { mp = headerStack.pop(); mp.addPartHeader(single); headerStack.push(mp); } else this.setContentHeader(single); break; // If we've reached the end of a multipart, it could // be a nested multipart. In that case we'll need to // Add the nested multipart to the multipart a level above. // If not nested, we've reached the end of the content headers // so set it. case T_END_MULTIPART: mp = headerStack.pop(); if (headerStack.isEmpty()) this.setContentHeader(mp); else { MultiPartHeader mp2 = headerStack.pop(); mp2.addPartHeader(mp); headerStack.push(mp2); } break; default: // ignore other tags break; } // switch } // for } catch (MimeException e) { throw new BadMessageException(e); } catch (MimeIOException e) { throw new BadMessageException(e); } if (LOGGER.isTraceEnabled()) LOGGER.trace("Message " + this.messageId + " successfully parsed."); }
From source file:org.apache.oodt.cas.cli.construct.StdCmdLineConstructor.java
public Set<CmdLineOptionInstance> construct(CmdLineIterable<ParsedArg> parsedArgs, Set<CmdLineOption> validOptions) throws CmdLineConstructionException { HashSet<CmdLineOptionInstance> optionInstances = new HashSet<CmdLineOptionInstance>(); Stack<CmdLineOptionInstance> groupOptions = new Stack<CmdLineOptionInstance>(); for (ParsedArg arg : parsedArgs) { if (arg.getType().equals(ParsedArg.Type.OPTION)) { // check if option is a valid one CmdLineOption option = getOptionByName(arg.getName(), validOptions); if (option == null) { throw new CmdLineConstructionException("Invalid option: '" + arg.getName() + "'"); }//www . j av a2 s .c o m // read found option CmdLineOptionInstance specifiedOption = getOption(parsedArgs, option); // Check if we are currently loading subOptions. if (!groupOptions.isEmpty()) { CmdLineOptionInstance currentGroup = groupOptions.peek(); // Check if option is NOT a subOption for current group. if (!isSubOption(currentGroup.getOption(), option)) { // Check if current group was expecting more subOptions. Set<CmdLineOption> requiredSubOptions = verifyGroupHasRequiredSubOptions(currentGroup); if (!requiredSubOptions.isEmpty()) { throw new CmdLineConstructionException( "Missing the following required subOptions for '" + currentGroup.getOption() + "': " + sortOptionsByRequiredStatus(requiredSubOptions)); } else if (currentGroup.getSubOptions().isEmpty()) { throw new CmdLineConstructionException( "Must specify a subOption for group option '" + currentGroup.getOption() + "'"); } else { // pop group and add to list of specified options. optionInstances.add(groupOptions.pop()); } // It is a sub-option... } else { // Add option to current group subOptions. currentGroup.addSubOption(specifiedOption); continue; } } if (option instanceof GroupCmdLineOption) { // Push group as current group. groupOptions.push(specifiedOption); if (!parsedArgs.hasNext()) { throw new CmdLineConstructionException( "Must specify a subOption for group option '" + specifiedOption.getOption() + "'"); } } else if (option.isSubOption()) { throw new CmdLineConstructionException( "Option '" + option + "' is a subOption, but was used at top level Option"); } else { // Option good to go. optionInstances.add(specifiedOption); } } else { throw new CmdLineConstructionException("Invalid argument: '" + arg + "'"); } } while (!groupOptions.isEmpty()) { CmdLineOptionInstance currentGroup = groupOptions.pop(); Set<CmdLineOption> requiredSubOptions = verifyGroupHasRequiredSubOptions(currentGroup); if (!requiredSubOptions.isEmpty()) { throw new CmdLineConstructionException("Missing the following required subOptions for '" + currentGroup.getOption() + "': " + sortOptionsByRequiredStatus(requiredSubOptions)); } else { optionInstances.add(currentGroup); } } return optionInstances; }
From source file:org.sakaiproject.lessonbuildertool.service.LessonBuilderEntityProducer.java
/** * {@inheritDoc}//from w ww. j av a 2 s .co m */ public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments) { //prepare the buffer for the results log StringBuilder results = new StringBuilder(); try { Site site = siteService.getSite(siteId); // start with an element with our very own (service) name Element element = doc.createElement(serviceName()); element.setAttribute(VERSION_ATTR, ARCHIVE_VERSION); ((Element) stack.peek()).appendChild(element); stack.push(element); Element lessonbuilder = doc.createElement(LESSONBUILDER); List<SimplePage> sitePages = simplePageToolDao.getSitePages(siteId); if (sitePages != null && !sitePages.isEmpty()) { for (SimplePage page : sitePages) addPage(doc, lessonbuilder, page, site); } Collection<ToolConfiguration> tools = site.getTools(myToolIds()); int count = 0; if (tools != null && !tools.isEmpty()) { for (ToolConfiguration config : tools) { element = doc.createElement(LESSONBUILDER); addAttr(doc, element, "toolid", config.getPageId()); addAttr(doc, element, "name", config.getContainingPage().getTitle()); Properties props = config.getPlacementConfig(); String roleList = props.getProperty("functions.require"); if (roleList == null) roleList = ""; addAttr(doc, element, "functions.require", roleList); // should be impossible for these nulls, but we've seen it if (simplePageToolDao.getTopLevelPageId(config.getPageId()) != null) addAttr(doc, element, "pageId", Long.toString(simplePageToolDao.getTopLevelPageId(config.getPageId()))); else logger.warn("archive site " + siteId + " tool page " + config.getPageId() + " null lesson"); // addPage(doc, element, simplePageToolDao.getTopLevelPageId(config.getPageId())); lessonbuilder.appendChild(element); count++; } results.append("archiving " + count + " LessonBuilder instances.\n"); } else { results.append("archiving no LessonBuilder instances.\n"); } ((Element) stack.peek()).appendChild(lessonbuilder); stack.push(lessonbuilder); stack.pop(); } catch (Exception any) { any.printStackTrace(); logger.warn("archive: exception archiving service: " + any + " " + serviceName()); } stack.pop(); return results.toString(); }
From source file:org.apache.tajo.engine.planner.LogicalPlanner.java
@Override public SelectionNode visitFilter(PlanContext context, Stack<Expr> stack, Selection selection) throws PlanningException { QueryBlock block = context.queryBlock; ExprNormalizedResult normalizedResult = normalizer.normalize(context, selection.getQual()); block.namedExprsMgr.addExpr(normalizedResult.baseExpr); if (normalizedResult.aggExprs.size() > 0 || normalizedResult.scalarExprs.size() > 0) { throw new VerifyException("Filter condition cannot include aggregation function"); }//w w w.ja va 2 s . c o m //////////////////////////////////////////////////////// // Visit and Build Child Plan //////////////////////////////////////////////////////// stack.push(selection); LogicalNode child = visit(context, stack, selection.getChild()); stack.pop(); //////////////////////////////////////////////////////// SelectionNode selectionNode = context.queryBlock.getNodeFromExpr(selection); selectionNode.setChild(child); selectionNode.setInSchema(child.getOutSchema()); selectionNode.setOutSchema(child.getOutSchema()); // Create EvalNode for a search condition. EvalNode searchCondition = exprAnnotator.createEvalNode(context, selection.getQual(), NameResolvingMode.RELS_AND_SUBEXPRS); EvalNode simplified = context.evalOptimizer.optimize(context, searchCondition); // set selection condition selectionNode.setQual(simplified); return selectionNode; }
From source file:com.unboundid.scim2.common.utils.SchemaUtils.java
/** * Gets SCIM schema attributes for a class. * * @param classesProcessed a stack containing the classes processed prior * to this class. This is used for cycle detection. * @param cls the class to get the attributes for. * @return a collection of SCIM schema attributes for the class. * @throws IntrospectionException thrown if an error occurs during * Introspection.// w ww. j ava 2 s . c o m */ private static Collection<AttributeDefinition> getAttributes(final Stack<String> classesProcessed, final Class<?> cls) throws IntrospectionException { String className = cls.getCanonicalName(); if (!cls.isAssignableFrom(AttributeDefinition.class) && classesProcessed.contains(className)) { throw new RuntimeException("Cycles detected in Schema"); } Collection<PropertyDescriptor> propertyDescriptors = getPropertyDescriptors(cls); Collection<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equals("subAttributes") && cls.isAssignableFrom(AttributeDefinition.class) && classesProcessed.contains(className)) { // Skip second nesting of subAttributes the second time around // since there is no subAttributes of subAttributes in SCIM. continue; } AttributeDefinition.Builder attributeBuilder = new AttributeDefinition.Builder(); Field field = findField(cls, propertyDescriptor.getName()); if (field == null) { continue; } Attribute schemaProperty = null; JsonProperty jsonProperty = null; if (field.isAnnotationPresent(Attribute.class)) { schemaProperty = field.getAnnotation(Attribute.class); } if (field.isAnnotationPresent(JsonProperty.class)) { jsonProperty = field.getAnnotation(JsonProperty.class); } // Only generate schema for annotated fields. if (schemaProperty == null) { continue; } addName(attributeBuilder, propertyDescriptor, jsonProperty); addDescription(attributeBuilder, schemaProperty); addCaseExact(attributeBuilder, schemaProperty); addRequired(attributeBuilder, schemaProperty); addReturned(attributeBuilder, schemaProperty); addUniqueness(attributeBuilder, schemaProperty); addReferenceTypes(attributeBuilder, schemaProperty); addMutability(attributeBuilder, schemaProperty); addMultiValued(attributeBuilder, propertyDescriptor, schemaProperty); addCanonicalValues(attributeBuilder, schemaProperty); Class propertyCls = propertyDescriptor.getPropertyType(); // if this is a multivalued attribute the real sub attribute class is the // the one specified in the annotation, not the list, set, array, etc. if ((schemaProperty.multiValueClass() != NullType.class)) { propertyCls = schemaProperty.multiValueClass(); } AttributeDefinition.Type type = getAttributeType(propertyCls); attributeBuilder.setType(type); if (type == AttributeDefinition.Type.COMPLEX) { // Add this class to the list to allow cycle detection classesProcessed.push(cls.getCanonicalName()); Collection<AttributeDefinition> subAttributes = getAttributes(classesProcessed, propertyCls); attributeBuilder .addSubAttributes(subAttributes.toArray(new AttributeDefinition[subAttributes.size()])); classesProcessed.pop(); } attributes.add(attributeBuilder.build()); } return attributes; }
From source file:com.joliciel.jochre.graphics.ShapeImpl.java
@Override public Collection<BridgeCandidate> getBridgeCandidates(double maxBridgeWidth) { if (this.bridgeCandidates == null) { TreeSet<VerticalLineSegment> lines = this.getVerticalLineSegments(); // Now, detect "bridges" which could indicate that the shape should be split // First, detect which spaces are "enclosed" and which touch the outer walls // To do this, build up a set of all inverse (white) lines TreeSet<VerticalLineSegment> inverseLines = new TreeSet<VerticalLineSegment>(); int currentX = -1; VerticalLineSegment previousLine = null; for (VerticalLineSegment line : lines) { //LOG.debug("Checking line x = " + line.x + ", top = " + line.yTop + ", bottom = " + line.yBottom); if (line.x != currentX) { // new x-coordinate if (previousLine != null && previousLine.yBottom < this.getHeight() - 1) { VerticalLineSegment inverseLine = new VerticalLineSegment(previousLine.x, previousLine.yBottom + 1); inverseLine.yBottom = this.getHeight() - 1; inverseLines.add(inverseLine); //LOG.debug("Adding inverse line x = " + inverseLine.x + ", top = " + inverseLine.yTop + ", bottom = " + inverseLine.yBottom); }/*from www . j ava2 s .c om*/ if (line.yTop > 0) { VerticalLineSegment inverseLine = new VerticalLineSegment(line.x, line.yTop - 1); inverseLine.yTop = 0; inverseLines.add(inverseLine); //LOG.debug("Adding inverse line x = " + inverseLine.x + ", top = " + inverseLine.yTop + ", bottom = " + inverseLine.yBottom); } currentX = line.x; } else if (previousLine != null) { VerticalLineSegment inverseLine = new VerticalLineSegment(previousLine.x, previousLine.yBottom + 1); inverseLine.yBottom = line.yTop - 1; inverseLines.add(inverseLine); //LOG.debug("Adding inverse line x = " + inverseLine.x + ", top = " + inverseLine.yTop + ", bottom = " + inverseLine.yBottom); } previousLine = line; } if (previousLine != null && previousLine.yBottom < this.getHeight() - 1) { VerticalLineSegment inverseLine = new VerticalLineSegment(previousLine.x, previousLine.yBottom + 1); inverseLine.yBottom = this.getHeight() - 1; inverseLines.add(inverseLine); //LOG.debug("Adding inverse line x = " + inverseLine.x + ", top = " + inverseLine.yTop + ", bottom = " + inverseLine.yBottom); } LOG.debug("inverseLines size: " + inverseLines.size()); // Calculate neighbours for inverse lines for (VerticalLineSegment inverseLine : inverseLines) { for (VerticalLineSegment otherLine : inverseLines) { if (otherLine.x == inverseLine.x + 1) { if (inverseLine.yTop - 1 <= otherLine.yBottom && otherLine.yTop <= inverseLine.yBottom + 1) { inverseLine.rightSegments.add(otherLine); otherLine.leftSegments.add(inverseLine); } } if (otherLine.x == inverseLine.x - 1) { if (inverseLine.yTop - 1 <= otherLine.yBottom && otherLine.yTop <= inverseLine.yBottom + 1) { inverseLine.leftSegments.add(otherLine); otherLine.rightSegments.add(inverseLine); } } } } // Eliminate any white lines which somehow touch an edge Stack<VerticalLineSegment> lineStack = new Stack<VerticalLineSegment>(); Set<VerticalLineSegment> outerInverseLines = new HashSet<VerticalLineSegment>(); for (VerticalLineSegment inverseLine : inverseLines) { if (inverseLine.yTop == 0 || inverseLine.x == 0 || inverseLine.yBottom == this.getHeight() - 1 || inverseLine.x == this.getWidth() - 1) lineStack.push(inverseLine); } while (!lineStack.isEmpty()) { VerticalLineSegment inverseLine = lineStack.pop(); if (!inverseLine.touched) { inverseLine.touched = true; outerInverseLines.add(inverseLine); //LOG.debug("Outer inverse line x = " + inverseLine.x + ", top = " + inverseLine.yTop + ", bottom = " + inverseLine.yBottom); for (VerticalLineSegment rightLine : inverseLine.rightSegments) lineStack.push(rightLine); for (VerticalLineSegment leftLine : inverseLine.leftSegments) { lineStack.push(leftLine); } } } LOG.debug("outerInverseLines size: " + outerInverseLines.size()); Set<VerticalLineSegment> enclosedInverseLines = new HashSet<VerticalLineSegment>(inverseLines); enclosedInverseLines.removeAll(outerInverseLines); LOG.debug("enclosedInverseLines.size: " + enclosedInverseLines.size()); if (LOG.isDebugEnabled()) { for (VerticalLineSegment inverseLine : enclosedInverseLines) LOG.debug("Enclosed inverse line x = " + inverseLine.x + ", top = " + inverseLine.yTop + ", bottom = " + inverseLine.yBottom); } // Add bridge candidates // based on maximum line length and having exactly one neighbour on each side LOG.debug("Adding bridge candidates"); List<BridgeCandidate> candidateList = new ArrayList<BridgeCandidate>(); for (VerticalLineSegment line : lines) { if (line.rightSegments.size() == 1 && line.leftSegments.size() == 1 && line.length() <= maxBridgeWidth) { // also the bridge width should be considered where two vertical lines touch each other // rather than for the full length of the line BridgeCandidate candidate = null; VerticalLineSegment rightLine = line.rightSegments.iterator().next(); VerticalLineSegment leftLine = line.leftSegments.iterator().next(); int leftTopTouch = (leftLine.yTop > line.yTop ? leftLine.yTop : line.yTop); int leftBottomTouch = (leftLine.yBottom < line.yBottom ? leftLine.yBottom : line.yBottom); int rightTopTouch = (rightLine.yTop > line.yTop ? rightLine.yTop : line.yTop); int rightBottomTouch = (rightLine.yBottom < line.yBottom ? rightLine.yBottom : line.yBottom); int rightLength = rightTopTouch - rightBottomTouch; int leftLength = leftTopTouch - leftBottomTouch; if (line.length() <= maxBridgeWidth || rightLength <= maxBridgeWidth || leftLength <= maxBridgeWidth) { candidate = new BridgeCandidate(this, line); if (rightLength < leftLength && rightLength < line.length()) { candidate.topTouch = rightTopTouch; candidate.bottomTouch = rightBottomTouch; } else if (leftLength < line.length()) { candidate.topTouch = leftTopTouch; candidate.bottomTouch = leftBottomTouch; } LOG.debug("Adding bridge candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); candidateList.add(candidate); } } } LOG.debug("Bridge candidate size: " + candidateList.size()); LOG.debug("Eliminating candidates with shorter neighbor"); Set<BridgeCandidate> candidatesToEliminate = null; if (candidateList.size() > 0) { // eliminate any bridge candidates that touch a shorter bridge candidate candidatesToEliminate = new HashSet<BridgeCandidate>(); for (int i = 0; i < candidateList.size() - 1; i++) { BridgeCandidate candidate = candidateList.get(i); for (int j = i + 1; j < candidateList.size(); j++) { BridgeCandidate otherCandidate = candidateList.get(j); if (otherCandidate.x == candidate.x + 1 && candidate.rightSegments.contains(otherCandidate)) { if ((candidate.bridgeWidth()) <= (otherCandidate.bridgeWidth())) { LOG.debug("Eliminating candidate x = " + otherCandidate.x + ", top = " + otherCandidate.yTop + ", bottom = " + otherCandidate.yBottom); candidatesToEliminate.add(otherCandidate); } else { LOG.debug("Eliminating candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); candidatesToEliminate.add(candidate); } } } } candidateList.removeAll(candidatesToEliminate); LOG.debug("Bridge candidate size: " + candidateList.size()); // To be a bridge, three additional things have to be true: // (A) intersection between right & left shape = null // (B) weight of right shape & weight of left shape > a certain threshold // (C) little overlap right boundary of left shape, left boundary of right shape LOG.debug("Eliminating candidates touching enclosed space"); // (A) intersection between right & left shape = null // Intersection between right and left shape is non-null // if the line segment X touches an enclosed space immediately above or below candidatesToEliminate = new HashSet<BridgeCandidate>(); for (BridgeCandidate candidate : candidateList) { boolean nullIntersection = true; for (VerticalLineSegment inverseLine : enclosedInverseLines) { if (candidate.x == inverseLine.x) { if (inverseLine.yBottom == candidate.yTop - 1 || inverseLine.yTop == candidate.yBottom + 1) { nullIntersection = false; break; } } } if (!nullIntersection) { LOG.debug("Eliminating candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); candidatesToEliminate.add(candidate); } } candidateList.removeAll(candidatesToEliminate); LOG.debug("Remaining bridge candidate size: " + candidateList.size()); // another criterion for avoiding "false splits" is that on both side of the bridge // the shapes pretty rapidly expand in width both up and down LOG.debug("Eliminating candidates without vertical expansion on both sides"); candidatesToEliminate = new HashSet<BridgeCandidate>(); int expansionLimit = (int) Math.ceil(((double) this.getWidth()) / 6.0); for (BridgeCandidate candidate : candidateList) { // take into account the portion touching on the right or left boolean isCandidate = true; Stack<VerticalLineSegment> leftLines = new Stack<VerticalLineSegment>(); Stack<Integer> leftDepths = new Stack<Integer>(); leftLines.push(candidate); leftDepths.push(0); int leftTop = candidate.topTouch; int leftBottom = candidate.bottomTouch; while (!leftLines.isEmpty()) { VerticalLineSegment line = leftLines.pop(); int depth = leftDepths.pop(); if (line.yTop < leftTop) leftTop = line.yTop; if (line.yBottom > leftBottom) leftBottom = line.yBottom; if (depth <= expansionLimit) { for (VerticalLineSegment leftSegment : line.leftSegments) { leftLines.push(leftSegment); leftDepths.push(depth + 1); } } } if (leftTop == candidate.topTouch || leftBottom == candidate.bottomTouch) isCandidate = false; if (isCandidate) { Stack<VerticalLineSegment> rightLines = new Stack<VerticalLineSegment>(); Stack<Integer> rightDepths = new Stack<Integer>(); rightLines.push(candidate); rightDepths.push(0); int rightTop = candidate.topTouch; int rightBottom = candidate.bottomTouch; while (!rightLines.isEmpty()) { VerticalLineSegment line = rightLines.pop(); int depth = rightDepths.pop(); if (line.yTop < rightTop) rightTop = line.yTop; if (line.yBottom > rightBottom) rightBottom = line.yBottom; if (depth <= expansionLimit) { for (VerticalLineSegment rightSegment : line.rightSegments) { rightLines.push(rightSegment); rightDepths.push(depth + 1); } } } if (rightTop == candidate.topTouch || rightBottom == candidate.bottomTouch) isCandidate = false; } if (!isCandidate) { LOG.debug("Eliminating candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); candidatesToEliminate.add(candidate); } } candidateList.removeAll(candidatesToEliminate); LOG.debug("Remaining bridge candidate size: " + candidateList.size()); if (LOG.isDebugEnabled()) { for (VerticalLineSegment candidate : candidateList) { LOG.debug("Remaining candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); } } } if (candidateList.size() > 0) { // (B) weight of right shape & weight of left shape > a certain threshold // (C) little overlap right boundary of left shape, left boundary of right shape // // We can now divide the shape into n groups, each separated by a candidate // We recursively build a group until we reach a candidate // and indicate whether it's the right or left border of the candidate. // We then keep going from the candidate on to the next one // We keep tab of the size of each group and of its right & left boundaries // at the end we can easily determine the right and left boundaries of each, // as well as the right & left pixel weight List<VerticalLineGroup> groups = new ArrayList<VerticalLineGroup>(); VerticalLineSegment firstLine = lines.first(); lineStack = new Stack<VerticalLineSegment>(); Stack<BridgeCandidate> candidateStack = new Stack<BridgeCandidate>(); Stack<Boolean> fromLeftStack = new Stack<Boolean>(); Stack<Boolean> candidateFromLeftStack = new Stack<Boolean>(); lineStack.push(firstLine); fromLeftStack.push(true); VerticalLineGroup group = new VerticalLineGroup(this); List<BridgeCandidate> touchedCandidates = new ArrayList<BridgeCandidate>(); while (!lineStack.isEmpty()) { while (!lineStack.isEmpty()) { VerticalLineSegment line = lineStack.pop(); boolean fromLeft = fromLeftStack.pop(); if (line.touched) continue; line.touched = true; if (candidateList.contains(line)) { // a candidate! LOG.debug("Touching candidate x = " + line.x + ", top = " + line.yTop + ", bottom = " + line.yBottom); BridgeCandidate candidate = null; for (BridgeCandidate existingCandidate : candidateList) { if (existingCandidate.equals(line)) { candidate = existingCandidate; break; } } boolean foundCandidate = touchedCandidates.contains(candidate); if (!foundCandidate) { touchedCandidates.add(candidate); candidateStack.push(candidate); candidateFromLeftStack.push(fromLeft); if (fromLeft) { // coming from the left group.rightCandidates.add(candidate); candidate.leftGroup = group; } else { group.leftCandidates.add(candidate); candidate.rightGroup = group; } } } else { // not a candidate LOG.debug("Touching line length = " + line.length() + ", x = " + line.x + ", top = " + line.yTop + ", bottom = " + line.yBottom); group.pixelCount += line.length(); if (line.x < group.leftBoundary) group.leftBoundary = line.x; if (line.x > group.rightBoundary) group.rightBoundary = line.x; if (line.yTop < group.topBoundary) group.topBoundary = line.yTop; if (line.yBottom > group.bottomBoundary) group.bottomBoundary = line.yBottom; for (VerticalLineSegment leftLine : line.leftSegments) { lineStack.push(leftLine); fromLeftStack.push(false); } for (VerticalLineSegment rightLine : line.rightSegments) { lineStack.push(rightLine); fromLeftStack.push(true); } } } // no more lines in this group groups.add(group); if (!candidateStack.isEmpty()) { BridgeCandidate candidate = candidateStack.pop(); boolean fromLeft = candidateFromLeftStack.pop(); //lineStack.push(candidate.line); //fromLeftStack.push(fromLeft); LOG.debug("*** New Group ***"); LOG.debug("Next candidate: x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); group = new VerticalLineGroup(this); if (fromLeft) { group.leftCandidates.add(candidate); candidate.rightGroup = group; } else { group.rightCandidates.add(candidate); candidate.leftGroup = group; } // add this candidate's neighbours to the lineStack for (VerticalLineSegment leftLine : candidate.leftSegments) { lineStack.push(leftLine); fromLeftStack.push(false); } for (VerticalLineSegment rightLine : candidate.rightSegments) { lineStack.push(rightLine); fromLeftStack.push(true); } } // next candidate on candidate stack } // no more lines to process if (LOG.isDebugEnabled()) { LOG.debug("Found " + groups.size() + " groups"); int i = 1; for (VerticalLineGroup aGroup : groups) { LOG.debug("Group " + i++ + ", pixelCount: " + aGroup.pixelCount + ", leftBoundary: " + aGroup.leftBoundary + ", rightBoundary: " + aGroup.rightBoundary); LOG.debug("Candidates on left: "); for (BridgeCandidate candidate : aGroup.leftCandidates) LOG.debug("Candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); LOG.debug("Candidates on right: "); for (BridgeCandidate candidate : aGroup.rightCandidates) LOG.debug("Candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); } LOG.debug("Found " + candidateList.size() + " candidates"); for (BridgeCandidate candidate : candidateList) { LOG.debug("Candidate x = " + candidate.x + ", top = " + candidate.yTop + ", bottom = " + candidate.yBottom); LOG.debug("- Left group = pixelCount: " + candidate.leftGroup.pixelCount + ", leftBoundary: " + candidate.leftGroup.leftBoundary + ", rightBoundary: " + candidate.leftGroup.rightBoundary); LOG.debug("- Right group = pixelCount: " + candidate.rightGroup.pixelCount + ", leftBoundary: " + candidate.rightGroup.leftBoundary + ", rightBoundary: " + candidate.rightGroup.rightBoundary); } } // should we log? // calculate each candidate's pixel totals and boundaries for (BridgeCandidate candidate : candidateList) { for (VerticalLineGroup lineGroup : groups) lineGroup.touched = false; Stack<VerticalLineGroup> groupStack = new Stack<VerticalLineGroup>(); groupStack.push(candidate.leftGroup); while (!groupStack.isEmpty()) { VerticalLineGroup lineGroup = groupStack.pop(); if (lineGroup.touched) continue; lineGroup.touched = true; candidate.leftPixels += lineGroup.pixelCount; if (lineGroup.leftBoundary < candidate.leftShapeLeftBoundary) candidate.leftShapeLeftBoundary = lineGroup.leftBoundary; if (lineGroup.rightBoundary > candidate.leftShapeRightBoundary) candidate.leftShapeRightBoundary = lineGroup.rightBoundary; for (BridgeCandidate leftCandidate : lineGroup.leftCandidates) { if (!candidate.equals(leftCandidate)) { candidate.leftPixels += leftCandidate.length(); groupStack.push(leftCandidate.leftGroup); } } for (BridgeCandidate rightCandidate : lineGroup.rightCandidates) { if (!candidate.equals(rightCandidate)) { candidate.leftPixels += rightCandidate.length(); groupStack.push(rightCandidate.rightGroup); } } } // next left group groupStack.push(candidate.rightGroup); while (!groupStack.isEmpty()) { VerticalLineGroup lineGroup = groupStack.pop(); if (lineGroup.touched) continue; lineGroup.touched = true; candidate.rightPixels += lineGroup.pixelCount; if (lineGroup.leftBoundary < candidate.rightShapeLeftBoundary) candidate.rightShapeLeftBoundary = lineGroup.leftBoundary; if (lineGroup.rightBoundary > candidate.rightShapeRightBoundary) candidate.rightShapeRightBoundary = lineGroup.rightBoundary; for (BridgeCandidate leftCandidate : lineGroup.leftCandidates) { if (!candidate.equals(leftCandidate)) { candidate.rightPixels += leftCandidate.length(); groupStack.push(leftCandidate.leftGroup); } } for (BridgeCandidate rightCandidate : lineGroup.rightCandidates) { if (!candidate.equals(rightCandidate)) { candidate.rightPixels += rightCandidate.length(); groupStack.push(rightCandidate.rightGroup); } } } // next right group } // next candidate } // do we have any candidates? this.bridgeCandidates = candidateList; } // lazy load return this.bridgeCandidates; }
From source file:com.mirth.connect.model.converters.NCPDPReader.java
private void parseSegment(String segment, ContentHandler contentHandler) throws SAXException { if (StringUtils.isBlank(segment)) { return;/*from w w w. j a v a 2 s . c o m*/ } boolean inCounter = false; boolean inCount = false; boolean hasMoreFields = true; String segmentId = StringUtils.EMPTY; String subSegment = StringUtils.EMPTY; Stack<String> fieldStack = new Stack<String>(); int fieldDelimeterIndex = segment.indexOf(fieldDelimeter); if (fieldDelimeterIndex == 0) { segment = segment.substring(fieldDelimeterIndex + fieldDelimeter.length()); fieldDelimeterIndex = segment.indexOf(fieldDelimeter); } if (fieldDelimeterIndex == -1) { logger.warn("Empty segment with no field seperators. Make sure batch file processing is disabled."); hasMoreFields = false; segmentId = segment; } else { segmentId = segment.substring(0, fieldDelimeterIndex); subSegment = segment.substring(fieldDelimeterIndex + fieldDelimeter.length(), segment.length()); } contentHandler.startElement("", NCPDPReference.getInstance().getSegment(segmentId, version), "", null); while (hasMoreFields) { fieldDelimeterIndex = subSegment.indexOf(fieldDelimeter); // not last field String field; if (fieldDelimeterIndex != -1) { field = subSegment.substring(0, subSegment.indexOf(fieldDelimeter)); subSegment = subSegment.substring(fieldDelimeterIndex + fieldDelimeter.length()); } else { field = subSegment; hasMoreFields = false; } String fieldId = field.substring(0, 2); String fieldDescription = NCPDPReference.getInstance().getDescription(fieldId, version); String fieldMessage = field.substring(2); if (inCount && !isRepeatingField(fieldDescription) && !fieldDescription.endsWith("Count")) { // if we are were in count field then end the element contentHandler.endElement("", fieldStack.pop(), ""); if (fieldStack.size() == 0) { inCount = false; } } if (fieldDescription.endsWith("Counter")) { if (inCounter) { contentHandler.endElement("", fieldStack.pop(), ""); } inCounter = true; AttributesImpl attr = new AttributesImpl(); attr.addAttribute("", "counter", "counter", "", fieldMessage); contentHandler.startElement("", fieldDescription, "", attr); fieldStack.push(fieldDescription); } else if (fieldDescription.endsWith("Count")) { // count field, add complex element inCount = true; AttributesImpl attr = new AttributesImpl(); attr.addAttribute("", fieldDescription, fieldDescription, "", fieldMessage); // start the repeating field element contentHandler.startElement("", fieldDescription, "", attr); fieldStack.push(fieldDescription); } else { contentHandler.startElement("", fieldDescription, "", null); contentHandler.characters(fieldMessage.toCharArray(), 0, fieldMessage.length()); contentHandler.endElement("", fieldDescription, ""); } } while (fieldStack.size() > 0) { // close remaining count and counters contentHandler.endElement("", fieldStack.pop(), ""); } contentHandler.endElement("", NCPDPReference.getInstance().getSegment(segmentId, version), ""); }
From source file:org.fornax.cartridges.sculptor.smartclient.server.ScServlet.java
private String mapObjToOutput(Object obj, int maxDepth, Stack<Object> serStack, boolean useGwtArray, boolean translateValue) { if (serStack.size() == 0) { log.log(Level.FINER, "Serializing START {0}", obj); }/*www . j a v a 2 s . c o m*/ // Avoid recursion if (serStack.size() == maxDepth && !(obj instanceof Date || obj instanceof Number || obj instanceof Boolean || obj instanceof CharSequence || obj instanceof Enum)) { String objId = getIdFromObj(obj); return objId == null ? Q + Q : objId; } if (serStack.contains(obj)) { return getIdFromObj(obj); // return Q+"ref: "+obj.getClass().getName()+"@"+obj.hashCode()+Q; } serStack.push(obj); String startArray = useGwtArray ? "$wnd.Array.create([" : "["; String endArray = useGwtArray ? "])" : "]"; StringBuilder recordData = new StringBuilder(); if (obj == null) { recordData.append("null"); } else if (obj instanceof Map) { recordData.append("{"); Map objMap = (Map) obj; String delim = ""; for (Object objKey : objMap.keySet()) { recordData.append(delim).append(objKey).append(":") .append(mapObjToOutput(objMap.get(objKey), maxDepth, serStack, useGwtArray, false)); delim = " , "; } recordData.append("}"); } else if (obj instanceof Collection) { recordData.append(startArray); Collection objSet = (Collection) obj; String delim = ""; for (Object objVal : objSet) { recordData.append(delim).append(mapObjToOutput(objVal, maxDepth, serStack, useGwtArray, false)); delim = " , "; } recordData.append(endArray); } else if (obj instanceof List) { recordData.append(startArray); List objList = (List) obj; String delim = ""; for (Object objVal : objList) { recordData.append(delim).append(mapObjToOutput(objVal, maxDepth, serStack, useGwtArray, false)); delim = " , "; } recordData.append(endArray); } else if (obj instanceof Object[]) { recordData.append(startArray); Object[] objArr = (Object[]) obj; String delim = ""; for (Object objVal : objArr) { recordData.append(delim).append(mapObjToOutput(objVal, maxDepth, serStack, useGwtArray, false)); delim = " , "; } recordData.append(endArray); } else if (obj instanceof Date) { Date objDate = (Date) obj; // recordData.append(Q+dateTimeFormat.format(objDate)+Q); recordData.append("new Date(" + objDate.getTime() + ")"); } else if (obj instanceof Boolean) { recordData.append(obj); } else if (obj instanceof Number) { recordData.append(obj); } else if (obj instanceof CharSequence) { String strObj = obj.toString(); if (strObj.startsWith(Main.JAVASCRIPT_PREFIX) && useGwtArray) { recordData.append(" ").append(strObj.substring(Main.JAVASCRIPT_PREFIX.length())); } else if (strObj.startsWith("function") && useGwtArray) { recordData.append(" ").append(strObj); } else { strObj = translateValue ? translate(strObj) : strObj; String escapeString = strObj.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\\\"") .replaceAll("\\r", "\\\\r").replaceAll("\\n", "\\\\n"); recordData.append(Q + escapeString + Q); } } else if (obj instanceof Enum) { String val = ((Enum) obj).name(); if (useGwtArray) { try { Method getValMethod = obj.getClass().getMethod("getValue", (Class[]) null); val = (String) getValMethod.invoke(obj, (Object[]) null); } catch (Exception e) { // no method getValue } } recordData.append(Q + val + Q); } else { String className = obj.getClass().getName(); ServiceDescription serviceForClass = findServiceByClassName(className); log.log(Level.FINER, "Serializing class {0}", className); if (serStack.size() > 2 && serviceForClass != null) { recordData.append(getIdFromObj(obj)); } else { // Use reflection recordData.append("{"); String delim = ""; String jsonPostfix = null; Method[] methods = obj.getClass().getMethods(); for (Method m : methods) { boolean translateThisValue = false; String mName; if (m.getName().startsWith(GET_TRANSLATE)) { translateThisValue = true; mName = m.getName().substring(GET_TRANSLATE_LENGTH); } else if (m.getName().startsWith("is")) { mName = m.getName().substring(2); } else { mName = m.getName().substring(3); } if (mName.length() > 1 && Character.isLowerCase(mName.charAt(1))) { mName = mName.substring(0, 1).toLowerCase() + mName.substring(1); } if (m.getName().startsWith("getJsonPostfix") && m.getParameterTypes().length == 0 && String.class.equals(m.getReturnType())) { try { jsonPostfix = (String) m.invoke(obj, new Object[] {}); } catch (Throwable e) { log.log(Level.FINE, "Mapping error", e); } } else if (!m.getDeclaringClass().getName().startsWith("org.hibernate") && m.getDeclaringClass() != Object.class && m.getDeclaringClass() != Class.class && (m.getName().startsWith("get") || m.getName().startsWith("is")) && m.getParameterTypes().length == 0 && m.getReturnType() != null && !isHiddenField(m.getDeclaringClass().getName(), mName)) { log.log(Level.FINEST, "Reflection invoking name={0} declaringClass={1} on {2}[{3}]", new Object[] { m.getName(), m.getDeclaringClass(), obj, obj.getClass() }); try { Object result = m.invoke(obj, new Object[] {}); if (result != null) { mName = mName.startsWith("xxx") ? mName.substring(3) : mName; String resultClassName = AopUtils.getTargetClass(result).getName(); String idVal = getIdFromObj(result); String valStr; if (findServiceByClassName(resultClassName) != null && idVal != null) { recordData.append(delim).append(mName).append(":").append(idVal); String refField = ds2Ref.get(resultClassName); if (refField != null) { Object realVal = getValFromObj(refField, result); valStr = realVal == null ? Q + Q : Q + realVal + Q; } else { valStr = Q + "UNKNOWN" + Q; } mName = mName + "_VAL"; delim = ", "; } else { valStr = mapObjToOutput(result, maxDepth, serStack, useGwtArray, translateThisValue); } recordData.append(delim).append(mName).append(":").append(valStr); delim = ", "; } } catch (Throwable e) { log.log(Level.FINE, "Mapping error", e); } } } if (jsonPostfix != null) { recordData.append(delim).append(jsonPostfix).append("}"); } else { recordData.append("}"); } } } serStack.pop(); return recordData.toString(); }
From source file:com.projity.pm.graphic.model.transform.NodeCacheTransformer.java
public void transfrom(List list) { model.clear();/*from ww w . j av a2s . c o m*/ if (list == null) return; boolean preserveHierarchy = transformer.isPreserveHierarchy(); if (!transformer.isShowSummary()) { preserveHierarchy = false; removeSummaries(list); } Map<GraphicNode, List<GraphicNode>> assignmentsMap = null; if (!transformer.isShowAssignments()) removeAssignments(list); if (!transformer.isShowEmptyLines()) removeVoids(list); if (transformer.isShowEmptyLines() && !transformer.isShowEndEmptyLines()) removeEndVoids(list); NodeTransformer composition = transformer.getTransformer(); NodeFilter hiddenFilter = transformer.getHiddenFilter(); if (hiddenFilter instanceof BaseFilter && !((BaseFilter) hiddenFilter).isActive()) hiddenFilter = null; //to avoid useless filtering in case of BaseFilter NodeFilter userFilter = (transformer.isNoneFilter()) ? null : transformer.getUserFilter(); boolean filtering = hiddenFilter != null || userFilter != null; NodeSorter sorter1 = transformer.getHiddenSorter(); NodeSorter sorter2 = transformer.getUserSorter(); boolean sorting = !(sorter1 == null && transformer.isNoneSorter()); NodeGrouper grouper = transformer.getUserGrouper(); boolean grouping = !transformer.isNoneGrouper(); if (!filtering && !sorting && !grouping) return; if (transformer.isShowAssignments() && preserveHierarchy && !transformer.isTreatAssignmentsAsTasks()) assignmentsMap = extractAssignments(list); List localList = null; Stack parents = null; boolean alreadyExcluded; if (preserveHierarchy) { localList = new ArrayList(); parents = new Stack(); } else localList = list; GraphicNode gnode, previous = null; Object current; for (Iterator i = list.iterator(); i.hasNext();) { gnode = (GraphicNode) i.next(); gnode.setFiltered(false); if (!gnode.isVoid()) { current = (composition == null) ? gnode.getNode() : composition.evaluate(gnode.getNode()); alreadyExcluded = false; if (hiddenFilter != null) { if (!hiddenFilter.evaluate(current)) { if (!gnode.isSummary() || !preserveHierarchy) { i.remove(); continue; } if (gnode.isSummary() && preserveHierarchy) gnode.setFiltered(true); alreadyExcluded = true; } } if (userFilter != null && !alreadyExcluded) { if (!userFilter.evaluate(current)) { if (!gnode.isSummary() || !preserveHierarchy) { i.remove(); continue; } if (gnode.isSummary() && preserveHierarchy) gnode.setFiltered(true); } } } if (preserveHierarchy) { //contruct a temporary tree for sorting and grouping // if (parents==null||previous==null){ // System.out.println("null"); // } if (gnode.getLevel() == 1) { localList.add(gnode); parents.clear(); } else { if (previous.getLevel() < gnode.getLevel()) { parents.push(previous); } else if (previous.getLevel() >= gnode.getLevel()) { while (parents.size() >= gnode.getLevel()) parents.pop(); } ((GraphicNode) parents.peek()).getChildren().add(gnode); } previous = gnode; } } //remove parents without children if (preserveHierarchy) { list.clear(); if (transformer.isShowEmptySummaries()) { if ("TaskUsage".equals(viewName)) filterBadBranches(localList); } else filterEmptySummaries(localList, false); } if (sorting) { if (sorter1 != null) sorter1.sortList(localList, new GraphicNodeComparator(sorter1, composition), preserveHierarchy); if (!transformer.isNoneSorter()) sorter2.sortList(localList, new GraphicNodeComparator(sorter2, composition), preserveHierarchy); } if (grouping) { List groups = grouper.getGroups(); levelOffset = groups.size(); List groupedList = new LinkedList(); groupList(localList, groupedList, groups.listIterator(), null, composition, preserveHierarchy); localList.clear(); localList.addAll(groupedList); } if (preserveHierarchy) { //converts tmp tree to list treeToList(localList, list); } if (assignmentsMap != null) recoverAssignments(list, assignmentsMap); // if (transformer.isShowEmptyLines()) // placeVoidNodes(list); }
From source file:org.apache.tajo.engine.planner.LogicalPlanner.java
@Override public LogicalNode visitJoin(PlanContext context, Stack<Expr> stack, Join join) throws PlanningException { // Phase 1: Init LogicalPlan plan = context.plan;/*from ww w.j a v a 2 s. c o m*/ QueryBlock block = context.queryBlock; if (join.hasQual()) { ExprNormalizedResult normalizedResult = normalizer.normalize(context, join.getQual(), true); block.namedExprsMgr.addExpr(normalizedResult.baseExpr); if (normalizedResult.aggExprs.size() > 0 || normalizedResult.scalarExprs.size() > 0) { throw new VerifyException("Filter condition cannot include aggregation function"); } } //////////////////////////////////////////////////////// // Visit and Build Child Plan //////////////////////////////////////////////////////// stack.push(join); LogicalNode left = visit(context, stack, join.getLeft()); LogicalNode right = visit(context, stack, join.getRight()); stack.pop(); //////////////////////////////////////////////////////// JoinNode joinNode = context.queryBlock.getNodeFromExpr(join); joinNode.setJoinType(join.getJoinType()); joinNode.setLeftChild(left); joinNode.setRightChild(right); // Set A merged input schema Schema merged; if (join.isNatural()) { merged = getNaturalJoinSchema(left, right); } else { merged = SchemaUtil.merge(left.getOutSchema(), right.getOutSchema()); } joinNode.setInSchema(merged); // Create EvalNode for a search condition. EvalNode joinCondition = null; if (join.hasQual()) { EvalNode evalNode = exprAnnotator.createEvalNode(context, join.getQual(), NameResolvingMode.LEGACY); joinCondition = context.evalOptimizer.optimize(context, evalNode); } List<String> newlyEvaluatedExprs = getNewlyEvaluatedExprsForJoin(context, joinNode, stack); List<Target> targets = TUtil.newList(PlannerUtil.schemaToTargets(merged)); for (String newAddedExpr : newlyEvaluatedExprs) { targets.add(block.namedExprsMgr.getTarget(newAddedExpr, true)); } joinNode.setTargets(targets.toArray(new Target[targets.size()])); // Determine join conditions if (join.isNatural()) { // if natural join, it should have the equi-join conditions by common column names EvalNode njCond = getNaturalJoinCondition(joinNode); joinNode.setJoinQual(njCond); } else if (join.hasQual()) { // otherwise, the given join conditions are set joinNode.setJoinQual(joinCondition); } return joinNode; }