Search in sources :

Example 1 with PACKAGE

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.PACKAGE in project siddhi by wso2.

the class SiddhiAnnotationProcessor method process.

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    // Iterate over all @Extension annotated elements.
    for (Element element : roundEnv.getElementsAnnotatedWith(Extension.class)) {
        // Check if a class has been annotated with @Extension.
        if (element.getKind() == ElementKind.CLASS) {
            String superClass = getMatchingSuperClass(element, new String[] { AnnotationConstants.SINK_MAPPER_SUPER_CLASS, AnnotationConstants.SINK_SUPER_CLASS, AnnotationConstants.FUNCTION_EXECUTOR_SUPER_CLASS, AnnotationConstants.AGGREGATION_ATTRIBUTE_SUPER_CLASS, AnnotationConstants.DISTRIBUTION_STRATEGY_SUPER_CLASS, AnnotationConstants.STREAM_PROCESSOR_SUPER_CLASS, AnnotationConstants.STREAM_FUNCTION_PROCESSOR_SUPER_CLASS, AnnotationConstants.STORE_SUPER_CLASS, AnnotationConstants.SOURCE_SUPER_CLASS, AnnotationConstants.SOURCE_MAPPER_SUPER_CLASS, AnnotationConstants.WINDOW_PROCESSOR_CLASS, AnnotationConstants.SCRIPT_SUPER_CLASS, AnnotationConstants.INCREMENTAL_ATTRIBUTE_AGGREGATOR_SUPER_CLASS });
            AbstractAnnotationProcessor abstractAnnotationProcessor = null;
            Extension annotation = element.getAnnotation(Extension.class);
            String name = annotation.name();
            String description = annotation.description();
            String namespace = annotation.namespace();
            Parameter[] parameters = annotation.parameters();
            ReturnAttribute[] returnAttributes = annotation.returnAttributes();
            SystemParameter[] systemParameters = annotation.systemParameter();
            Example[] examples = annotation.examples();
            String extensionClassFullName = element.asType().toString();
            if (superClass != null) {
                switch(superClass) {
                    case AnnotationConstants.DISTRIBUTION_STRATEGY_SUPER_CLASS:
                        abstractAnnotationProcessor = new DistributionStrategyValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    case AnnotationConstants.SINK_MAPPER_SUPER_CLASS:
                        abstractAnnotationProcessor = new SinkMapperValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    case AnnotationConstants.SINK_SUPER_CLASS:
                        abstractAnnotationProcessor = new SinkValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    case AnnotationConstants.FUNCTION_EXECUTOR_SUPER_CLASS:
                        abstractAnnotationProcessor = new FunctionExecutorValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    case AnnotationConstants.AGGREGATION_ATTRIBUTE_SUPER_CLASS:
                        abstractAnnotationProcessor = new AggregationAttributeValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    case AnnotationConstants.STREAM_PROCESSOR_SUPER_CLASS:
                        abstractAnnotationProcessor = new StreamProcessorValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    case AnnotationConstants.SOURCE_SUPER_CLASS:
                        abstractAnnotationProcessor = new SourceValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    case AnnotationConstants.SOURCE_MAPPER_SUPER_CLASS:
                        abstractAnnotationProcessor = new SourceMapperValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    case AnnotationConstants.STORE_SUPER_CLASS:
                        abstractAnnotationProcessor = new StoreValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    case AnnotationConstants.STREAM_FUNCTION_PROCESSOR_SUPER_CLASS:
                        abstractAnnotationProcessor = new StreamFunctionProcessorValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    case AnnotationConstants.WINDOW_PROCESSOR_CLASS:
                        abstractAnnotationProcessor = new WindowProcessorValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    case AnnotationConstants.SCRIPT_SUPER_CLASS:
                        abstractAnnotationProcessor = new ScriptValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    case AnnotationConstants.INCREMENTAL_ATTRIBUTE_AGGREGATOR_SUPER_CLASS:
                        abstractAnnotationProcessor = new IncrementalAggregationAttributeValidationAnnotationProcessor(extensionClassFullName);
                        break;
                    default:
                        // Throw error if no matching super class.
                        showBuildError(MessageFormat.format("Default switch case executed as there is no " + "matching super class option for @{0}.", superClass), element);
                        break;
                }
                if (abstractAnnotationProcessor != null) {
                    try {
                        abstractAnnotationProcessor.basicParameterValidation(name, description, namespace);
                        abstractAnnotationProcessor.parameterValidation(parameters);
                        abstractAnnotationProcessor.returnAttributesValidation(returnAttributes);
                        abstractAnnotationProcessor.systemParametersValidation(systemParameters);
                        abstractAnnotationProcessor.examplesValidation(examples);
                    } catch (AnnotationValidationException e) {
                        showBuildError(e.getMessage(), element);
                    }
                } else {
                    showBuildError(MessageFormat.format("Error while validation, " + "abstractAnnotationProcessor cannot be null.", superClass), element);
                }
            } else {
                // Throw error if no matching super class.
                showBuildError("Class does not have a matching Siddhi Extension super class.", element);
            }
        } else {
            // Throw error if the element returned is method or package.
            showBuildError(MessageFormat.format("Only classes can be annotated with @{0}.", Extension.class.getCanonicalName()), element);
        }
    }
    // Returning false since this processor only validates.
    return false;
}
Also used : TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) AnnotationValidationException(org.wso2.siddhi.annotation.util.AnnotationValidationException) ReturnAttribute(org.wso2.siddhi.annotation.ReturnAttribute) Example(org.wso2.siddhi.annotation.Example) SystemParameter(org.wso2.siddhi.annotation.SystemParameter) Extension(org.wso2.siddhi.annotation.Extension) Parameter(org.wso2.siddhi.annotation.Parameter) SystemParameter(org.wso2.siddhi.annotation.SystemParameter)

