Search in sources :

Example 1 with Struct

use of org.ballerinalang.connector.api.Struct in project ballerina by ballerina-lang.

the class InitEndpoint method execute.

@Override
public void execute(Context context) {
    Struct clientEndpoint = BLangConnectorSPIUtil.getConnectorEndpointStruct(context);
    Struct clientEndpointConfig = clientEndpoint.getStructField(Constants.CLIENT_ENDPOINT_CONFIG);
    // Extract parameters from the endpoint config
    String database = clientEndpointConfig.getEnumField(Constants.EndpointConfig.DATABASE);
    String host = clientEndpointConfig.getStringField(Constants.EndpointConfig.HOST);
    int port = (int) clientEndpointConfig.getIntField(Constants.EndpointConfig.PORT);
    String name = clientEndpointConfig.getStringField(Constants.EndpointConfig.NAME);
    String username = clientEndpointConfig.getStringField(Constants.EndpointConfig.USERNAME);
    String password = clientEndpointConfig.getStringField(Constants.EndpointConfig.PASSWORD);
    Struct options = clientEndpointConfig.getStructField(Constants.EndpointConfig.OPTIONS);
    SQLDatasource datasource = new SQLDatasource();
    datasource.init(options, database, host, port, username, password, name);
    BStruct ballerinaClientConnector;
    if (clientEndpoint.getNativeData(Constants.B_CONNECTOR) != null) {
        ballerinaClientConnector = (BStruct) clientEndpoint.getNativeData(Constants.B_CONNECTOR);
    } else {
        ballerinaClientConnector = BLangConnectorSPIUtil.createBStruct(context.getProgramFile(), Constants.SQL_PACKAGE_PATH, Constants.CLIENT_CONNECTOR, database, host, port, name, username, password, options, clientEndpointConfig);
        clientEndpoint.addNativeData(Constants.B_CONNECTOR, ballerinaClientConnector);
    }
    ballerinaClientConnector.addNativeData(Constants.CLIENT_CONNECTOR, datasource);
    context.setReturnValues();
}
Also used : BStruct(org.ballerinalang.model.values.BStruct) SQLDatasource(org.ballerinalang.nativeimpl.actions.data.sql.SQLDatasource) BStruct(org.ballerinalang.model.values.BStruct) Struct(org.ballerinalang.connector.api.Struct)

Example 2 with Struct

use of org.ballerinalang.connector.api.Struct in project ballerina by ballerina-lang.

the class WebSocketServicesRegistry method findFullWebSocketUpgradePath.

/**
 * Find the Full path for WebSocket upgrade.
 *
 * @param service {@link WebSocketService} which the full path should be found.
 * @return the full path of the WebSocket upgrade.
 */
private String findFullWebSocketUpgradePath(WebSocketService service) {
    // Find Base path for WebSocket
    Annotation configAnnotation = WebSocketUtil.getServiceConfigAnnotation(service, HttpConstants.PROTOCOL_PACKAGE_HTTP);
    String basePath = null;
    if (configAnnotation != null) {
        Struct annStruct = configAnnotation.getValue();
        String annotationValue = annStruct.getStringField(HttpConstants.ANN_CONFIG_ATTR_BASE_PATH);
        if (annotationValue != null && !annotationValue.trim().isEmpty()) {
            basePath = refactorUri(annotationValue);
        }
    }
    return basePath;
}
Also used : Annotation(org.ballerinalang.connector.api.Annotation) Struct(org.ballerinalang.connector.api.Struct)

Example 3 with Struct

use of org.ballerinalang.connector.api.Struct 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 4 with Struct

use of org.ballerinalang.connector.api.Struct in project ballerina by ballerina-lang.

the class CreateHttpClient method populateSenderConfigurationOptions.

