Search in sources :

Example 11 with WorkflowStatus

use of org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus in project carbon-apimgt by wso2.

the class APIPublisherImplTestCase method testUpdateAPIWorkflowStatus.

@Test(description = "Update API Status when its workflow status is pending", expectedExceptions = APIManagementException.class)
public void testUpdateAPIWorkflowStatus() throws APIManagementException, LifecycleException {
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    WorkflowDAO workflowDAO = Mockito.mock(WorkflowDAO.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    APIGateway gateway = Mockito.mock(APIGateway.class);
    APIPublisherImpl apiPublisher = getApiPublisherImpl(apiLifecycleManager, apiDAO, workflowDAO, gateway);
    API api = SampleTestObjectCreator.createDefaultAPI().workflowStatus(APIMgtConstants.APILCWorkflowStatus.PENDING.toString()).build();
    String uuid = api.getId();
    String lcState = api.getLifeCycleStatus();
    String lifecycleId = api.getLifecycleInstanceId();
    Mockito.when(apiDAO.getAPI(uuid)).thenReturn(api);
    LifecycleState lifecycleState = SampleTestObjectCreator.getMockLifecycleStateObject(lifecycleId);
    Mockito.when(apiLifecycleManager.getLifecycleDataForState(lifecycleId, lcState)).thenReturn(lifecycleState);
    Mockito.when(apiLifecycleManager.executeLifecycleEvent(APIStatus.CREATED.getStatus(), APIStatus.PUBLISHED.getStatus(), lifecycleId, USER, api)).thenReturn(lifecycleState);
    API.APIBuilder apiBuilder = new API.APIBuilder(api);
    apiBuilder.lifecycleState(lifecycleState);
    apiBuilder.updatedBy(USER);
    api = apiBuilder.build();
    lifecycleState.setState(APIStatus.PUBLISHED.getStatus());
    apiPublisher.updateAPIStatus(uuid, APIStatus.PUBLISHED.getStatus(), new HashMap<>());
    Mockito.verify(apiLifecycleManager, Mockito.times(1)).executeLifecycleEvent(APIStatus.CREATED.getStatus(), APIStatus.PUBLISHED.getStatus(), lifecycleId, USER, api);
}
Also used : WorkflowDAO(org.wso2.carbon.apimgt.core.dao.WorkflowDAO) APILifecycleManager(org.wso2.carbon.apimgt.core.api.APILifecycleManager) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) API(org.wso2.carbon.apimgt.core.models.API) LifecycleState(org.wso2.carbon.lcm.core.impl.LifecycleState) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) Test(org.testng.annotations.Test)

Example 12 with WorkflowStatus

use of org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus in project carbon-apimgt by wso2.

the class ApiDAOImpl method getCompositeAPISummaryList.

private List<CompositeAPI> getCompositeAPISummaryList(Connection connection, PreparedStatement statement) throws SQLException, APIMgtDAOException {
    List<CompositeAPI> apiList = new ArrayList<>();
    try (ResultSet rs = statement.executeQuery()) {
        while (rs.next()) {
            String apiPrimaryKey = rs.getString("UUID");
            CompositeAPI apiSummary = new CompositeAPI.Builder().id(apiPrimaryKey).provider(rs.getString("PROVIDER")).name(rs.getString("NAME")).version(rs.getString("VERSION")).context(rs.getString("CONTEXT")).description(rs.getString("DESCRIPTION")).applicationId(getCompositeAPIApplicationId(connection, apiPrimaryKey)).workflowStatus(rs.getString("LC_WORKFLOW_STATUS")).threatProtectionPolicies(getThreatProtectionPolicies(connection, apiPrimaryKey)).build();
            apiList.add(apiSummary);
        }
    }
    return apiList;
}
Also used : ArrayList(java.util.ArrayList) ResultSet(java.sql.ResultSet) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI)

Example 13 with WorkflowStatus

use of org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus in project carbon-apimgt by wso2.

the class AbstractAPIManager method populateAPIInformation.

