List of usage examples for java.util Stack pop
public synchronized E pop()
From source file:org.apache.tajo.engine.planner.LogicalPlanner.java
@Override public LogicalNode visitGroupBy(PlanContext context, Stack<Expr> stack, Aggregation aggregation) throws PlanningException { // Initialization Phase: LogicalPlan plan = context.plan;//from w w w . j a va 2 s .c om QueryBlock block = context.queryBlock; // Normalize grouping keys and add normalized grouping keys to NamedExprManager int groupingKeyNum = aggregation.getGroupSet()[0].getGroupingSets().length; ExprNormalizedResult[] normalizedResults = new ExprNormalizedResult[groupingKeyNum]; for (int i = 0; i < groupingKeyNum; i++) { Expr groupingKey = aggregation.getGroupSet()[0].getGroupingSets()[i]; normalizedResults[i] = normalizer.normalize(context, groupingKey); } String[] groupingKeyRefNames = new String[groupingKeyNum]; for (int i = 0; i < groupingKeyNum; i++) { groupingKeyRefNames[i] = block.namedExprsMgr.addExpr(normalizedResults[i].baseExpr); block.namedExprsMgr.addNamedExprArray(normalizedResults[i].aggExprs); block.namedExprsMgr.addNamedExprArray(normalizedResults[i].scalarExprs); } //////////////////////////////////////////////////////// // Visit and Build Child Plan //////////////////////////////////////////////////////// stack.push(aggregation); LogicalNode child = visit(context, stack, aggregation.getChild()); stack.pop(); //////////////////////////////////////////////////////// GroupbyNode groupingNode = context.queryBlock.getNodeFromExpr(aggregation); groupingNode.setChild(child); groupingNode.setInSchema(child.getOutSchema()); // Set grouping sets List<Column> groupingColumns = Lists.newArrayList(); for (int i = 0; i < groupingKeyRefNames.length; i++) { String refName = groupingKeyRefNames[i]; if (context.getQueryBlock().isConstReference(refName)) { continue; } else if (block.namedExprsMgr.isEvaluated(groupingKeyRefNames[i])) { groupingColumns.add(block.namedExprsMgr.getTarget(groupingKeyRefNames[i]).getNamedColumn()); } else { throw new PlanningException("Each grouping column expression must be a scalar expression."); } } int effectiveGroupingKeyNum = groupingColumns.size(); groupingNode.setGroupingColumns(groupingColumns.toArray(new Column[effectiveGroupingKeyNum])); //////////////////////////////////////////////////////// // Visit and Build Child Plan //////////////////////////////////////////////////////// // create EvalNodes and check if each EvalNode can be evaluated here. List<String> aggEvalNames = TUtil.newList(); List<AggregationFunctionCallEval> aggEvalNodes = TUtil.newList(); boolean includeDistinctFunction = false; for (Iterator<NamedExpr> iterator = block.namedExprsMgr.getIteratorForUnevaluatedExprs(); iterator .hasNext();) { NamedExpr namedExpr = iterator.next(); try { includeDistinctFunction |= PlannerUtil.existsDistinctAggregationFunction(namedExpr.getExpr()); EvalNode evalNode = exprAnnotator.createEvalNode(context, namedExpr.getExpr(), NameResolvingMode.SUBEXPRS_AND_RELS); if (evalNode.getType() == EvalType.AGG_FUNCTION) { block.namedExprsMgr.markAsEvaluated(namedExpr.getAlias(), evalNode); aggEvalNames.add(namedExpr.getAlias()); aggEvalNodes.add((AggregationFunctionCallEval) evalNode); } } catch (VerifyException ve) { } } // if there is at least one distinct aggregation function groupingNode.setDistinct(includeDistinctFunction); groupingNode.setAggFunctions(aggEvalNodes.toArray(new AggregationFunctionCallEval[aggEvalNodes.size()])); Target[] targets = new Target[effectiveGroupingKeyNum + aggEvalNames.size()]; // In target, grouping columns will be followed by aggregation evals. // // col1, col2, col3, sum(..), agv(..) // ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^ // grouping keys aggregation evals // Build grouping keys for (int i = 0; i < effectiveGroupingKeyNum; i++) { Target target = block.namedExprsMgr.getTarget(groupingNode.getGroupingColumns()[i].getQualifiedName()); targets[i] = target; } for (int i = 0, targetIdx = effectiveGroupingKeyNum; i < aggEvalNodes.size(); i++, targetIdx++) { targets[targetIdx] = block.namedExprsMgr.getTarget(aggEvalNames.get(i)); } groupingNode.setTargets(targets); block.unsetAggregationRequire(); verifyProjectedFields(block, groupingNode); return groupingNode; }
From source file:org.apache.synapse.core.axis2.SynapseCallbackReceiver.java
/** * Handle the response or error (during a failed send) message received for an outgoing request * * @param messageID Request message ID * @param response the Axis2 MessageContext that has been received and has to be handled * @param synapseOutMsgCtx the corresponding (outgoing) Synapse MessageContext for the above * Axis2 MC, that holds Synapse specific information such as the error * handler stack and local properties etc. * @throws AxisFault if the message cannot be processed */// www . j a v a2 s. com private void handleMessage(String messageID, MessageContext response, org.apache.synapse.MessageContext synapseOutMsgCtx, AsyncCallback callback) throws AxisFault { // apply the tenant information to the out message context TenantInfoConfigurator configurator = synapseOutMsgCtx.getEnvironment().getTenantInfoConfigurator(); if (configurator != null) { configurator.applyTenantInfo(synapseOutMsgCtx); } Object o = response.getProperty(SynapseConstants.SENDING_FAULT); if (o != null && Boolean.TRUE.equals(o)) { StatisticsReporter.reportFaultForAll(synapseOutMsgCtx, ErrorLogFactory.createErrorLog(response)); // there is a sending fault. propagate the fault to fault handlers. Stack faultStack = synapseOutMsgCtx.getFaultStack(); if (faultStack != null && !faultStack.isEmpty()) { // if we have access to the full synapseOutMsgCtx.getEnvelope(), then let // it flow with the error details. Else, replace its envelope with the // fault envelope try { synapseOutMsgCtx.getEnvelope().build(); } catch (OMException x) { synapseOutMsgCtx.setEnvelope(response.getEnvelope()); } Exception e = (Exception) response.getProperty(SynapseConstants.ERROR_EXCEPTION); synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE); synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE, response.getProperty(SynapseConstants.ERROR_CODE)); synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_MESSAGE, response.getProperty(SynapseConstants.ERROR_MESSAGE)); synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_DETAIL, response.getProperty(SynapseConstants.ERROR_DETAIL)); synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_EXCEPTION, e); if (synapseOutMsgCtx.getEnvironment().isContinuationEnabled()) { synapseOutMsgCtx.setContinuationEnabled(true); ContinuationStackManager.clearStack(synapseOutMsgCtx); } if (log.isDebugEnabled()) { log.debug("[Failed Request Message ID : " + messageID + "]" + " [New to be Retried Request Message ID : " + synapseOutMsgCtx.getMessageID() + "]"); } int errorCode = (Integer) response.getProperty(SynapseConstants.ERROR_CODE); //If a timeout has occured and the timeout action of the callback is to discard the message if (errorCode == SynapseConstants.NHTTP_CONNECTION_TIMEOUT && callback.getTimeOutAction() == SynapseConstants.DISCARD) { //Do not execute any fault sequences. Discard message if (log.isWarnEnabled()) { log.warn("Synapse timed out for the request with Message ID : " + messageID + ". Ignoring fault handlers since the timeout action is DISCARD"); } faultStack.removeAllElements(); } else { ((FaultHandler) faultStack.pop()).handleFault(synapseOutMsgCtx, null); } } } else { // there can always be only one instance of an Endpoint in the faultStack of a message // if the send was successful, so remove it before we proceed any further Stack faultStack = synapseOutMsgCtx.getFaultStack(); Endpoint successfulEndpoint = null; if (faultStack != null && !faultStack.isEmpty() && faultStack.peek() instanceof Endpoint) { successfulEndpoint = (Endpoint) faultStack.pop(); } if (log.isDebugEnabled()) { log.debug("Synapse received an asynchronous response message"); log.debug("Received To: " + (response.getTo() != null ? response.getTo().getAddress() : "null")); log.debug("SOAPAction: " + (response.getSoapAction() != null ? response.getSoapAction() : "null")); log.debug("WSA-Action: " + (response.getWSAAction() != null ? response.getWSAAction() : "null")); String[] cids = response.getAttachmentMap().getAllContentIDs(); if (cids != null && cids.length > 0) { for (String cid : cids) { log.debug("Attachment : " + cid); } } log.debug("Body : \n" + response.getEnvelope()); } MessageContext axisOutMsgCtx = ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext(); //Processes 'Accept-Encoding' ResponseAcceptEncodingProcessor.process(response, axisOutMsgCtx); response.setServiceContext(null); response.setOperationContext(axisOutMsgCtx.getOperationContext()); response.setAxisMessage( axisOutMsgCtx.getAxisOperation().getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE)); // set properties on response response.setServerSide(true); response.setProperty(SynapseConstants.ISRESPONSE_PROPERTY, Boolean.TRUE); response.setProperty(MessageContext.TRANSPORT_OUT, axisOutMsgCtx.getProperty(MessageContext.TRANSPORT_OUT)); response.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO, axisOutMsgCtx.getProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO)); response.setTransportIn(axisOutMsgCtx.getTransportIn()); response.setTransportOut(axisOutMsgCtx.getTransportOut()); // If request is REST assume that the response is REST too response.setDoingREST(axisOutMsgCtx.isDoingREST()); if (axisOutMsgCtx.isDoingMTOM()) { response.setDoingMTOM(true); response.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE); } if (axisOutMsgCtx.isDoingSwA()) { response.setDoingSwA(true); response.setProperty(org.apache.axis2.Constants.Configuration.ENABLE_SWA, org.apache.axis2.Constants.VALUE_TRUE); } // when axis2 receives a soap message without addressing headers it users // DISABLE_ADDRESSING_FOR_OUT_MESSAGES property to keep it and hence avoid addressing // headers on the response. this causes a problem for synapse if the original message // it receivs (from client) has addressing and the synaspse service invocation has not // engage addressing. in this case when synapse receives the response from the server // addessing In handler dissable addressing since that response does not have addressing // headers. synapse sends the response to its orignal client using the same message // context. Then this response does not have addressing headers since it already // disable. to avoid this we need to set the DISABLE_ADDRESSING_FOR_OUT_MESSAGES // property state to original state. if (axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES) != null) { response.setProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, axisOutMsgCtx.getProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES)); } else { response.removeProperty(AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES); } Object messageType = axisOutMsgCtx.getProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); if (!HTTPConstants.MEDIA_TYPE_X_WWW_FORM.equals(messageType)) { // copy the message type property that's used by the out message to the // response message response.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, messageType); } // compare original received message (axisOutMsgCtx) soap version with the response // if they are different change to original version if (axisOutMsgCtx.isSOAP11() != response.isSOAP11()) { if (axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP12toSOAP11(response); } else { SOAPUtils.convertSOAP11toSOAP12(response); } } if (axisOutMsgCtx.getMessageID() != null) { response.setRelationships(new RelatesTo[] { new RelatesTo(axisOutMsgCtx.getMessageID()) }); } response.setReplyTo(axisOutMsgCtx.getReplyTo()); response.setFaultTo(axisOutMsgCtx.getFaultTo()); if (axisOutMsgCtx.isPropertyTrue(NhttpConstants.IGNORE_SC_ACCEPTED)) { response.setProperty(NhttpConstants.FORCE_SC_ACCEPTED, Constants.VALUE_TRUE); } // axis2 client options still contains properties such as policy files used in // outgoing request. Need to remove those. removeUnwantedClientOptions(response); // create the synapse message context for the response Axis2MessageContext synapseInMessageContext = new Axis2MessageContext(response, synapseOutMsgCtx.getConfiguration(), synapseOutMsgCtx.getEnvironment()); synapseInMessageContext.setResponse(true); Object obj = synapseOutMsgCtx.getProperty(SynapseConstants.FORCE_ERROR_PROPERTY); String errorOnSOAPFault = (String) obj; if (Constants.VALUE_TRUE.equals(errorOnSOAPFault) && successfulEndpoint != null) { if (log.isDebugEnabled()) { log.debug("FORCE_ERROR_ON_SOAP_FAULT is true, checking for SOAPFault"); } try { RelayUtils.buildMessage( ((Axis2MessageContext) synapseInMessageContext).getAxis2MessageContext(), true); } catch (Exception e) { // handleException("Error while building message", e, synapseInMessageContext); } if ((synapseInMessageContext.getEnvelope() != null) && synapseInMessageContext.getEnvelope().hasFault()) { if (log.isDebugEnabled()) { log.debug("SOAPFault found in response message, forcing endpoint " + successfulEndpoint.getName() + " to fail"); } //setup new pipe configuration..if failure happens (this will be setup as the source writer and during the TargetContext //clean up operation the writer will be reset and pull to the buffer MessageContext axis2OUTMC = ((Axis2MessageContext) synapseOutMsgCtx).getAxis2MessageContext(); NHttpServerConnection conn = (NHttpServerConnection) axis2OUTMC .getProperty("pass-through.Source-Connection"); if (conn != null) { SourceConfiguration sourceConfiguration = (SourceConfiguration) axis2OUTMC .getProperty("PASS_THROUGH_SOURCE_CONFIGURATION"); Pipe pipe = new Pipe(conn, sourceConfiguration.getBufferFactory().getBuffer(), "source", sourceConfiguration); axis2OUTMC.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe); } StatisticsReporter.reportFaultForAll(synapseOutMsgCtx, ErrorLogFactory.createErrorLog(response)); synapseOutMsgCtx.setProperty(SynapseConstants.SENDING_FAULT, Boolean.TRUE); synapseOutMsgCtx.setProperty(SynapseConstants.ERROR_CODE, SynapseConstants.ENDPOINT_CUSTOM_ERROR); boolean failOver = false; if (successfulEndpoint instanceof AbstractEndpoint) { Endpoint endpoint = ((AbstractEndpoint) successfulEndpoint).getParentEndpoint(); if (endpoint != null && (endpoint instanceof FailoverEndpoint)) { failOver = true; } } // set the properties of the original MC to the new MC for (Object key : synapseOutMsgCtx.getPropertyKeySet()) { synapseInMessageContext.setProperty((String) key, synapseOutMsgCtx.getProperty((String) key)); } if (failOver) { //we may required to handle same message for failover cases only other than that //should treat based on the incoming message ((FaultHandler) successfulEndpoint).handleFault(synapseOutMsgCtx, null); } else { faultStack = synapseOutMsgCtx.getFaultStack(); if (faultStack != null) { synapseInMessageContext.getFaultStack().addAll(faultStack); ((FaultHandler) successfulEndpoint).handleFault(synapseInMessageContext, null); } } return; } else { successfulEndpoint.onSuccess(); } } else if (successfulEndpoint != null) { successfulEndpoint.onSuccess(); } synapseInMessageContext.setTo(new EndpointReference(AddressingConstants.Final.WSA_ANONYMOUS_URL)); synapseInMessageContext.setTracingState(synapseOutMsgCtx.getTracingState()); // set the properties of the original MC to the new MC for (Object key : synapseOutMsgCtx.getPropertyKeySet()) { synapseInMessageContext.setProperty((String) key, synapseOutMsgCtx.getProperty((String) key)); } // Copy SequenceCallStack from original MC to the new MC Boolean isContinuationCall = (Boolean) synapseOutMsgCtx.getProperty(SynapseConstants.CONTINUATION_CALL); if (isContinuationCall != null && isContinuationCall) { // Set the message direction if (!synapseOutMsgCtx.isResponse()) { synapseInMessageContext.setResponse(false); } Stack<ContinuationState> seqContinuationStates = synapseOutMsgCtx.getContinuationStateStack(); for (int i = 0; i < seqContinuationStates.size(); i++) { synapseInMessageContext.pushContinuationState(seqContinuationStates.get(i)); } } Boolean isConcurrencyThrottleEnabled = (Boolean) synapseOutMsgCtx .getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE); if (isConcurrencyThrottleEnabled != null && isConcurrencyThrottleEnabled) { ConcurrentAccessController concurrentAccessController = (ConcurrentAccessController) synapseOutMsgCtx .getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_CONTROLLER); int available = concurrentAccessController.incrementAndGet(); int concurrentLimit = concurrentAccessController.getLimit(); if (log.isDebugEnabled()) { log.debug("Concurrency Throttle : Connection returned" + " :: " + available + " of available of " + concurrentLimit + " connections"); } ConcurrentAccessReplicator concurrentAccessReplicator = (ConcurrentAccessReplicator) synapseOutMsgCtx .getProperty(SynapseConstants.SYNAPSE_CONCURRENT_ACCESS_REPLICATOR); String throttleKey = (String) synapseOutMsgCtx .getProperty(SynapseConstants.SYNAPSE_CONCURRENCY_THROTTLE_KEY); if (concurrentAccessReplicator != null) { concurrentAccessReplicator.replicate(throttleKey, concurrentAccessController); } } // If this response is related to session affinity endpoints -Server initiated session Dispatcher dispatcher = (Dispatcher) synapseOutMsgCtx .getProperty(SynapseConstants.PROP_SAL_ENDPOINT_CURRENT_DISPATCHER); if (dispatcher != null && dispatcher.isServerInitiatedSession()) { dispatcher.updateSession(synapseInMessageContext); } StatisticsReporter.reportForAllOnResponseReceived(synapseInMessageContext); // send the response message through the synapse mediation flow try { synapseOutMsgCtx.getEnvironment().injectMessage(synapseInMessageContext); } catch (SynapseException syne) { Stack stack = synapseInMessageContext.getFaultStack(); if (stack != null && !stack.isEmpty()) { ((FaultHandler) stack.pop()).handleFault(synapseInMessageContext, syne); } else { log.error("Synapse encountered an exception, " + "No error handlers found - [Message Dropped]\n" + syne.getMessage()); } } } }
From source file:com.sun.socialsite.pojos.PropDefinition.java
protected void init(PropDefinition profileDef, InputStream input) throws SocialSiteException { try {/* ww w . j av a2 s . c om*/ XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader parser = factory.createXMLStreamReader(input); String ns = null; // TODO: namespace for ProfileDef // hold the current things we're working on Map<String, DisplaySectionDefinition> sdefs = new LinkedHashMap<String, DisplaySectionDefinition>(); Stack<PropertyDefinitionHolder> propertyHolderStack = new Stack<PropertyDefinitionHolder>(); List<AllowedValue> allowedValues = null; PropertyDefinition pdef = null; for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) { switch (event) { case XMLStreamConstants.START_ELEMENT: log.debug("START ELEMENT -- " + parser.getLocalName()); if ("display-section".equals(parser.getLocalName())) { propertyHolderStack.push(new DisplaySectionDefinition(parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey"))); } else if ("property".equals(parser.getLocalName())) { PropertyDefinitionHolder holder = propertyHolderStack.peek(); pdef = new PropertyDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey"), parser.getAttributeValue(ns, "type")); } else if ("object".equals(parser.getLocalName())) { PropertyDefinitionHolder holder = propertyHolderStack.peek(); propertyHolderStack.push(new PropertyObjectDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey"))); } else if ("collection".equals(parser.getLocalName())) { PropertyDefinitionHolder holder = propertyHolderStack.peek(); propertyHolderStack.push(new PropertyObjectCollectionDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey"))); } else if ("allowed-values".equals(parser.getLocalName())) { allowedValues = new ArrayList<AllowedValue>(); } else if ("value".equals(parser.getLocalName())) { AllowedValue allowedValue = new AllowedValue(parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")); allowedValues.add(allowedValue); } else if ("default-value".equals(parser.getLocalName())) { pdef.setDefaultValue(parser.getText()); } break; case XMLStreamConstants.END_ELEMENT: log.debug("END ELEMENT -- " + parser.getLocalName()); if ("display-section".equals(parser.getLocalName())) { DisplaySectionDefinition sdef = (DisplaySectionDefinition) propertyHolderStack.pop(); sdefs.put(sdef.getName(), sdef); } else if ("property".equals(parser.getLocalName())) { PropertyDefinitionHolder holder = propertyHolderStack.peek(); holder.getPropertyDefinitions().add(pdef); propertyDefs.put(pdef.getName(), pdef); pdef = null; } else if ("object".equals(parser.getLocalName())) { PropertyObjectDefinition odef = (PropertyObjectDefinition) propertyHolderStack.pop(); PropertyDefinitionHolder holder = propertyHolderStack.peek(); holder.getPropertyObjectDefinitions().add(odef); // add to list of all property object defs propertyObjectDefs.put(odef.getName(), odef); odef = null; } else if ("collection".equals(parser.getLocalName())) { PropertyObjectCollectionDefinition cdef = (PropertyObjectCollectionDefinition) propertyHolderStack .pop(); PropertyDefinitionHolder holder = propertyHolderStack.peek(); holder.getPropertyObjectCollectionDefinitions().add(cdef); // add to list of all property object defs propertyObjectCollectionDefs.put(cdef.getName(), cdef); cdef = null; } else if ("allowed-values".equals(parser.getLocalName())) { pdef.setAllowedValues(allowedValues); allowedValues = null; } break; case XMLStreamConstants.CHARACTERS: break; case XMLStreamConstants.CDATA: break; } // end switch } // end while parser.close(); profileDef.sectionDefs = sdefs; } catch (Exception ex) { throw new SocialSiteException("ERROR parsing profile definitions", ex); } }
From source file:com.joliciel.jochre.graphics.SegmenterImpl.java
void findContiguousPixels(ImageGrid sourceImage, WritableImageGrid mirror, Shape shape, int x, int y, int blackThreshold) { // let's imagine // 0 X 0 0 x x // x x x 0 0 x // 0 0 x x x x // so we have to go up and to the left to keep finding contiguous black pixels. Stack<int[]> pointStack = new Stack<int[]>(); pointStack.push(new int[] { x, y }); while (!pointStack.isEmpty()) { int[] point = pointStack.pop(); x = point[0];//w ww. j ava 2 s .c om y = point[1]; // Add this pixel to the mirror so that we don't touch it again. mirror.setPixel(x, y, 1); for (int rely = y - 1; rely <= y + 1; rely++) { for (int relx = x - 1; relx <= x + 1; relx++) { if (mirror.getPixel(relx, rely) > 0) continue; if (sourceImage.isPixelBlack(relx, rely, blackThreshold)) { if (relx < shape.getLeft()) shape.setLeft(relx); if (relx > shape.getRight()) shape.setRight(relx); if (rely > shape.getBottom()) shape.setBottom(rely); // we don't have to check top, cause it's all going // from top to bottom. pointStack.push(new int[] { relx, rely }); } } } } }
From source file:com.hippo.vectorold.drawable.VectorDrawable.java
private void inflateInternal(Resources res, XmlPullParser parser, AttributeSet attrs) 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); currentGroup.mChildren.add(path); if (path.getPathName() != null) { pathRenderer.mVGTargetsMap.put(path.getPathName(), path); }//from w w w .j av a2s.c om noPathTag = false; state.mChangingConfigurations |= path.mChangingConfigurations; } else if (SHAPE_CLIP_PATH.equals(tagName)) { final VClipPath path = new VClipPath(); path.inflate(res, attrs); 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); 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:org.apache.tajo.engine.planner.LogicalPlanner.java
@Override public LogicalNode visitProjection(PlanContext context, Stack<Expr> stack, Projection projection) throws PlanningException { LogicalPlan plan = context.plan;// w w w .j av a 2 s . c o m QueryBlock block = context.queryBlock; // If a non-from statement is given if (!projection.hasChild()) { return buildPlanForNoneFromStatement(context, stack, projection); } String[] referenceNames; // in prephase, insert all target list into NamedExprManagers. // Then it gets reference names, each of which points an expression in target list. Pair<String[], ExprNormalizer.WindowSpecReferences[]> referencesPair = doProjectionPrephase(context, projection); referenceNames = referencesPair.getFirst(); //////////////////////////////////////////////////////// // Visit and Build Child Plan //////////////////////////////////////////////////////// stack.push(projection); LogicalNode child = visit(context, stack, projection.getChild()); // check if it is implicit aggregation. If so, it inserts group-by node to its child. if (block.isAggregationRequired()) { child = insertGroupbyNode(context, child, stack); } if (block.hasWindowSpecs()) { LogicalNode windowAggNode = insertWindowAggNode(context, child, stack, referenceNames, referencesPair.getSecond()); if (windowAggNode != null) { child = windowAggNode; } } stack.pop(); //////////////////////////////////////////////////////// ProjectionNode projectionNode; Target[] targets; targets = buildTargets(context, referenceNames); // Set ProjectionNode projectionNode = context.queryBlock.getNodeFromExpr(projection); projectionNode.setInSchema(child.getOutSchema()); projectionNode.setTargets(targets); projectionNode.setChild(child); if (projection.isDistinct() && block.hasNode(NodeType.GROUP_BY)) { throw new VerifyException("Cannot support grouping and distinct at the same time yet"); } else { if (projection.isDistinct()) { insertDistinctOperator(context, projectionNode, child, stack); } } // It's for debugging and unit tests purpose. // It sets raw targets, all of them are raw expressions instead of references. if (context.debugOrUnitTests) { setRawTargets(context, targets, referenceNames, projection); } verifyProjectedFields(block, projectionNode); return projectionNode; }
From source file:gdt.data.store.Entigrator.java
/** * List containers of the entity // w ww .j a v a 2s .c o m * @param entity the entity. * @return the array of keys of containers. */ public String[] ent_listContainers(Sack entity) { if (entity == null) { // LOGGER.severe(":ent_listContainers:entity is null"); return null; } Core[] ca = entity.elementGet("container"); if (ca == null) { // LOGGER.info(":ent_listContainers:no 'container' element in entity=" + entity.getProperty("label")); return null; } Stack<String> s = new Stack<String>(); Sack container; boolean modified = false; for (Core aCa : ca) { if (entity.getKey().equals(aCa.value)) continue; container = getMember("entity.base", aCa.value); if (container == null) { entity.removeElementItem("container", aCa.name); modified = true; continue; } s.push(aCa.value); } if (modified) save(entity); int cnt = s.size(); if (cnt < 1) { //LOGGER.info(":ent_listContainers:empty 'container' element in entity=" + entity.getProperty("label")); return null; } String[] sa = new String[cnt]; for (int i = 0; i < cnt; i++) sa[i] = s.pop(); return sa; }
From source file:com.concursive.connect.web.webdav.servlets.WebdavServlet.java
/** * PROPFIND Method.//ww w . j a v a2s . c o m * * @param context Description of the Parameter * @throws javax.servlet.ServletException Description of the Exception * @throws java.io.IOException Description of the Exception */ protected void doPropfind(ActionContext context) throws ServletException, IOException { String path = getRelativePath(context.getRequest()); //fix for windows clients if (path.equals("/files")) { path = ""; } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) { context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN); return; } // Properties which are to be displayed. Vector properties = null; // Propfind depth int depth = INFINITY; // Propfind type int type = FIND_ALL_PROP; String depthStr = context.getRequest().getHeader("Depth"); if (depthStr == null) { depth = INFINITY; } else { if (depthStr.equals("0")) { depth = 0; } else if (depthStr.equals("1")) { depth = 1; } else if (depthStr.equals("infinity")) { depth = INFINITY; } } /* * Read the request xml and determine all the properties */ /* Node propNode = null; DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse (new InputSource(context.getRequest().getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); NodeList childList = rootElement.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: if (currentNode.getNodeName().endsWith("prop")) { type = FIND_BY_PROPERTY; propNode = currentNode; } if (currentNode.getNodeName().endsWith("propname")) { type = FIND_PROPERTY_NAMES; } if (currentNode.getNodeName().endsWith("allprop")) { type = FIND_ALL_PROP; } break; } } } catch (Exception e) { // Most likely there was no content : we use the defaults. // TODO : Enhance that ! e.printStackTrace(System.out); } if (type == FIND_BY_PROPERTY) { properties = new Vector(); NodeList childList = propNode.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); String propertyName = null; if (nodeName.indexOf(':') != -1) { propertyName = nodeName.substring (nodeName.indexOf(':') + 1); } else { propertyName = nodeName; } // href is a live property which is handled differently properties.addElement(propertyName); break; } } } */ // Properties have been determined // Retrieve the resources Connection db = null; boolean exists = true; boolean status = true; Object object = null; ModuleContext resources = null; StringBuffer xmlsb = new StringBuffer(); try { db = this.getConnection(context); resources = getCFSResources(db, context); if (resources == null) { context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } object = resources.lookup(db, path); } catch (NamingException e) { //e.printStackTrace(System.out); exists = false; int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector currentLockNullResources = (Vector) lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = (String) lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS); context.getResponse().setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING); parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type, properties); generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); //e.printStackTrace(System.out); return; } } } } } catch (SQLException e) { e.printStackTrace(System.out); context.getResponse().sendError(SQLERROR, e.getMessage()); status = false; } finally { this.freeConnection(db, context); } if (!status) { return; } if (!exists) { context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, path); return; } context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS); context.getResponse().setContentType("text/xml; charset=UTF-8"); // Create multistatus object ////System.out.println("Creating Multistatus Object"); XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING); //System.out.println("Depth: " + depth); if (depth == 0) { parseProperties(context, resources, generatedXML, path, type, properties); } else { // The stack always contains the object of the current level Stack stack = new Stack(); stack.push(path); // Stack of the objects one level below Stack stackBelow = new Stack(); while ((!stack.isEmpty()) && (depth >= 0)) { String currentPath = (String) stack.pop(); if (!currentPath.equals(path)) { parseProperties(context, resources, generatedXML, currentPath, type, properties); } try { db = this.getConnection(context); object = resources.lookup(db, currentPath); } catch (NamingException e) { continue; } catch (SQLException e) { //e.printStackTrace(System.out); context.getResponse().sendError(SQLERROR, e.getMessage()); status = false; } finally { this.freeConnection(db, context); } if (!status) { return; } if ((object instanceof ModuleContext) && depth > 0) { // Get a list of all the resources at the current path and store them // in the stack try { NamingEnumeration enum1 = resources.list(currentPath); int count = 0; while (enum1.hasMoreElements()) { NameClassPair ncPair = (NameClassPair) enum1.nextElement(); String newPath = currentPath; if (!(newPath.endsWith("/"))) { newPath += "/"; } newPath += ncPair.getName(); stackBelow.push(newPath); count++; } if (currentPath.equals(path) && count == 0) { // This directory does not have any files or folders. parseProperties(context, resources, generatedXML, properties); } } catch (NamingException e) { //e.printStackTrace(System.out); context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } // Displaying the lock-null resources present in that collection String lockPath = currentPath; if (lockPath.endsWith("/")) { lockPath = lockPath.substring(0, lockPath.length() - 1); } Vector currentLockNullResources = (Vector) lockNullResources.get(lockPath); if (currentLockNullResources != null) { Enumeration lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = (String) lockNullResourcesList.nextElement(); System.out.println("Lock null path: " + lockNullPath); parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type, properties); } } } if (stack.isEmpty()) { depth--; stack = stackBelow; stackBelow = new Stack(); } xmlsb.append(generatedXML.toString()); //System.out.println("xml : " + generatedXML.toString()); generatedXML.sendData(); } } generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING); xmlsb.append(generatedXML.toString()); generatedXML.sendData(); //System.out.println("xml: " + xmlsb.toString()); }
From source file:hudson.model.Hudson.java
/** * Gets all the {@link Item}s recursively in the {@link ItemGroup} tree * and filter them by the given type.//from www .ja va2 s . c o m */ public <T extends Item> List<T> getAllItems(Class<T> type) { List<T> r = new ArrayList<T>(); Stack<ItemGroup> q = new Stack<ItemGroup>(); q.push(this); while (!q.isEmpty()) { ItemGroup<?> parent = q.pop(); for (Item i : parent.getItems()) { if (type.isInstance(i)) { if (i.hasPermission(Item.READ)) r.add(type.cast(i)); } if (i instanceof ItemGroup) q.push((ItemGroup) i); } } return r; }