private void populateSenderConfigurationOptions(SenderConfiguration senderConfiguration, Struct clientEndpointConfig) {
    ProxyServerConfiguration proxyServerConfiguration = null;
    boolean followRedirect = false;
    int maxRedirectCount = DEFAULT_MAX_REDIRECT_COUNT;
    Struct followRedirects = clientEndpointConfig.getStructField(HttpConstants.FOLLOW_REDIRECT_STRUCT_REFERENCE);
    if (followRedirects != null) {
        followRedirect = followRedirects.getBooleanField(HttpConstants.FOLLOW_REDIRECT_ENABLED);
        maxRedirectCount = (int) followRedirects.getIntField(HttpConstants.FOLLOW_REDIRECT_MAXCOUNT);
    }
    Struct secureSocket = null;
    Value[] targetServices = clientEndpointConfig.getArrayField(HttpConstants.TARGET_SERVICES);
    for (Value targetService : targetServices) {
        secureSocket = targetService.getStructValue().getStructField(HttpConstants.ENDPOINT_CONFIG_SECURE_SOCKET);
        if (secureSocket != null) {
            Struct trustStore = secureSocket.getStructField(HttpConstants.ENDPOINT_CONFIG_TRUST_STORE);
            Struct keyStore = secureSocket.getStructField(HttpConstants.ENDPOINT_CONFIG_KEY_STORE);
            Struct protocols = secureSocket.getStructField(HttpConstants.ENDPOINT_CONFIG_PROTOCOLS);
            Struct validateCert = secureSocket.getStructField(HttpConstants.ENDPOINT_CONFIG_VALIDATE_CERT);
            List<Parameter> clientParams = new ArrayList<>();
            if (trustStore != null) {
                String trustStoreFile = trustStore.getStringField(HttpConstants.FILE_PATH);
                if (StringUtils.isNotBlank(trustStoreFile)) {
                    senderConfiguration.setTrustStoreFile(trustStoreFile);
                }
                String trustStorePassword = trustStore.getStringField(HttpConstants.PASSWORD);
                if (StringUtils.isNotBlank(trustStorePassword)) {
                    senderConfiguration.setTrustStorePass(trustStorePassword);
                }
            }
            if (keyStore != null) {
                String keyStoreFile = keyStore.getStringField(HttpConstants.FILE_PATH);
                if (StringUtils.isNotBlank(keyStoreFile)) {
                    senderConfiguration.setKeyStoreFile(keyStoreFile);
                }
                String keyStorePassword = keyStore.getStringField(HttpConstants.PASSWORD);
                if (StringUtils.isNotBlank(keyStorePassword)) {
                    senderConfiguration.setKeyStorePassword(keyStorePassword);
                }
            }
            if (protocols != null) {
                String sslEnabledProtocols = protocols.getStringField(HttpConstants.ENABLED_PROTOCOLS);
                if (StringUtils.isNotBlank(sslEnabledProtocols)) {
                    Parameter clientProtocols = new Parameter(HttpConstants.SSL_ENABLED_PROTOCOLS, sslEnabledProtocols);
                    clientParams.add(clientProtocols);
                }
                String sslProtocol = protocols.getStringField(HttpConstants.PROTOCOL_VERSION);
                if (StringUtils.isNotBlank(sslProtocol)) {
                    senderConfiguration.setSSLProtocol(sslProtocol);
                }
            }
            if (validateCert != null) {
                boolean validateCertEnabled = validateCert.getBooleanField(HttpConstants.ENABLE);
                int cacheSize = (int) validateCert.getIntField(HttpConstants.SSL_CONFIG_CACHE_SIZE);
                int cacheValidityPeriod = (int) validateCert.getIntField(HttpConstants.SSL_CONFIG_CACHE_VALIDITY_PERIOD);
                senderConfiguration.setValidateCertEnabled(validateCertEnabled);
                if (cacheValidityPeriod != 0) {
                    senderConfiguration.setCacheValidityPeriod(cacheValidityPeriod);
                }
                if (cacheSize != 0) {
                    senderConfiguration.setCacheSize(cacheSize);
                }
            }
            boolean hostNameVerificationEnabled = secureSocket.getBooleanField(HttpConstants.SSL_CONFIG_HOST_NAME_VERIFICATION_ENABLED);
            senderConfiguration.setHostNameVerificationEnabled(hostNameVerificationEnabled);
            String ciphers = secureSocket.getStringField(HttpConstants.SSL_CONFIG_CIPHERS);
            if (StringUtils.isNotBlank(ciphers)) {
                Parameter clientCiphers = new Parameter(HttpConstants.CIPHERS, ciphers);
                clientParams.add(clientCiphers);
            }
            String enableSessionCreation = String.valueOf(secureSocket.getBooleanField(HttpConstants.SSL_CONFIG_ENABLE_SESSION_CREATION));
            Parameter clientEnableSessionCreation = new Parameter(HttpConstants.SSL_CONFIG_ENABLE_SESSION_CREATION, enableSessionCreation);
            clientParams.add(clientEnableSessionCreation);
            if (!clientParams.isEmpty()) {
                senderConfiguration.setParameters(clientParams);
            }
        }
    }
    Struct proxy = clientEndpointConfig.getStructField(HttpConstants.PROXY_STRUCT_REFERENCE);
    if (proxy != null) {
        String proxyHost = proxy.getStringField(HttpConstants.PROXY_HOST);
        int proxyPort = (int) proxy.getIntField(HttpConstants.PROXY_PORT);
        String proxyUserName = proxy.getStringField(HttpConstants.PROXY_USERNAME);
        String proxyPassword = proxy.getStringField(HttpConstants.PROXY_PASSWORD);
        try {
            proxyServerConfiguration = new ProxyServerConfiguration(proxyHost, proxyPort);
        } catch (UnknownHostException e) {
            throw new BallerinaConnectorException("Failed to resolve host" + proxyHost, e);
        }
        if (!proxyUserName.isEmpty()) {
            proxyServerConfiguration.setProxyUsername(proxyUserName);
        }
        if (!proxyPassword.isEmpty()) {
            proxyServerConfiguration.setProxyPassword(proxyPassword);
        }
        senderConfiguration.setProxyServerConfiguration(proxyServerConfiguration);
    }
    senderConfiguration.setFollowRedirect(followRedirect);
    senderConfiguration.setMaxRedirectCount(maxRedirectCount);
    // For the moment we don't have to pass it down to transport as we only support
    // chunking. Once we start supporting gzip, deflate, etc, we need to parse down the config.
    String transferEncoding = clientEndpointConfig.getEnumField(HttpConstants.CLIENT_EP_TRNASFER_ENCODING);
    if (transferEncoding != null && !HttpConstants.ANN_CONFIG_ATTR_CHUNKING.equalsIgnoreCase(transferEncoding)) {
        throw new BallerinaConnectorException("Unsupported configuration found for Transfer-Encoding : " + transferEncoding);
    }
    String chunking = clientEndpointConfig.getEnumField(HttpConstants.CLIENT_EP_CHUNKING);
    senderConfiguration.setChunkingConfig(HttpUtil.getChunkConfig(chunking));
    long endpointTimeout = clientEndpointConfig.getIntField(HttpConstants.CLIENT_EP_ENDPOINT_TIMEOUT);
    if (endpointTimeout < 0 || !isInteger(endpointTimeout)) {
        throw new BallerinaConnectorException("invalid idle timeout: " + endpointTimeout);
    }
    senderConfiguration.setSocketIdleTimeout((int) endpointTimeout);
    boolean isKeepAlive = clientEndpointConfig.getBooleanField(HttpConstants.CLIENT_EP_IS_KEEP_ALIVE);
    senderConfiguration.setKeepAlive(isKeepAlive);
    String httpVersion = clientEndpointConfig.getStringField(HttpConstants.CLIENT_EP_HTTP_VERSION);
    if (httpVersion != null) {
        senderConfiguration.setHttpVersion(httpVersion);
    }
    String forwardedExtension = clientEndpointConfig.getStringField(HttpConstants.CLIENT_EP_FORWARDED);
    senderConfiguration.setForwardedExtensionConfig(HttpUtil.getForwardedExtensionConfig(forwardedExtension));
}
Also used : BallerinaConnectorException(org.ballerinalang.connector.api.BallerinaConnectorException) UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) BStruct(org.ballerinalang.model.values.BStruct) Struct(org.ballerinalang.connector.api.Struct) ProxyServerConfiguration(org.wso2.transport.http.netty.common.ProxyServerConfiguration) Value(org.ballerinalang.connector.api.Value) Parameter(org.wso2.transport.http.netty.config.Parameter)