protected void populateAPIInformation(String uuid, String organization, API api) throws APIManagementException, OASPersistenceException, ParseException, AsyncSpecPersistenceException {
    Organization org = new Organization(organization);
    // UUID
    if (api.getUuid() == null) {
        api.setUuid(uuid);
    }
    api.setOrganization(organization);
    // environment
    String environmentString = null;
    if (api.getEnvironments() != null) {
        environmentString = String.join(",", api.getEnvironments());
    }
    api.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIIdentifier apiId = api.getId();
    WorkflowDTO workflow;
    String currentApiUuid = uuid;
    if (api.isRevision() && api.getRevisionedApiId() != null) {
        currentApiUuid = api.getRevisionedApiId();
    }
    workflow = APIUtil.getAPIWorkflowStatus(currentApiUuid, WF_TYPE_AM_API_STATE);
    if (workflow != null) {
        WorkflowStatus status = workflow.getStatus();
        api.setWorkflowStatus(status.toString());
    }
    // TODO try to use a single query to get info from db
    int internalId = apiMgtDAO.getAPIID(currentApiUuid);
    apiId.setId(internalId);
    apiMgtDAO.setServiceStatusInfoToAPI(api, internalId);
    // api level tier
    String apiLevelTier;
    if (api.isRevision()) {
        apiLevelTier = apiMgtDAO.getAPILevelTier(api.getRevisionedApiId(), api.getUuid());
    } else {
        apiLevelTier = apiMgtDAO.getAPILevelTier(internalId);
    }
    api.setApiLevelPolicy(apiLevelTier);
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = api.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (api.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(APIUtil.getInternalOrganizationId(organization));
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, api.getId().getApiName());
    api.setAvailableTiers(availableTier);
    // Scopes
    Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(currentApiUuid, organization);
    api.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
    // templates
    String resourceConfigsString;
    if (api.getSwaggerDefinition() != null) {
        resourceConfigsString = api.getSwaggerDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
    }
    api.setSwaggerDefinition(resourceConfigsString);
    if (resourceConfigsString == null) {
        if (api.getAsyncApiDefinition() != null) {
            resourceConfigsString = api.getAsyncApiDefinition();
        } else {
            resourceConfigsString = apiPersistenceInstance.getAsyncDefinition(org, uuid);
        }
        api.setAsyncApiDefinition(resourceConfigsString);
    }
    if (api.getType() != null && APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
        api.setGraphQLSchema(getGraphqlSchemaDefinition(uuid, organization));
    }
    JSONParser jsonParser = new JSONParser();
    JSONObject paths = null;
    if (resourceConfigsString != null) {
        JSONObject resourceConfigsJSON = (JSONObject) jsonParser.parse(resourceConfigsString);
        paths = (JSONObject) resourceConfigsJSON.get(APIConstants.SWAGGER_PATHS);
    }
    Set<URITemplate> uriTemplates = apiMgtDAO.getURITemplatesOfAPI(api.getUuid());
    for (URITemplate uriTemplate : uriTemplates) {
        String uTemplate = uriTemplate.getUriTemplate();
        String method = uriTemplate.getHTTPVerb();
        List<Scope> oldTemplateScopes = uriTemplate.retrieveAllScopes();
        List<Scope> newTemplateScopes = new ArrayList<>();
        if (!oldTemplateScopes.isEmpty()) {
            for (Scope templateScope : oldTemplateScopes) {
                Scope scope = scopeToKeyMapping.get(templateScope.getKey());
                newTemplateScopes.add(scope);
            }
        }
        uriTemplate.addAllScopes(newTemplateScopes);
        uriTemplate.setResourceURI(api.getUrl());
        uriTemplate.setResourceSandboxURI(api.getSandboxUrl());
        // AWS Lambda: set arn & timeout to URI template
        if (paths != null) {
            JSONObject path = (JSONObject) paths.get(uTemplate);
            if (path != null) {
                JSONObject operation = (JSONObject) path.get(method.toLowerCase());
                if (operation != null) {
                    if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME)) {
                        uriTemplate.setAmznResourceName((String) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_NAME));
                    }
                    if (operation.containsKey(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)) {
                        uriTemplate.setAmznResourceTimeout(((Long) operation.get(APIConstants.SWAGGER_X_AMZN_RESOURCE_TIMEOUT)).intValue());
                    }
                }
            }
        }
    }
    if (APIConstants.IMPLEMENTATION_TYPE_INLINE.equalsIgnoreCase(api.getImplementation())) {
        for (URITemplate template : uriTemplates) {
            template.setMediationScript(template.getAggregatedMediationScript());
        }
    }
    api.setUriTemplates(uriTemplates);
    // CORS . if null is returned, set default config from the configuration
    if (api.getCorsConfiguration() == null) {
        api.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = api.getApiCategories();
    if (categories != null) {
        List<String> categoriesOfAPI = new ArrayList<String>();
        for (APICategory apiCategory : categories) {
            categoriesOfAPI.add(apiCategory.getName());
        }
        List<APICategory> categoryList = new ArrayList<>();
        if (!categoriesOfAPI.isEmpty()) {
            // category array retrieved from artifact has only the category name, therefore we need to fetch
            // categories
            // and fill out missing attributes before attaching the list to the api
            List<APICategory> allCategories = APIUtil.getAllAPICategoriesOfOrganization(organization);
            // todo-category: optimize this loop with breaks
            for (String categoryName : categoriesOfAPI) {
                for (APICategory category : allCategories) {
                    if (categoryName.equals(category.getName())) {
                        categoryList.add(category);
                        break;
                    }
                }
            }
        }
        api.setApiCategories(categoryList);
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Tier(org.wso2.carbon.apimgt.api.model.Tier) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) ArrayList(java.util.ArrayList) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus) Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) APICategory(org.wso2.carbon.apimgt.api.model.APICategory) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 14 with WorkflowStatus

