Search in sources :

Example 6 with WorkflowStatus

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

the class SampleTestObjectCreator method createDefaultAPI.

public static API.APIBuilder createDefaultAPI() {
    Set<String> transport = new HashSet<>();
    transport.add(HTTP);
    transport.add(HTTPS);
    Set<String> tags = new HashSet<>();
    tags.add(TAG_CLIMATE);
    Set<Policy> policies = new HashSet<>();
    policies.add(goldSubscriptionPolicy);
    policies.add(silverSubscriptionPolicy);
    policies.add(bronzeSubscriptionPolicy);
    BusinessInformation businessInformation = new BusinessInformation();
    businessInformation.setBusinessOwner(NAME_BUSINESS_OWNER_1);
    businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_1);
    businessInformation.setTechnicalOwner(NAME_TECHNICAL_OWNER_1);
    businessInformation.setTechnicalOwnerEmail(EMAIL_TECHNICAL_OWNER_1);
    String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
    Set<String> visibleRoles = new HashSet<>();
    visibleRoles.add("testRple");
    List<String> labels = new ArrayList<>();
    labels.add("testLabel");
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setEnabled(true);
    corsConfiguration.setAllowMethods(Arrays.asList(APIMgtConstants.FunctionsConstants.GET, APIMgtConstants.FunctionsConstants.POST, APIMgtConstants.FunctionsConstants.DELETE));
    corsConfiguration.setAllowHeaders(Arrays.asList(ALLOWED_HEADER_AUTHORIZATION, ALLOWED_HEADER_CUSTOM));
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setAllowOrigins(Arrays.asList("*"));
    Map<String, Endpoint> endpointMap = new HashMap<>();
    endpointMap.put("TestEndpoint", createMockEndpoint());
    API.APIBuilder apiBuilder = new API.APIBuilder(ADMIN, "WeatherAPI", API_VERSION).id(UUID.randomUUID().toString()).context("weather").description("Get Weather Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).lifecycleInstanceId(UUID.randomUUID().toString()).endpoint(Collections.emptyMap()).wsdlUri("http://localhost:9443/echo?wsdl").isResponseCachingEnabled(false).cacheTimeout(60).isDefaultVersion(false).apiPolicy(unlimitedApiPolicy).transport(transport).tags(tags).policies(policies).visibility(API.Visibility.PUBLIC).visibleRoles(visibleRoles).businessInformation(businessInformation).corsConfiguration(corsConfiguration).createdTime(LocalDateTime.now()).createdBy(ADMIN).updatedBy(ADMIN).lastUpdatedTime(LocalDateTime.now()).apiPermission(permissionJson).uriTemplates(getMockUriTemplates()).apiDefinition(apiDefinition).workflowStatus(WORKFLOW_STATUS).labels(labels).endpoint(endpointMap);
    Map map = new HashMap();
    map.put(DEVELOPER_ROLE_ID, 6);
    map.put(ADMIN_ROLE_ID, 15);
    apiBuilder.permissionMap(map);
    return apiBuilder;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) API(org.wso2.carbon.apimgt.core.models.API) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 7 with WorkflowStatus

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

the class AbstractAPIManager method getAPIProductbyUUID.

/**
 * Get API Product by registry artifact id
 *
 * @param uuid                  Registry artifact id
 * @param requestedTenantDomain tenantDomain for the registry
 * @return API Product of the provided artifact id
 * @throws APIManagementException
 */
