use of org.wso2.carbon.humantask.core.engine.commands.Complete in project carbon-apimgt by wso2.
the class SubscriberRegistrationInterceptor method handleMessage.
/**
* Handles the incoming message after post authentication. Only used in Store REST API, to register a newly
* signed up store user who hasn't logged in to Store for the first time either via REST API or Store UI.
* This method will register the user as a subscriber
* (register in AM_SUBSCRIBER table, add the default application for subscriber etc.).
*
* @param message cxf message
*/
@Override
@MethodStats
public void handleMessage(Message message) {
String username = RestApiCommonUtil.getLoggedInUsername();
// by-passes the interceptor if user is an annonymous user
if (username.equalsIgnoreCase(APIConstants.WSO2_ANONYMOUS_USER)) {
return;
}
// checking if the subscriber exists in the subscriber cache
Cache<String, Subscriber> subscriberCache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.API_SUBSCRIBER_CACHE);
if (subscriberCache.get(username) != null) {
return;
}
// check the existence in the database
String groupId = RestApiUtil.getLoggedInUserGroupId();
String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
try {
// takes a consumer object using the user set in thread local carbon context
APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
Subscriber subscriber = apiConsumer.getSubscriber(username);
if (subscriber == null) {
synchronized ((username + LOCK_POSTFIX).intern()) {
subscriber = apiConsumer.getSubscriber(username);
if (subscriber == null) {
message.getExchange().get(RestApiConstants.USER_REST_API_SCOPES);
if (!hasSubscribeScope(message)) {
// permission. It should be allowed.
if (logger.isDebugEnabled()) {
logger.debug("User " + username + " does not have subscribe scope " + "(" + APIM_SUBSCRIBE_SCOPE + ")");
}
return;
}
if (!APIConstants.SUPER_TENANT_DOMAIN.equalsIgnoreCase(tenantDomain)) {
loadTenantRegistry();
}
apiConsumer.addSubscriber(username, groupId);
// The subscriber object added here is not a complete subscriber object. It will only contain
// username
subscriberCache.put(username, new Subscriber(username));
if (logger.isDebugEnabled()) {
logger.debug("Subscriber " + username + " added to AM_SUBSCRIBER database");
}
}
}
} else {
subscriberCache.put(username, subscriber);
}
} catch (APIManagementException e) {
RestApiUtil.handleInternalServerError("Unable to add the subscriber " + username, e, logger);
}
}
use of org.wso2.carbon.humantask.core.engine.commands.Complete in project carbon-apimgt by wso2.
the class PolicyDAOImpl method getSubscriptionPolicyById.
/**
* Retrieves {@link SubscriptionPolicy} with policy uuid <code>uuid</code>
* <p>This will retrieve complete details about the ApplicationPolicy with all pipelins and conditions.</p>
*
* @param uuid uuid of the policy to retrieve from the database
* @return {@link SubscriptionPolicy}
*/
private SubscriptionPolicy getSubscriptionPolicyById(String uuid) throws SQLException, APIMgtDAOException {
final String query = "SELECT NAME, UUID, QUOTA_TYPE, TIME_UNIT, UNIT_TIME, QUOTA, QUOTA_UNIT, DESCRIPTION, " + "DISPLAY_NAME, CUSTOM_ATTRIBUTES, IS_DEPLOYED, RATE_LIMIT_COUNT, RATE_LIMIT_TIME_UNIT, " + "STOP_ON_QUOTA_REACH, BILLING_PLAN FROM AM_SUBSCRIPTION_POLICY WHERE UUID = ?";
try (Connection conn = DAOUtil.getConnection();
PreparedStatement statement = conn.prepareStatement(query)) {
statement.setString(1, uuid);
statement.execute();
try (ResultSet rs = statement.getResultSet()) {
if (rs.next()) {
return createSubscriptionPolicyFromResultSet(uuid, rs);
} else {
// not found
String msg = "Subscription Policy not found for id: " + uuid;
log.warn(msg);
throw new APIMgtDAOException(msg, ExceptionCodes.POLICY_NOT_FOUND);
}
}
}
}
use of org.wso2.carbon.humantask.core.engine.commands.Complete in project carbon-apimgt by wso2.
the class FileEncryptionUtilityTestCase method testEncryptFiles.
@Test(priority = 2, description = "Test complete flow of encrypting files")
public void testEncryptFiles() throws Exception {
FileEncryptionConfigurations config = new FileEncryptionConfigurations();
List<String> filesToEncrypt = new ArrayList<>();
filesToEncrypt.add(testFileToEncrypt);
config.setFilesToEncrypt(filesToEncrypt);
SecureVault secureVault = Mockito.mock(SecureVault.class);
FileEncryptionUtility fileEncryptionUtility = FileEncryptionUtility.getInstance();
fileEncryptionUtility.setConfig(config);
fileEncryptionUtility.setAesKeyFileLocation();
fileEncryptionUtility.setSecureVault(secureVault);
Answer nonEncryptedAesKey = invocation -> {
Object[] args = invocation.getArguments();
return args[0];
};
Mockito.when(secureVault.encrypt(Mockito.anyString().getBytes())).thenAnswer(nonEncryptedAesKey);
Mockito.when(secureVault.decrypt(Mockito.anyString().getBytes())).thenAnswer(nonEncryptedAesKey);
fileEncryptionUtility.createAndStoreAESKey();
fileEncryptionUtility.encryptFiles();
Assert.assertTrue(Files.notExists(Paths.get(originalFilePath)));
Assert.assertEquals(fileEncryptionUtility.readFromEncryptedFile(encryptedFilePath), someText);
}
use of org.wso2.carbon.humantask.core.engine.commands.Complete in project carbon-apimgt by wso2.
the class APIGatewayPublisherImpl method deleteAPI.
@Override
public void deleteAPI(API api) throws GatewayException {
// build the message to send
APIEvent apiDeleteEvent = new APIEvent(APIMgtConstants.GatewayEventTypes.API_DELETE);
apiDeleteEvent.setLabels(api.getLabels());
apiDeleteEvent.setApiSummary(toAPISummary(api));
publishToPublisherTopic(apiDeleteEvent);
if (log.isDebugEnabled()) {
log.debug("API : " + api.getName() + " deleted event has been successfully published to broker");
}
if (api.hasOwnGateway()) {
// Delete the Gateway - check how we can assume that we complete the deletion
try {
List<String> labels = api.getLabels();
if (labels != null && !labels.isEmpty()) {
removeContainerBasedGateway(labels.toArray()[0].toString(), api);
} else {
log.error("Could not delete container based gateways as labels could not find in the API.");
}
} catch (ContainerBasedGatewayException e) {
String msg = "Error while removing the container based gateway";
throw new GatewayException(msg, e, ExceptionCodes.CONTAINER_GATEWAY_REMOVAL_FAILED);
}
}
}
use of org.wso2.carbon.humantask.core.engine.commands.Complete in project carbon-apimgt by wso2.
the class APIStateChangeWorkflow method completeWorkflow.
@Override
public WorkflowResponse completeWorkflow(WorkflowExecutor workflowExecutor) throws APIManagementException {
WorkflowResponse response = workflowExecutor.complete(this);
setStatus(response.getWorkflowStatus());
if (WorkflowStatus.APPROVED == response.getWorkflowStatus()) {
if (log.isDebugEnabled()) {
log.debug("API state change workflow complete: Approved");
}
String invoker = getAttribute(APIMgtConstants.WorkflowConstants.ATTRIBUTE_API_LC_INVOKER);
String currentState = getAttribute(APIMgtConstants.WorkflowConstants.ATTRIBUTE_API_CUR_STATE);
String targetState = getAttribute(APIMgtConstants.WorkflowConstants.ATTRIBUTE_API_TARGET_STATE);
boolean hasOwnGateway = Boolean.valueOf(getAttribute(APIMgtConstants.WorkflowConstants.ATTRIBUTE_HAS_OWN_GATEWAY));
String label = getAttribute(APIMgtConstants.WorkflowConstants.ATTRIBUTE_API_AUTOGEN_LABEL);
if (hasOwnGateway) {
// (CREATED to DEPRECATED)
if ((currentState.equalsIgnoreCase(APIStatus.CREATED.getStatus()) || currentState.equalsIgnoreCase(APIStatus.MAINTENANCE.getStatus()) || currentState.equalsIgnoreCase(APIStatus.PROTOTYPED.getStatus())) && (targetState.equalsIgnoreCase(APIStatus.PUBLISHED.getStatus()) || targetState.equalsIgnoreCase(APIStatus.PROTOTYPED.getStatus()) || targetState.equalsIgnoreCase(APIStatus.DEPRECATED.getStatus()))) {
try {
// No need to auto-generate the label again As hasOwnGateway is true.
// create the gateway
API api = apiDAO.getAPI(getWorkflowReference());
apiGateway.createContainerBasedGateway(label, api);
} catch (ContainerBasedGatewayException e) {
// Revert already added labels
DedicatedGateway dedicatedGateway = new DedicatedGateway();
dedicatedGateway.setEnabled(false);
dedicatedGateway.setApiId(getWorkflowReference());
dedicatedGateway.setUpdatedBy(invoker);
List<String> labels = new ArrayList<>();
labels.add(labelDAO.getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_GATEWAY));
labels.add(labelDAO.getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_STORE));
apiDAO.updateDedicatedGateway(dedicatedGateway, labels);
throw new APIManagementException("Error while updating lifecycle state in Private Jet Mode", e, ExceptionCodes.DEDICATED_CONTAINER_GATEWAY_CREATION_FAILED);
}
}
}
String localTime = getAttribute(APIMgtConstants.WorkflowConstants.ATTRIBUTE_API_LAST_UPTIME);
LocalDateTime time = LocalDateTime.parse(localTime);
updateAPIStatusForWorkflowComplete(getWorkflowReference(), targetState, invoker, time);
// After publishing the state change to the Gateway, remove the gateway for following occasions.
if (hasOwnGateway) {
if ((currentState.equalsIgnoreCase(APIStatus.PUBLISHED.getStatus()) || currentState.equalsIgnoreCase(APIStatus.PROTOTYPED.getStatus()) || currentState.equalsIgnoreCase(APIStatus.DEPRECATED.getStatus())) && (targetState.equalsIgnoreCase(APIStatus.CREATED.getStatus()) || targetState.equalsIgnoreCase(APIStatus.MAINTENANCE.getStatus()) || targetState.equalsIgnoreCase(APIStatus.PROTOTYPED.getStatus())) || targetState.equalsIgnoreCase(APIStatus.RETIRED.getStatus())) {
// remove gateway
API api = apiDAO.getAPI(getWorkflowReference());
apiGateway.removeContainerBasedGateway(label, api);
}
}
} else if (WorkflowStatus.REJECTED == response.getWorkflowStatus()) {
if (log.isDebugEnabled()) {
log.debug("API state change workflow complete: Rejected");
}
apiDAO.updateAPIWorkflowStatus(getWorkflowReference(), APIMgtConstants.APILCWorkflowStatus.REJECTED);
}
updateWorkflowEntries(this);
return response;
}
Aggregations