Search in sources :

Example 36 with URL

use of org.apache.axis2.util.URL 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.";
                throw new SOAPException(SOAP_INVOKE_ERROR_CODE, 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();
                throw new SOAPException(SOAP_INVOKE_ERROR_CODE, errorMsg);
            }
        } else {
            String urlNotFoundErrorMsg = "Service URL is not provided. serviceURL must be provided.";
            throw new SOAPException(SOAP_INVOKE_ERROR_CODE, urlNotFoundErrorMsg);
        }
        if (payload != null) {
            payloadRequest = payload.getValue(execution).toString();
        } else {
            String payloadNotFoundErrorMsg = "Payload request is not provided. Payload must be provided.";
            throw new SOAPException(SOAP_INVOKE_ERROR_CODE, 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";
                throw new SOAPException(SOAP_INVOKE_ERROR_CODE, 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.setVariableLocal(outVarName, responseStr);
        } else {
            String outputNotFoundErrorMsg = "Output variable is not provided. " + "outputVariable must be provided to save " + "the response.";
            throw new SOAPException(SOAP_INVOKE_ERROR_CODE, outputNotFoundErrorMsg);
        }
    } catch (AxisFault axisFault) {
        log.error("Axis2 Fault", axisFault);
        throw new SOAPException(SOAP_INVOKE_ERROR_CODE, "Exception while getting response :" + axisFault.getMessage());
    } catch (XMLStreamException | RegistryException e) {
        log.error("Exception in processing", e);
        throw new SOAPException(SOAP_INVOKE_ERROR_CODE, "Exception in processing  :" + e.getMessage());
    }
}
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)

Example 37 with URL

use of org.apache.axis2.util.URL in project jaggery by wso2.

the class TomcatJaggeryWebappsDeployer method handleWebappDeployment.

/**
 * Deployment procedure of Jaggery apps
 *
 * @param webappFile                The Jaggery app file to be deployed
 * @param contextStr                jaggery app context string
 * @param webContextParams          context-params for this Jaggery app
 * @param applicationEventListeners Application event listeners
 * @throws CarbonException If a deployment error occurs
 */