Example 5 with Struct

use of org.ballerinalang.connector.api.Struct in project ballerina by ballerina-lang.

the class NonListeningRegister method execute.

@Override
public void execute(Context context) {
    Service service = BLangConnectorSPIUtil.getServiceRegistered(context);
    Struct serviceEndpoint = BLangConnectorSPIUtil.getConnectorEndpointStruct(context);
    HTTPServicesRegistry httpServicesRegistry = getHttpServicesRegistry(serviceEndpoint);
    WebSocketServicesRegistry webSocketServicesRegistry = getWebSocketServicesRegistry(serviceEndpoint);
    // TODO: In HTTP to WebSocket upgrade register WebSocket service in WebSocketServiceRegistry
    if (HttpConstants.HTTP_SERVICE_ENDPOINT_NAME.equals(service.getEndpointName())) {
        httpServicesRegistry.registerService(service);
    }
    if (WebSocketConstants.WEBSOCKET_ENDPOINT_NAME.equals(service.getEndpointName())) {
        WebSocketService webSocketService = new WebSocketService(service);
        webSocketServicesRegistry.registerService(webSocketService);
    }
    context.setReturnValues();
}
Also used : HTTPServicesRegistry(org.ballerinalang.net.http.HTTPServicesRegistry) WebSocketServicesRegistry(org.ballerinalang.net.http.WebSocketServicesRegistry) Service(org.ballerinalang.connector.api.Service) WebSocketService(org.ballerinalang.net.http.WebSocketService) WebSocketService(org.ballerinalang.net.http.WebSocketService) Struct(org.ballerinalang.connector.api.Struct)

