Java Code Examples for org.antlr.runtime.tree.Tree#getChild()

The following examples show how to use org.antlr.runtime.tree.Tree#getChild() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Query.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private static Evaluator<?> buildFunctionExpressionEvaluator(final Tree tree, final int offset) {
    if (tree.getChildCount() == 0) {
        throw new AttributeExpressionLanguageParsingException("EXPRESSION tree node has no children");
    }
    final int firstChildIndex = tree.getChildCount() - offset - 1;
    if (firstChildIndex == 0) {
        return buildEvaluator(tree.getChild(0));
    }

    final Tree functionTree = tree.getChild(firstChildIndex);
    final Evaluator<?> subjectEvaluator = buildFunctionExpressionEvaluator(tree, offset + 1);

    final Tree functionNameTree = functionTree.getChild(0);
    final List<Evaluator<?>> argEvaluators = new ArrayList<>();
    for (int i = 1; i < functionTree.getChildCount(); i++) {
        argEvaluators.add(buildEvaluator(functionTree.getChild(i)));
    }
    return buildFunctionEvaluator(functionNameTree, subjectEvaluator, argEvaluators);
}
 
Example 2
Source File: QueryTreeTransformer.java    From cuba with Apache License 2.0 6 votes vote down vote up
public void replaceWithCount(String entityName) {
    Tree selectedItems = queryTree.getAstSelectedItemsNode();
    boolean isDistinct = "distinct".equalsIgnoreCase(selectedItems.getChild(0).getText());
    if (!(isDistinct && selectedItems.getChildCount() == 2 ||
            selectedItems.getChildCount() == 1))
        throw new IllegalStateException("Cannot replace with count if multiple fields selected");

    SelectedItemNode selectedItemNode;
    if (isDistinct)
        selectedItems.deleteChild(0);

    selectedItemNode = (SelectedItemNode) selectedItems.getChild(0);
    AggregateExpressionNode countNode = createAggregateCount(createWord(entityName), isDistinct);
    selectedItemNode.deleteChild(0);
    selectedItemNode.addChild(countNode);

    Tree orderBy = queryTree.getAstTree().getFirstChildWithType(JPA2Lexer.T_ORDER_BY);
    if (orderBy != null) {
        queryTree.getAstTree().deleteChild(orderBy.getChildIndex());
    }
    queryTree.getAstTree().freshenParentAndChildIndexes();
}
 
Example 3
Source File: QueryHelper.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Gets the children as a List
 * @param tree Tree
 * @return either emptyList or the children.
 */
public static List<Tree> getChildren(Tree tree)
{
    if (tree!=null && tree.getChildCount() > 0)
    {
        List<Tree> children = new ArrayList<Tree>(tree.getChildCount());
        for (int i = 0; i < tree.getChildCount(); i++) {
            Tree child = tree.getChild(i);
            children.add(child);
        }
        return children;
    }

    //Default
    return Collections.emptyList();
}
 
Example 4
Source File: RuleBlock.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Parse rule Implication Method (or rule activation method)
 * @param tree : Tree to parse
 */
private void fclTreeRuleBlockRule(Tree tree, RuleConnectionMethod and, RuleConnectionMethod or) {
	if (debug) Gpr.debug("Tree: " + tree.toStringTree());
	Rule fuzzyRule = new Rule(tree.getChild(0).getText(), this);

	for (int childNum = 1; childNum < tree.getChildCount(); childNum++) {
		Tree child = tree.getChild(childNum);
		if (debug) Gpr.debug("\t\tChild: " + child.toStringTree());
		String type = child.getText();

		if (type.equalsIgnoreCase("IF")) fuzzyRule.setAntecedents(fclTreeRuleBlockRuleIf(child.getChild(0), and, or));
		else if (type.equalsIgnoreCase("THEN")) fclTreeRuleBlockRuleThen(child, fuzzyRule);
		else if (type.equalsIgnoreCase("WITH")) fclTreeRuleBlockRuleWith(child, fuzzyRule);
		else throw new RuntimeException("Unknown (or unimplemented) rule block item: " + type);
	}

	add(fuzzyRule);
}
 
Example 5
Source File: FunctionBlock.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Parse a tree for singletons membership function
 * @param tree : Tree to parse
 * @return A new membership function
 */