protected void handleWebappDeployment(File webappFile, String contextStr, List<WebContextParameter> webContextParams, List<Object> applicationEventListeners) throws CarbonException {
    String filename = webappFile.getName();
    ArrayList<Object> listeners = new ArrayList<Object>(1);
    // listeners.add(new CarbonServletRequestListener());
    SecurityConstraint securityConstraint = new SecurityConstraint();
    securityConstraint.setAuthConstraint(true);
    SecurityCollection securityCollection = new SecurityCollection();
    securityCollection.setName("ConfigDir");
    securityCollection.setDescription("Jaggery Configuration Dir");
    securityCollection.addPattern("/" + JaggeryCoreConstants.JAGGERY_CONF_FILE);
    securityConstraint.addCollection(securityCollection);
    WebApplicationsHolder webApplicationsHolder = WebAppUtils.getWebappHolder(webappFile.getAbsolutePath(), configurationContext);
    try {
        JSONObject jaggeryConfigObj = readJaggeryConfig(webappFile);
        Tomcat tomcat = DataHolder.getCarbonTomcatService().getTomcat();
        Context context = DataHolder.getCarbonTomcatService().addWebApp(contextStr, webappFile.getAbsolutePath(), new JaggeryDeployerManager.JaggeryConfListener(jaggeryConfigObj, securityConstraint));
        // deploying web app for url mapping inside virtual host
        if (DataHolder.getHotUpdateService() != null) {
            List<String> hostNames = DataHolder.getHotUpdateService().getMappigsPerWebapp(contextStr);
            for (String hostName : hostNames) {
                Host host = DataHolder.getHotUpdateService().addHost(hostName);
                /*                    ApplicationContext.getCurrentApplicationContext().putUrlMappingForApplication(hostName, contextStr);
  */
                Context contextForHost = DataHolder.getCarbonTomcatService().addWebApp(host, "/", webappFile.getAbsolutePath(), new JaggeryDeployerManager.JaggeryConfListener(jaggeryConfigObj, securityConstraint));
                log.info("Deployed JaggeryApp on host: " + contextForHost);
            }
        }
        Manager manager = context.getManager();
        if (isDistributable(context, jaggeryConfigObj)) {
            // Clusterable manager implementation as DeltaManager
            context.setDistributable(true);
            // Using clusterable manager
            CarbonTomcatClusterableSessionManager sessionManager;
            if (manager instanceof CarbonTomcatClusterableSessionManager) {
                sessionManager = (CarbonTomcatClusterableSessionManager) manager;
                sessionManager.setOwnerTenantId(tenantId);
            } else {
                sessionManager = new CarbonTomcatClusterableSessionManager(tenantId);
                context.setManager(sessionManager);
            }
            Object alreadyinsertedSMMap = configurationContext.getProperty(CarbonConstants.TOMCAT_SESSION_MANAGER_MAP);
            if (alreadyinsertedSMMap != null) {
                ((Map<String, CarbonTomcatClusterableSessionManager>) alreadyinsertedSMMap).put(context.getName(), sessionManager);
            } else {
                sessionManagerMap.put(context.getName(), sessionManager);
                configurationContext.setProperty(CarbonConstants.TOMCAT_SESSION_MANAGER_MAP, sessionManagerMap);
            }
        } else {
            if (manager instanceof CarbonTomcatSessionManager) {
                ((CarbonTomcatSessionManager) manager).setOwnerTenantId(tenantId);
            } else if (manager instanceof CarbonTomcatSessionPersistentManager) {
                ((CarbonTomcatSessionPersistentManager) manager).setOwnerTenantId(tenantId);
                log.debug(manager.getInfo() + " enabled Tomcat HTTP Session Persistent mode using " + ((CarbonTomcatSessionPersistentManager) manager).getStore().getInfo());
            } else {
                context.setManager(new CarbonTomcatSessionManager(tenantId));
            }
        }
        context.setReloadable(false);
        JaggeryApplication webapp = new JaggeryApplication(this, context, webappFile);
        webapp.setServletContextParameters(webContextParams);
        webapp.setState("Started");
        webApplicationsHolder.getStartedWebapps().put(filename, webapp);
        webApplicationsHolder.getFaultyWebapps().remove(filename);
        registerApplicationEventListeners(applicationEventListeners, context);
        log.info("Deployed webapp: " + webapp);
    } catch (Throwable e) {
        // catching a Throwable here to avoid web-apps crashing the server during startup
        StandardContext context = new StandardContext();
        context.setName(webappFile.getName());
        context.addParameter(WebappsConstants.FAULTY_WEBAPP, "true");
        JaggeryApplication webapp = new JaggeryApplication(this, context, webappFile);
        webapp.setProperty(WebappsConstants.WEBAPP_FILTER, JaggeryConstants.JAGGERY_WEBAPP_FILTER_PROP);
        String msg = "Error while deploying webapp: " + webapp;
        log.error(msg, e);
        webapp.setFaultReason(new Exception(msg, e));
        webApplicationsHolder.getFaultyWebapps().put(filename, webapp);
        webApplicationsHolder.getStartedWebapps().remove(filename);
        throw new CarbonException(msg, e);
    }
}
Also used : ConfigurationContext(org.apache.axis2.context.ConfigurationContext) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) Tomcat(org.apache.catalina.startup.Tomcat) JaggeryDeployerManager(org.jaggeryjs.jaggery.core.manager.JaggeryDeployerManager) ArrayList(java.util.ArrayList) CarbonException(org.wso2.carbon.CarbonException) Host(org.apache.catalina.Host) CarbonTomcatClusterableSessionManager(org.wso2.carbon.core.session.CarbonTomcatClusterableSessionManager) Manager(org.apache.catalina.Manager) JaggeryDeployerManager(org.jaggeryjs.jaggery.core.manager.JaggeryDeployerManager) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) CarbonException(org.wso2.carbon.CarbonException) JSONObject(org.json.simple.JSONObject) CarbonTomcatClusterableSessionManager(org.wso2.carbon.core.session.CarbonTomcatClusterableSessionManager) StandardContext(org.apache.catalina.core.StandardContext) JSONObject(org.json.simple.JSONObject) Map(java.util.Map) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection)