public APIProduct getAPIProductbyUUID(String uuid, String requestedTenantDomain) throws APIManagementException {
    try {
        Registry registry;
        if (requestedTenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(requestedTenantDomain)) {
            int id = getTenantManager().getTenantId(requestedTenantDomain);
            registry = getRegistryService().getGovernanceSystemRegistry(id);
        } else {
            if (this.tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(this.tenantDomain)) {
                // at this point, requested tenant = carbon.super but logged in user is anonymous or tenant
                registry = getRegistryService().getGovernanceSystemRegistry(MultitenantConstants.SUPER_TENANT_ID);
            } else {
                // both requested tenant and logged in user's tenant are carbon.super
                registry = this.registry;
            }
        }
        GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry, APIConstants.API_KEY);
        GenericArtifact apiProductArtifact = artifactManager.getGenericArtifact(uuid);
        if (apiProductArtifact != null) {
            APIProduct apiProduct = getApiProduct(registry, apiProductArtifact);
            WorkflowDTO workflowDTO = APIUtil.getAPIWorkflowStatus(apiProduct.getUuid(), WF_TYPE_AM_API_PRODUCT_STATE);
            if (workflowDTO != null) {
                WorkflowStatus status = workflowDTO.getStatus();
                apiProduct.setWorkflowStatus(status.toString());
            }
            return apiProduct;
        } else {
            String msg = "Failed to get API Product. API Product artifact corresponding to artifactId " + uuid + " does not exist";
            throw new APIMgtResourceNotFoundException(msg);
        }
    } catch (RegistryException e) {
        String msg = "Failed to get API Product";
        throw new APIManagementException(msg, e);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String msg = "Failed to get API Product";
        throw new APIManagementException(msg, e);
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException)

Example 8 with WorkflowStatus

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

the class AbstractAPIManager method populateAPIProductInformation.