private MembershipFunction fclTreeFuzzifyTermSingletons(Tree tree) {
	if (debug) Gpr.debug("Tree: " + tree.toStringTree());

	// Count number of points
	int numPoints = 0;
	for (int childNum = 0; childNum < tree.getChildCount(); childNum++) {
		Tree child = tree.getChild(childNum);

		String leaveName = child.getText();
		if (leaveName.equalsIgnoreCase("(")) numPoints++;
		if (debug) Gpr.debug("leaveName : " + leaveName + "\tnumPoints: " + numPoints);
	}

	// Parse multiple points (for piece-wise linear)
	return fclTreeFuzzifyTermSingletonsPoints(tree.getChild(0), numPoints);
}
 
Example 6
Source File: RuleAST.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public ActionAST getLexerAction() {
	Tree blk = getFirstChildWithType(ANTLRParser.BLOCK);
	if ( blk.getChildCount()==1 ) {
		Tree onlyAlt = blk.getChild(0);
		Tree lastChild = onlyAlt.getChild(onlyAlt.getChildCount()-1);
		if ( lastChild.getType()==ANTLRParser.ACTION ) {
			return (ActionAST)lastChild;
		}
	}
	return null;
}
 
Example 7
Source File: QueryParserDriver.java    From spork with Apache License 2.0 5 votes vote down vote up
static void traverseImport(Tree t, List<CommonTree> nodes) {
    if (t.getText().equalsIgnoreCase(IMPORT_DEF)) {
        nodes.add((CommonTree)t);
    }
    int n = t.getChildCount();
    for (int i = 0; i < n; i++) {
        Tree t0 = t.getChild(i);
        traverseImport(t0, nodes);
    }
}
 
Example 8
Source File: FunctionBlock.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Parse a tree for generilized bell membership function
 * @param tree : Tree to parse
 * @return A new membership function
 */
private MembershipFunction fclTreeFuzzifyTermGenBell(Tree tree) {
	if (debug) Gpr.debug("Tree: " + tree.toStringTree());
	Tree child = tree.getChild(0);
	Value a = new Value(child, this);
	Value b = new Value(tree.getChild(1), this);
	Value mean = new Value(tree.getChild(2), this);
	MembershipFunction membershipFunction = new MembershipFunctionGenBell(a, b, mean);
	return membershipFunction;
}
 
Example 9
Source File: CliClient.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private void executeConnect(Tree statement)
{
    Tree idList = statement.getChild(0);
    int portNumber = Integer.parseInt(statement.getChild(1).getText());

    StringBuilder hostName = new StringBuilder();
    int idCount = idList.getChildCount();
    for (int idx = 0; idx < idCount; idx++)
    {
        hostName.append(idList.getChild(idx).getText());
    }

    // disconnect current connection, if any.
    // This is a no-op, if you aren't currently connected.
    CliMain.disconnect();

    // now, connect to the newly specified host name and port
    sessionState.hostName = hostName.toString();
    sessionState.thriftPort = portNumber;

    // if we have user name and password
    if (statement.getChildCount() == 4)
    {
        sessionState.username = statement.getChild(2).getText();
        sessionState.password = CliUtils.unescapeSQLString(statement.getChild(3).getText());
    }

    CliMain.connect(sessionState.hostName, sessionState.thriftPort);
}
 
Example 10
Source File: CliClient.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private void executeCount(Tree statement)
        throws TException, InvalidRequestException, UnavailableException, TimedOutException
{
    if (!CliMain.isConnected() || !hasKeySpace())
        return;

    Tree columnFamilySpec = statement.getChild(0);

    String columnFamily = CliCompiler.getColumnFamily(columnFamilySpec, currentCfDefs());
    int columnSpecCnt = CliCompiler.numColumnSpecifiers(columnFamilySpec);

    ColumnParent colParent = new ColumnParent(columnFamily).setSuper_column((ByteBuffer) null);

    if (columnSpecCnt != 0)
    {
        Tree columnTree = columnFamilySpec.getChild(2);

        byte[] superColumn = (columnTree.getType() == CliParser.FUNCTION_CALL)
                              ? convertValueByFunction(columnTree, null, null).array()
                              : columnNameAsByteArray(CliCompiler.getColumn(columnFamilySpec, 0), columnFamily);

        colParent = new ColumnParent(columnFamily).setSuper_column(superColumn);
    }

    SliceRange range = new SliceRange(ByteBufferUtil.EMPTY_BYTE_BUFFER, ByteBufferUtil.EMPTY_BYTE_BUFFER, false, Integer.MAX_VALUE);
    SlicePredicate predicate = new SlicePredicate().setColumn_names(null).setSlice_range(range);

    int count = thriftClient.get_count(getKeyAsBytes(columnFamily, columnFamilySpec.getChild(1)), colParent, predicate, consistencyLevel);
    sessionState.out.printf("%d cells%n", count);
}
 
