Search in sources :

Example 81 with ParseException

use of org.json.simple.parser.ParseException in project carbon-apimgt by wso2.

the class AbstractKeyManager method validateOAuthAppCreationProperties.

protected void validateOAuthAppCreationProperties(OAuthApplicationInfo oAuthApplicationInfo) throws APIManagementException {
    String type = getType();
    List<String> missedRequiredValues = new ArrayList<>();
    KeyManagerConnectorConfiguration keyManagerConnectorConfiguration = ServiceReferenceHolder.getInstance().getKeyManagerConnectorConfiguration(type);
    if (keyManagerConnectorConfiguration != null) {
        List<ConfigurationDto> applicationConfigurationDtoList = keyManagerConnectorConfiguration.getApplicationConfigurations();
        Object additionalProperties = oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES);
        try {
            if (additionalProperties != null) {
                JSONObject additionalPropertiesJson;
                if (additionalProperties instanceof JSONObject) {
                    additionalPropertiesJson = (JSONObject) additionalProperties;
                } else {
                    additionalPropertiesJson = (JSONObject) new JSONParser().parse((String) additionalProperties);
                }
                for (ConfigurationDto configurationDto : applicationConfigurationDtoList) {
                    Object value = additionalPropertiesJson.get(configurationDto.getName());
                    if (value == null) {
                        if (configurationDto.isRequired()) {
                            missedRequiredValues.add(configurationDto.getName());
                        }
                    }
                }
                if (!missedRequiredValues.isEmpty()) {
                    throw new APIManagementException("Missing required properties to create/update oauth " + "application", ExceptionCodes.KEY_MANAGER_MISSING_REQUIRED_PROPERTIES_IN_APPLICATION);
                }
            }
        } catch (ParseException e) {
            throw new APIManagementException("Error while parsing the addition properties of OAuth " + "application");
        }
    } else {
        throw new APIManagementException("Invalid Key Manager Type " + type, ExceptionCodes.KEY_MANAGER_NOT_REGISTERED);
    }
}
Also used : KeyManagerConnectorConfiguration(org.wso2.carbon.apimgt.api.model.KeyManagerConnectorConfiguration) ConfigurationDto(org.wso2.carbon.apimgt.api.model.ConfigurationDto) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 82 with ParseException

use of org.json.simple.parser.ParseException in project carbon-apimgt by wso2.

the class AbstractKeyManager method buildFromJSON.

/**
 * This method will accept json String and will do the json parse will set oAuth application properties to OAuthApplicationInfo object.
 *
 * @param jsonInput this jsonInput will contain set of oAuth application properties.
 * @return OAuthApplicationInfo object will be return.
 * @throws APIManagementException
 */
public OAuthApplicationInfo buildFromJSON(OAuthApplicationInfo oAuthApplicationInfo, String jsonInput) throws APIManagementException {
    // initiate json parser.
    JSONParser parser = new JSONParser();
    JSONObject jsonObject;
    try {
        // parse json String
        jsonObject = (JSONObject) parser.parse(jsonInput);
        if (jsonObject != null) {
            // create a map to hold json parsed objects.
            Map<String, Object> params = (Map) jsonObject;
            if (params.get(APIConstants.JSON_CALLBACK_URL) != null) {
                oAuthApplicationInfo.setCallBackURL((String) params.get(APIConstants.JSON_CALLBACK_URL));
            }
            if (params.get(APIConstants.JSON_GRANT_TYPES) != null) {
                String grantTypeString = params.get(APIConstants.JSON_GRANT_TYPES).toString();
                if (StringUtils.isEmpty(oAuthApplicationInfo.getCallBackURL()) && (grantTypeString.contains("implicit") || grantTypeString.contains("authorization_code"))) {
                    throw new EmptyCallbackURLForCodeGrantsException("The callback url must have at least one URI " + "value when using Authorization code or implicit grant types.");
                }
            }
            // set client Id
            if (params.get(APIConstants.JSON_CLIENT_ID) != null) {
                oAuthApplicationInfo.setClientId((String) params.get(APIConstants.JSON_CLIENT_ID));
            }
            // set client secret
            if (params.get(APIConstants.JSON_CLIENT_SECRET) != null) {
                oAuthApplicationInfo.setClientSecret((String) params.get(APIConstants.JSON_CLIENT_SECRET));
            }
            // copy all params map in to OAuthApplicationInfo's Map object.
            oAuthApplicationInfo.putAll(params);
            validateOAuthAppCreationProperties(oAuthApplicationInfo);
            return oAuthApplicationInfo;
        }
    } catch (ParseException e) {
        handleException("Error occurred while parsing JSON String", e);
    }
    return null;
}
Also used : JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) EmptyCallbackURLForCodeGrantsException(org.wso2.carbon.apimgt.api.EmptyCallbackURLForCodeGrantsException)