protected void populateAPIProductInformation(String uuid, String organization, APIProduct apiProduct) throws APIManagementException, OASPersistenceException, ParseException {
    Organization org = new Organization(organization);
    apiProduct.setOrganization(organization);
    ApiMgtDAO.getInstance().setAPIProductFromDB(apiProduct);
    apiProduct.setRating(Float.toString(APIUtil.getAverageRating(apiProduct.getProductId())));
    List<APIProductResource> resources = ApiMgtDAO.getInstance().getAPIProductResourceMappings(apiProduct.getId());
    Map<String, Scope> uniqueAPIProductScopeKeyMappings = new LinkedHashMap<>();
    for (APIProductResource resource : resources) {
        List<Scope> resourceScopes = resource.getUriTemplate().retrieveAllScopes();
        ListIterator it = resourceScopes.listIterator();
        while (it.hasNext()) {
            Scope resourceScope = (Scope) it.next();
            String scopeKey = resourceScope.getKey();
            if (!uniqueAPIProductScopeKeyMappings.containsKey(scopeKey)) {
                resourceScope = APIUtil.getScopeByName(scopeKey, organization);
                uniqueAPIProductScopeKeyMappings.put(scopeKey, resourceScope);
            } else {
                resourceScope = uniqueAPIProductScopeKeyMappings.get(scopeKey);
            }
            it.set(resourceScope);
        }
    }
    for (APIProductResource resource : resources) {
        String resourceAPIUUID = resource.getApiIdentifier().getUUID();
        resource.setApiId(resourceAPIUUID);
        try {
            PublisherAPI publisherAPI = apiPersistenceInstance.getPublisherAPI(org, resourceAPIUUID);
            API api = APIMapper.INSTANCE.toApi(publisherAPI);
            if (api.isAdvertiseOnly()) {
                resource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
            } else {
                resource.setEndpointConfig(api.getEndpointConfig());
            }
            resource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
        } catch (APIPersistenceException e) {
            throw new APIManagementException("Error while retrieving the api for api product " + e);
        }
    }
    apiProduct.setProductResources(resources);
    // UUID
    if (apiProduct.getUuid() == null) {
        apiProduct.setUuid(uuid);
    }
    // environment
    String environmentString = null;
    if (apiProduct.getEnvironments() != null) {
        environmentString = String.join(",", apiProduct.getEnvironments());
    }
    apiProduct.setEnvironments(APIUtil.extractEnvironmentsForAPI(environmentString, organization));
    // workflow status
    APIProductIdentifier productIdentifier = apiProduct.getId();
    WorkflowDTO workflow;
    String currentApiProductUuid = uuid;
    if (apiProduct.isRevision() && apiProduct.getRevisionedApiProductId() != null) {
        currentApiProductUuid = apiProduct.getRevisionedApiProductId();
    }
    workflow = APIUtil.getAPIWorkflowStatus(currentApiProductUuid, WF_TYPE_AM_API_PRODUCT_STATE);
    if (workflow != null) {
        WorkflowStatus status = workflow.getStatus();
        apiProduct.setWorkflowStatus(status.toString());
    }
    // available tier
    String tiers = null;
    Set<Tier> tiersSet = apiProduct.getAvailableTiers();
    Set<String> tierNameSet = new HashSet<String>();
    for (Tier t : tiersSet) {
        tierNameSet.add(t.getName());
    }
    if (apiProduct.getAvailableTiers() != null) {
        tiers = String.join("||", tierNameSet);
    }
    Map<String, Tier> definedTiers = APIUtil.getTiers(tenantId);
    Set<Tier> availableTier = APIUtil.getAvailableTiers(definedTiers, tiers, apiProduct.getId().getName());
    apiProduct.setAvailableTiers(availableTier);
    // Scopes
    /*
        Map<String, Scope> scopeToKeyMapping = APIUtil.getAPIScopes(api.getId(), requestedTenantDomain);
        apiProduct.setScopes(new LinkedHashSet<>(scopeToKeyMapping.values()));
        */
    // templates
    String resourceConfigsString = null;
    if (apiProduct.getDefinition() != null) {
        resourceConfigsString = apiProduct.getDefinition();
    } else {
        resourceConfigsString = apiPersistenceInstance.getOASDefinition(org, uuid);
        apiProduct.setDefinition(resourceConfigsString);
    }
    // CORS . if null is returned, set default config from the configuration
    if (apiProduct.getCorsConfiguration() == null) {
        apiProduct.setCorsConfiguration(APIUtil.getDefaultCorsConfiguration());
    }
    // set category
    List<APICategory> categories = apiProduct.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;
                    }
                }
            }
        }
        apiProduct.setApiCategories(categoryList);
    }
}
Also used : WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Tier(org.wso2.carbon.apimgt.api.model.Tier) ListIterator(java.util.ListIterator) WorkflowStatus(org.wso2.carbon.apimgt.impl.workflow.WorkflowStatus) Scope(org.wso2.carbon.apimgt.api.model.Scope) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) APICategory(org.wso2.carbon.apimgt.api.model.APICategory)

Example 9 with WorkflowStatus

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

the class ApiMgtDAO method getworkflowReferenceByExternalWorkflowReferenceID.

/**
 * Get the Pending workflow Request using ExternalWorkflowReference for a particular tenant
 *
 * @param externelWorkflowRef of pending workflow request
 * @param status              workflow status of workflow pending process
 * @param tenantDomain        tenant domain of user
 * @return workflow pending request
 */