Example 11
Source File: FunctionBlock.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Parse a tree for "Fuzzify" item
 * @param tree : Tree to parse
 * @return Variable (old or created)
 */
private Variable fclTreeFuzzify(Tree tree) {
	Gpr.checkRootNode("FUZZIFY", tree);
	if (debug) Gpr.debug("Tree: " + tree.toStringTree());
	Tree child = tree.getChild(0);
	String varName = child.getText();

	// Get variable (or create a new one)
	Variable variable = getVariable(varName);
	if (variable == null) {
		variable = new Variable(varName);
		setVariable(varName, variable);
		if (debug) Gpr.debug("Variable '" + varName + "' does not exist => Creating it");
	}

	// Explore each sibling in this level
	for (int childNum = 1; childNum < tree.getChildCount(); childNum++) {
		child = tree.getChild(childNum);
		if (debug) Gpr.debug("\t\tChild: " + child.toStringTree());
		String leaveName = child.getText();

		if (leaveName.equalsIgnoreCase("TERM")) {
			LinguisticTerm linguisticTerm = fclTreeFuzzifyTerm(child, variable);
			variable.add(linguisticTerm);
		} else throw new RuntimeException("Unknown/Unimplemented item '" + leaveName + "'");
	}

	return variable;
}
 
Example 12
Source File: FunctionBlock.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Parse a tree for trapetzoidal membership function
 * @param tree : Tree to parse
 * @return A new membership function
 */
private MembershipFunction fclTreeFuzzifyTermTrapetzoidal(Tree tree) {
	if (debug) Gpr.debug("Tree: " + tree.toStringTree());
	Value min = new Value(tree.getChild(0), this);
	Value midLow = new Value(tree.getChild(1), this);
	Value midHigh = new Value(tree.getChild(2), this);
	Value max = new Value(tree.getChild(3), this);
	MembershipFunction membershipFunction = new MembershipFunctionTrapetzoidal(min, midLow, midHigh, max);
	return membershipFunction;
}
 
Example 13
Source File: HL7Query.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void toTreeString(final Tree tree, final StringBuilder sb, final int indentLevel) {
    final String nodeName = tree.getText();
    for (int i = 0; i < indentLevel; i++) {
        sb.append(" ");
    }
    sb.append(nodeName);
    sb.append("\n");

    for (int i = 0; i < tree.getChildCount(); i++) {
        final Tree child = tree.getChild(i);
        toTreeString(child, sb, indentLevel + 2);
    }
}
 
Example 14
Source File: FunctionBlock.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Parse a tree for cosine membership function
 * @param tree : tree to parse
 * @return A new membership function
 */
private MembershipFunction fclTreeFuzzifyTermCosine(Tree tree) {
	if (debug) Gpr.debug("Tree: " + tree.toStringTree());
	Value net_max = new Value(tree.getChild(0), this);
	Value offset = new Value(tree.getChild(1), this);
	MembershipFunction membershipFunction = new MembershipFunctionCosine(net_max, offset);
	return membershipFunction;
}
 
Example 15
Source File: FIS.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Create a "Fuzzy inference system (FIS)" from an FCL definition string
 * @param lexer : lexer to use
 * @param verbose : be verbose?
 * @return A new FIS (or null on error)
 */
private static FIS createFromLexer(FclLexer lexer, boolean verbose) throws RecognitionException {
	FIS fis = new FIS();
	CommonTokenStream tokens = new CommonTokenStream(lexer);
	FclParser parser = new FclParser(tokens);

	// FclParser.fcl_return root = parser.fcl();
	FclParser.main_return root;
	root = parser.main();
	Tree parseTree = (Tree) root.getTree();

	// Error loading file?
	if (parseTree == null) {
		System.err.println("Can't create FIS");
		return null;
	}

	if (debug) Gpr.debug("Tree: " + parseTree.toStringTree());

	// Add every FunctionBlock (there may be more than one in each FCL file)
	for (int childNum = 0; childNum < parseTree.getChildCount(); childNum++) {
		Tree child = parseTree.getChild(childNum);
		if (debug) Gpr.debug("Child " + childNum + ":\t" + child + "\tTree:'" + child.toStringTree() + "'");

		// Create a new FunctionBlock
		FunctionBlock functionBlock = new FunctionBlock(fis);

		// Generate fuzzyRuleSet based on tree
		String name = functionBlock.fclTree(child);
		if (debug) Gpr.debug("FunctionBlock Name: '" + name + "'");
		fis.addFunctionBlock(name, functionBlock);
	}

	return fis;
}
 
