Search in sources :

Example 26 with Complete

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);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Example 27 with Complete

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);
            }
        }
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 28 with Complete

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);
}
Also used : AfterClass(org.testng.annotations.AfterClass) Files(java.nio.file.Files) BeforeClass(org.testng.annotations.BeforeClass) Test(org.testng.annotations.Test) File(java.io.File) APIFileUtils(org.wso2.carbon.apimgt.core.util.APIFileUtils) ArrayList(java.util.ArrayList) Mockito(org.mockito.Mockito) Answer(org.mockito.stubbing.Answer) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) List(java.util.List) Assert(org.testng.Assert) Paths(java.nio.file.Paths) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SecureVault(org.wso2.carbon.secvault.SecureVault) FileEncryptionConfigurations(org.wso2.carbon.apimgt.core.configuration.models.FileEncryptionConfigurations) FileEncryptionConfigurations(org.wso2.carbon.apimgt.core.configuration.models.FileEncryptionConfigurations) Answer(org.mockito.stubbing.Answer) SecureVault(org.wso2.carbon.secvault.SecureVault) ArrayList(java.util.ArrayList) Test(org.testng.annotations.Test)

Example 29 with Complete

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);
        }
    }
}
Also used : APIEvent(org.wso2.carbon.apimgt.core.models.events.APIEvent) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) ContainerBasedGatewayException(org.wso2.carbon.apimgt.core.exception.ContainerBasedGatewayException) ContainerBasedGatewayException(org.wso2.carbon.apimgt.core.exception.ContainerBasedGatewayException)

Example 30 with Complete

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;
}
Also used : LocalDateTime(java.time.LocalDateTime) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) ContainerBasedGatewayException(org.wso2.carbon.apimgt.core.exception.ContainerBasedGatewayException) API(org.wso2.carbon.apimgt.core.models.API) ArrayList(java.util.ArrayList) List(java.util.List) DedicatedGateway(org.wso2.carbon.apimgt.core.models.DedicatedGateway)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)23 ApiMgtDAO (org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO)14 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)9 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 Test (org.junit.Test)5 UserRegistrationConfigDTO (org.wso2.carbon.apimgt.impl.dto.UserRegistrationConfigDTO)5 List (java.util.List)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 WorkflowResponse (org.wso2.carbon.apimgt.api.WorkflowResponse)4 Connection (java.sql.Connection)3 PreparedStatement (java.sql.PreparedStatement)3 ResultSet (java.sql.ResultSet)3 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)3 ApplicationRegistrationWorkflowDTO (org.wso2.carbon.apimgt.impl.dto.ApplicationRegistrationWorkflowDTO)3 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)3 IOException (java.io.IOException)2 SQLException (java.sql.SQLException)2 RepositoryService (org.activiti.engine.RepositoryService)2 Element (org.w3c.dom.Element)2