Search in sources :

Example 1 with Address

use of org.wso2.carbon.consent.mgt.core.model.Address in project wso2-axis2-transports by wso2.

the class RabbitMQConnectionFactory method initConnectionFactory.

/**
 * Initialize connection factory
 */
private void initConnectionFactory() {
    connectionFactory = new ConnectionFactory();
    String hostName = parameters.get(RabbitMQConstants.SERVER_HOST_NAME);
    String portValue = parameters.get(RabbitMQConstants.SERVER_PORT);
    String serverRetryIntervalS = parameters.get(RabbitMQConstants.SERVER_RETRY_INTERVAL);
    String retryIntervalS = parameters.get(RabbitMQConstants.RETRY_INTERVAL);
    String retryCountS = parameters.get(RabbitMQConstants.RETRY_COUNT);
    String heartbeat = parameters.get(RabbitMQConstants.HEARTBEAT);
    String connectionTimeout = parameters.get(RabbitMQConstants.CONNECTION_TIMEOUT);
    String sslEnabledS = parameters.get(RabbitMQConstants.SSL_ENABLED);
    String userName = parameters.get(RabbitMQConstants.SERVER_USER_NAME);
    String password = parameters.get(RabbitMQConstants.SERVER_PASSWORD);
    String virtualHost = parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST);
    String connectionPoolSizeS = parameters.get(RabbitMQConstants.CONNECTION_POOL_SIZE);
    if (!StringUtils.isEmpty(heartbeat)) {
        try {
            int heartbeatValue = Integer.parseInt(heartbeat);
            connectionFactory.setRequestedHeartbeat(heartbeatValue);
        } catch (NumberFormatException e) {
            // proceeding with rabbitmq default value
            log.warn("Number format error in reading heartbeat value. Proceeding with default");
        }
    }
    if (!StringUtils.isEmpty(connectionTimeout)) {
        try {
            int connectionTimeoutValue = Integer.parseInt(connectionTimeout);
            connectionFactory.setConnectionTimeout(connectionTimeoutValue);
        } catch (NumberFormatException e) {
            // proceeding with rabbitmq default value
            log.warn("Number format error in reading connection timeout value. Proceeding with default");
        }
    }
    if (!StringUtils.isEmpty(connectionPoolSizeS)) {
        try {
            connectionPoolSize = Integer.parseInt(connectionPoolSizeS);
        } catch (NumberFormatException e) {
            // proceeding with rabbitmq default value
            log.warn("Number format error in reading connection timeout value. Proceeding with default");
        }
    }
    if (!StringUtils.isEmpty(sslEnabledS)) {
        try {
            boolean sslEnabled = Boolean.parseBoolean(sslEnabledS);
            if (sslEnabled) {
                String keyStoreLocation = parameters.get(RabbitMQConstants.SSL_KEYSTORE_LOCATION);
                String keyStoreType = parameters.get(RabbitMQConstants.SSL_KEYSTORE_TYPE);
                String keyStorePassword = parameters.get(RabbitMQConstants.SSL_KEYSTORE_PASSWORD);
                String trustStoreLocation = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_LOCATION);
                String trustStoreType = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_TYPE);
                String trustStorePassword = parameters.get(RabbitMQConstants.SSL_TRUSTSTORE_PASSWORD);
                String sslVersion = parameters.get(RabbitMQConstants.SSL_VERSION);
                if (StringUtils.isEmpty(keyStoreLocation) || StringUtils.isEmpty(keyStoreType) || StringUtils.isEmpty(keyStorePassword) || StringUtils.isEmpty(trustStoreLocation) || StringUtils.isEmpty(trustStoreType) || StringUtils.isEmpty(trustStorePassword)) {
                    log.info("Trustore and keystore information is not provided");
                    if (StringUtils.isNotEmpty(sslVersion)) {
                        connectionFactory.useSslProtocol(sslVersion);
                    } else {
                        log.info("Proceeding with default SSL configuration");
                        connectionFactory.useSslProtocol();
                    }
                } else {
                    char[] keyPassphrase = keyStorePassword.toCharArray();
                    KeyStore ks = KeyStore.getInstance(keyStoreType);
                    ks.load(new FileInputStream(keyStoreLocation), keyPassphrase);
                    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    kmf.init(ks, keyPassphrase);
                    char[] trustPassphrase = trustStorePassword.toCharArray();
                    KeyStore tks = KeyStore.getInstance(trustStoreType);
                    tks.load(new FileInputStream(trustStoreLocation), trustPassphrase);
                    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    tmf.init(tks);
                    SSLContext c = SSLContext.getInstance(sslVersion);
                    c.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
                    connectionFactory.useSslProtocol(c);
                }
            }
        } catch (Exception e) {
            log.warn("Format error in SSL enabled value. Proceeding without enabling SSL", e);
        }
    }
    if (!StringUtils.isEmpty(retryCountS)) {
        try {
            retryCount = Integer.parseInt(retryCountS);
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading retry count value. Proceeding with default value (3)", e);
        }
    }
    // Resolving hostname(s) and port(s)
    if (!StringUtils.isEmpty(hostName) && !StringUtils.isEmpty(portValue)) {
        String[] hostNames = hostName.split(",");
        String[] portValues = portValue.split(",");
        if (hostNames.length == portValues.length) {
            addresses = new Address[hostNames.length];
            for (int i = 0; i < hostNames.length; i++) {
                if (!hostNames[i].isEmpty() && !portValues[i].isEmpty()) {
                    try {
                        addresses[i] = new Address(hostNames[i].trim(), Integer.parseInt(portValues[i].trim()));
                    } catch (NumberFormatException e) {
                        handleException("Number format error in port number", e);
                    }
                }
            }
        }
    } else {
        handleException("Host name(s) and port(s) are not correctly defined");
    }
    if (!StringUtils.isEmpty(userName)) {
        connectionFactory.setUsername(userName);
    }
    if (!StringUtils.isEmpty(password)) {
        connectionFactory.setPassword(password);
    }
    if (!StringUtils.isEmpty(virtualHost)) {
        connectionFactory.setVirtualHost(virtualHost);
    }
    if (!StringUtils.isEmpty(retryIntervalS)) {
        try {
            retryInterval = Integer.parseInt(retryIntervalS);
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading retry interval value. Proceeding with default value (30000ms)", e);
        }
    }
    if (!StringUtils.isEmpty(serverRetryIntervalS)) {
        try {
            int serverRetryInterval = Integer.parseInt(serverRetryIntervalS);
            connectionFactory.setNetworkRecoveryInterval(serverRetryInterval);
        } catch (NumberFormatException e) {
            log.warn("Number format error in reading server retry interval value. Proceeding with default value", e);
        }
    }
    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.setTopologyRecoveryEnabled(false);
}
Also used : Address(com.rabbitmq.client.Address) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) AxisRabbitMQException(org.apache.axis2.transport.rabbitmq.utils.AxisRabbitMQException) SecureVaultException(org.wso2.securevault.SecureVaultException) IOException(java.io.IOException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) TrustManagerFactory(javax.net.ssl.TrustManagerFactory)

