use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.
the class AsyncApiParser method generateAsyncAPIDefinition.
public String generateAsyncAPIDefinition(API api) throws APIManagementException {
Aai20Document aaiDocument = new Aai20Document();
aaiDocument.info = aaiDocument.createInfo();
aaiDocument.info.title = api.getId().getName();
aaiDocument.info.version = api.getId().getVersion();
if (!APIConstants.API_TYPE_WEBSUB.equals(api.getType())) {
Aai20Server server = (Aai20Server) aaiDocument.createServer("production");
JSONObject endpointConfig = new JSONObject(api.getEndpointConfig());
server.url = endpointConfig.getJSONObject("production_endpoints").getString("url");
server.protocol = api.getType().toLowerCase();
aaiDocument.addServer("production", server);
}
Map<String, AaiChannelItem> channels = new HashMap<>();
for (URITemplate uriTemplate : api.getUriTemplates()) {
Aai20ChannelItem channelItem = aaiDocument.createChannelItem(uriTemplate.getUriTemplate());
Aai20Operation subscribeOp = new Aai20Operation(channelItem, "subscribe");
channelItem.subscribe = subscribeOp;
if (APIConstants.API_TYPE_WS.equals(api.getType())) {
Aai20Operation publishOp = new Aai20Operation(channelItem, "publish");
channelItem.publish = publishOp;
}
channels.put(uriTemplate.getUriTemplate(), channelItem);
}
aaiDocument.channels = channels;
return Library.writeDocumentToJSONString(aaiDocument);
}
use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.
the class APIStateChangeWSWorkflowExecutor method execute.
@Override
public WorkflowResponse execute(WorkflowDTO workflowDTO) throws WorkflowException {
if (log.isDebugEnabled()) {
log.debug("Executing API State change Workflow.");
log.debug("Execute workflowDTO " + workflowDTO.toString());
}
if (stateList != null) {
Map<String, List<String>> stateActionMap = getSelectedStatesToApprove();
APIStateWorkflowDTO apiStateWorkFlowDTO = (APIStateWorkflowDTO) workflowDTO;
if (stateActionMap.containsKey(apiStateWorkFlowDTO.getApiCurrentState().toUpperCase()) && stateActionMap.get(apiStateWorkFlowDTO.getApiCurrentState().toUpperCase()).contains(apiStateWorkFlowDTO.getApiLCAction())) {
// set the auth application related info. This will be used to call the callback service
setOAuthApplicationInfo(apiStateWorkFlowDTO);
// build request payload
String jsonPayload = buildPayloadForBPMNProcess(apiStateWorkFlowDTO);
if (log.isDebugEnabled()) {
log.debug("APIStateChange payload: " + jsonPayload);
}
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());
HttpPost httpPost = new HttpPost(serviceEndpoint + RUNTIME_INSTANCE_RESOURCE_PATH);
// Generate the basic auth header using provided user credentials
String authHeader = getBasicAuthHeader();
httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
StringEntity requestEntity = new StringEntity(jsonPayload, ContentType.APPLICATION_JSON);
httpPost.setEntity(requestEntity);
try {
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
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 the BPMN process server from the WorkflowExecutor.";
log.error(errorMsg, e);
throw new WorkflowException(errorMsg, e);
} finally {
httpPost.reset();
}
super.execute(workflowDTO);
} else {
// For any other states, act as simpleworkflow executor.
workflowDTO.setStatus(WorkflowStatus.APPROVED);
// calling super.complete() instead of complete() to act as the simpleworkflow executor
super.complete(workflowDTO);
}
} else {
String msg = "State change list is not provided. Please check <stateList> element in ";
log.error(msg);
throw new WorkflowException(msg);
}
return new GeneralWorkflowResponse();
}
use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.
the class AbstractApplicationRegistrationWorkflowExecutor method dogenerateKeysForApplication.
public static void dogenerateKeysForApplication(ApplicationRegistrationWorkflowDTO workflowDTO) throws APIManagementException {
log.debug("Registering Application and creating an Access Token... ");
Application application = workflowDTO.getApplication();
Subscriber subscriber = application.getSubscriber();
ApiMgtDAO dao = ApiMgtDAO.getInstance();
if (subscriber == null || workflowDTO.getAllowedDomains() == null) {
dao.populateAppRegistrationWorkflowDTO(workflowDTO);
}
try {
// get new key manager
// Here the default flow is set expecting an ID as the keymanager as this flow only involves new applications
String keyManagerId = workflowDTO.getKeyManager();
KeyManagerConfigurationDTO km = dao.getKeyManagerConfigurationByUUID(keyManagerId);
String tenantDomain = km.getOrganization();
String keyManagerName = km.getName();
KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(tenantDomain, keyManagerName);
if (keyManager == null) {
throw new APIManagementException("Key Manager " + keyManagerName + " not configured");
}
workflowDTO.getAppInfoDTO().getOAuthApplicationInfo().setClientName(application.getName());
// set applications attributes to the oAuthApplicationInfo
workflowDTO.getAppInfoDTO().getOAuthApplicationInfo().putAllAppAttributes(application.getApplicationAttributes());
// createApplication on oAuthorization server.
OAuthApplicationInfo oAuthApplication = keyManager.createApplication(workflowDTO.getAppInfoDTO());
// update associateApplication
ApplicationUtils.updateOAuthAppAssociation(application, workflowDTO.getKeyType(), oAuthApplication, keyManagerId);
// change create application status in to completed.
dao.updateApplicationRegistration(APIConstants.AppRegistrationStatus.REGISTRATION_COMPLETED, workflowDTO.getKeyType(), workflowDTO.getApplication().getId(), keyManagerId);
workflowDTO.setApplicationInfo(oAuthApplication);
AccessTokenInfo tokenInfo;
Object enableTokenGeneration = keyManager.getKeyManagerConfiguration().getParameter(APIConstants.KeyManager.ENABLE_TOKEN_GENERATION);
if (enableTokenGeneration != null && (Boolean) enableTokenGeneration && oAuthApplication.getJsonString().contains(APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS)) {
AccessTokenRequest tokenRequest = ApplicationUtils.createAccessTokenRequest(keyManager, oAuthApplication, null);
tokenInfo = keyManager.getNewApplicationAccessToken(tokenRequest);
} else {
tokenInfo = new AccessTokenInfo();
tokenInfo.setAccessToken("");
tokenInfo.setValidityPeriod(0L);
String[] noScopes = new String[] { "N/A" };
tokenInfo.setScope(noScopes);
oAuthApplication.addParameter("tokenScope", Arrays.toString(noScopes));
}
workflowDTO.setAccessTokenInfo(tokenInfo);
} catch (Exception e) {
APIUtil.handleException("Error occurred while executing SubscriberKeyMgtClient.", e);
}
}
use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.
the class OrganizationPurgeDAO method deleteApplicationList.
/**
* Deletes Applications along with subscriptions, keys and registration data
*
* @param organization Organization
* @throws APIManagementException if failed to delete applications for organization
*/
public void deleteApplicationList(String organization) throws APIManagementException {
try (Connection connection = APIMgtDBUtil.getConnection()) {
connection.setAutoCommit(false);
if (multiGroupAppSharingEnabled) {
updateGroupIDMappingsBulk(connection, organization);
}
try (PreparedStatement prepStmtGetConsumerKey = connection.prepareStatement(OrganizationPurgeConstants.GET_CONSUMER_KEYS_OF_APPLICATION_LIST_SQL);
PreparedStatement deleteDomainApp = connection.prepareStatement(SQLConstants.REMOVE_APPLICATION_FROM_DOMAIN_MAPPINGS_SQL)) {
prepStmtGetConsumerKey.setString(1, organization);
try (ResultSet rs = prepStmtGetConsumerKey.executeQuery()) {
while (rs.next()) {
String consumerKey = rs.getString(APIConstants.FIELD_CONSUMER_KEY);
String keyManagerName = rs.getString("NAME");
String keyManagerOrganization = rs.getString("ORGANIZATION");
// This is true when OAuth App has been created by pasting consumer key/secret in the screen.
String mode = rs.getString("CREATE_MODE");
if (consumerKey != null) {
deleteDomainApp.setString(1, consumerKey);
deleteDomainApp.addBatch();
KeyManager keyManager = KeyManagerHolder.getKeyManagerInstance(keyManagerOrganization, keyManagerName);
if (keyManager != null) {
try {
keyManager.deleteMappedApplication(consumerKey);
log.info("Mapped application deleted for consumer key: " + consumerKey + " and organization: " + organization);
} catch (APIManagementException e) {
handleException("Error while Deleting Client Application for consumer key: " + consumerKey + " and organization: " + organization, e);
}
}
// call delete.
if (!APIConstants.OAuthAppMode.MAPPED.name().equals(mode)) {
// delete on oAuthorization server.
if (log.isDebugEnabled()) {
log.debug("Deleting Oauth application with consumer key " + consumerKey + " from the " + "Oauth server for organization: " + organization);
}
if (keyManager != null) {
try {
keyManager.deleteApplication(consumerKey);
log.info("Client application deleted for consumer key: " + consumerKey + " and organization: " + organization);
} catch (APIManagementException e) {
handleException("Error while Deleting Client Application for organization: " + organization, e);
}
}
}
}
}
}
deleteDomainApp.executeBatch();
} catch (SQLException domainAppsException) {
connection.rollback();
log.error("Failed to rollback removing domain applications for organization: " + organization, domainAppsException);
}
if (log.isDebugEnabled()) {
log.debug("Subscription Key mapping details are deleted successfully for Applications for " + "organization: " + organization);
}
try (PreparedStatement deleteApp = connection.prepareStatement(OrganizationPurgeConstants.REMOVE_APPLICATION_LIST_FROM_APPLICATIONS_SQL)) {
deleteApp.setString(1, organization);
deleteApp.execute();
} catch (SQLException appDeletionException) {
connection.rollback();
log.error("Failed to rollback removing applications for organization: " + organization, appDeletionException);
}
if (log.isDebugEnabled()) {
log.debug("Applications are deleted successfully for organization: " + organization);
}
connection.commit();
} catch (SQLException e) {
handleException("Error while removing application details from the database for organization: " + organization, e);
}
}
use of org.wso2.broker.amqp.Server in project carbon-apimgt by wso2.
the class ThrottleDataPublisher method publishNonThrottledEvent.
/**
* This method used to pass message context and let it run within separate thread.
*
* @param messageContext is message context object that holds
*/
public void publishNonThrottledEvent(String applicationLevelThrottleKey, String applicationLevelTier, String apiLevelThrottleKey, String apiLevelTier, String subscriptionLevelThrottleKey, String subscriptionLevelTier, String resourceLevelThrottleKey, String resourceLevelTier, String authorizedUser, String apiContext, String apiVersion, String appTenant, String apiTenant, String appId, MessageContext messageContext, AuthenticationContext authenticationContext) {
try {
if (dataPublisherPool != null) {
DataProcessAndPublishingAgent agent = dataPublisherPool.get();
agent.setDataReference(applicationLevelThrottleKey, applicationLevelTier, apiLevelThrottleKey, apiLevelTier, subscriptionLevelThrottleKey, subscriptionLevelTier, resourceLevelThrottleKey, resourceLevelTier, authorizedUser, apiContext, apiVersion, appTenant, apiTenant, appId, messageContext, authenticationContext);
if (log.isDebugEnabled()) {
log.debug("Publishing throttle data from gateway to traffic-manager for: " + apiContext + " with ID: " + messageContext.getMessageID() + " started" + " at " + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
}
executor.execute(agent);
if (log.isDebugEnabled()) {
log.debug("Publishing throttle data from gateway to traffic-manager for: " + apiContext + " with ID: " + messageContext.getMessageID() + " ended" + " at " + new SimpleDateFormat("[yyyy.MM.dd HH:mm:ss,SSS zzz]").format(new Date()));
}
} else {
log.debug("Throttle data publisher pool is not initialized.");
}
} catch (Exception e) {
log.error("Error while publishing throttling events to global policy server", e);
}
}
Aggregations