Search in sources :

Example 1 with ServiceURL

use of org.wso2.carbon.identity.core.ServiceURL in project carbon-apimgt by wso2.

the class APILoggerManager method invokeService.

private String invokeService(String path, String tenantDomain) throws IOException, APIManagementException {
    String serviceURLStr = eventHubConfigurationDto.getServiceUrl().concat(APIConstants.INTERNAL_WEB_APP_EP);
    HttpGet method = new HttpGet(serviceURLStr + path);
    URL serviceURL = new URL(serviceURLStr + path);
    byte[] credentials = getServiceCredentials(eventHubConfigurationDto);
    int servicePort = serviceURL.getPort();
    String serviceProtocol = serviceURL.getProtocol();
    method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, StandardCharsets.UTF_8));
    if (tenantDomain != null) {
        method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
    }
    HttpClient httpClient = APIUtil.getHttpClient(servicePort, serviceProtocol);
    HttpResponse httpResponse = null;
    int retryCount = 0;
    boolean retry;
    do {
        try {
            httpResponse = httpClient.execute(method);
            retry = false;
        } catch (IOException ex) {
            retryCount++;
            if (retryCount < RETRIEVAL_RETRIES) {
                retry = true;
                log.warn("Failed retrieving " + path + " from remote endpoint: " + ex.getMessage() + ". Retrying after " + RETRIEVAL_TIMEOUT_IN_SECONDS + " seconds.");
                try {
                    Thread.sleep(RETRIEVAL_TIMEOUT_IN_SECONDS * 1000L);
                } catch (InterruptedException e) {
                // Ignore
                }
            } else {
                throw new APIManagementException("Error while calling internal service", ex);
            }
        }
    } while (retry);
    if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) {
        log.error("Could not retrieve subscriptions for tenantDomain : " + tenantDomain);
        throw new APIManagementException("Error while retrieving subscription from " + path);
    }
    return EntityUtils.toString(httpResponse.getEntity(), UTF8);
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpGet(org.apache.http.client.methods.HttpGet) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URL(java.net.URL)

Example 2 with ServiceURL

use of org.wso2.carbon.identity.core.ServiceURL in project carbon-apimgt by wso2.

the class APIManagerConfiguration method readChildElements.

