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);
}
}
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;
}
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;
}
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());
}
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();
}
}
}
Aggregations