Example 2 with PACKAGE

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.PACKAGE in project carbon-apimgt by wso2.

the class ApisApiServiceImplTestCase method apisApiIdGatewayConfigGetTestCase.

@Test
public void apisApiIdGatewayConfigGetTestCase() throws Exception {
    ApisApiServiceImpl apisApiService = new ApisApiServiceImpl();
    APIMgtAdminServiceImpl adminService = Mockito.mock(APIMgtAdminServiceImpl.class);
    String apiID = UUID.randomUUID().toString();
    String gatewayConfig = "package deployment.org.wso2.apim;\n" + "import ballerina.net.http;\n" + "\n" + "@http:BasePath(\"/aaa1\")\n" + "service aaa1_1489666767745 {\n" + "\n" + "    @http:GET\n" + "    @http:Path(\"/*\")\n" + "    resource get_star_ (message m) {\n" + "        http:ClientConnector productionEndpoint = create http:ClientConnector(getUrlFromKey" + "(\"aaa1_1.0.0__ep\"));\n   http:ClientConnector sandboxEndpoint = create http:ClientConnector" + "(getUrlFromKey(\"aaa1_1.0.0__ep\"));\n message response;\n string endpointType;\n string " + "productionType;\n \n \n      endpointType = \"production\";\n productionType = \"production\";\n" + "\n      if (endpointType == productionType) {\n" + "            response = http:ClientConnector.execute(productionEndpoint, \"get\", \"\", m);\n" + "        } else {\n" + "            response = http:ClientConnector.execute(sandboxEndpoint, \"get\", \"\", m);\n" + "        }\n" + "\n" + "        reply response;\n" + "    }\n" + "}";
    Mockito.when(adminService.getAPIGatewayServiceConfig(apiID)).thenReturn(gatewayConfig);
    APIManagerFactory instance = Mockito.mock(APIManagerFactory.class);
    PowerMockito.mockStatic(APIManagerFactory.class);
    PowerMockito.when(APIManagerFactory.getInstance()).thenReturn(instance);
    Mockito.when(instance.getAPIMgtAdminService()).thenReturn(adminService);
    Response response = apisApiService.apisApiIdGatewayConfigGet(apiID, null, getRequest());
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
}
Also used : Response(javax.ws.rs.core.Response) APIManagerFactory(org.wso2.carbon.apimgt.core.impl.APIManagerFactory) APIMgtAdminServiceImpl(org.wso2.carbon.apimgt.core.impl.APIMgtAdminServiceImpl) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 3 with PACKAGE

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.PACKAGE in project ballerina by ballerina-lang.