use of org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus in project carbon-apimgt by wso2.

the class ApiMgtDAO method getworkflowReferenceByExternalWorkflowReference.

/**
 * Get the Pending workflow Request using ExternalWorkflowReference
 *
 * @param externalWorkflowRef
 * @return workflow pending request
 * @throws APIManagementException
 */
public Workflow getworkflowReferenceByExternalWorkflowReference(String externalWorkflowRef) throws APIManagementException {
    ResultSet rs = null;
    Workflow workflow = new Workflow();
    String sqlQuery = SQLConstants.GET_ALL_WORKFLOW_DETAILS_BY_EXTERNALWORKFLOWREF;
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement prepStmt = connection.prepareStatement(sqlQuery)) {
        try {
            prepStmt.setString(1, externalWorkflowRef);
            rs = prepStmt.executeQuery();
            while (rs.next()) {
                workflow.setWorkflowId(rs.getInt("WF_ID"));
                workflow.setWorkflowReference(rs.getString("WF_REFERENCE"));
                workflow.setWorkflowType(rs.getString("WF_TYPE"));
                String workflowstatus = rs.getString("WF_STATUS");
                workflow.setStatus(org.wso2.carbon.apimgt.api.WorkflowStatus.valueOf(workflowstatus));
                workflow.setCreatedTime(rs.getTimestamp("WF_CREATED_TIME").toString());
                workflow.setUpdatedTime(rs.getTimestamp("WF_UPDATED_TIME").toString());
                workflow.setWorkflowStatusDesc(rs.getString("WF_STATUS_DESC"));
                workflow.setTenantId(rs.getInt("TENANT_ID"));
                workflow.setTenantDomain(rs.getString("TENANT_DOMAIN"));
                workflow.setExternalWorkflowReference(rs.getString("WF_EXTERNAL_REFERENCE"));
                InputStream metadatablob = rs.getBinaryStream("WF_METADATA");
                byte[] metadataByte;
                if (metadatablob != null) {
                    String metadata = APIMgtDBUtil.getStringFromInputStream(metadatablob);
                    Gson metadataGson = new Gson();
                    JSONObject metadataJson = metadataGson.fromJson(metadata, JSONObject.class);
                    workflow.setMetadata(metadataJson);
                } else {
                    JSONObject metadataJson = new JSONObject();
                    workflow.setMetadata(metadataJson);
                }
            }
        } catch (SQLException e) {
            handleException("Error when retriving the workflow details. ", e);
        } finally {
            APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
        }
    } catch (SQLException e) {
        handleException("Error when retriving the workflow details. ", e);
    }
    return workflow;
}
Also used : JSONObject(org.json.simple.JSONObject) SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ResultSet(java.sql.ResultSet) Connection(java.sql.Connection) Workflow(org.wso2.carbon.apimgt.api.model.Workflow) Gson(com.google.gson.Gson) PreparedStatement(java.sql.PreparedStatement)

Example 15 with WorkflowStatus

use of org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus in project carbon-apimgt by wso2.

the class ApiMgtDAO method getworkflows.

/**
 * Get the Pending workflow Requests using WorkflowType for a particular tenant
 *
 * @param workflowType Type of the workflow pending request
 * @param status       workflow status of workflow pending request
 * @param tenantDomain tenantDomain of the user
 * @return List of workflow pending request
 * @throws APIManagementException
 */