private void readChildElements(OMElement serverConfig, Stack<String> nameStack) throws APIManagementException {
    for (Iterator childElements = serverConfig.getChildElements(); childElements.hasNext(); ) {
        OMElement element = (OMElement) childElements.next();
        String localName = element.getLocalName();
        nameStack.push(localName);
        if ("APIKeyValidator".equals(localName)) {
            OMElement keyManagerServiceUrl = element.getFirstChildWithName(new QName(APIConstants.AUTHSERVER_URL));
            if (keyManagerServiceUrl != null) {
                String serviceUrl = keyManagerServiceUrl.getText();
                addKeyManagerConfigsAsSystemProperties(APIUtil.replaceSystemProperty(serviceUrl));
            }
        } else if (TOKEN_REVOCATION_NOTIFIERS.equals(localName)) {
            tokenRevocationClassName = element.getAttributeValue(new QName("class"));
        } else if (REALTIME_NOTIFIER.equals(localName)) {
            Iterator revocationPropertiesIterator = element.getChildrenWithLocalName("Property");
            Properties properties = new Properties();
            while (revocationPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) revocationPropertiesIterator.next();
                properties.setProperty(propertyElem.getAttributeValue(new QName("name")), propertyElem.getText());
            }
            realtimeNotifierProperties = properties;
        } else if (PERSISTENT_NOTIFIER.equals(localName)) {
            Iterator revocationPropertiesIterator = element.getChildrenWithLocalName("Property");
            Properties properties = new Properties();
            while (revocationPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) revocationPropertiesIterator.next();
                if (propertyElem.getAttributeValue(new QName("name")).equalsIgnoreCase("password")) {
                    if (secretResolver.isInitialized() && secretResolver.isTokenProtected(TOKEN_REVOCATION_NOTIFIERS_PASSWORD)) {
                        properties.setProperty(propertyElem.getAttributeValue(new QName("name")), secretResolver.resolve(TOKEN_REVOCATION_NOTIFIERS_PASSWORD));
                    } else {
                        properties.setProperty(propertyElem.getAttributeValue(new QName("name")), propertyElem.getText());
                    }
                } else {
                    properties.setProperty(propertyElem.getAttributeValue(new QName("name")), propertyElem.getText());
                }
            }
            persistentNotifierProperties = properties;
        } else if ("Analytics".equals(localName)) {
            OMElement properties = element.getFirstChildWithName(new QName("Properties"));
            Iterator analyticsPropertiesIterator = properties.getChildrenWithLocalName("Property");
            Map<String, String> analyticsProps = new HashMap<>();
            while (analyticsPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) analyticsPropertiesIterator.next();
                String name = propertyElem.getAttributeValue(new QName("name"));
                String value = propertyElem.getText();
                analyticsProps.put(name, value);
            }
            OMElement authTokenElement = element.getFirstChildWithName(new QName("AuthToken"));
            String resolvedAuthToken = MiscellaneousUtil.resolve(authTokenElement, secretResolver);
            analyticsProps.put("auth.api.token", resolvedAuthToken);
            analyticsProperties = analyticsProps;
        } else if ("PersistenceConfigs".equals(localName)) {
            OMElement properties = element.getFirstChildWithName(new QName("Properties"));
            Iterator analyticsPropertiesIterator = properties.getChildrenWithLocalName("Property");
            Map<String, String> persistenceProps = new HashMap<>();
            while (analyticsPropertiesIterator.hasNext()) {
                OMElement propertyElem = (OMElement) analyticsPropertiesIterator.next();
                String name = propertyElem.getAttributeValue(new QName("name"));
                String value = propertyElem.getText();
                persistenceProps.put(name, value);
            }
            persistenceProperties = persistenceProps;
        } else if (APIConstants.REDIS_CONFIG.equals(localName)) {
            OMElement redisHost = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_HOST));
            OMElement redisPort = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_PORT));
            OMElement redisUser = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_USER));
            OMElement redisPassword = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_PASSWORD));
            OMElement redisDatabaseId = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_DATABASE_ID));
            OMElement redisConnectionTimeout = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_CONNECTION_TIMEOUT));
            OMElement redisIsSslEnabled = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_IS_SSL_ENABLED));
            OMElement propertiesElement = element.getFirstChildWithName(new QName(APIConstants.CONFIG_REDIS_PROPERTIES));
            redisConfig.setRedisEnabled(true);
            redisConfig.setHost(redisHost.getText());
            redisConfig.setPort(Integer.parseInt(redisPort.getText()));
            if (redisUser != null && redisPassword != null && redisDatabaseId != null && redisConnectionTimeout != null && redisIsSslEnabled != null) {
                redisConfig.setUser(redisUser.getText());
                redisConfig.setPassword(MiscellaneousUtil.resolve(redisPassword, secretResolver).toCharArray());
                redisConfig.setDatabaseId(Integer.parseInt(redisDatabaseId.getText()));
                redisConfig.setConnectionTimeout(Integer.parseInt(redisConnectionTimeout.getText()));
                redisConfig.setSslEnabled(Boolean.parseBoolean(redisIsSslEnabled.getText()));
            }
            if (propertiesElement != null) {
                Iterator<OMElement> properties = propertiesElement.getChildElements();
                if (properties != null) {
                    while (properties.hasNext()) {
                        OMElement propertyNode = properties.next();
                        if (APIConstants.CONFIG_REDIS_MAX_TOTAL.equals(propertyNode.getLocalName())) {
                            redisConfig.setMaxTotal(Integer.parseInt(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_MAX_IDLE.equals(propertyNode.getLocalName())) {
                            redisConfig.setMaxIdle(Integer.parseInt(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_MIN_IDLE.equals(propertyNode.getLocalName())) {
                            redisConfig.setMinIdle(Integer.parseInt(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TEST_ON_BORROW.equals(propertyNode.getLocalName())) {
                            redisConfig.setTestOnBorrow(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TEST_ON_RETURN.equals(propertyNode.getLocalName())) {
                            redisConfig.setTestOnReturn(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TEST_WHILE_IDLE.equals(propertyNode.getLocalName())) {
                            redisConfig.setTestWhileIdle(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_BLOCK_WHEN_EXHAUSTED.equals(propertyNode.getLocalName())) {
                            redisConfig.setBlockWhenExhausted(Boolean.parseBoolean(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_MIN_EVICTABLE_IDLE_TIME_IN_MILLIS.equals(propertyNode.getLocalName())) {
                            redisConfig.setMinEvictableIdleTimeMillis(Long.parseLong(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_TIME_BETWEEN_EVICTION_RUNS_IN_MILLIS.equals(propertyNode.getLocalName())) {
                            redisConfig.setTimeBetweenEvictionRunsMillis(Long.parseLong(propertyNode.getText()));
                        } else if (APIConstants.CONFIG_REDIS_NUM_TESTS_PER_EVICTION_RUNS.equals(propertyNode.getLocalName())) {
                            redisConfig.setNumTestsPerEvictionRun(Integer.parseInt(propertyNode.getText()));
                        }
                    }
                }
            }
        } else if (elementHasText(element)) {
            String key = getKey(nameStack);
            String value = MiscellaneousUtil.resolve(element, secretResolver);
            addToConfiguration(key, APIUtil.replaceSystemProperty(value));
        } else if ("Environments".equals(localName)) {
            Iterator environmentIterator = element.getChildrenWithLocalName("Environment");
            apiGatewayEnvironments = new LinkedHashMap<String, Environment>();
            while (environmentIterator.hasNext()) {
                OMElement environmentElem = (OMElement) environmentIterator.next();
                setEnvironmentConfig(environmentElem);
            }
        } else if (APIConstants.EXTERNAL_API_STORES.equals(localName)) {
            // Initialize 'externalAPIStores' config elements
            Iterator apistoreIterator = element.getChildrenWithLocalName("ExternalAPIStore");
            externalAPIStores = new HashSet<APIStore>();
            while (apistoreIterator.hasNext()) {
                APIStore store = new APIStore();
                OMElement storeElem = (OMElement) apistoreIterator.next();
                String type = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_TYPE));
                // Set Store type [eg:wso2]
                store.setType(type);
                String className = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_CLASS_NAME));
                try {
                    store.setPublisher((APIPublisher) APIUtil.getClassInstance(className));
                } catch (InstantiationException e) {
                    String msg = "One or more classes defined in" + APIConstants.EXTERNAL_API_STORE_CLASS_NAME + "cannot be instantiated";
                    log.error(msg, e);
                    throw new APIManagementException(msg, e);
                } catch (IllegalAccessException e) {
                    String msg = "One or more classes defined in" + APIConstants.EXTERNAL_API_STORE_CLASS_NAME + "cannot be access";
                    log.error(msg, e);
                    throw new APIManagementException(msg, e);
                } catch (ClassNotFoundException e) {
                    String msg = "One or more classes defined in" + APIConstants.EXTERNAL_API_STORE_CLASS_NAME + "cannot be found";
                    log.error(msg, e);
                    throw new APIManagementException(msg, e);
                }
                String name = storeElem.getAttributeValue(new QName(APIConstants.EXTERNAL_API_STORE_ID));
                if (name == null) {
                    log.error("The ExternalAPIStore name attribute is not defined in api-manager.xml.");
                }
                // Set store name
                store.setName(name);
                OMElement configDisplayName = storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_DISPLAY_NAME));
                String displayName = (configDisplayName != null) ? APIUtil.replaceSystemProperty(configDisplayName.getText()) : name;
                // Set store display name
                store.setDisplayName(displayName);
                store.setEndpoint(APIUtil.replaceSystemProperty(storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_ENDPOINT)).getText()));
                store.setPublished(false);
                if (APIConstants.WSO2_API_STORE_TYPE.equals(type)) {
                    OMElement password = storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_PASSWORD));
                    if (password != null) {
                        String value = MiscellaneousUtil.resolve(password, secretResolver);
                        store.setPassword(APIUtil.replaceSystemProperty(value));
                        store.setUsername(APIUtil.replaceSystemProperty(storeElem.getFirstChildWithName(new QName(APIConstants.EXTERNAL_API_STORE_USERNAME)).getText()));
                    } else {
                        log.error("The user-credentials of API Publisher is not defined in the <ExternalAPIStore> " + "config of api-manager.xml.");
                    }
                }
                externalAPIStores.add(store);
            }
        } else if (APIConstants.LOGIN_CONFIGS.equals(localName)) {
            Iterator loginConfigIterator = element.getChildrenWithLocalName(APIConstants.LOGIN_CONFIGS);
            while (loginConfigIterator.hasNext()) {
                OMElement loginOMElement = (OMElement) loginConfigIterator.next();
                parseLoginConfig(loginOMElement);
            }
        } else if (APIConstants.AdvancedThrottleConstants.THROTTLING_CONFIGURATIONS.equals(localName)) {
            setThrottleProperties(serverConfig);
        } else if (APIConstants.WorkflowConfigConstants.WORKFLOW.equals(localName)) {
            setWorkflowProperties(serverConfig);
        } else if (APIConstants.ApplicationAttributes.APPLICATION_ATTRIBUTES.equals(localName)) {
            Iterator iterator = element.getChildrenWithLocalName(APIConstants.ApplicationAttributes.ATTRIBUTE);
            while (iterator.hasNext()) {
                OMElement omElement = (OMElement) iterator.next();
                Iterator attributes = omElement.getChildElements();
                JSONObject jsonObject = new JSONObject();
                boolean isHidden = Boolean.parseBoolean(omElement.getAttributeValue(new QName(APIConstants.ApplicationAttributes.HIDDEN)));
                boolean isRequired = Boolean.parseBoolean(omElement.getAttributeValue(new QName(APIConstants.ApplicationAttributes.REQUIRED)));
                jsonObject.put(APIConstants.ApplicationAttributes.HIDDEN, isHidden);
                while (attributes.hasNext()) {
                    OMElement attribute = (OMElement) attributes.next();
                    if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.NAME)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.ATTRIBUTE, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.DESCRIPTION)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.DESCRIPTION, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.TOOLTIP)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.TOOLTIP, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.TYPE)) {
                        jsonObject.put(APIConstants.ApplicationAttributes.TYPE, attribute.getText());
                    } else if (attribute.getLocalName().equals(APIConstants.ApplicationAttributes.DEFAULT) && isRequired) {
                        jsonObject.put(APIConstants.ApplicationAttributes.DEFAULT, attribute.getText());
                    }
                }
                if (isHidden && isRequired && !jsonObject.containsKey(APIConstants.ApplicationAttributes.DEFAULT)) {
                    log.error("A default value needs to be given for required, hidden application attributes.");
                }
                jsonObject.put(APIConstants.ApplicationAttributes.REQUIRED, isRequired);
                applicationAttributes.add(jsonObject);
            }
        } else if (APIConstants.Monetization.MONETIZATION_CONFIG.equals(localName)) {
            OMElement additionalAttributes = element.getFirstChildWithName(new QName(APIConstants.Monetization.ADDITIONAL_ATTRIBUTES));
            if (additionalAttributes != null) {
                setMonetizationAdditionalAttributes(additionalAttributes);
            }
        } else if (APIConstants.JWT_CONFIGS.equals(localName)) {
            setJWTConfiguration(element);
        } else if (APIConstants.TOKEN_ISSUERS.equals(localName)) {
            setJWTTokenIssuers(element);
        } else if (APIConstants.API_RECOMMENDATION.equals(localName)) {
            setRecommendationConfigurations(element);
        } else if (APIConstants.GlobalCacheInvalidation.GLOBAL_CACHE_INVALIDATION.equals(localName)) {
            setGlobalCacheInvalidationConfiguration(element);
        } else if (APIConstants.KeyManager.EVENT_HUB_CONFIGURATIONS.equals(localName)) {
            setEventHubConfiguration(element);
        } else if (APIConstants.GatewayArtifactSynchronizer.SYNC_RUNTIME_ARTIFACTS_PUBLISHER_CONFIG.equals(localName)) {
            setRuntimeArtifactsSyncPublisherConfig(element);
        } else if (APIConstants.GatewayArtifactSynchronizer.SYNC_RUNTIME_ARTIFACTS_GATEWAY_CONFIG.equals(localName)) {
            setRuntimeArtifactsSyncGatewayConfig(element);
        } else if (APIConstants.SkipListConstants.SKIP_LIST_CONFIG.equals(localName)) {
            setSkipListConfigurations(element);
        } else if (APIConstants.ExtensionListenerConstants.EXTENSION_LISTENERS.equals(localName)) {
            setExtensionListenerConfigurations(element);
        } else if (APIConstants.JWT_AUDIENCES.equals(localName)) {
            setRestApiJWTAuthAudiences(element);
        }
        readChildElements(element, nameStack);
        nameStack.pop();
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) QName(javax.xml.namespace.QName) OMElement(org.apache.axiom.om.OMElement) GatewayArtifactSynchronizerProperties(org.wso2.carbon.apimgt.impl.dto.GatewayArtifactSynchronizerProperties) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) Properties(java.util.Properties) ThrottleProperties(org.wso2.carbon.apimgt.impl.dto.ThrottleProperties) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) Iterator(java.util.Iterator) Environment(org.wso2.carbon.apimgt.api.model.Environment) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment) APIPublisher(org.wso2.carbon.apimgt.api.model.APIPublisher) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet) APIStore(org.wso2.carbon.apimgt.api.model.APIStore)

