Search in sources :

Example 21 with Source

use of org.wso2.siddhi.core.stream.input.source.Source in project wso2-synapse by wso2.

the class EventSourceFactory method createEventSource.

@SuppressWarnings({ "UnusedDeclaration" })
public static SynapseEventSource createEventSource(OMElement elem, Properties properties) {
    SynapseEventSource eventSource = null;
    OMAttribute name = elem.getAttribute(new QName(XMLConfigConstants.NULL_NAMESPACE, "name"));
    if (name == null) {
        handleException("The 'name' attribute is required for a event source de");
    } else {
        eventSource = new SynapseEventSource(name.getAttributeValue());
    }
    OMElement subscriptionManagerElem = elem.getFirstChildWithName(SUBSCRIPTION_MANAGER_QNAME);
    if (eventSource != null && subscriptionManagerElem != null) {
        OMAttribute clazz = subscriptionManagerElem.getAttribute(new QName(XMLConfigConstants.NULL_NAMESPACE, "class"));
        if (clazz != null) {
            String className = clazz.getAttributeValue();
            try {
                Class subscriptionManagerClass = Class.forName(className);
                SubscriptionManager manager = (SubscriptionManager) subscriptionManagerClass.newInstance();
                Iterator itr = subscriptionManagerElem.getChildrenWithName(PROPERTIES_QNAME);
                while (itr.hasNext()) {
                    OMElement propElem = (OMElement) itr.next();
                    String propName = propElem.getAttribute(new QName("name")).getAttributeValue();
                    String propValue = propElem.getAttribute(new QName("value")).getAttributeValue();
                    if (propName != null && !"".equals(propName.trim()) && propValue != null && !"".equals(propValue.trim())) {
                        propName = propName.trim();
                        propValue = propValue.trim();
                        PasswordManager passwordManager = PasswordManager.getInstance();
                        String key = eventSource.getName() + "." + propName;
                        if (passwordManager.isInitialized() && passwordManager.isTokenProtected(key)) {
                            eventSource.putConfigurationProperty(propName, propValue);
                            propValue = passwordManager.resolve(propValue);
                        }
                        manager.addProperty(propName, propValue);
                    }
                }
                eventSource.setSubscriptionManager(manager);
                eventSource.getSubscriptionManager().init();
            } catch (ClassNotFoundException e) {
                handleException("SubscriptionManager class not found", e);
            } catch (IllegalAccessException e) {
                handleException("Unable to access the SubscriptionManager object", e);
            } catch (InstantiationException e) {
                handleException("Unable to instantiate the SubscriptionManager object", e);
            }
        } else {
            handleException("SynapseSubscription manager class is a required attribute");
        }
    } else {
        handleException("SynapseSubscription Manager has not been specified for the event source");
    }
    try {
        createStaticSubscriptions(elem, eventSource);
    } catch (EventException e) {
        handleException("Static subscription creation failure", e);
    }
    return eventSource;
}
Also used : SynapseEventSource(org.apache.synapse.eventing.SynapseEventSource) EventException(org.wso2.eventing.exceptions.EventException) QName(javax.xml.namespace.QName) PasswordManager(org.wso2.securevault.PasswordManager) OMElement(org.apache.axiom.om.OMElement) SubscriptionManager(org.wso2.eventing.SubscriptionManager) Iterator(java.util.Iterator) OMAttribute(org.apache.axiom.om.OMAttribute)

Example 22 with Source

use of org.wso2.siddhi.core.stream.input.source.Source in project ballerina by ballerina-lang.

the class AbstractHTTPAction method send.

/**
 * Send outbound request through the client connector. If the Content-Type is multipart, check whether the boundary
 * exist. If not get a new boundary string and add it as a parameter to Content-Type, just before sending header
 * info through wire. If a boundary string exist at this point, serialize multipart entity body, else serialize
 * entity body which can either be a message data source or a byte channel.
 *
 * @param dataContext               holds the ballerina context and callback
 * @param outboundRequestMsg        Outbound request that needs to be sent across the wire
 * @param async                     whether a handle should be return
 * @return connector future for this particular request
 * @throws Exception When an error occurs while sending the outbound request via client connector
 */