public Workflow getworkflowReferenceByExternalWorkflowReferenceID(String externelWorkflowRef, String status, String tenantDomain) throws APIManagementException {
    ResultSet rs = null;
    Workflow workflow = new Workflow();
    String sqlQuery = SQLConstants.GET_ALL_WORKFLOW_DETAILS_BY_EXTERNAL_WORKFLOW_REFERENCE;
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement prepStmt = connection.prepareStatement(sqlQuery)) {
        try {
            prepStmt.setString(1, externelWorkflowRef);
            prepStmt.setString(2, status);
            prepStmt.setString(3, tenantDomain);
            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.setWorkflowDescription(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 targetStream = rs.getBinaryStream("WF_METADATA");
                InputStream propertiesTargetStream = rs.getBinaryStream("WF_PROPERTIES");
                if (targetStream != null) {
                    String metadata = APIMgtDBUtil.getStringFromInputStream(targetStream);
                    Gson metadataGson = new Gson();
                    JSONObject metadataJson = metadataGson.fromJson(metadata, JSONObject.class);
                    workflow.setMetadata(metadataJson);
                } else {
                    JSONObject metadataJson = new JSONObject();
                    workflow.setMetadata(metadataJson);
                }
                if (propertiesTargetStream != null) {
                    String properties = APIMgtDBUtil.getStringFromInputStream(propertiesTargetStream);
                    Gson propertiesGson = new Gson();
                    JSONObject propertiesJson = propertiesGson.fromJson(properties, JSONObject.class);
                    workflow.setProperties(propertiesJson);
                } else {
                    JSONObject propertiesJson = new JSONObject();
                    workflow.setProperties(propertiesJson);
                }
            }
        } 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 10 with WorkflowStatus

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

the class SampleTestObjectCreator method createDefaultAPI.

public static API.APIBuilder createDefaultAPI() {
    Set<String> transport = new HashSet<>();
    transport.add(HTTP);
    transport.add(HTTPS);
    Set<String> tags = new HashSet<>();
    tags.add(TAG_CLIMATE);
    Set<Policy> policies = new HashSet<>();
    policies.add(goldSubscriptionPolicy);
    policies.add(silverSubscriptionPolicy);
    policies.add(bronzeSubscriptionPolicy);
    BusinessInformation businessInformation = new BusinessInformation();
    businessInformation.setBusinessOwner(NAME_BUSINESS_OWNER_1);
    businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_1);
    businessInformation.setTechnicalOwner(NAME_TECHNICAL_OWNER_1);
    businessInformation.setTechnicalOwnerEmail(EMAIL_TECHNICAL_OWNER_1);
    String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
    Set<String> visibleRoles = new HashSet<>();
    visibleRoles.add("testRple");
    List<String> labels = new ArrayList<>();
    labels.add("testLabel");
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setEnabled(true);
    corsConfiguration.setAllowMethods(Arrays.asList(APIMgtConstants.FunctionsConstants.GET, APIMgtConstants.FunctionsConstants.POST, APIMgtConstants.FunctionsConstants.DELETE));
    corsConfiguration.setAllowHeaders(Arrays.asList(ALLOWED_HEADER_AUTHORIZATION, ALLOWED_HEADER_CUSTOM));
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setAllowOrigins(Arrays.asList("*"));
    Map<String, Endpoint> endpointMap = new HashMap<>();
    endpointMap.put("TestEndpoint", createMockEndpoint());
    API.APIBuilder apiBuilder = new API.APIBuilder(ADMIN, "WeatherAPI", API_VERSION).id(UUID.randomUUID().toString()).context("weather").description("Get Weather Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).lifecycleInstanceId(UUID.randomUUID().toString()).endpoint(Collections.emptyMap()).wsdlUri("http://localhost:9443/echo?wsdl").isResponseCachingEnabled(false).cacheTimeout(60).isDefaultVersion(false).apiPolicy(unlimitedApiPolicy).transport(transport).tags(tags).policies(policies).visibility(API.Visibility.PUBLIC).visibleRoles(visibleRoles).businessInformation(businessInformation).corsConfiguration(corsConfiguration).createdTime(LocalDateTime.now()).createdBy(ADMIN).updatedBy(ADMIN).lastUpdatedTime(LocalDateTime.now()).apiPermission(permissionJson).uriTemplates(getMockUriTemplates()).apiDefinition(apiDefinition).workflowStatus(WORKFLOW_STATUS).labels(labels).endpoint(endpointMap);
    Map map = new HashMap();
    map.put(DEVELOPER_ROLE_ID, 6);
    map.put(ADMIN_ROLE_ID, 15);
    apiBuilder.permissionMap(map);
    return apiBuilder;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) QuotaPolicy(org.wso2.carbon.apimgt.core.models.policy.QuotaPolicy) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

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