the class TestAnnotationProcessor method process.

@Override
public void process(FunctionNode functionNode, List<AnnotationAttachmentNode> annotations) {
    // to avoid processing those, we have to have below check.
    if (!suite.getSuiteName().equals(functionNode.getPosition().getSource().getPackageName())) {
        return;
    }
    // traverse through the annotations of this function
    for (AnnotationAttachmentNode attachmentNode : annotations) {
        String annotationName = attachmentNode.getAnnotationName().getValue();
        String functionName = functionNode.getName().getValue();
        if (BEFORE_SUITE_ANNOTATION_NAME.equals(annotationName)) {
            suite.addBeforeSuiteFunction(functionName);
        } else if (AFTER_SUITE_ANNOTATION_NAME.equals(annotationName)) {
            suite.addAfterSuiteFunction(functionName);
        } else if (BEFORE_EACH_ANNOTATION_NAME.equals(annotationName)) {
            suite.addBeforeEachFunction(functionName);
        } else if (AFTER_EACH_ANNOTATION_NAME.equals(annotationName)) {
            suite.addAfterEachFunction(functionName);
        } else if (MOCK_ANNOTATION_NAME.equals(annotationName)) {
            String[] vals = new String[2];
            // If package property not present the package is .
            // TODO: when default values are supported in annotation struct we can remove this
            vals[0] = ".";
            if (attachmentNode.getExpression() instanceof BLangRecordLiteral) {
                List<BLangRecordLiteral.BLangRecordKeyValue> attributes = ((BLangRecordLiteral) attachmentNode.getExpression()).getKeyValuePairs();
                attributes.forEach(attributeNode -> {
                    String name = attributeNode.getKey().toString();
                    String value = attributeNode.getValue().toString();
                    if (PACKAGE.equals(name)) {
                        vals[0] = value;
                    } else if (FUNCTION.equals(name)) {
                        vals[1] = value;
                    }
                });
                suite.addMockFunction(vals[0] + MOCK_ANNOTATION_DELIMITER + vals[1], functionName);
            }
        } else if (TEST_ANNOTATION_NAME.equals(annotationName)) {
            Test test = new Test();
            test.setTestName(functionName);
            AtomicBoolean shouldSkip = new AtomicBoolean();
            AtomicBoolean groupsFound = new AtomicBoolean();
            List<String> groups = registry.getGroups();
            boolean shouldIncludeGroups = registry.shouldIncludeGroups();
            if (attachmentNode.getExpression() instanceof BLangRecordLiteral) {
                List<BLangRecordLiteral.BLangRecordKeyValue> attributes = ((BLangRecordLiteral) attachmentNode.getExpression()).getKeyValuePairs();
                attributes.forEach(attributeNode -> {
                    String name = attributeNode.getKey().toString();
                    // Check if enable property is present in the annotation
                    if (TEST_ENABLE_ANNOTATION_NAME.equals(name) && "false".equals(attributeNode.getValue().toString())) {
                        // If enable is false, disable the test, no further processing is needed
                        shouldSkip.set(true);
                        return;
                    }
                    // Check whether user has provided a group list
                    if (groups != null && !groups.isEmpty()) {
                        // check if groups attribute is present in the annotation
                        if (GROUP_ANNOTATION_NAME.equals(name)) {
                            if (attributeNode.getValue() instanceof BLangArrayLiteral) {
                                BLangArrayLiteral values = (BLangArrayLiteral) attributeNode.getValue();
                                boolean isGroupPresent = isGroupAvailable(groups, values.exprs.stream().map(node -> node.toString()).collect(Collectors.toList()));
                                if (shouldIncludeGroups) {
                                    // include only if the test belong to one of these groups
                                    if (!isGroupPresent) {
                                        // skip the test if this group is not defined in this test
                                        shouldSkip.set(true);
                                        return;
                                    }
                                } else {
                                    // exclude only if the test belong to one of these groups
                                    if (isGroupPresent) {
                                        // skip if this test belongs to one of the excluded groups
                                        shouldSkip.set(true);
                                        return;
                                    }
                                }
                                groupsFound.set(true);
                            }
                        }
                    }
                    if (VALUE_SET_ANNOTATION_NAME.equals(name)) {
                        test.setDataProvider(attributeNode.getValue().toString());
                    }
                    if (BEFORE_FUNCTION.equals(name)) {
                        test.setBeforeTestFunction(attributeNode.getValue().toString());
                    }
                    if (AFTER_FUNCTION.equals(name)) {
                        test.setAfterTestFunction(attributeNode.getValue().toString());
                    }
                    if (DEPENDS_ON_FUNCTIONS.equals(name)) {
                        if (attributeNode.getValue() instanceof BLangArrayLiteral) {
                            BLangArrayLiteral values = (BLangArrayLiteral) attributeNode.getValue();
                            values.exprs.stream().map(node -> node.toString()).forEach(test::addDependsOnTestFunction);
                        }
                    }
                });
            }
            if (groups != null && !groups.isEmpty() && !groupsFound.get() && shouldIncludeGroups) {
                // if the user has asked to run only a specific list of groups and this test doesn't have
                // that group, we should skip the test
                shouldSkip.set(true);
            }
            if (!shouldSkip.get()) {
                suite.addTests(test);
            }
        } else {
        // disregard this annotation
        }
    }
}
Also used : Arrays(java.util.Arrays) PackageNode(org.ballerinalang.model.tree.PackageNode) BType(org.ballerinalang.model.types.BType) ProgramFile(org.ballerinalang.util.codegen.ProgramFile) TestSuite(org.ballerinalang.testerina.core.entity.TestSuite) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BallerinaException(org.ballerinalang.util.exceptions.BallerinaException) BLangRecordLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral) DiagnosticLog(org.ballerinalang.util.diagnostic.DiagnosticLog) PackageInfo(org.ballerinalang.util.codegen.PackageInfo) ArrayList(java.util.ArrayList) SupportedAnnotationPackages(org.ballerinalang.compiler.plugins.SupportedAnnotationPackages) AbstractCompilerPlugin(org.ballerinalang.compiler.plugins.AbstractCompilerPlugin) Vector(java.util.Vector) Map(java.util.Map) TesterinaFunction(org.ballerinalang.testerina.core.entity.TesterinaFunction) BLangArrayLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangArrayLiteral) LinkedList(java.util.LinkedList) BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) FunctionNode(org.ballerinalang.model.tree.FunctionNode) TypeTags(org.ballerinalang.model.types.TypeTags) Collectors(java.util.stream.Collectors) AnnotationAttachmentNode(org.ballerinalang.model.tree.AnnotationAttachmentNode) BArrayType(org.ballerinalang.model.types.BArrayType) List(java.util.List) Instruction(org.ballerinalang.util.codegen.Instruction) Test(org.ballerinalang.testerina.core.entity.Test) Queue(java.util.Queue) FunctionInfo(org.ballerinalang.util.codegen.FunctionInfo) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.ballerinalang.testerina.core.entity.Test) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) BLangArrayLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangArrayLiteral) BLangRecordLiteral(org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral) AnnotationAttachmentNode(org.ballerinalang.model.tree.AnnotationAttachmentNode)