Example 83 with ParseException

use of org.json.simple.parser.ParseException in project carbon-apimgt by wso2.

the class AbstractKeyManager method buildAccessTokenRequestFromJSON.

public AccessTokenRequest buildAccessTokenRequestFromJSON(String jsonInput, AccessTokenRequest tokenRequest) throws APIManagementException {
    if (jsonInput == null || jsonInput.isEmpty()) {
        log.debug("JsonInput is null or Empty.");
        return tokenRequest;
    }
    JSONParser parser = new JSONParser();
    JSONObject jsonObject;
    if (tokenRequest == null) {
        log.debug("Input request is null. Creating a new Request Object.");
        tokenRequest = new AccessTokenRequest();
    }
    try {
        jsonObject = (JSONObject) parser.parse(jsonInput);
        // Getting parameters from input string and setting in TokenRequest.
        if (jsonObject != null && !jsonObject.isEmpty()) {
            Map<String, Object> params = (Map<String, Object>) jsonObject;
            if (null != params.get(ApplicationConstants.OAUTH_CLIENT_ID)) {
                tokenRequest.setClientId((String) params.get(ApplicationConstants.OAUTH_CLIENT_ID));
            }
            if (null != params.get(ApplicationConstants.OAUTH_CLIENT_SECRET)) {
                tokenRequest.setClientSecret((String) params.get(ApplicationConstants.OAUTH_CLIENT_SECRET));
            }
            if (null != params.get(ApplicationConstants.VALIDITY_PERIOD)) {
                tokenRequest.setValidityPeriod(Long.parseLong((String) params.get(ApplicationConstants.VALIDITY_PERIOD)));
            }
            if (APIConstants.OAuthConstants.TOKEN_EXCHANGE.equals(tokenRequest.getGrantType())) {
                tokenRequest.addRequestParam(APIConstants.OAuthConstants.SUBJECT_TOKEN, params.get(APIConstants.OAuthConstants.SUBJECT_TOKEN));
            }
            return tokenRequest;
        }
    } catch (ParseException e) {
        handleException("Error occurred while parsing JSON String", e);
    }
    return null;
}
Also used : JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map)

Example 84 with ParseException

use of org.json.simple.parser.ParseException 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 85 with ParseException

use of org.json.simple.parser.ParseException 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)

Aggregations

ParseException (org.json.simple.parser.ParseException)259 JSONObject (org.json.simple.JSONObject)193 JSONParser (org.json.simple.parser.JSONParser)186 JSONArray (org.json.simple.JSONArray)84 IOException (java.io.IOException)72 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)50 HashMap (java.util.HashMap)41 ArrayList (java.util.ArrayList)34 Map (java.util.Map)23 HashSet (java.util.HashSet)18 API (org.wso2.carbon.apimgt.api.model.API)18 BufferedReader (java.io.BufferedReader)13 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)13 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)13 List (java.util.List)12 File (java.io.File)11 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)11 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)11 InputStreamReader (java.io.InputStreamReader)10 URL (java.net.URL)10