use of org.wso2.carbon.apimgt.impl.workflow.WorkflowException in project carbon-apimgt by wso2.
the class APIStoreImpl method addApplication.
@Override
public ApplicationCreationResponse addApplication(Application application) throws APIManagementException {
ApplicationCreationResponse applicationResponse = null;
try {
if (getApplicationDAO().isApplicationNameExists(application.getName())) {
String message = "An application already exists with a duplicate name - " + application.getName();
log.error(message);
throw new APIMgtResourceAlreadyExistsException(message, ExceptionCodes.APPLICATION_ALREADY_EXISTS);
}
// Tier validation
Policy tier = application.getPolicy();
if (tier == null) {
String message = "Tier name cannot be null - " + application.getName();
log.error(message);
throw new APIManagementException(message, ExceptionCodes.TIER_CANNOT_BE_NULL);
} else {
Policy policy = getPolicyDAO().getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.application, tier.getPolicyName());
if (policy == null) {
String message = "Specified tier " + tier.getPolicyName() + " is invalid";
log.error(message);
throw new APIManagementException(message, ExceptionCodes.TIER_CANNOT_BE_NULL);
}
application.setPolicy(policy);
}
// Generate UUID for application
String generatedUuid = UUID.randomUUID().toString();
application.setId(generatedUuid);
String permissionString = application.getPermissionString();
if (permissionString != null && !("").equals(permissionString)) {
HashMap roleNamePermissionList;
roleNamePermissionList = getAPIPermissionArray(permissionString);
application.setPermissionMap(roleNamePermissionList);
}
application.setCreatedTime(LocalDateTime.now());
getApplicationDAO().addApplication(application);
WorkflowExecutor appCreationWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION);
ApplicationCreationWorkflow workflow = new ApplicationCreationWorkflow(getApplicationDAO(), getWorkflowDAO(), getApiGateway());
workflow.setApplication(application);
workflow.setCreatedBy(getUsername());
workflow.setWorkflowReference(application.getId());
workflow.setExternalWorkflowReference(UUID.randomUUID().toString());
workflow.setCreatedTime(LocalDateTime.now());
String workflowDescription = "Application [ " + application.getName() + " ] creation request from application creator - " + getUsername() + " with throttling tier - " + tier.getPolicyName() + "";
workflow.setWorkflowDescription(workflowDescription);
WorkflowResponse response = appCreationWFExecutor.execute(workflow);
workflow.setStatus(response.getWorkflowStatus());
if (WorkflowStatus.CREATED != response.getWorkflowStatus()) {
completeWorkflow(appCreationWFExecutor, workflow);
} else {
getApplicationDAO().updateApplicationState(generatedUuid, APIMgtConstants.ApplicationStatus.APPLICATION_ONHOLD);
addWorkflowEntries(workflow);
}
APIUtils.logDebug("successfully added application with appId " + application.getId(), log);
applicationResponse = new ApplicationCreationResponse(application.getId(), response);
} catch (APIMgtDAOException e) {
String errorMsg = "Error occurred while creating the application - " + application.getName();
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
} catch (ParseException e) {
String errorMsg = "Error occurred while parsing the permission json from swagger in application - " + application.getName();
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
} catch (WorkflowException e) {
String errorMsg = "Error occurred in workflow";
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, ExceptionCodes.WORKFLOW_EXCEPTION);
}
return applicationResponse;
}
use of org.wso2.carbon.apimgt.impl.workflow.WorkflowException in project carbon-apimgt by wso2.
the class TenantWorkflowConfigHolder method setInstanceProperty.
/**
* Find and invoke the setter method with the name of form setXXX passing in the value given
* on the POJO object
*
* @param name name of the setter field
* @param val value to be set
* @param obj POJO instance
*/
public void setInstanceProperty(String name, Object val, Object obj) throws WorkflowException {
String mName = "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1);
Method method;
try {
Method[] methods = obj.getClass().getMethods();
boolean invoked = false;
for (Method method1 : methods) {
if (mName.equals(method1.getName())) {
Class[] params = method1.getParameterTypes();
if (params.length != 1) {
handleException("Did not find a setter method named : " + mName + "() that takes a single String, int, long, float, double ," + "OMElement or boolean parameter");
} else if (val instanceof String) {
String value = (String) val;
if (String.class.equals(params[0])) {
method = obj.getClass().getMethod(mName, String.class);
method.invoke(obj, new String[] { value });
} else if (int.class.equals(params[0])) {
method = obj.getClass().getMethod(mName, int.class);
method.invoke(obj, new Integer[] { Integer.valueOf(value) });
} else if (long.class.equals(params[0])) {
method = obj.getClass().getMethod(mName, long.class);
method.invoke(obj, new Long[] { Long.valueOf(value) });
} else if (float.class.equals(params[0])) {
method = obj.getClass().getMethod(mName, float.class);
method.invoke(obj, new Float[] { new Float(value) });
} else if (double.class.equals(params[0])) {
method = obj.getClass().getMethod(mName, double.class);
method.invoke(obj, new Double[] { new Double(value) });
} else if (boolean.class.equals(params[0])) {
method = obj.getClass().getMethod(mName, boolean.class);
method.invoke(obj, new Boolean[] { Boolean.valueOf(value) });
} else if (Class.forName("[C").equals(params[0])) {
method = obj.getClass().getMethod(mName, Class.forName("[C"));
method.invoke(obj, value.toCharArray());
} else {
continue;
}
} else if (val instanceof OMElement && OMElement.class.equals(params[0])) {
method = obj.getClass().getMethod(mName, OMElement.class);
method.invoke(obj, new OMElement[] { (OMElement) val });
} else {
continue;
}
invoked = true;
break;
}
}
if (!invoked) {
handleException("Did not find a setter method named : " + mName + "() that takes a single String, int, long, float, double " + "or boolean parameter");
}
} catch (Exception e) {
handleException("Error invoking setter method named : " + mName + "() that takes a single String, int, long, float, double " + "or boolean parameter", e);
}
}
use of org.wso2.carbon.apimgt.impl.workflow.WorkflowException in project carbon-apimgt by wso2.
the class TenantWorkflowConfigHolder method load.
public void load() throws WorkflowException, RegistryException {
workflowExecutorMap = new ConcurrentHashMap<>();
InputStream in = null;
try {
String workFlowConfig = ServiceReferenceHolder.getInstance().getApimConfigService().getWorkFlowConfig(tenantDomain);
if (StringUtils.isNotEmpty(workFlowConfig)) {
in = new ByteArrayInputStream(workFlowConfig.getBytes());
StAXOMBuilder builder = new StAXOMBuilder(in);
secretResolver = SecretResolverFactory.create(builder.getDocumentElement(), true);
OMElement workflowExtensionsElem = builder.getDocument().getFirstChildWithName(new QName(WorkflowConstants.WORKFLOW_EXTENSIONS));
OMElement workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.APPLICATION_CREATION));
String executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
Class clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
WorkflowExecutor workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
loadProperties(workflowElem, workFlowExecutor);
workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_APPLICATION_CREATION, workFlowExecutor);
workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.PRODUCTION_APPLICATION_REGISTRATION));
executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
loadProperties(workflowElem, workFlowExecutor);
workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_PRODUCTION, workFlowExecutor);
workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.SANDBOX_APPLICATION_REGISTRATION));
executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
loadProperties(workflowElem, workFlowExecutor);
workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_APPLICATION_REGISTRATION_SANDBOX, workFlowExecutor);
workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.USER_SIGN_UP));
executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
loadProperties(workflowElem, workFlowExecutor);
workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_USER_SIGNUP, workFlowExecutor);
workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.SUBSCRIPTION_CREATION));
executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
loadProperties(workflowElem, workFlowExecutor);
workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_CREATION, workFlowExecutor);
workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.SUBSCRIPTION_UPDATE));
if (workflowElem != null) {
executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
loadProperties(workflowElem, workFlowExecutor);
workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE, workFlowExecutor);
} else {
executorClass = DEFAULT_SUBSCRIPTION_UPDATE_EXECUTOR_CLASS;
clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_UPDATE, workFlowExecutor);
}
workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.SUBSCRIPTION_DELETION));
executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
loadProperties(workflowElem, workFlowExecutor);
workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_SUBSCRIPTION_DELETION, workFlowExecutor);
workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.APPLICATION_DELETION));
executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
loadProperties(workflowElem, workFlowExecutor);
workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_APPLICATION_DELETION, workFlowExecutor);
workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.API_STATE_CHANGE));
if (workflowElem == null) {
// TO handle migrated environment, create the default simple workflow executor
workflowElem = OMAbstractFactory.getOMFactory().createOMElement(new QName(WorkflowConstants.API_STATE_CHANGE));
executorClass = WorkflowConstants.DEFAULT_EXECUTOR_API_STATE_CHANGE;
workflowElem.addAttribute(WorkflowConstants.EXECUTOR, executorClass, null);
} else {
executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
}
clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
loadProperties(workflowElem, workFlowExecutor);
workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_API_STATE, workFlowExecutor);
workflowElem = workflowExtensionsElem.getFirstChildWithName(new QName(WorkflowConstants.API_PRODUCT_STATE_CHANGE));
if (workflowElem == null) {
// To handle migration, create the default simple workflow executor
workflowElem = OMAbstractFactory.getOMFactory().createOMElement(new QName(WorkflowConstants.API_PRODUCT_STATE_CHANGE));
executorClass = WorkflowConstants.DEFAULT_EXECUTOR_API_PRODUCT_STATE_CHANGE;
workflowElem.addAttribute(WorkflowConstants.EXECUTOR, executorClass, null);
} else {
executorClass = workflowElem.getAttributeValue(new QName(WorkflowConstants.EXECUTOR));
}
clazz = TenantWorkflowConfigHolder.class.getClassLoader().loadClass(executorClass);
workFlowExecutor = (WorkflowExecutor) clazz.newInstance();
loadProperties(workflowElem, workFlowExecutor);
workflowExecutorMap.put(WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE, workFlowExecutor);
}
} catch (XMLStreamException e) {
log.error("Error building xml", e);
handleException("Error building xml", e);
} catch (ClassNotFoundException e) {
log.error("Unable to find class", e);
handleException("Unable to find class", e);
} catch (InstantiationException e) {
log.error("Unable to instantiate class", e);
handleException("Unable to instantiate class", e);
} catch (IllegalAccessException e) {
log.error("Illegal attempt to invoke class methods", e);
handleException("Illegal attempt to invoke class methods", e);
} catch (WorkflowException e) {
log.error("Unable to load workflow executor class", e);
handleException("Unable to load workflow executor class", e);
} catch (APIManagementException e) {
log.error("Unable to retrieve workflow configurations", e);
handleException("Unable to retrieve workflow configurations", e);
} finally {
IOUtils.closeQuietly(in);
}
}
use of org.wso2.carbon.apimgt.impl.workflow.WorkflowException 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.wso2.carbon.apimgt.impl.workflow.WorkflowException in project carbon-apimgt by wso2.
the class APIStateChangeWSWorkflowExecutor method complete.
/**
* Complete the API state change workflow process.
*/
@Override
public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowException {
if (log.isDebugEnabled()) {
log.debug("Completing API State change Workflow..");
log.debug("response: " + workflowDTO.toString());
}
workflowDTO.setUpdatedTime(System.currentTimeMillis());
super.complete(workflowDTO);
String action = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_API_LC_ACTION);
String apiName = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_APINAME);
String providerName = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_APIPROVIDER);
String version = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_APIVERSION);
String invoker = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_INVOKER);
String currentStatus = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_APISTATE);
int tenantId = workflowDTO.getTenantId();
ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
try {
// tenant flow is already started from the rest api service impl. no need to start from here
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(invoker);
Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(invoker, tenantId);
APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, version);
GenericArtifact apiArtifact = APIUtil.getAPIArtifact(apiIdentifier, registry);
if (WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) {
String targetStatus;
apiArtifact.invokeAction(action, APIConstants.API_LIFE_CYCLE);
targetStatus = apiArtifact.getLifecycleState();
if (!currentStatus.equals(targetStatus)) {
apiMgtDAO.recordAPILifeCycleEvent(apiArtifact.getId(), currentStatus.toUpperCase(), targetStatus.toUpperCase(), invoker, tenantId);
}
if (log.isDebugEnabled()) {
String logMessage = "API Status changed successfully. API Name: " + apiIdentifier.getApiName() + ", API Version " + apiIdentifier.getVersion() + ", New Status : " + targetStatus;
log.debug(logMessage);
}
}
} catch (RegistryException e) {
String errorMsg = "Could not complete api state change workflow";
log.error(errorMsg, e);
throw new WorkflowException(errorMsg, e);
} catch (APIManagementException e) {
String errorMsg = "Could not complete api state change workflow";
log.error(errorMsg, e);
throw new WorkflowException(errorMsg, e);
}
return new GeneralWorkflowResponse();
}
Aggregations