Example 4 with PACKAGE

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.PACKAGE in project ballerina by ballerina-lang.

the class HtmlDocTest method testAnonymousStructs.

@Test(description = "Tests whether anonymous structs are documented.")
public void testAnonymousStructs() {
    BLangPackage bLangPackage = createPackage("package x.y; " + "@Description { value:\"Represents a person\"}" + "@Field {value:\"id: The identification number\"}\n" + "@Field {value:\"address: The address of the person.\"}" + "public struct Person {" + "  string id;" + "  struct {" + "     string address1;" + "     string address2;" + "     string state = \"MN\";" + "  } address;" + "}");
    Page page = generatePage(bLangPackage);
    Assert.assertEquals(page.constructs.size(), 1);
    Assert.assertTrue(page.constructs.get(0) instanceof StructDoc, "Documentable of type StructDoc expected.");
    StructDoc personStructDoc = (StructDoc) page.constructs.get(0);
    Assert.assertEquals(personStructDoc.fields.size(), 2, "2 fields are expected.");
    Assert.assertEquals(personStructDoc.fields.get(0).name, "id", "Field \"id\" expected.");
    Assert.assertEquals(personStructDoc.fields.get(1).name, "address", "Field \"address\" expected.");
    Assert.assertEquals(personStructDoc.fields.get(1).description, "The address of the person.");
    Assert.assertEquals(personStructDoc.fields.get(1).dataType, "struct {string address1, string address2, string state}");
}
Also used : BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) Page(org.ballerinalang.docgen.model.Page) StructDoc(org.ballerinalang.docgen.model.StructDoc) Test(org.testng.annotations.Test)