private void send(DataContext dataContext, HTTPCarbonMessage outboundRequestMsg, boolean async) throws Exception {
    BStruct bConnector = (BStruct) dataContext.context.getRefArgument(0);
    Struct httpClient = BLangConnectorSPIUtil.toStruct(bConnector);
    HttpClientConnector clientConnector = (HttpClientConnector) httpClient.getNativeData(HttpConstants.HTTP_CLIENT);
    String contentType = HttpUtil.getContentTypeFromTransportMessage(outboundRequestMsg);
    String boundaryString = null;
    if (HeaderUtil.isMultipart(contentType)) {
        boundaryString = HttpUtil.addBoundaryIfNotExist(outboundRequestMsg, contentType);
    }
    HttpMessageDataStreamer outboundMsgDataStreamer = new HttpMessageDataStreamer(outboundRequestMsg);
    OutputStream messageOutputStream = outboundMsgDataStreamer.getOutputStream();
    RetryConfig retryConfig = getRetryConfiguration(httpClient);
    HTTPClientConnectorListener httpClientConnectorLister = new HTTPClientConnectorListener(dataContext, retryConfig, outboundRequestMsg, outboundMsgDataStreamer);
    HttpResponseFuture future = clientConnector.send(outboundRequestMsg);
    if (async) {
        future.setResponseHandleListener(httpClientConnectorLister);
    } else {
        future.setHttpConnectorListener(httpClientConnectorLister);
    }
    try {
        if (boundaryString != null) {
            serializeMultiparts(dataContext.context, messageOutputStream, boundaryString);
        } else {
            serializeDataSource(dataContext.context, messageOutputStream);
        }
    } catch (IOException | EncoderException serializerException) {
        // We don't have to do anything here as the client connector will notify
        // the error though the listener
        logger.warn("couldn't serialize the message", serializerException);
    }
}
Also used : EncoderException(io.netty.handler.codec.EncoderException) BStruct(org.ballerinalang.model.values.BStruct) HttpClientConnector(org.wso2.transport.http.netty.contract.HttpClientConnector) RetryConfig(org.ballerinalang.net.http.RetryConfig) HttpMessageDataStreamer(org.wso2.transport.http.netty.message.HttpMessageDataStreamer) OutputStream(java.io.OutputStream) HttpResponseFuture(org.wso2.transport.http.netty.contract.HttpResponseFuture) IOException(java.io.IOException) ResponseCacheControlStruct(org.ballerinalang.net.http.caching.ResponseCacheControlStruct) Struct(org.ballerinalang.connector.api.Struct) BStruct(org.ballerinalang.model.values.BStruct)

Example 23 with Source

use of org.wso2.siddhi.core.stream.input.source.Source in project ballerina by ballerina-lang.

the class SwaggerConverterUtils method generateSwaggerDefinitions.

/**
 * This method will generate ballerina string from swagger definition. Since ballerina service definition is super
 * set of swagger definition we will take both swagger and ballerina definition and merge swagger changes to
 * ballerina definition selectively to prevent data loss
 *
 * @param ballerinaSource ballerina definition to be process as ballerina definition
 * @param serviceName service name
 * @return String representation of converted ballerina source
 * @throws IOException when error occur while processing input swagger and ballerina definitions.
 */