Example 2 with Address

use of org.wso2.carbon.consent.mgt.core.model.Address in project carbon-apimgt by wso2.

the class DASThriftTestServer method start.

public void start(int receiverPort) throws DataBridgeException {
    DataPublisherTestUtil.setKeyStoreParams();
    streamDefinitionStore = getStreamDefinitionStore();
    numberOfEventsReceived = new AtomicInteger(0);
    DataBridge databridge = new DataBridge(new AuthenticationHandler() {

        public boolean authenticate(String userName, String password) {
            // allays authenticate to true
            return true;
        }

        public void initContext(AgentSession agentSession) {
        // To change body of implemented methods use File | Settings |
        // File Templates.
        }

        public void destroyContext(AgentSession agentSession) {
        }
    }, streamDefinitionStore, DataPublisherTestUtil.getDataBridgeConfigPath());
    thriftDataReceiver = new ThriftDataReceiver(receiverPort, databridge);
    databridge.subscribe(new AgentCallback() {

        int totalSize = 0;

        @Override
        public void definedStream(StreamDefinition streamDefinition) {
            log.info("StreamDefinition " + streamDefinition);
        }

        @Override
        public void removeStream(StreamDefinition streamDefinition) {
            log.info("StreamDefinition remove " + streamDefinition);
        }

        /**
         * Retrving and handling all the events to DAS event receiver
         * @param eventList list of event it received
         * @param credentials client credentials
         */
        public void receive(List<Event> eventList, Credentials credentials) {
            for (Event event : eventList) {
                String streamKey = event.getStreamId();
                if (!dataTables.containsKey(streamKey)) {
                    dataTables.put(streamKey, new ArrayList<Event>());
                }
                dataTables.get(streamKey).add(event);
                log.info("===  " + event.toString());
            }
            numberOfEventsReceived.addAndGet(eventList.size());
            log.info("Received events : " + numberOfEventsReceived);
        }
    });
    String address = "localhost";
    log.info("DAS Test Thrift Server starting on " + address);
    thriftDataReceiver.start(address);
    log.info("DAS Test Thrift Server Started");
}
Also used : AgentSession(org.wso2.carbon.databridge.core.Utils.AgentSession) StreamDefinition(org.wso2.carbon.databridge.commons.StreamDefinition) ArrayList(java.util.ArrayList) AgentCallback(org.wso2.carbon.databridge.core.AgentCallback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ThriftDataReceiver(org.wso2.carbon.databridge.receiver.thrift.ThriftDataReceiver) Event(org.wso2.carbon.databridge.commons.Event) AuthenticationHandler(org.wso2.carbon.databridge.core.internal.authentication.AuthenticationHandler) Credentials(org.wso2.carbon.databridge.commons.Credentials) DataBridge(org.wso2.carbon.databridge.core.DataBridge)

Example 3 with Address

use of org.wso2.carbon.consent.mgt.core.model.Address in project carbon-apimgt by wso2.

the class DataProcessAndPublishingAgent method run.

public void run() {
    JSONObject jsonObMap = new JSONObject();
    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    if (ipAddress != null && ipAddress.length() > 0) {
        if (ipAddress.contains(":") && ipAddress.split(":").length == 2) {
            log.warn("Client port will be ignored and only the IP address (IPV4) will concern from " + ipAddress);
            ipAddress = ipAddress.split(":")[0];
        }
        try {
            InetAddress address = APIUtil.getAddress(ipAddress);
            if (address instanceof Inet4Address) {
                jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(ipAddress));
                jsonObMap.put(APIThrottleConstants.IPv6, 0);
            } else if (address instanceof Inet6Address) {
                jsonObMap.put(APIThrottleConstants.IPv6, APIUtil.ipToBigInteger(ipAddress));
                jsonObMap.put(APIThrottleConstants.IP, 0);
            }
        } catch (UnknownHostException e) {
            // send empty value as ip
            log.error("Error while parsing host IP " + ipAddress, e);
            jsonObMap.put(APIThrottleConstants.IPv6, 0);
            jsonObMap.put(APIThrottleConstants.IP, 0);
        }
    }
    // HeaderMap will only be set if the Header Publishing has been enabled.
    if (getThrottleProperties().isEnableHeaderConditions()) {
        if (this.headersMap != null) {
            jsonObMap.putAll(this.headersMap);
        }
    }
    // adding any custom property if available to stream's property map
    if (this.customPropertyMap != null) {
        jsonObMap.putAll(this.customPropertyMap);
    }
    // Setting query parameters
    if (getThrottleProperties().isEnableQueryParamConditions()) {
        Map<String, String> queryParams = GatewayUtils.getQueryParams(axis2MessageContext);
        if (queryParams != null) {
            jsonObMap.putAll(queryParams);
        }
    }
    // Publish jwt claims
    if (getThrottleProperties().isEnableJwtConditions()) {
        if (authenticationContext.getCallerToken() != null) {
            Map<String, String> assertions = JWTUtil.getJWTClaims(authenticationContext.getCallerToken());
            if (assertions != null) {
                jsonObMap.putAll(assertions);
            }
        }
    }
    // this parameter will be used to capture message size and pass it to calculation logic
    ArrayList<VerbInfoDTO> list = (ArrayList<VerbInfoDTO>) messageContext.getProperty(APIConstants.VERB_INFO_DTO);
    boolean isVerbInfoContentAware = false;
    if (list != null && !list.isEmpty()) {
        VerbInfoDTO verbInfoDTO = list.get(0);
        isVerbInfoContentAware = verbInfoDTO.isContentAware();
    }
    if (authenticationContext.isContentAwareTierPresent() || isVerbInfoContentAware) {
        if (log.isDebugEnabled()) {
            log.debug("Message size: " + messageSizeInBytes + "B");
        }
        jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, messageSizeInBytes);
        if (!StringUtils.isEmpty(authenticationContext.getApplicationName())) {
            jsonObMap.put(APIThrottleConstants.APPLICATION_NAME, authenticationContext.getApplicationName());
        }
        if (!StringUtils.isEmpty(authenticationContext.getProductName()) && !StringUtils.isEmpty(authenticationContext.getProductProvider())) {
            jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_PRODUCT_SUBSCRIPTION_TYPE);
        } else {
            jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_SUBSCRIPTION_TYPE);
        }
    }
    Object[] objects = new Object[] { messageContext.getMessageID(), this.applicationLevelThrottleKey, this.applicationLevelTier, this.apiLevelThrottleKey, this.apiLevelTier, this.subscriptionLevelThrottleKey, this.subscriptionLevelTier, this.resourceLevelThrottleKey, this.resourceLevelTier, this.authorizedUser, this.apiContext, this.apiVersion, this.appTenant, this.apiTenant, this.appId, this.apiName, jsonObMap.toString() };
    org.wso2.carbon.databridge.commons.Event event = new org.wso2.carbon.databridge.commons.Event(streamID, System.currentTimeMillis(), null, null, objects);
    dataPublisher.tryPublish(event);
}
Also used : Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) ArrayList(java.util.ArrayList) Inet6Address(java.net.Inet6Address) JSONObject(org.json.simple.JSONObject) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) JSONObject(org.json.simple.JSONObject) InetAddress(java.net.InetAddress) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 4 with Address