Example 5 with PACKAGE

use of org.wso2.ballerinalang.compiler.codegen.CodeGenerator.VariableIndex.Kind.PACKAGE in project ballerina by ballerina-lang.

the class HtmlDocTest method testGlobalVariables.

@Test(description = "Annotation in a package should be shown in the constructs")
public void testGlobalVariables() throws Exception {
    BLangPackage bLangPackage = createPackage("package x.y; " + "public int total = 98;" + "public string content = \"Name\";");
    Page page = generatePage(bLangPackage);
    Assert.assertEquals(page.constructs.size(), 2);
    Assert.assertEquals(page.constructs.get(0).name, "total");
    Assert.assertEquals(page.constructs.get(1).name, "content");
}
Also used : BLangPackage(org.wso2.ballerinalang.compiler.tree.BLangPackage) Page(org.ballerinalang.docgen.model.Page) Test(org.testng.annotations.Test)

Aggregations

BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)49 ArrayList (java.util.ArrayList)34 Test (org.testng.annotations.Test)29 Page (org.ballerinalang.docgen.model.Page)18 File (java.io.File)16 CompilerContext (org.wso2.ballerinalang.compiler.util.CompilerContext)16 IOException (java.io.IOException)15 Path (java.nio.file.Path)13 List (java.util.List)13 BLangStruct (org.wso2.ballerinalang.compiler.tree.BLangStruct)11 PackageID (org.ballerinalang.model.elements.PackageID)10 Compiler (org.wso2.ballerinalang.compiler.Compiler)10 BLangFunction (org.wso2.ballerinalang.compiler.tree.BLangFunction)10 CompilerOptions (org.wso2.ballerinalang.compiler.util.CompilerOptions)10 Collectors (java.util.stream.Collectors)9 Arrays (java.util.Arrays)8 CompilerPhase (org.ballerinalang.compiler.CompilerPhase)7 BInvokableSymbol (org.wso2.ballerinalang.compiler.semantics.model.symbols.BInvokableSymbol)6 BPackageSymbol (org.wso2.ballerinalang.compiler.semantics.model.symbols.BPackageSymbol)6 BLangNode (org.wso2.ballerinalang.compiler.tree.BLangNode)6