public static String generateSwaggerDefinitions(String ballerinaSource, String serviceName) throws IOException {
    // Get the ballerina model using the ballerina source code.
    BFile balFile = new BFile();
    balFile.setContent(ballerinaSource);
    BLangCompilationUnit topCompilationUnit = SwaggerConverterUtils.getTopLevelNodeFromBallerinaFile(balFile);
    String httpAlias = getAlias(topCompilationUnit, Constants.BALLERINA_HTTP_PACKAGE_NAME);
    String swaggerAlias = getAlias(topCompilationUnit, Constants.SWAGGER_PACKAGE_NAME);
    SwaggerServiceMapper swaggerServiceMapper = new SwaggerServiceMapper(httpAlias, swaggerAlias);
    String swaggerSource = StringUtils.EMPTY;
    for (TopLevelNode topLevelNode : topCompilationUnit.getTopLevelNodes()) {
        if (topLevelNode instanceof BLangService) {
            ServiceNode serviceDefinition = (ServiceNode) topLevelNode;
            // Generate swagger string for the mentioned service name.
            if (StringUtils.isNotBlank(serviceName)) {
                if (serviceDefinition.getName().getValue().equals(serviceName)) {
                    Swagger swaggerDefinition = swaggerServiceMapper.convertServiceToSwagger(serviceDefinition);
                    swaggerSource = swaggerServiceMapper.generateSwaggerString(swaggerDefinition);
                    break;
                }
            } else {
                // If no service name mentioned, then generate swagger definition for the first service.
                Swagger swaggerDefinition = swaggerServiceMapper.convertServiceToSwagger(serviceDefinition);
                swaggerSource = swaggerServiceMapper.generateSwaggerString(swaggerDefinition);
                break;
            }
        }
    }
    return swaggerSource;
}
Also used : ServiceNode(org.ballerinalang.model.tree.ServiceNode) BLangService(org.wso2.ballerinalang.compiler.tree.BLangService) Swagger(io.swagger.models.Swagger) BFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BFile) BLangCompilationUnit(org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit) TopLevelNode(org.ballerinalang.model.tree.TopLevelNode)

Example 24 with Source

use of org.wso2.siddhi.core.stream.input.source.Source in project ballerina by ballerina-lang.

the class SwaggerConverterUtils method generateOAS3Definitions.

/**
 * This method will generate open API 3.X specification for given ballerina service. Since we will need to
 * support both swagger 2.0 and OAS 3.0 it was implemented to convert to swagger by default and convert it
 * to OAS on demand.
 *
 * @param ballerinaSource ballerina source to be converted to swagger/OAS definition
 * @param serviceName specific service name within ballerina source that need to map OAS
 * @return Generated OAS3 string output.
 * @throws IOException When error occurs while converting, parsing input source.
 */
public static String generateOAS3Definitions(String ballerinaSource, String serviceName) throws IOException {
    // Get the ballerina model using the ballerina source code.
    BFile balFile = new BFile();
    balFile.setContent(ballerinaSource);
    // Create empty swagger object.
    Swagger swaggerDefinition = new Swagger();
    BLangCompilationUnit topCompilationUnit = SwaggerConverterUtils.getTopLevelNodeFromBallerinaFile(balFile);
    String httpAlias = getAlias(topCompilationUnit, Constants.BALLERINA_HTTP_PACKAGE_NAME);
    String swaggerAlias = getAlias(topCompilationUnit, Constants.SWAGGER_PACKAGE_NAME);
    SwaggerServiceMapper swaggerServiceMapper = new SwaggerServiceMapper(httpAlias, swaggerAlias);
    String swaggerSource = StringUtils.EMPTY;
    for (TopLevelNode topLevelNode : topCompilationUnit.getTopLevelNodes()) {
        if (topLevelNode instanceof BLangService) {
            ServiceNode serviceDefinition = (ServiceNode) topLevelNode;
            // Generate swagger string for the mentioned service name.
            if (StringUtils.isNotBlank(serviceName)) {
                if (serviceDefinition.getName().getValue().equals(serviceName)) {
                    swaggerDefinition = swaggerServiceMapper.convertServiceToSwagger(serviceDefinition);
                    break;
                }
            } else {
                // If no service name mentioned, then generate swagger definition for the first service.
                swaggerDefinition = swaggerServiceMapper.convertServiceToSwagger(serviceDefinition);
                break;
            }
        }
    }
    swaggerSource = swaggerServiceMapper.generateSwaggerString(swaggerDefinition);
    SwaggerConverter converter = new SwaggerConverter();
    return Yaml.pretty(converter.readContents(swaggerSource, null, null).getOpenAPI());
}
Also used : ServiceNode(org.ballerinalang.model.tree.ServiceNode) Swagger(io.swagger.models.Swagger) BLangService(org.wso2.ballerinalang.compiler.tree.BLangService) SwaggerConverter(io.swagger.v3.parser.converter.SwaggerConverter) BFile(org.ballerinalang.composer.service.ballerina.parser.service.model.BFile) BLangCompilationUnit(org.wso2.ballerinalang.compiler.tree.BLangCompilationUnit) TopLevelNode(org.ballerinalang.model.tree.TopLevelNode)