Example 16
Source File: FunctionBlock.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Parse a tree for gaussian membership function
 * @param tree : Tree to parse
 * @return A new membership function
 */
private MembershipFunction fclTreeFuzzifyTermGauss(Tree tree) {
	if (debug) Gpr.debug("Tree: " + tree.toStringTree());
	Tree child = tree.getChild(0);
	Value mean = new Value(child, this);
	Value stdev = new Value(tree.getChild(1), this);
	MembershipFunction membershipFunction = new MembershipFunctionGaussian(mean, stdev);
	return membershipFunction;
}
 
Example 17
Source File: FunctionBlock.java    From jFuzzyLogic with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Parse a tree for gaussian2 membership function
 * @param tree : Tree to parse
 * @return A new membership function
 */
private MembershipFunction fclTreeFuzzifyTermGauss2(Tree tree) {
	if (debug) Gpr.debug("Tree: " + tree.toStringTree());
	Tree child = tree.getChild(0);
	Value mean = new Value(child, this);
	Value stdev = new Value(tree.getChild(1), this);
	Value mean2 = new Value(tree.getChild(2), this);
	Value stdev2 = new Value(tree.getChild(3), this);
	MembershipFunction membershipFunction = new MembershipFunctionGaussian2(mean, stdev, mean2, stdev2);
	return membershipFunction;
}
 
Example 18
Source File: FTSTest.java    From alfresco-data-model with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testMapLoneStar() throws Exception
{
    final String ftsExpression = "* AND * AND * AND * AND * AND * AND * AND * AND * AND * AND *";
    AlfrescoFunctionEvaluationContext functionContext = new AlfrescoFunctionEvaluationContext(null, null, NamespaceService.CONTENT_MODEL_1_0_URI);

    Map<String, String> templates = new HashMap<String, String>();
    String keywordsTemplate = "%(cm:name cm:title cm:description ia:whatEvent ia:descriptionEvent lnk:title lnk:description TEXT TAG)";
    String keywordsKey = "keywords";
    templates.put(keywordsKey, keywordsTemplate);

    final FTSParser.Mode mode = FTSParser.Mode.DEFAULT_DISJUNCTION;
    final Connective defaultFieldConnective = Connective.OR;

    class TestMock extends FTSQueryParser.TestNodeBuilder
    {
        private void test(CommonTree initialNode, CommonTree replacedNode)
        {
            if (initialNode.getType() == FTSParser.TERM &&
                    initialNode.getChildCount() == 1 &&
                    initialNode.getChild(0).getType() == FTSParser.STAR)
            {
                // input is the lone star
                Tree node = replacedNode;
                while (true)
                {
                    if (node.getChildCount() == 1)
                    {
                        node = node.getChild(0);
                        if (node.getType() == FTSParser.TERM)
                        {
                            assertEquals("Lone star should be mapped to " + FTSQueryParser.VALUE_REPLACELONESTAR, node.getChildCount(), 2);
                            Tree child1 = node.getChild(0);
                            assertEquals("Lone star should be mapped to " + FTSQueryParser.VALUE_REPLACELONESTAR, child1.getType(), FTSParser.ID);
                            assertEquals("Lone star should be mapped to " + FTSQueryParser.VALUE_REPLACELONESTAR, child1.getText(), "T");
                            Tree child2 = node.getChild(1);
                            assertEquals("Lone star should be mapped to " + FTSQueryParser.VALUE_REPLACELONESTAR, child2.getType(), FTSParser.FIELD_REF);
                            assertEquals("Lone star should be mapped to " + FTSQueryParser.VALUE_REPLACELONESTAR, child2.getChild(0).getText(), "ISNODE");
                            // checking done
                            break;
                        }
                    }
                    else
                    {
                        // wrong structure of the replaced node
                        fail("Lone star should be mapped to " + FTSQueryParser.VALUE_REPLACELONESTAR);
                    }
                }
            }
        }
        
        @Override
        protected CommonTree build(CommonTree fieldReferenceNode, CommonTree argNode, QueryModelFactory factory, FunctionEvaluationContext functionEvaluationContext,
                Selector selector, Map<String, Column> columnMap, Map<String, CommonTree> templateTrees, String defaultField)
        {
            CommonTree testNode = super.build(fieldReferenceNode, argNode, factory, functionEvaluationContext, selector, columnMap, templateTrees, defaultField);
            test(argNode, testNode);
            return testNode;
        }
    }

    FTSQueryParser.setTestNodeBuilder(new TestMock());
    try
    {
        FTSQueryParser.buildFTS(ftsExpression, new LuceneQueryModelFactory(), functionContext, null, null,
                mode, defaultFieldConnective, templates, keywordsKey, FTSQueryParser.RerankPhase.SINGLE_PASS);
    }
    finally
    {
        // set default logic
        FTSQueryParser.setTestNodeBuilder(new FTSQueryParser.TestNodeBuilder());
    }
}
 