Example 38 with URL

use of org.apache.axis2.util.URL in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method setOAuthApplicationInfo.

/**
 * set information that are needed to invoke callback service
 */
private void setOAuthApplicationInfo(APIStateWorkflowDTO apiStateWorkFlowDTO) throws WorkflowException {
    // if credentials are not defined in the workflow-extension.xml file call dcr endpoint and generate a
    // oauth application and pass the client id and secret
    WorkflowProperties workflowProperties = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
    if (clientId == null || clientSecret == null) {
        String dcrUsername = workflowProperties.getdCREndpointUser();
        String dcrPassword = workflowProperties.getdCREndpointPassword();
        byte[] encodedAuth = Base64.encodeBase64((dcrUsername + ":" + dcrPassword).getBytes(Charset.forName("ISO-8859-1")));
        JSONObject payload = new JSONObject();
        payload.put(PayloadConstants.KEY_OAUTH_APPNAME, WorkflowConstants.WORKFLOW_OAUTH_APP_NAME);
        payload.put(PayloadConstants.KEY_OAUTH_OWNER, dcrUsername);
        payload.put(PayloadConstants.KEY_OAUTH_SAASAPP, "true");
        payload.put(PayloadConstants.KEY_OAUTH_GRANT_TYPES, WorkflowConstants.WORKFLOW_OAUTH_APP_GRANT_TYPES);
        URL serviceEndpointURL = new URL(workflowProperties.getdCREndPoint());
        HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
        HttpPost httpPost = new HttpPost(workflowProperties.getdCREndPoint());
        String authHeader = "Basic " + new String(encodedAuth);
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        StringEntity requestEntity = new StringEntity(payload.toJSONString(), ContentType.APPLICATION_JSON);
        httpPost.setEntity(requestEntity);
        try {
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                String responseStr = EntityUtils.toString(entity);
                if (log.isDebugEnabled()) {
                    log.debug("Workflow oauth app created: " + responseStr);
                }
                JSONParser parser = new JSONParser();
                JSONObject obj = (JSONObject) parser.parse(responseStr);
                clientId = (String) obj.get(PayloadConstants.VARIABLE_CLIENTID);
                clientSecret = (String) obj.get(PayloadConstants.VARIABLE_CLIENTSECRET);
            } else {
                String error = "Error while starting the process:  " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
                log.error(error);
                throw new WorkflowException(error);
            }
        } catch (ClientProtocolException e) {
            String errorMsg = "Error while creating the http client";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } catch (IOException e) {
            String errorMsg = "Error while connecting to dcr endpoint";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } catch (ParseException e) {
            String errorMsg = "Error while parsing response from DCR endpoint";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } finally {
            httpPost.reset();
        }
    }
    apiStateWorkFlowDTO.setClientId(clientId);
    apiStateWorkFlowDTO.setClientSecret(clientSecret);
    apiStateWorkFlowDTO.setScope(WorkflowConstants.API_WF_SCOPE);
    apiStateWorkFlowDTO.setTokenAPI(workflowProperties.getTokenEndPoint());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) URL(org.apache.axis2.util.URL) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.simple.JSONObject) HttpClient(org.apache.http.client.HttpClient) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 39 with URL

use of org.apache.axis2.util.URL in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method cleanUpPendingTask.

/**
 * Handle cleanup task for api state change workflow ws executor. This queries the BPMN process related to the given
 * workflow reference id and delete that process
 */
