List of usage examples for java.util Stack peek
public synchronized E peek()
From source file:org.ohmage.db.DbHelper.java
/** * Utility method that populates the Survey and SurveyPrompt tables for the * campaign identified by campaignUrn and containing the given xml as * campaignXML./*from w w w . j av a2 s.com*/ * * Note that this method takes a db handle so that it can be used in a * transaction. * * @param db * a handle to an existing writable db * @param campaignUrn * the urn of the campaign for which we're populating subtables * @param campaignXML * the XML for the campaign (not validated by this method) * @return * */ public boolean populateSurveysFromCampaignXML(SQLiteDatabase db, String campaignUrn, String campaignXML) { try { // dump all the surveys (and consequently survey prompts) before we // do anything // this is (perhaps surprisingly) desired behavior, as the surveys + // survey prompts // should always reflect the state of the campaign XML, valid or not db.delete(Tables.SURVEYS, Surveys.CAMPAIGN_URN + "=?", new String[] { campaignUrn }); // do a pass over the XML to gather surveys and survey prompts XmlPullParser xpp = Xml.newPullParser(); xpp.setInput(new ByteArrayInputStream(campaignXML.getBytes("UTF-8")), "UTF-8"); int eventType = xpp.getEventType(); String tagName; // various stacks to maintain state while walking through the xml // tree Stack<String> tagStack = new Stack<String>(); Survey curSurvey = null; // valid only within a survey, null // otherwise Vector<SurveyPrompt> prompts = new Vector<SurveyPrompt>(); // valid // only // within // a // survey, // empty // otherwise Vector<JSONObject> properties = new Vector<JSONObject>(); // valid // only // within // a // prompt, // empty // otherwise // iterate through the xml, paying attention only to surveys and // prompts // note that this does no validation outside of preventing itself // from crashing catastrophically while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { tagName = xpp.getName(); tagStack.push(tagName); if (tagName.equalsIgnoreCase("survey")) { if (curSurvey != null) throw new XmlPullParserException("encountered a survey tag inside another survey tag"); curSurvey = new Survey(); curSurvey.mCampaignUrn = campaignUrn; } else if (tagName.equalsIgnoreCase("prompt")) { SurveyPrompt sp = new SurveyPrompt(); // FIXME: add the campaign + survey ID to make lookups // easier? prompts.add(sp); } else if (tagName.equalsIgnoreCase("property")) { properties.add(new JSONObject()); } } else if (eventType == XmlPullParser.TEXT) { if (tagStack.size() >= 2) { // we may be in an entity>property situation, so check // and assign accordingly if (tagStack.get(tagStack.size() - 2).equalsIgnoreCase("survey")) { // populating the current survey object with its // properties here if (tagStack.peek().equalsIgnoreCase("id")) curSurvey.mSurveyID = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("title")) curSurvey.mTitle = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("description")) curSurvey.mDescription = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("submitText")) curSurvey.mSubmitText = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("showSummary")) curSurvey.mShowSummary = xpp.getText().equals("true") ? true : false; else if (tagStack.peek().equalsIgnoreCase("editSummary")) curSurvey.mEditSummary = xpp.getText().equals("true") ? true : false; else if (tagStack.peek().equalsIgnoreCase("summaryText")) curSurvey.mSummaryText = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("introText")) curSurvey.mIntroText = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("anytime")) curSurvey.mAnytime = xpp.getText().equals("true") ? true : false; } else if (tagStack.get(tagStack.size() - 2).equalsIgnoreCase("prompt")) { SurveyPrompt sp = prompts.lastElement(); // populating the last encountered survey prompt // with its properties here if (tagStack.peek().equalsIgnoreCase("id")) sp.mPromptID = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("promptText")) sp.mPromptText = xpp.getText(); else if (tagStack.peek().equalsIgnoreCase("promptType")) sp.mPromptType = xpp.getText(); } else if (tagStack.get(tagStack.size() - 2).equalsIgnoreCase("property")) { JSONObject curProperty = properties.lastElement(); // populating the last encountered property if (tagStack.peek().equalsIgnoreCase("key")) curProperty.put("key", xpp.getText()); else if (tagStack.peek().equalsIgnoreCase("label")) curProperty.put("label", xpp.getText()); else if (tagStack.peek().equalsIgnoreCase("value")) curProperty.put("value", xpp.getText()); } } } else if (eventType == XmlPullParser.END_TAG) { tagName = xpp.getName(); tagStack.pop(); if (tagName.equalsIgnoreCase("survey")) { // store the current survey to the database long surveyPID = db.insert(Tables.SURVEYS, null, curSurvey.toCV()); // also store all the prompts we accumulated for it for (SurveyPrompt sp : prompts) { sp.mSurveyID = curSurvey.mSurveyID; sp.mSurveyPID = surveyPID; sp.mCompositeID = curSurvey.mCampaignUrn + ":" + curSurvey.mSurveyID; db.insert(Tables.SURVEY_PROMPTS, null, sp.toCV()); } // flush the prompts we've stored up so far prompts.clear(); // Create Streams here OhmagePDVManager.getInstance().createStreamForSurvey(campaignUrn, curSurvey.mSurveyID); // and clear us from being in any survey curSurvey = null; } else if (tagName.equalsIgnoreCase("prompt")) { SurveyPrompt sp = prompts.lastElement(); // update the current prompt with the collected // properties JSONArray propertyArray = new JSONArray(); for (JSONObject property : properties) propertyArray.put(property); // encode it as json and stuff it in the surveyprompt sp.mProperties = propertyArray.toString(); // and wipe the properties properties.clear(); } } eventType = xpp.next(); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; }
From source file:com.udojava.evalex.Expression.java
/** * Implementation of the <i>Shunting Yard</i> algorithm to transform an * infix expression to a RPN expression. * * @param expression The input expression in infx. * @return A RPN representation of the expression, with each token as a list * member.//from w w w . jav a 2 s . c o m */ private List<String> shuntingYard(String expression) { List<String> outputQueue = new ArrayList<>(); Stack<String> stack = new Stack<>(); Tokenizer tokenizer = new Tokenizer(expression); String lastFunction = null; String previousToken = null; while (tokenizer.hasNext()) { String token = tokenizer.next(); if (isNumber(token)) { if (token.startsWith("x")) { BigInteger bd = new BigInteger(token.substring(1), 16); outputQueue.add(bd.toString(10)); } else if (token.startsWith("b")) { BigInteger bd = new BigInteger(token.substring(1), 2); outputQueue.add(bd.toString(10)); } else if (token.startsWith("o")) { BigInteger bd = new BigInteger(token.substring(1), 8); outputQueue.add(bd.toString(10)); } else { outputQueue.add(token); } } else if (mainVars.containsKey(token)) { outputQueue.add(token); } else if (functions.containsKey(token.toUpperCase(Locale.ROOT))) { stack.push(token); lastFunction = token; } else if ((Character.isLetter(token.charAt(0)) || token.charAt(0) == '_') && !operators.containsKey(token)) { mainVars.put(token, new MyComplex(0, 0)); // create variable outputQueue.add(token); //stack.push(token); } else if (",".equals(token)) { if (operators.containsKey(previousToken)) { throw new ExpressionException("Missing parameter(s) for operator " + previousToken + " at character position " + (tokenizer.getPos() - 1 - previousToken.length())); } while (!stack.isEmpty() && !"(".equals(stack.peek())) { outputQueue.add(stack.pop()); } if (stack.isEmpty()) { throw new ExpressionException("Parse error for function '" + lastFunction + "'"); } } else if (operators.containsKey(token)) { if (",".equals(previousToken) || "(".equals(previousToken)) { throw new ExpressionException("Missing parameter(s) for operator " + token + " at character position " + (tokenizer.getPos() - token.length())); } Operator o1 = operators.get(token); String token2 = stack.isEmpty() ? null : stack.peek(); while (token2 != null && operators.containsKey(token2) && ((o1.isLeftAssoc() && o1.getPrecedence() <= operators.get(token2).getPrecedence()) || (o1.getPrecedence() < operators.get(token2).getPrecedence()))) { outputQueue.add(stack.pop()); token2 = stack.isEmpty() ? null : stack.peek(); } stack.push(token); } else if ("(".equals(token)) { if (previousToken != null) { if (isNumber(previousToken)) { throw new ExpressionException( "Missing operator at character position " + tokenizer.getPos()); } // if the ( is preceded by a valid function, then it // denotes the start of a parameter list if (functions.containsKey(previousToken.toUpperCase(Locale.ROOT))) { outputQueue.add(token); } } stack.push(token); } else if (")".equals(token)) { if (operators.containsKey(previousToken)) { throw new ExpressionException("Missing parameter(s) for operator " + previousToken + " at character position " + (tokenizer.getPos() - 1 - previousToken.length())); } while (!stack.isEmpty() && !"(".equals(stack.peek())) { outputQueue.add(stack.pop()); } if (stack.isEmpty()) { throw new ExpressionException("Mismatched parentheses"); } stack.pop(); if (!stack.isEmpty() && functions.containsKey(stack.peek().toUpperCase(Locale.ROOT))) { outputQueue.add(stack.pop()); } } previousToken = token; } while (!stack.isEmpty()) { String element = stack.pop(); if ("(".equals(element) || ")".equals(element)) { throw new ExpressionException("Mismatched parentheses"); } if (!operators.containsKey(element)) { throw new ExpressionException("Unknown operator or function: " + element); } outputQueue.add(element); } return outputQueue; }
From source file:org.apache.tajo.engine.planner.rewrite.ProjectionPushDownRule.java
@Override public LogicalNode visitProjection(Context context, LogicalPlan plan, LogicalPlan.QueryBlock block, ProjectionNode node, Stack<LogicalNode> stack) throws PlanningException { Context newContext = new Context(context); Target[] targets = node.getTargets(); int targetNum = targets.length; String[] referenceNames = new String[targetNum]; for (int i = 0; i < targetNum; i++) { referenceNames[i] = newContext.addExpr(targets[i]); }/* w w w .j a va2 s. co m*/ LogicalNode child = super.visitProjection(newContext, plan, block, node, stack); node.setInSchema(child.getOutSchema()); int evaluationCount = 0; List<Target> finalTargets = TUtil.newList(); for (String referenceName : referenceNames) { Target target = context.targetListMgr.getTarget(referenceName); if (target.getEvalTree().getType() == EvalType.CONST) { finalTargets.add(target); } else if (context.targetListMgr.isEvaluated(referenceName)) { if (context.targetListMgr.isNativeAlias(referenceName)) { String realRefName = context.targetListMgr.getRealReferenceName(referenceName); finalTargets.add(new Target(new FieldEval(realRefName, target.getDataType()), referenceName)); } else { finalTargets.add(new Target(new FieldEval(target.getNamedColumn()))); } } else if (LogicalPlanner.checkIfBeEvaluatedAtThis(target.getEvalTree(), node)) { finalTargets.add(target); context.targetListMgr.markAsEvaluated(target); evaluationCount++; } } node.setTargets(finalTargets.toArray(new Target[finalTargets.size()])); LogicalPlanner.verifyProjectedFields(block, node); // Removing ProjectionNode // TODO - Consider INSERT and CTAS statement, and then remove the check of stack.empty. if (evaluationCount == 0 && PlannerUtil.targetToSchema(finalTargets).equals(child.getOutSchema())) { if (stack.empty()) { // if it is topmost, set it as the root of this block. block.setRoot(child); } else { LogicalNode parentNode = stack.peek(); switch (parentNode.getType()) { case ROOT: LogicalRootNode rootNode = (LogicalRootNode) parentNode; rootNode.setChild(child); rootNode.setInSchema(child.getOutSchema()); rootNode.setOutSchema(child.getOutSchema()); break; case TABLE_SUBQUERY: TableSubQueryNode tableSubQueryNode = (TableSubQueryNode) parentNode; tableSubQueryNode.setSubQuery(child); break; case STORE: StoreTableNode storeTableNode = (StoreTableNode) parentNode; storeTableNode.setChild(child); storeTableNode.setInSchema(child.getOutSchema()); break; case INSERT: InsertNode insertNode = (InsertNode) parentNode; insertNode.setSubQuery(child); break; case CREATE_TABLE: CreateTableNode createTableNode = (CreateTableNode) parentNode; createTableNode.setChild(child); createTableNode.setInSchema(child.getOutSchema()); break; default: throw new PlanningException("Unexpected Parent Node: " + parentNode.getType()); } plan.addHistory("ProjectionNode is eliminated."); } return child; } else { return node; } }
From source file:org.apache.tajo.plan.rewrite.rules.ProjectionPushDownRule.java
@Override public LogicalNode visitProjection(Context context, LogicalPlan plan, LogicalPlan.QueryBlock block, ProjectionNode node, Stack<LogicalNode> stack) throws TajoException { Context newContext = new Context(context); List<Target> targets = node.getTargets(); int targetNum = targets.size(); String[] referenceNames = new String[targetNum]; for (int i = 0; i < targetNum; i++) { referenceNames[i] = newContext.addExpr(targets.get(i)); }//from www.j a v a 2 s . co m LogicalNode child = super.visitProjection(newContext, plan, block, node, stack); node.setInSchema(child.getOutSchema()); int evaluationCount = 0; List<Target> finalTargets = new ArrayList<>(); for (String referenceName : referenceNames) { Target target = context.targetListMgr.getTarget(referenceName); if (target.getEvalTree().getType() == EvalType.CONST) { finalTargets.add(target); } else if (context.targetListMgr.isEvaluated(referenceName)) { if (context.targetListMgr.isNativeAlias(referenceName)) { String realRefName = context.targetListMgr.getRealReferenceName(referenceName); finalTargets.add(new Target(new FieldEval(realRefName, target.getDataType()), referenceName)); } else { finalTargets.add(new Target(new FieldEval(target.getNamedColumn()))); } } else if (LogicalPlanner.checkIfBeEvaluatedAtThis(target.getEvalTree(), node)) { finalTargets.add(target); context.targetListMgr.markAsEvaluated(target); evaluationCount++; } } node.setTargets(finalTargets); LogicalPlanner.verifyProjectedFields(block, node); // Removing ProjectionNode // TODO - Consider INSERT and CTAS statement, and then remove the check of stack.empty. if (evaluationCount == 0 && PlannerUtil.targetToSchema(finalTargets).equals(child.getOutSchema())) { if (stack.empty()) { // if it is topmost, set it as the root of this block. block.setRoot(child); } else { LogicalNode parentNode = stack.peek(); switch (parentNode.getType()) { case ROOT: LogicalRootNode rootNode = (LogicalRootNode) parentNode; rootNode.setChild(child); rootNode.setInSchema(child.getOutSchema()); rootNode.setOutSchema(child.getOutSchema()); break; case TABLE_SUBQUERY: TableSubQueryNode tableSubQueryNode = (TableSubQueryNode) parentNode; tableSubQueryNode.setSubQuery(child); break; case STORE: StoreTableNode storeTableNode = (StoreTableNode) parentNode; storeTableNode.setChild(child); storeTableNode.setInSchema(child.getOutSchema()); break; case INSERT: InsertNode insertNode = (InsertNode) parentNode; insertNode.setSubQuery(child); break; case CREATE_TABLE: CreateTableNode createTableNode = (CreateTableNode) parentNode; createTableNode.setChild(child); createTableNode.setInSchema(child.getOutSchema()); break; case CREATE_INDEX: CreateIndexNode createIndexNode = (CreateIndexNode) parentNode; createIndexNode.setChild(child); createIndexNode.setInSchema(child.getOutSchema()); break; default: throw new TajoInternalError("unexpected parent node: " + parentNode.getType()); } plan.addHistory("ProjectionNode is eliminated."); } return child; } else { return node; } }
From source file:com.taobao.tdhs.jdbc.sqlparser.ParseSQL.java
private boolean checkSpecialStr(String sqlstring, String searchStr) { //????searchStr Stack<String> stack = new Stack<String>(); boolean exist_danyinhao = false; for (int i = 0; i < sqlstring.length(); i++) { ///*from ww w . j av a2 s . co m*/ if (sqlstring.substring(i, i + 1).equals("'") == false) { stack.push(sqlstring.substring(i, i + 1)); } //' if (sqlstring.substring(i, i + 1).equals("'")) { //?\,?,\,,?? int count = 0; int k = i; boolean real_danyinhao; while (k - 1 >= 0 && sqlstring.substring(k - 1, k).equals("\\") == true) { k--; count++; } //System.out.println("\\:"+count); if (count % 2 == 0) { //?? real_danyinhao = true; } else { //???,value real_danyinhao = false; stack.push(sqlstring.substring(i, i + 1)); } if (real_danyinhao == true) { if (exist_danyinhao == false) { exist_danyinhao = true; stack.push(sqlstring.substring(i, i + 1)); } else { boolean find_real_danyinhao = false; while (find_real_danyinhao == false) { while (!stack.pop().equals("'")) { ; } //???,??\ if (stack.isEmpty() == false && stack.peek().equals("\\")) { //?,??? count = 0; while (stack.peek().equals("\\")) { stack.pop(); count++; } if (count % 2 == 0) { //? find_real_danyinhao = true; } else { //? find_real_danyinhao = false; } } else { // find_real_danyinhao = true; } } exist_danyinhao = false; } } } } //end for logger.debug(stack.toString()); if (stack.isEmpty() == false && stack.search(searchStr) > -1) { stack.clear(); return true; } else { return false; } }
From source file:org.ganges.expressionengine.Compiler.java
/** * It builds the tree of Expression objects using tokens from RPN Stack. * /*from w w w . j a v a2 s. c om*/ * @param rpnTokens the stack of tokens in RPN structure * @param expressionContext the object which may contain contextual information for expressions * @return the tree of expression objects * @throws ExpressionEngineException */ protected Expression buildExpression(Stack<ExpressionToken> rpnTokens, ExpressionContext expressionContext) throws ExpressionEngineException { Stack<Expression> expressionStack = new Stack<Expression>(); int size = rpnTokens.size(); for (int i = 0; i < size; i++) { ExpressionToken token = rpnTokens.get(i); // By default expression is for operand element. String type = ExpressionFactory.OPERAND; Object initializationParameters = token.getValue(); // Expression for operator if (grammar.isOperator(token)) { // Expression for function/unary operator if (isUnary(token)) { type = grammar.isFunction(token.getValue()) ? ExpressionFactory.FUNCTION : ExpressionFactory.UNARY; /* * Earlier we were assuming that expressionStack must have * at least one expression in case of Unary Expression. * Hence we were asserting for at least one expression in * expression stack here. But this assumption failed in case * of function call with zero arguments. So the assertion * has been removed now. * * @see Bug ID: 1691820 @ sourceforge */ initializationParameters = expressionStack.size() == 0 ? null : expressionStack.pop(); } else { if (expressionStack.size() < 2) { throw new ExpressionEngineException( "Something wrong while compiling expression, as expression stack has less than 2 expression in case of binray expression. expressionStack[" + expressionStack + "]"); } type = ExpressionFactory.BINARY; Expression rightExpression = expressionStack.pop(); Expression leftExpression = expressionStack.pop(); initializationParameters = new Expression[] { leftExpression, rightExpression }; } } LOGGER.debug("token[" + token + "]"); Expression expression = ExpressionFactory.getInstance().createExpression(token.getValue(), type); LOGGER.debug("expression[" + expression + "]"); expressionContext.setContextProperty(ExpressionEngineConstants.EXPRESSION_CONTENXT_TOKEN, token.getValue()); expression.initialize(expressionContext, initializationParameters); expressionContext.setContextProperty(ExpressionEngineConstants.EXPRESSION_CONTENXT_TOKEN, null); expressionStack.push(expression); } if (expressionStack.size() != 1) { throw new ExpressionEngineException( "Unable to compile expression. Expression Stack size should be one here. expressionStackSize[" + expressionStack.size() + "] rpnTokens[" + rpnTokens + "]"); } return expressionStack.peek(); }
From source file:org.vedantatree.expressionoasis.Compiler.java
/** * Builds a tree of Expression objects representing the expression. * // w ww . j a v a2 s . c om * @param expression the string representing the expression to build * @param expressionContext the object which may contain contextual information for expressions * @return the tree of expression objects * @throws ExpressionEngineException */ public Expression compile(String expression, ExpressionContext expressionContext, boolean validate) throws ExpressionEngineException { Stack<ExpressionToken> rpnTokens = getTokensInRPN(expression); Stack<Expression> expressionStack = new Stack<Expression>(); int size = rpnTokens.size(); for (int i = 0; i < size; i++) { ExpressionToken token = rpnTokens.get(i); // By default expression is for operand element. String type = ExpressionFactory.OPERAND; Object initializationParameters = token.getValue(); // Expression for operator if (grammar.isOperator(token)) { // Expression for function/unary operator if (isUnary(token)) { type = grammar.isFunction(token.getValue()) ? ExpressionFactory.FUNCTION : ExpressionFactory.UNARY; /* * Earlier we were assuming that expressionStack must have * at least one expression in case of Unary Expression. * Hence we were asserting for at least one expression in * expression stack here. But this assumption failed in case * of function call with zero arguments. So the assertion * has been removed now. * * @see Bug ID: 1691820 @ sourceforge */ initializationParameters = expressionStack.size() == 0 ? null : expressionStack.pop(); } else { if (expressionStack.size() < 2) { throw new ExpressionEngineException( "Something wrong while compiling expression, as expression stack has less than 2 expression in case of binray expression. expressionStack[" + expressionStack + "]"); } type = ExpressionFactory.BINARY; Expression rightExpression = expressionStack.pop(); Expression leftExpression = expressionStack.pop(); initializationParameters = new Expression[] { leftExpression, rightExpression }; } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("token[" + token + "]"); } Expression compiledExpression = ExpressionFactory.getInstance().createExpression(token.getValue(), type); if (LOGGER.isDebugEnabled()) { LOGGER.debug("expression[" + compiledExpression + "]"); } expressionContext.setContextProperty(ExpressionEngineConstants.EXPRESSION_CONTENXT_TOKEN, token.getValue()); compiledExpression.initialize(expressionContext, initializationParameters, validate); expressionContext.setContextProperty(ExpressionEngineConstants.EXPRESSION_CONTENXT_TOKEN, null); expressionStack.push(compiledExpression); } if (expressionStack.size() != 1) { throw new ExpressionEngineException( "Unable to compile expression. Expression Stack size should be one here. expressionStackSize[" + expressionStack.size() + "] rpnTokens[" + rpnTokens + "]"); } return expressionStack.peek(); }
From source file:org.eclipse.php.internal.core.ast.rewrite.ASTRewriteAnalyzer.java
final void doCopySourcePostVisit(ASTNode node, Stack nodeEndStack) { while (!nodeEndStack.isEmpty() && nodeEndStack.peek() == node) { nodeEndStack.pop();/* ww w . ja v a 2s. c o m*/ this.currentEdit = this.currentEdit.getParent(); } }
From source file:org.apache.tajo.engine.planner.rewrite.ProjectionPushDownRule.java
public LogicalNode visitJoin(Context context, LogicalPlan plan, LogicalPlan.QueryBlock block, JoinNode node, Stack<LogicalNode> stack) throws PlanningException { Context newContext = new Context(context); String joinQualReference = null; if (node.hasJoinQual()) { for (EvalNode eachQual : AlgebraicUtil.toConjunctiveNormalFormArray(node.getJoinQual())) { if (eachQual instanceof BinaryEval) { BinaryEval binaryQual = (BinaryEval) eachQual; for (int i = 0; i < 2; i++) { EvalNode term = binaryQual.getChild(i); pushDownIfComplexTermInJoinCondition(newContext, eachQual, term); }/*from w w w . j av a 2 s . co m*/ } } joinQualReference = newContext.addExpr(node.getJoinQual()); newContext.addNecessaryReferences(node.getJoinQual()); } String[] referenceNames = null; if (node.hasTargets()) { referenceNames = new String[node.getTargets().length]; int i = 0; for (Iterator<Target> it = getFilteredTarget(node.getTargets(), context.requiredSet); it.hasNext();) { Target target = it.next(); referenceNames[i++] = newContext.addExpr(target); } } stack.push(node); LogicalNode left = visit(newContext, plan, block, node.getLeftChild(), stack); LogicalNode right = visit(newContext, plan, block, node.getRightChild(), stack); stack.pop(); Schema merged = SchemaUtil.merge(left.getOutSchema(), right.getOutSchema()); node.setInSchema(merged); if (node.hasJoinQual()) { Target target = context.targetListMgr.getTarget(joinQualReference); if (newContext.targetListMgr.isEvaluated(joinQualReference)) { throw new PlanningException( "Join condition must be evaluated in the proper Join Node: " + joinQualReference); } else { node.setJoinQual(target.getEvalTree()); newContext.targetListMgr.markAsEvaluated(target); } } LinkedHashSet<Target> projectedTargets = Sets.newLinkedHashSet(); for (Iterator<String> it = getFilteredReferences(context.targetListMgr.getNames(), context.requiredSet); it .hasNext();) { String referenceName = it.next(); Target target = context.targetListMgr.getTarget(referenceName); if (context.targetListMgr.isEvaluated(referenceName)) { Target fieldReference = new Target(new FieldEval(target.getNamedColumn())); if (LogicalPlanner.checkIfBeEvaluatedAtJoin(block, fieldReference.getEvalTree(), node, stack.peek().getType() != NodeType.JOIN)) { projectedTargets.add(fieldReference); } } else if (LogicalPlanner.checkIfBeEvaluatedAtJoin(block, target.getEvalTree(), node, stack.peek().getType() != NodeType.JOIN)) { projectedTargets.add(target); context.targetListMgr.markAsEvaluated(target); } } node.setTargets(projectedTargets.toArray(new Target[projectedTargets.size()])); LogicalPlanner.verifyProjectedFields(block, node); return node; }
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 *///from www. j a v a 2s. co m 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()); } } } }