Example 19
Source File: CliClient.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
/**
 * Used to parse meta tree and compile meta attributes into List<ColumnDef>
 * @param cfDef - column family definition
 * @param meta (Tree representing Array of the hashes with metadata attributes)
 * @return List<ColumnDef> List of the ColumnDef's
 *
 * meta is in following format - ^(ARRAY ^(HASH ^(PAIR .. ..) ^(PAIR .. ..)) ^(HASH ...))
 */
private List<ColumnDef> getCFColumnMetaFromTree(CfDef cfDef, Tree meta)
{
    // this list will be returned
    List<ColumnDef> columnDefinitions = new ArrayList<ColumnDef>();

    // each child node is a ^(HASH ...)
    for (int i = 0; i < meta.getChildCount(); i++)
    {
        Tree metaHash = meta.getChild(i);

        ColumnDef columnDefinition = new ColumnDef();

        // each child node is ^(PAIR $key $value)
        for (int j = 0; j < metaHash.getChildCount(); j++)
        {
            Tree metaPair = metaHash.getChild(j);

            // current $key
            String metaKey = CliUtils.unescapeSQLString(metaPair.getChild(0).getText());
            // current $value
            String metaVal = CliUtils.unescapeSQLString(metaPair.getChild(1).getText());

            if (metaKey.equals("column_name"))
            {
                if (cfDef.column_type.equals("Super"))
                    columnDefinition.setName(subColumnNameAsByteArray(metaVal, cfDef));
                else
                    columnDefinition.setName(columnNameAsByteArray(metaVal, cfDef));
            }
            else if (metaKey.equals("validation_class"))
            {
                columnDefinition.setValidation_class(metaVal);
            }
            else if (metaKey.equals("index_type"))
            {
                columnDefinition.setIndex_type(getIndexTypeFromString(metaVal));
            }
            else if (metaKey.equals("index_options"))
            {
                columnDefinition.setIndex_options(getStrategyOptionsFromTree(metaPair.getChild(1)));
            }
            else if (metaKey.equals("index_name"))
            {
                columnDefinition.setIndex_name(metaVal);
            }
            else
            {
                throw new RuntimeException("Unsupported column_metadata pair given => " + metaKey + ": " + metaVal);
            }
        }

        // validating columnDef structure, 'name' and 'validation_class' must be set
        try
        {
            columnDefinition.validate();
        }
        catch (TException e)
        {
            throw new RuntimeException(e);
        }

        columnDefinitions.add(columnDefinition);
    }

    return columnDefinitions;
}
 
Example 20
Source File: CliClient.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
/**
 * Used to convert value (function argument, string) into byte[]
 * @param functionCall - tree representing function call ^(FUNCTION_CALL function_name value)
 * @param columnFamily - column family definition (CfDef)
 * @param columnName   - column name as byte[] (used to update CfDef)
 * @param withUpdate   - also updates column family metadata for given column
 * @return byte[] - string value as byte[]
 */
private ByteBuffer convertValueByFunction(Tree functionCall, CfDef columnFamily, ByteBuffer columnName, boolean withUpdate)
{
    String functionName = functionCall.getChild(0).getText();
    Tree argumentTree = functionCall.getChild(1);
    String functionArg  = (argumentTree == null) ? "" : CliUtils.unescapeSQLString(argumentTree.getText());
    AbstractType<?> validator = getTypeByFunction(functionName);

    try
    {

        ByteBuffer value;

        if (functionArg.isEmpty())
        {
            if (validator instanceof TimeUUIDType)
            {
                value = ByteBuffer.wrap(UUIDGen.getTimeUUIDBytes());
            }
            else if (validator instanceof LexicalUUIDType)
            {
                value = ByteBuffer.wrap(UUIDGen.decompose(UUID.randomUUID()));
            }
            else if (validator instanceof BytesType)
            {
                value = ByteBuffer.wrap(new byte[0]);
            }
            else
            {
                throw new RuntimeException(String.format("Argument for '%s' could not be empty.", functionName));
            }
        }
        else
        {
            value = getBytesAccordingToType(functionArg, validator);
        }

        // performing ColumnDef local validator update
        if (withUpdate)
        {
            updateColumnMetaData(columnFamily, columnName, validator.toString());
        }

        return value;
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}