Aggregations

Struct (org.ballerinalang.connector.api.Struct)26 BStruct (org.ballerinalang.model.values.BStruct)16 BallerinaConnectorException (org.ballerinalang.connector.api.BallerinaConnectorException)9 ArrayList (java.util.ArrayList)4 Annotation (org.ballerinalang.connector.api.Annotation)4 Service (org.ballerinalang.connector.api.Service)4 WebSocketService (org.ballerinalang.net.http.WebSocketService)4 WebSocketServicesRegistry (org.ballerinalang.net.http.WebSocketServicesRegistry)4 IOException (java.io.IOException)3 EndpointConfiguration (org.ballerinalang.net.grpc.config.EndpointConfiguration)3 HTTPServicesRegistry (org.ballerinalang.net.http.HTTPServicesRegistry)3 ResponseCacheControlStruct (org.ballerinalang.net.http.caching.ResponseCacheControlStruct)3 WebSubServicesRegistry (org.ballerinalang.net.websub.WebSubServicesRegistry)3 SslContext (io.netty.handler.ssl.SslContext)2 Resource (org.ballerinalang.connector.api.Resource)2 Value (org.ballerinalang.connector.api.Value)2 BLogManager (org.ballerinalang.logging.BLogManager)2 SSLHandlerFactory (org.ballerinalang.net.grpc.ssl.SSLHandlerFactory)2 RetryConfig (org.ballerinalang.net.http.RetryConfig)2 BallerinaException (org.ballerinalang.util.exceptions.BallerinaException)2