Example 3 with ServiceURL

use of org.wso2.carbon.identity.core.ServiceURL in project carbon-apimgt by wso2.

the class APIUtil method isAPIGatewayKeyCacheEnabled.

public static boolean isAPIGatewayKeyCacheEnabled() {
    try {
        APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
        String serviceURL = config.getFirstProperty(APIConstants.GATEWAY_TOKEN_CACHE_ENABLED);
        return Boolean.parseBoolean(serviceURL);
    } catch (Exception e) {
        log.error("Did not found valid API Validation Information cache configuration. Use default configuration" + e);
    }
    return true;
}
Also used : APIManagerConfiguration(org.wso2.carbon.apimgt.impl.APIManagerConfiguration) KeyStoreException(java.security.KeyStoreException) JSONException(org.json.JSONException) XMLStreamException(javax.xml.stream.XMLStreamException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ExceptionException(org.wso2.carbon.core.commons.stub.loggeduserinfo.ExceptionException) APIMgtInternalException(org.wso2.carbon.apimgt.api.APIMgtInternalException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URISyntaxException(java.net.URISyntaxException) SignatureException(java.security.SignatureException) RemoteException(java.rmi.RemoteException) CertificateEncodingException(javax.security.cert.CertificateEncodingException) AuthorizationFailedException(org.wso2.carbon.registry.core.secure.AuthorizationFailedException) EventPublisherException(org.wso2.carbon.apimgt.eventing.EventPublisherException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) ValidationException(org.everit.json.schema.ValidationException) CryptoException(org.wso2.carbon.core.util.CryptoException) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SocketException(java.net.SocketException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) CertificateException(java.security.cert.CertificateException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 4 with ServiceURL

use of org.wso2.carbon.identity.core.ServiceURL in project carbon-business-process by wso2.

the class RESTTask method execute.

@Override
public void execute(DelegateExecution execution) {
    if (method == null) {
        String error = "HTTP method for the REST task not found. Please specify the \"method\" form property.";
        throw new RESTClientException(BAD_REQUEST, error);
    }
    if (log.isDebugEnabled()) {
        if (serviceURL != null) {
            log.debug("Executing RESTInvokeTask " + method.getValue(execution).toString() + " - " + serviceURL.getValue(execution).toString());
        } else if (serviceRef != null) {
            log.debug("Executing RESTInvokeTask " + method.getValue(execution).toString() + " - " + serviceRef.getValue(execution).toString());
        }
    }
    RESTInvoker restInvoker = BPMNRestExtensionHolder.getInstance().getRestInvoker();
    RESTResponse response = null;
    String url = null;
    String bUsername = null;
    String bPassword = null;
    JsonNodeObject jsonHeaders = null;
    boolean contentAvailable = false;
    try {
        if (serviceURL != null) {
            url = serviceURL.getValue(execution).toString();
            if (basicAuthUsername != null && basicAuthPassword != null) {
                bUsername = basicAuthUsername.getValue(execution).toString();
                bPassword = basicAuthPassword.getValue(execution).toString();
            }
        } else if (serviceRef != null) {
            String resourcePath = serviceRef.getValue(execution).toString();
            String registryPath;
            int tenantIdInt = Integer.parseInt(execution.getTenantId());
            RealmService realmService = RegistryContext.getBaseInstance().getRealmService();
            String domain = realmService.getTenantManager().getDomain(tenantIdInt);
            Registry registry;
            Resource urlResource;
            try {
                PrivilegedCarbonContext.startTenantFlow();
                if (domain != null) {
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(domain);
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantIdInt);
                } else {
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
                    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantIdInt);
                }
                if (resourcePath.startsWith(GOVERNANCE_REGISTRY_PREFIX)) {
                    registryPath = resourcePath.substring(GOVERNANCE_REGISTRY_PREFIX.length());
                    registry = BPMNExtensionsComponent.getRegistryService().getGovernanceSystemRegistry(tenantIdInt);
                } else if (resourcePath.startsWith(CONFIGURATION_REGISTRY_PREFIX)) {
                    registryPath = resourcePath.substring(CONFIGURATION_REGISTRY_PREFIX.length());
                    registry = BPMNExtensionsComponent.getRegistryService().getConfigSystemRegistry(tenantIdInt);
                } else {
                    String msg = "Registry type is not specified for service reference in " + getTaskDetails(execution) + ". serviceRef should begin with gov:/ or conf:/ to indicate the registry type.";
                    throw new RESTClientException(BAD_REQUEST, msg);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Reading endpoint from registry location: " + registryPath + " for task " + getTaskDetails(execution));
                }
                urlResource = registry.get(registryPath);
            } finally {
                PrivilegedCarbonContext.endTenantFlow();
            }
            if (urlResource != null) {
                String uepContent = new String((byte[]) urlResource.getContent(), Charset.defaultCharset());
                UnifiedEndpointFactory uepFactory = new UnifiedEndpointFactory();
                OMElement uepElement = AXIOMUtil.stringToOM(uepContent);
                UnifiedEndpoint uep = uepFactory.createEndpoint(uepElement);
                url = uep.getAddress();
                bUsername = uep.getAuthorizationUserName();
                bPassword = uep.getAuthorizationPassword();
            } else {
                String errorMsg = "Endpoint resource " + registryPath + " is not found. Failed to execute REST invocation in task " + getTaskDetails(execution);
                throw new RESTClientException(errorMsg);
            }
        } else {
            String urlNotFoundErrorMsg = "Service URL is not provided for " + getTaskDetails(execution) + ". serviceURL or serviceRef must be provided.";
            throw new RESTClientException(BAD_REQUEST, urlNotFoundErrorMsg);
        }
        if (headers != null) {
            String headerContent = headers.getValue(execution).toString();
            jsonHeaders = JSONUtils.parse(headerContent);
        }
        if (POST_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
            String inputContent = input.getValue(execution).toString();
            response = restInvoker.invokePOST(new URI(url), jsonHeaders, bUsername, bPassword, inputContent);
        } else if (GET_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
            response = restInvoker.invokeGET(new URI(url), jsonHeaders, bUsername, bPassword);
        } else if (PUT_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
            String inputContent = input.getValue(execution).toString();
            response = restInvoker.invokePUT(new URI(url), jsonHeaders, bUsername, bPassword, inputContent);
        } else if (DELETE_METHOD.equals(method.getValue(execution).toString().trim().toUpperCase())) {
            response = restInvoker.invokeDELETE(new URI(url), jsonHeaders, bUsername, bPassword);
        } else {
            String errorMsg = "Unsupported http method. The REST task only supports GET, POST, PUT and DELETE operations";
            throw new RESTClientException(METHOD_NOT_ALLOWED, errorMsg);
        }
        Object output = response.getContent();
        if (output != null) {
            contentAvailable = !response.getContent().equals("");
        }
        boolean contentTypeAvailable = false;
        if (response.getContentType() != null) {
            contentTypeAvailable = true;
        }
        if (contentAvailable && contentTypeAvailable && response.getContentType().contains(APPLICATION_JSON)) {
            output = JSONUtils.parse(String.valueOf(output));
        } else if (contentAvailable && contentTypeAvailable && response.getContentType().contains(APPLICATION_XML)) {
            output = Utils.parse(String.valueOf(output));
        } else {
            output = StringEscapeUtils.escapeXml(String.valueOf(output));
        }
        boolean isDefaultVarAvailable = false;
        if (enableDefaultVariable != null) {
            isDefaultVarAvailable = Boolean.valueOf(enableDefaultVariable.getValue(execution).toString());
        }
        if (outputVariable != null) {
            String outVarName = outputVariable.getValue(execution).toString();
            execution.setVariable(outVarName, output);
        } else if (outputMappings != null) {
            String outMappings = outputMappings.getValue(execution).toString();
            outMappings = outMappings.trim();
            String[] mappings = outMappings.split(",");
            for (String mapping : mappings) {
                String[] mappingParts = mapping.split(":");
                String varName = mappingParts[0];
                String expression = mappingParts[1];
                String defaultVariableStr = null;
                if (mappingParts.length == 3) {
                    defaultVariableStr = mappingParts[2];
                }
                Object value;
                if (output instanceof JsonNodeObject) {
                    try {
                        value = ((JsonNodeObject) output).jsonPath(expression);
                    } catch (BPMNJsonException e) {
                        if (isDefaultVarAvailable) {
                            value = null;
                            if (StringUtils.isNotBlank(defaultVariableStr)) {
                                value = execution.getVariable(defaultVariableStr);
                            }
                        } else {
                            throw e;
                        }
                    }
                } else if (output instanceof XMLDocument) {
                    try {
                        value = ((XMLDocument) output).xPath(expression);
                    } catch (BPMNXmlException e) {
                        if (isDefaultVarAvailable) {
                            value = null;
                            if (StringUtils.isNotBlank(defaultVariableStr)) {
                                value = execution.getVariable(defaultVariableStr);
                            }
                        } else {
                            throw e;
                        }
                    }
                } else {
                    String errorMessage = "Unrecognized content type found. " + "HTTP Status : " + response.getHttpStatus() + ", Response Content : " + output.toString();
                    setErrorDetailsForTaskExecution(execution, UNRECOGNIZED_CONTENT_TYPE, errorMessage, response);
                    throw new RESTClientException(UNRECOGNIZED_CONTENT_TYPE, errorMessage);
                }
                execution.setVariable(varName, value);
            }
        } else {
            String outputNotFoundErrorMsg = "An outputVariable or outputMappings is not provided. " + "Either an output variable or output mappings  must be provided to save " + "the response.";
            throw new RESTClientException(BAD_REQUEST, outputNotFoundErrorMsg);
        }
        if (responseHeaderVariable != null) {
            StringBuilder headerJsonStr = new StringBuilder();
            headerJsonStr.append("{");
            String prefix = "";
            for (Header header : response.getHeaders()) {
                headerJsonStr.append(prefix);
                String name = header.getName().replaceAll("\"", "");
                String value = header.getValue().replaceAll("\"", "");
                headerJsonStr.append("\"").append(name).append("\":\"").append(value).append("\"");
                prefix = ",";
            }
            headerJsonStr.append("}");
            JsonNodeObject headerJson = JSONUtils.parse(headerJsonStr.toString());
            execution.setVariable(responseHeaderVariable.getValue(execution).toString(), headerJson);
        }
        if (httpStatusVariable != null) {
            execution.setVariable(httpStatusVariable.getValue(execution).toString(), response.getHttpStatus());
        }
    } catch (RegistryException | XMLStreamException | URISyntaxException | IOException | SAXException | ParserConfigurationException e) {
        String errorMessage = "Failed to execute " + method.getValue(execution).toString() + " " + url + " within task " + getTaskDetails(execution);
        setErrorDetailsForTaskExecution(execution, REST_INVOKE_ERROR, errorMessage, response);
        log.error(errorMessage, e);
        throw new RESTClientException(REST_INVOKE_ERROR, errorMessage);
    } catch (BPMNJsonException | BPMNXmlException e) {
        String errorMessage = "Failed to extract values for output mappings, the response content" + " doesn't support the expression" + method.getValue(execution).toString() + " " + url + " within task " + getTaskDetails(execution);
        setErrorDetailsForTaskExecution(execution, INVALID_RESPONSE_CONTENT, errorMessage, response);
        log.error(errorMessage, e);
        throw new RESTClientException(INVALID_RESPONSE_CONTENT, errorMessage);
    } catch (UserStoreException e) {
        String errorMessage = "Failed to obtain tenant domain information";
        setErrorDetailsForTaskExecution(execution, INTERNAL_SERVER_ERROR, errorMessage, response);
        log.error(errorMessage, e);
        throw new RESTClientException(INTERNAL_SERVER_ERROR, errorMessage);
    }
}
Also used : BPMNJsonException(org.wso2.carbon.bpmn.core.types.datatypes.json.BPMNJsonException) JsonNodeObject(org.wso2.carbon.bpmn.core.types.datatypes.json.api.JsonNodeObject) OMElement(org.apache.axiom.om.OMElement) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) UnifiedEndpointFactory(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpointFactory) XMLDocument(org.wso2.carbon.bpmn.core.types.datatypes.xml.api.XMLDocument) SAXException(org.xml.sax.SAXException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Resource(org.wso2.carbon.registry.api.Resource) Registry(org.wso2.carbon.registry.api.Registry) IOException(java.io.IOException) RegistryException(org.wso2.carbon.registry.api.RegistryException) Header(org.apache.http.Header) XMLStreamException(javax.xml.stream.XMLStreamException) RealmService(org.wso2.carbon.user.core.service.RealmService) UnifiedEndpoint(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpoint) JsonNodeObject(org.wso2.carbon.bpmn.core.types.datatypes.json.api.JsonNodeObject) BPMNXmlException(org.wso2.carbon.bpmn.core.types.datatypes.xml.BPMNXmlException)

Example 5 with ServiceURL

use of org.wso2.carbon.identity.core.ServiceURL in project carbon-business-process by wso2.

the class SOAPTask method execute.

@Override
public void execute(DelegateExecution execution) {
    String endpointURL;
    String payloadRequest;
    String version;
    String connection;
    String transferEncoding;
    String[] transportHeaderList;
    String action = "";
    String soapVersionURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
    List<Header> headerList = new ArrayList<Header>();
    try {
        if (serviceURL != null) {
            endpointURL = serviceURL.getValue(execution).toString();
        } else if (serviceRef != null) {
            String resourcePath = serviceRef.getValue(execution).toString();
            String registryPath;
            String tenantId = execution.getTenantId();
            Registry registry;
            if (resourcePath.startsWith(GOVERNANCE_REGISTRY_PREFIX)) {
                registryPath = resourcePath.substring(GOVERNANCE_REGISTRY_PREFIX.length());
                registry = BPMNExtensionsComponent.getRegistryService().getGovernanceSystemRegistry(Integer.parseInt(tenantId));
            } else if (resourcePath.startsWith(CONFIGURATION_REGISTRY_PREFIX)) {
                registryPath = resourcePath.substring(CONFIGURATION_REGISTRY_PREFIX.length());
                registry = BPMNExtensionsComponent.getRegistryService().getConfigSystemRegistry(Integer.parseInt(tenantId));
            } else {
                String msg = "Registry type is not specified for service reference in " + " serviceRef should begin with gov:/ or conf:/ to indicate the registry type.";
                setErrorDetailsForTaskExecution(execution, BAD_REQUEST, msg);
                throw new SOAPException(BAD_REQUEST, msg);
            }
            if (log.isDebugEnabled()) {
                log.debug("Reading endpoint from registry location: " + registryPath + " for task " + execution.getCurrentActivityName());
            }
            Resource urlResource = registry.get(registryPath);
            if (urlResource != null) {
                String uepContent = new String((byte[]) urlResource.getContent(), Charset.defaultCharset());
                UnifiedEndpointFactory uepFactory = new UnifiedEndpointFactory();
                OMElement uepElement = AXIOMUtil.stringToOM(uepContent);
                UnifiedEndpoint uep = uepFactory.createEndpoint(uepElement);
                endpointURL = uep.getAddress();
            } else {
                String errorMsg = "Endpoint resource " + registryPath + " is not found. Failed to execute REST invocation in task " + execution.getCurrentActivityName();
                setErrorDetailsForTaskExecution(execution, BAD_REQUEST, errorMsg);
                throw new SOAPException(BAD_REQUEST, errorMsg);
            }
        } else {
            String urlNotFoundErrorMsg = "Service URL is not provided. serviceURL must be provided.";
            setErrorDetailsForTaskExecution(execution, BAD_REQUEST, urlNotFoundErrorMsg);
            throw new SOAPException(BAD_REQUEST, urlNotFoundErrorMsg);
        }
        if (payload != null) {
            payloadRequest = payload.getValue(execution).toString();
        } else {
            String payloadNotFoundErrorMsg = "Payload request is not provided. Payload must be provided.";
            setErrorDetailsForTaskExecution(execution, BAD_REQUEST, payloadNotFoundErrorMsg);
            throw new SOAPException(BAD_REQUEST, payloadNotFoundErrorMsg);
        }
        if (soapVersion != null) {
            version = soapVersion.getValue(execution).toString();
            if (version.equalsIgnoreCase(SOAP12_VERSION)) {
                soapVersionURI = SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            } else if (version.equalsIgnoreCase(SOAP11_VERSION)) {
                soapVersionURI = SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI;
            } else {
                String invalidVersionErrorMsg = "Invalid soap version string specified";
                setErrorDetailsForTaskExecution(execution, BAD_REQUEST, invalidVersionErrorMsg);
                throw new SOAPException(BAD_REQUEST, invalidVersionErrorMsg);
            }
        }
        // Adding the connection
        Header connectionHeader = new Header();
        if (httpConnection != null) {
            connection = httpConnection.getValue(execution).toString();
            if (connection != null && !connection.trim().equals("Keep-Alive")) {
                log.debug("Setting Keep-Alive header ");
                connectionHeader.setName("Connection");
                connectionHeader.setValue(connection);
                headerList.add(connectionHeader);
            }
        }
        // Adding the additional transport headers
        if (transportHeaders != null) {
            String headerContent = transportHeaders.getValue(execution).toString();
            if (headerContent != null) {
                transportHeaderList = headerContent.split(",");
                for (String transportHeader : transportHeaderList) {
                    String[] pair = transportHeader.split(":");
                    Header additionalHeader = new Header();
                    if (pair.length == 1) {
                        additionalHeader.setName(pair[0]);
                        additionalHeader.setValue("");
                        if (log.isDebugEnabled()) {
                            log.debug("Adding transport headers " + pair[0]);
                        }
                    } else {
                        additionalHeader.setName(pair[0]);
                        additionalHeader.setValue(pair[1]);
                        if (log.isDebugEnabled()) {
                            log.debug("Adding transport headers " + pair[0] + " " + pair[1]);
                        }
                    }
                    headerList.add(additionalHeader);
                }
            }
        }
        // Adding the soap action
        if (soapAction != null) {
            action = soapAction.getValue(execution).toString();
            if (log.isDebugEnabled()) {
                log.debug("Setting soap action " + soapAction);
            }
        }
        // Converting the payload to an OMElement
        OMElement payLoad = AXIOMUtil.stringToOM(payloadRequest);
        // Creating the Service client
        ServiceClient sender = new ServiceClient();
        OMElement response;
        // Creating options to set the headers
        Options options = new Options();
        options.setTo(new EndpointReference(endpointURL));
        options.setAction(action);
        options.setSoapVersionURI(soapVersionURI);
        options.setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_HEADERS, headerList);
        // Adding the soap header block to the SOAP Header block when creating the SOAP Envelope
        if (headers != null) {
            String headerContent = headers.getValue(execution).toString();
            OMElement headerElement = AXIOMUtil.stringToOM(headerContent);
            sender.addHeader(headerElement);
            if (log.isDebugEnabled()) {
                log.debug("Adding soap header " + headerContent);
            }
        }
        // Adding the transfer encoding
        if (httpTransferEncoding != null) {
            transferEncoding = httpTransferEncoding.getValue(execution).toString();
            if (transferEncoding.equalsIgnoreCase("chunked")) {
                options.setProperty(HTTPConstants.CHUNKED, Boolean.TRUE);
                if (log.isDebugEnabled()) {
                    log.debug("Enabling transfer encoding chunked ");
                }
            } else {
                options.setProperty(HTTPConstants.CHUNKED, Boolean.FALSE);
                if (log.isDebugEnabled()) {
                    log.debug("Disabling transfer encoding chunked ");
                }
            }
        }
        sender.setOptions(options);
        // Invoking the endpoint
        response = sender.sendReceive(payLoad);
        // Getting the response as a string
        String responseStr = response.toStringWithConsume();
        if (outputVariable != null) {
            String outVarName = outputVariable.getValue(execution).toString();
            execution.setVariable(outVarName, responseStr);
        } else {
            String outputNotFoundErrorMsg = "Output variable is not provided. " + "outputVariable must be provided to save " + "the response.";
            setErrorDetailsForTaskExecution(execution, BAD_REQUEST, outputNotFoundErrorMsg);
            throw new SOAPException(BAD_REQUEST, outputNotFoundErrorMsg);
        }
    } catch (AxisFault axisFault) {
        log.error("Axis2 Fault", axisFault);
        String errMsg = "Exception while getting response :" + axisFault.getMessage();
        setErrorDetailsForTaskExecution(execution, SOAP_INVOKE_ERROR_CODE, errMsg);
        throw new SOAPException(SOAP_INVOKE_ERROR_CODE, "Exception while getting response :" + axisFault.getMessage());
    } catch (XMLStreamException | RegistryException e) {
        log.error("Exception in processing", e);
        String errMsg = "Exception in processing  :" + e.getMessage();
        setErrorDetailsForTaskExecution(execution, INTERNAL_SERVER_ERROR, errMsg);
        throw new SOAPException(INTERNAL_SERVER_ERROR, errMsg);
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) Options(org.apache.axis2.client.Options) ArrayList(java.util.ArrayList) Resource(org.wso2.carbon.registry.api.Resource) OMElement(org.apache.axiom.om.OMElement) Registry(org.wso2.carbon.registry.api.Registry) RegistryException(org.wso2.carbon.registry.api.RegistryException) UnifiedEndpointFactory(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpointFactory) EndpointReference(org.apache.axis2.addressing.EndpointReference) Header(org.apache.commons.httpclient.Header) XMLStreamException(javax.xml.stream.XMLStreamException) ServiceClient(org.apache.axis2.client.ServiceClient) UnifiedEndpoint(org.wso2.carbon.unifiedendpoint.core.UnifiedEndpoint)

Aggregations

OMElement (org.apache.axiom.om.OMElement)6 IOException (java.io.IOException)5 URISyntaxException (java.net.URISyntaxException)3 Iterator (java.util.Iterator)3 Properties (java.util.Properties)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 Response (javax.ws.rs.core.Response)3 QName (javax.xml.namespace.QName)3 XMLStreamException (javax.xml.stream.XMLStreamException)3 ServiceClient (org.apache.axis2.client.ServiceClient)3 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3 ServiceURL (org.wso2.carbon.identity.core.ServiceURL)3 ServiceURLBuilder (org.wso2.carbon.identity.core.ServiceURLBuilder)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 URI (java.net.URI)2 URL (java.net.URL)2 HashMap (java.util.HashMap)2 LinkedHashMap (java.util.LinkedHashMap)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2