@Override
public void cleanUpPendingTask(String workflowExtRef) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Starting cleanup task for APIStateChangeWSWorkflowExecutor for :" + workflowExtRef);
    }
    String errorMsg;
    if (serviceEndpoint == null) {
        // set the bps endpoint from the global configurations
        WorkflowProperties workflowProperties = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
        serviceEndpoint = workflowProperties.getServerUrl();
    }
    URL serviceEndpointURL = new URL(serviceEndpoint);
    HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
    // get the basic auth header value to connect to the bpmn process
    String authHeader = getBasicAuthHeader();
    JSONParser parser = new JSONParser();
    HttpGet httpGet = null;
    HttpDelete httpDelete = null;
    try {
        // Get the process instance details related to the given workflow reference id. If there is a process that
        // is already started with the given wf reference as the businesskey, that process needes to be deleted
        httpGet = new HttpGet(serviceEndpoint + RUNTIME_INSTANCE_RESOURCE_PATH + "?businessKey=" + workflowExtRef);
        httpGet.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String processId = null;
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // already exists a process related to the given workflow reference
            String responseStr = EntityUtils.toString(entity);
            if (log.isDebugEnabled()) {
                log.debug("Process instance details for ref : " + workflowExtRef + ": " + responseStr);
            }
            JSONObject obj = (JSONObject) parser.parse(responseStr);
            JSONArray data = (JSONArray) obj.get(PayloadConstants.DATA);
            if (data != null) {
                JSONObject instanceDetails = (JSONObject) data.get(0);
                // extract the id related to that process. this id is used to delete the process
                processId = (String) instanceDetails.get(PayloadConstants.ID);
            }
            if (processId != null) {
                // delete the process using the id
                httpDelete = new HttpDelete(serviceEndpoint + RUNTIME_INSTANCE_RESOURCE_PATH + "/" + processId);
                httpDelete.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
                response = httpClient.execute(httpDelete);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
                    errorMsg = "Error while deleting process instance details for " + workflowExtRef + " code: " + response.getStatusLine().getStatusCode();
                    log.error(errorMsg);
                    throw new WorkflowException(errorMsg);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Successfully deleted process instance for  : " + workflowExtRef);
                }
                // remove entry from the db
                ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
                apiMgtDAO.removeWorkflowEntry(workflowExtRef, WorkflowConstants.WF_TYPE_AM_API_STATE.toString());
            }
        } else {
            errorMsg = "Error while getting process instance details for " + workflowExtRef + " code: " + response.getStatusLine().getStatusCode();
            log.error(errorMsg);
            throw new WorkflowException(errorMsg);
        }
    } catch (ClientProtocolException e) {
        log.error("Error while creating the http client", e);
        throw new WorkflowException("Error while creating the http client", e);
    } catch (IOException e) {
        log.error("Error while connecting to the BPMN process server from the WorkflowExecutor.", e);
        throw new WorkflowException("Error while connecting to the external service", e);
    } catch (ParseException e) {
        log.error("Error while parsing response from BPS server", e);
        throw new WorkflowException("Error while parsing response from BPS server", e);
    } catch (APIManagementException e) {
        log.error("Error removing the workflow entry", e);
        throw new WorkflowException("Error removing the workflow entry", e);
    } finally {
        if (httpGet != null) {
            httpGet.reset();
        }
        if (httpDelete != null) {
            httpDelete.reset();
        }
    }
}
Also used : HttpDelete(org.apache.http.client.methods.HttpDelete) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) JSONArray(org.json.simple.JSONArray) HttpResponse(org.apache.http.HttpResponse) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) IOException(java.io.IOException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) URL(org.apache.axis2.util.URL) ClientProtocolException(org.apache.http.client.ClientProtocolException) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpClient(org.apache.http.client.HttpClient) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 40 with URL

use of org.apache.axis2.util.URL in project carbon-apimgt by wso2.

the class TokenRevocationNotifierImpl method sendMessageToPersistentStorage.