Example 25 with Source

use of org.wso2.siddhi.core.stream.input.source.Source in project ballerina by ballerina-lang.

the class DocumentationTest method testDocTransformer.

@Test(description = "Test doc transformer.")
public void testDocTransformer() {
    CompileResult compileResult = BCompileUtil.compile("test-src/documentation/transformer.bal");
    Assert.assertEquals(0, compileResult.getWarnCount());
    PackageNode packageNode = compileResult.getAST();
    List<BLangDocumentation> docNodes = ((BLangTransformer) packageNode.getTransformers().get(0)).docAttachments;
    BLangDocumentation dNode = docNodes.get(0);
    Assert.assertNotNull(dNode);
    Assert.assertEquals(dNode.documentationText, "\n" + " Transformer Foo Person -> Employee\n" + " ");
    Assert.assertEquals(dNode.getAttributes().size(), 3);
    Assert.assertEquals(dNode.getAttributes().get(0).documentationField.getValue(), "p");
    Assert.assertEquals(dNode.getAttributes().get(0).documentationText, " input struct Person source used for transformation\n ");
    Assert.assertEquals(dNode.getAttributes().get(1).documentationField.getValue(), "e");
    Assert.assertEquals(dNode.getAttributes().get(1).documentationText, " output struct Employee struct which Person transformed to\n ");
    Assert.assertEquals(dNode.getAttributes().get(2).documentationField.getValue(), "defaultAddress");
    Assert.assertEquals(dNode.getAttributes().get(2).documentationText, " address which serves Eg: `POSTCODE 112`\n");
}
Also used : BLangTransformer(org.wso2.ballerinalang.compiler.tree.BLangTransformer) BLangDocumentation(org.wso2.ballerinalang.compiler.tree.BLangDocumentation) CompileResult(org.ballerinalang.launcher.util.CompileResult) PackageNode(org.ballerinalang.model.tree.PackageNode) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)22 CompilerContext (org.wso2.ballerinalang.compiler.util.CompilerContext)15 ArrayList (java.util.ArrayList)11 CompilerOptions (org.wso2.ballerinalang.compiler.util.CompilerOptions)11 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)11 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)11 ANTLRInputStream (org.antlr.v4.runtime.ANTLRInputStream)8 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)8 ParseTree (org.antlr.v4.runtime.tree.ParseTree)8 OMElement (org.apache.axiom.om.OMElement)8 TopLevelNode (org.ballerinalang.model.tree.TopLevelNode)8 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)8 DiagnosticPos (org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos)8 DocumentInfo (org.wso2.carbon.apimgt.core.models.DocumentInfo)8 Event (org.wso2.siddhi.core.event.Event)8 HashMap (java.util.HashMap)7 List (java.util.List)7 Compiler (org.wso2.ballerinalang.compiler.Compiler)7 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)6 SiddhiQLBaseVisitorImpl (org.wso2.siddhi.query.compiler.internal.SiddhiQLBaseVisitorImpl)6