public Workflow[] getworkflows(String workflowType, String status, String tenantDomain) throws APIManagementException {
    ResultSet rs = null;
    Workflow[] workflows = null;
    String sqlQuery;
    if (workflowType != null) {
        sqlQuery = SQLConstants.GET_ALL_WORKFLOW_DETAILS_BY_WORKFLOW_TYPE;
    } else {
        sqlQuery = SQLConstants.GET_ALL_WORKFLOW_DETAILS;
    }
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement prepStmt = connection.prepareStatement(sqlQuery)) {
        try {
            if (workflowType != null) {
                prepStmt.setString(1, workflowType);
                prepStmt.setString(2, status);
                prepStmt.setString(3, tenantDomain);
            } else {
                prepStmt.setString(1, status);
                prepStmt.setString(2, tenantDomain);
            }
            rs = prepStmt.executeQuery();
            ArrayList<Workflow> workflowsList = new ArrayList<Workflow>();
            Workflow workflow;
            while (rs.next()) {
                workflow = new Workflow();
                workflow.setWorkflowId(rs.getInt("WF_ID"));
                workflow.setWorkflowReference(rs.getString("WF_REFERENCE"));
                workflow.setWorkflowType(rs.getString("WF_TYPE"));
                String workflowstatus = rs.getString("WF_STATUS");
                workflow.setStatus(org.wso2.carbon.apimgt.api.WorkflowStatus.valueOf(workflowstatus));
                workflow.setCreatedTime(rs.getTimestamp("WF_CREATED_TIME").toString());
                workflow.setUpdatedTime(rs.getTimestamp("WF_UPDATED_TIME").toString());
                workflow.setWorkflowStatusDesc(rs.getString("WF_STATUS_DESC"));
                workflow.setTenantId(rs.getInt("TENANT_ID"));
                workflow.setTenantDomain(rs.getString("TENANT_DOMAIN"));
                workflow.setExternalWorkflowReference(rs.getString("WF_EXTERNAL_REFERENCE"));
                workflow.setWorkflowDescription(rs.getString("WF_STATUS_DESC"));
                InputStream metadataBlob = rs.getBinaryStream("WF_METADATA");
                InputStream propertiesBlob = rs.getBinaryStream("WF_PROPERTIES");
                if (metadataBlob != null) {
                    String metadata = APIMgtDBUtil.getStringFromInputStream(metadataBlob);
                    Gson metadataGson = new Gson();
                    JSONObject metadataJson = metadataGson.fromJson(metadata, JSONObject.class);
                    workflow.setMetadata(metadataJson);
                } else {
                    JSONObject metadataJson = new JSONObject();
                    workflow.setMetadata(metadataJson);
                }
                if (propertiesBlob != null) {
                    String properties = APIMgtDBUtil.getStringFromInputStream(propertiesBlob);
                    Gson propertiesGson = new Gson();
                    JSONObject propertiesJson = propertiesGson.fromJson(properties, JSONObject.class);
                    workflow.setProperties(propertiesJson);
                } else {
                    JSONObject propertiesJson = new JSONObject();
                    workflow.setProperties(propertiesJson);
                }
                workflowsList.add(workflow);
            }
            workflows = workflowsList.toArray(new Workflow[workflowsList.size()]);
        } catch (SQLException e) {
            handleException("Error when retrieve all the workflow details. ", e);
        } finally {
            APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
        }
    } catch (SQLException e) {
        handleException("Error when retrieve all the workflow details. ", e);
    }
    return workflows;
}
Also used : JSONObject(org.json.simple.JSONObject) SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ResultSet(java.sql.ResultSet) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) Workflow(org.wso2.carbon.apimgt.api.model.Workflow) Gson(com.google.gson.Gson) PreparedStatement(java.sql.PreparedStatement)

Aggregations

ArrayList (java.util.ArrayList)9 ResultSet (java.sql.ResultSet)6 API (org.wso2.carbon.apimgt.core.models.API)6 WorkflowDTO (org.wso2.carbon.apimgt.impl.dto.WorkflowDTO)6 WorkflowStatus (org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus)6 HashSet (java.util.HashSet)5 JSONObject (org.json.simple.JSONObject)5 Connection (java.sql.Connection)4 PreparedStatement (java.sql.PreparedStatement)4 SQLException (java.sql.SQLException)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)4 Gson (com.google.gson.Gson)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 InputStream (java.io.InputStream)3 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)3 API (org.wso2.carbon.apimgt.api.model.API)3 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)3 Workflow (org.wso2.carbon.apimgt.api.model.Workflow)3