/**
 * Method to send the revoked token to the persistent storage
 *
 * @param revokedToken token to be revoked
 * @param properties persistent notifier properties read from the config
 */
@Override
public void sendMessageToPersistentStorage(String revokedToken, Properties properties) {
    // Variables related to Persistent Notifier
    String defaultPersistentNotifierHostname = "https://localhost:2379/v2/keys/jti/";
    String persistentNotifierHostname = properties.getProperty("hostname", defaultPersistentNotifierHostname);
    String persistentNotifierTTL = properties.getProperty("ttl", DEFAULT_TTL);
    String defaultPersistentNotifierUsername = "root";
    String persistentNotifierUsername = properties.getProperty("username", defaultPersistentNotifierUsername);
    String defaultPersistentNotifierPassword = "root";
    String persistentNotifierPassword = properties.getProperty("password", defaultPersistentNotifierPassword);
    String etcdEndpoint = persistentNotifierHostname + revokedToken;
    URL etcdEndpointURL = new URL(etcdEndpoint);
    String etcdEndpointProtocol = etcdEndpointURL.getProtocol();
    int etcdEndpointPort = etcdEndpointURL.getPort();
    HttpClient etcdEPClient = APIUtil.getHttpClient(etcdEndpointPort, etcdEndpointProtocol);
    HttpPut httpETCDPut = new HttpPut(etcdEndpoint);
    byte[] encodedAuth = Base64.encodeBase64((persistentNotifierUsername + ":" + persistentNotifierPassword).getBytes(StandardCharsets.UTF_8));
    String authHeader = "Basic " + new String(encodedAuth, StandardCharsets.UTF_8);
    httpETCDPut.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
    List<NameValuePair> etcdParams = new ArrayList<>(2);
    etcdParams.add(new BasicNameValuePair("value", "true"));
    etcdParams.add(new BasicNameValuePair("ttl", persistentNotifierTTL));
    // Send the revoked token to the persistent storage Server
    httpETCDPut.setEntity(new UrlEncodedFormEntity(etcdParams, StandardCharsets.UTF_8));
    HttpResponse etcdResponse;
    try {
        etcdResponse = etcdEPClient.execute(httpETCDPut);
        if (etcdResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK || etcdResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            if (log.isDebugEnabled()) {
                log.debug("Successfully submitted the request for revoked token. HTTP status :" + etcdResponse.getStatusLine().getStatusCode());
            }
        } else {
            log.error("Sending revoked token to persistent storage failed. HTTP error code : " + etcdResponse.getStatusLine().getStatusCode());
        }
    } catch (IOException e) {
        log.error("Error while sending revoked token to the persistent storage :", e);
    }
}
Also used : BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) URL(org.apache.axis2.util.URL) HttpPut(org.apache.http.client.methods.HttpPut) HttpClient(org.apache.http.client.HttpClient) BasicNameValuePair(org.apache.http.message.BasicNameValuePair)

Aggregations

IOException (java.io.IOException)31 EndpointReference (org.apache.axis2.addressing.EndpointReference)29 AxisFault (org.apache.axis2.AxisFault)27 URL (java.net.URL)21 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)19 URL (org.apache.axis2.util.URL)19 HttpClient (org.apache.http.client.HttpClient)19 Options (org.apache.axis2.client.Options)18 MalformedURLException (java.net.MalformedURLException)17 OMElement (org.apache.axiom.om.OMElement)17 MessageContext (org.apache.axis2.context.MessageContext)16 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)16 ServiceClient (org.apache.axis2.client.ServiceClient)13 SynapseException (org.apache.synapse.SynapseException)13 AxisConfiguration (org.apache.axis2.engine.AxisConfiguration)12 AxisService (org.apache.axis2.description.AxisService)10 StringEntity (org.apache.http.entity.StringEntity)9 SynapseConfiguration (org.apache.synapse.config.SynapseConfiguration)9 Map (java.util.Map)7 JSONObject (org.json.JSONObject)7