use of org.wso2.carbon.consent.mgt.core.model.Address in project carbon-apimgt by wso2.

the class DataProcessAndPublishingAgent method setDataReference.

/**
 * This method will use to set message context.
 */
public void setDataReference(String applicationLevelThrottleKey, String applicationLevelTier, String apiLevelThrottleKey, String apiLevelTier, String subscriptionLevelThrottleKey, String subscriptionLevelTier, String resourceLevelThrottleKey, String resourceLevelTier, String authorizedUser, String apiContext, String apiVersion, String appTenant, String apiTenant, String appId, MessageContext messageContext, AuthenticationContext authenticationContext) {
    if (!StringUtils.isEmpty(apiLevelTier)) {
        resourceLevelTier = apiLevelTier;
        resourceLevelThrottleKey = apiLevelThrottleKey;
    }
    this.authenticationContext = authenticationContext;
    this.messageContext = messageContext;
    this.applicationLevelThrottleKey = applicationLevelThrottleKey;
    this.applicationLevelTier = applicationLevelTier;
    this.apiLevelThrottleKey = apiLevelThrottleKey;
    this.subscriptionLevelThrottleKey = subscriptionLevelThrottleKey;
    this.subscriptionLevelTier = subscriptionLevelTier;
    this.resourceLevelThrottleKey = resourceLevelThrottleKey;
    this.resourceLevelTier = resourceLevelTier;
    this.authorizedUser = authorizedUser;
    this.apiContext = apiContext;
    this.apiVersion = apiVersion;
    this.appTenant = appTenant;
    this.apiTenant = apiTenant;
    this.appId = appId;
    this.apiName = GatewayUtils.getAPINameFromContextAndVersion(messageContext);
    this.messageSizeInBytes = 0;
    ArrayList<VerbInfoDTO> list = (ArrayList<VerbInfoDTO>) messageContext.getProperty(APIConstants.VERB_INFO_DTO);
    boolean isVerbInfoContentAware = false;
    if (list != null && !list.isEmpty()) {
        VerbInfoDTO verbInfoDTO = list.get(0);
        isVerbInfoContentAware = verbInfoDTO.isContentAware();
    }
    // Build the message if needed from here since it cannot be done from the run() method because content
    // in axis2MessageContext is modified.
    org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    Map<String, String> transportHeaderMap = (Map<String, String>) axis2MessageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    if (transportHeaderMap != null) {
        this.headersMap = new HashMap<>(transportHeaderMap);
    }
    if (messageContext.getProperty(APIThrottleConstants.CUSTOM_PROPERTY) != null) {
        HashMap<String, Object> propertyFromMsgCtx = (HashMap<String, Object>) messageContext.getProperty(APIThrottleConstants.CUSTOM_PROPERTY);
        if (propertyFromMsgCtx != null) {
            this.customPropertyMap = (Map<String, Object>) propertyFromMsgCtx.clone();
        }
    }
    this.ipAddress = GatewayUtils.getIp(axis2MessageContext);
    if (log.isDebugEnabled()) {
        log.debug("Remote IP address : " + ipAddress);
    }
    if (authenticationContext.isContentAwareTierPresent() || isVerbInfoContentAware) {
        Object contentLength = transportHeaderMap.get(APIThrottleConstants.CONTENT_LENGTH);
        if (contentLength != null) {
            log.debug("Content lenght found in the request. Using it as the message size..");
            messageSizeInBytes = Long.parseLong(contentLength.toString());
        } else {
            log.debug("Building the message to get the message size..");
            try {
                buildMessage(axis2MessageContext);
            } catch (Exception ex) {
                // In case of any exception, it won't be propagated up,and set response size to 0
                log.error("Error occurred while building the message to" + " calculate the response body size", ex);
            }
            SOAPEnvelope env = messageContext.getEnvelope();
            if (env != null) {
                SOAPBody soapbody = env.getBody();
                if (soapbody != null) {
                    byte[] size = soapbody.toString().getBytes(Charset.defaultCharset());
                    messageSizeInBytes = size.length;
                }
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SOAPEnvelope(org.apache.axiom.soap.SOAPEnvelope) XMLStreamException(javax.xml.stream.XMLStreamException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) SOAPBody(org.apache.axiom.soap.SOAPBody) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) JSONObject(org.json.simple.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 5 with Address

use of org.wso2.carbon.consent.mgt.core.model.Address in project carbon-apimgt by wso2.

the class WSDL11ProcessorImpl method updateEndpointsOfSingleWSDL.

/**
 * Update the endpoint information of the provided WSDL definition when an API and the environment details are
 * provided
 *
 * @param api API
 * @param environmentName name of the gateway environment
 * @param environmentType type of the gateway environment
 * @param wsdlDefinition WSDL 1.1 definition
 * @throws APIMgtWSDLException when error occurred while updating the endpoints
 */
private void updateEndpointsOfSingleWSDL(API api, String environmentName, String environmentType, Definition wsdlDefinition) throws APIMgtWSDLException {
    Map serviceMap = wsdlDefinition.getAllServices();
    URL addressURI;
    String organization = api.getOrganization();
    for (Object entry : serviceMap.entrySet()) {
        Map.Entry svcEntry = (Map.Entry) entry;
        Service svc = (Service) svcEntry.getValue();
        Map portMap = svc.getPorts();
        for (Object o : portMap.entrySet()) {
            Map.Entry portEntry = (Map.Entry) o;
            Port port = (Port) portEntry.getValue();
            List<ExtensibilityElement> extensibilityElementList = port.getExtensibilityElements();
            String endpointTransport;
            for (ExtensibilityElement extensibilityElement : extensibilityElementList) {
                try {
                    addressURI = new URL(getAddressUrl(extensibilityElement));
                    endpointTransport = determineURLTransport(addressURI.getProtocol(), api.getTransports());
                    if (log.isDebugEnabled()) {
                        log.debug("Address URI for the port:" + port.getName() + " is " + addressURI.toString());
                    }
                } catch (MalformedURLException e) {
                    if (log.isDebugEnabled()) {
                        log.debug("Error occurred while getting the wsdl address location [" + getAddressUrl(extensibilityElement) + "]");
                    }
                    endpointTransport = determineURLTransport("https", api.getTransports());
                // This string to URL conversion done in order to identify URL transport eg - http or https.
                // Here if there is a conversion failure , consider "https" as default protocol
                }
                try {
                    setAddressUrl(extensibilityElement, endpointTransport, api.getContext(), environmentName, environmentType, organization);
                } catch (APIManagementException e) {
                    throw new APIMgtWSDLException("Error while setting gateway access URLs in the WSDL", e);
                }
            }
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) Port(javax.wsdl.Port) Service(javax.wsdl.Service) URL(java.net.URL) ExtensibilityElement(javax.wsdl.extensions.ExtensibilityElement) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIMgtWSDLException(org.wso2.carbon.apimgt.impl.wsdl.exceptions.APIMgtWSDLException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Test (org.testng.annotations.Test)13 HashMap (java.util.HashMap)11 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)8 Map (java.util.Map)7 Test (org.junit.Test)7 UserStoreException (org.wso2.carbon.user.api.UserStoreException)7 IOException (java.io.IOException)6 MalformedURLException (java.net.MalformedURLException)6 ArrayList (java.util.ArrayList)6 API (org.wso2.carbon.apimgt.api.model.API)6 OMElement (org.apache.axiom.om.OMElement)4 Matchers.anyString (org.mockito.Matchers.anyString)4 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)4 APIMgtWSDLException (org.wso2.carbon.apimgt.impl.wsdl.exceptions.APIMgtWSDLException)4 IdentityException (org.wso2.carbon.identity.base.IdentityException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 WSDLException (javax.wsdl.WSDLException)3 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)3 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)3 BLangStruct (org.wso2.ballerinalang.compiler.tree.BLangStruct)3