Search in sources :

Example 96 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method setOAuthApplicationInfo.

/**
 * set information that are needed to invoke callback service
 */
private void setOAuthApplicationInfo(APIStateWorkflowDTO apiStateWorkFlowDTO) throws WorkflowException {
    // if credentials are not defined in the workflow-extension.xml file call dcr endpoint and generate a
    // oauth application and pass the client id and secret
    WorkflowProperties workflowProperties = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
    if (clientId == null || clientSecret == null) {
        String dcrUsername = workflowProperties.getdCREndpointUser();
        String dcrPassword = workflowProperties.getdCREndpointPassword();
        byte[] encodedAuth = Base64.encodeBase64((dcrUsername + ":" + dcrPassword).getBytes(Charset.forName("ISO-8859-1")));
        JSONObject payload = new JSONObject();
        payload.put(PayloadConstants.KEY_OAUTH_APPNAME, WorkflowConstants.WORKFLOW_OAUTH_APP_NAME);
        payload.put(PayloadConstants.KEY_OAUTH_OWNER, dcrUsername);
        payload.put(PayloadConstants.KEY_OAUTH_SAASAPP, "true");
        payload.put(PayloadConstants.KEY_OAUTH_GRANT_TYPES, WorkflowConstants.WORKFLOW_OAUTH_APP_GRANT_TYPES);
        URL serviceEndpointURL = new URL(workflowProperties.getdCREndPoint());
        HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
        HttpPost httpPost = new HttpPost(workflowProperties.getdCREndPoint());
        String authHeader = "Basic " + new String(encodedAuth);
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        StringEntity requestEntity = new StringEntity(payload.toJSONString(), ContentType.APPLICATION_JSON);
        httpPost.setEntity(requestEntity);
        try {
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                String responseStr = EntityUtils.toString(entity);
                if (log.isDebugEnabled()) {
                    log.debug("Workflow oauth app created: " + responseStr);
                }
                JSONParser parser = new JSONParser();
                JSONObject obj = (JSONObject) parser.parse(responseStr);
                clientId = (String) obj.get(PayloadConstants.VARIABLE_CLIENTID);
                clientSecret = (String) obj.get(PayloadConstants.VARIABLE_CLIENTSECRET);
            } else {
                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 dcr endpoint";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } catch (ParseException e) {
            String errorMsg = "Error while parsing response from DCR endpoint";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } finally {
            httpPost.reset();
        }
    }
    apiStateWorkFlowDTO.setClientId(clientId);
    apiStateWorkFlowDTO.setClientSecret(clientSecret);
    apiStateWorkFlowDTO.setScope(WorkflowConstants.API_WF_SCOPE);
    apiStateWorkFlowDTO.setTokenAPI(workflowProperties.getTokenEndPoint());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) URL(org.apache.axis2.util.URL) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.simple.JSONObject) HttpClient(org.apache.http.client.HttpClient) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 97 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method cleanUpPendingTask.

/**
 * Handle cleanup task for api state change workflow ws executor. This queries the BPMN process related to the given
 * workflow reference id and delete that process
 */
@Override
public void cleanUpPendingTask(String workflowExtRef) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Starting cleanup task for APIStateChangeWSWorkflowExecutor for :" + workflowExtRef);
    }
    String errorMsg;
    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());
    // get the basic auth header value to connect to the bpmn process
    String authHeader = getBasicAuthHeader();
    JSONParser parser = new JSONParser();
    HttpGet httpGet = null;
    HttpDelete httpDelete = null;
    try {
        // Get the process instance details related to the given workflow reference id. If there is a process that
        // is already started with the given wf reference as the businesskey, that process needes to be deleted
        httpGet = new HttpGet(serviceEndpoint + RUNTIME_INSTANCE_RESOURCE_PATH + "?businessKey=" + workflowExtRef);
        httpGet.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String processId = null;
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // already exists a process related to the given workflow reference
            String responseStr = EntityUtils.toString(entity);
            if (log.isDebugEnabled()) {
                log.debug("Process instance details for ref : " + workflowExtRef + ": " + responseStr);
            }
            JSONObject obj = (JSONObject) parser.parse(responseStr);
            JSONArray data = (JSONArray) obj.get(PayloadConstants.DATA);
            if (data != null) {
                JSONObject instanceDetails = (JSONObject) data.get(0);
                // extract the id related to that process. this id is used to delete the process
                processId = (String) instanceDetails.get(PayloadConstants.ID);
            }
            if (processId != null) {
                // delete the process using the id
                httpDelete = new HttpDelete(serviceEndpoint + RUNTIME_INSTANCE_RESOURCE_PATH + "/" + processId);
                httpDelete.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
                response = httpClient.execute(httpDelete);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_NO_CONTENT) {
                    errorMsg = "Error while deleting process instance details for " + workflowExtRef + " code: " + response.getStatusLine().getStatusCode();
                    log.error(errorMsg);
                    throw new WorkflowException(errorMsg);
                }
                if (log.isDebugEnabled()) {
                    log.debug("Successfully deleted process instance for  : " + workflowExtRef);
                }
                // remove entry from the db
                ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
                apiMgtDAO.removeWorkflowEntry(workflowExtRef, WorkflowConstants.WF_TYPE_AM_API_STATE.toString());
            }
        } else {
            errorMsg = "Error while getting process instance details for " + workflowExtRef + " code: " + response.getStatusLine().getStatusCode();
            log.error(errorMsg);
            throw new WorkflowException(errorMsg);
        }
    } catch (ClientProtocolException e) {
        log.error("Error while creating the http client", e);
        throw new WorkflowException("Error while creating the http client", e);
    } catch (IOException e) {
        log.error("Error while connecting to the BPMN process server from the WorkflowExecutor.", e);
        throw new WorkflowException("Error while connecting to the external service", e);
    } catch (ParseException e) {
        log.error("Error while parsing response from BPS server", e);
        throw new WorkflowException("Error while parsing response from BPS server", e);
    } catch (APIManagementException e) {
        log.error("Error removing the workflow entry", e);
        throw new WorkflowException("Error removing the workflow entry", e);
    } finally {
        if (httpGet != null) {
            httpGet.reset();
        }
        if (httpDelete != null) {
            httpDelete.reset();
        }
    }
}
Also used : HttpDelete(org.apache.http.client.methods.HttpDelete) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) JSONArray(org.json.simple.JSONArray) HttpResponse(org.apache.http.HttpResponse) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) IOException(java.io.IOException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) URL(org.apache.axis2.util.URL) ClientProtocolException(org.apache.http.client.ClientProtocolException) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpClient(org.apache.http.client.HttpClient) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Example 98 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class APIUtil method createEndpoint.

/**
 * Create an Endpoint
 *
 * @param endpointUrl Endpoint url
 * @param registry    Registry space to save the endpoint
 * @return Path of the created resource
 * @throws APIManagementException If an error occurs while adding the endpoint
 */
public static String createEndpoint(String endpointUrl, Registry registry) throws APIManagementException {
    try {
        EndpointManager endpointManager = new EndpointManager(registry);
        Endpoint endpoint = endpointManager.newEndpoint(endpointUrl);
        endpointManager.addEndpoint(endpoint);
        return GovernanceUtils.getArtifactPath(registry, endpoint.getId());
    } catch (RegistryException e) {
        String msg = "Failed to import endpoint " + endpointUrl + " to registry ";
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    }
}
Also used : Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) EndpointManager(org.wso2.carbon.governance.api.endpoints.EndpointManager) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 99 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class RegistryPersistenceUtil method getAPI.

/**
 * This Method is different from getAPI method, as this one returns
 * URLTemplates without aggregating duplicates. This is to be used for building synapse config.
 *
 * @param artifact
 * @param registry
 * @return API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException
 */
public static API getAPI(GovernanceArtifact artifact, Registry registry) throws APIManagementException {
    API api;
    try {
        String providerName = artifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = artifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion, artifact.getId());
        api = new API(apiIdentifier);
        // set uuid
        api.setUuid(artifact.getId());
        // set rating
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        // String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR
        // + RegistryPersistenceUtil.replaceEmailDomain(api.getId().getProviderName())
        // + RegistryConstants.PATH_SEPARATOR + api.getId().getName() + RegistryConstants.PATH_SEPARATOR
        // + api.getId().getVersion() + RegistryConstants.PATH_SEPARATOR + APIConstants.API_KEY;
        Resource apiResource = registry.get(artifactPath);
        api = setResourceProperties(api, apiResource, artifactPath);
        // set description
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        // set url
        api.setStatus(getLcStateFromArtifact(artifact));
        api.setThumbnailUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL));
        api.setWsdlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WSDL));
        api.setWadlUrl(artifact.getAttribute(APIConstants.API_OVERVIEW_WADL));
        api.setTechnicalOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER));
        api.setTechnicalOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
        api.setBusinessOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER));
        api.setBusinessOwnerEmail(artifact.getAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
        api.setVisibility(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY));
        api.setVisibleRoles(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES));
        api.setVisibleTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS));
        api.setEndpointSecured(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_SECURED)));
        api.setEndpointAuthDigest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_AUTH_DIGEST)));
        api.setEndpointUTUsername(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_USERNAME));
        if (!((APIConstants.DEFAULT_MODIFIED_ENDPOINT_PASSWORD).equals(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD)))) {
            api.setEndpointUTPassword(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
        } else {
            // If APIEndpointPasswordRegistryHandler is enabled take password from the registry hidden property
            api.setEndpointUTPassword(apiResource.getProperty(APIConstants.REGISTRY_HIDDEN_ENDPOINT_PROPERTY));
        }
        api.setTransports(artifact.getAttribute(APIConstants.API_OVERVIEW_TRANSPORTS));
        api.setInSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_INSEQUENCE));
        api.setOutSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_OUTSEQUENCE));
        api.setFaultSequence(artifact.getAttribute(APIConstants.API_OVERVIEW_FAULTSEQUENCE));
        api.setResponseCache(artifact.getAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setProductionMaxTps(artifact.getAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS));
        api.setSandboxMaxTps(artifact.getAttribute(APIConstants.API_SANDBOX_THROTTLE_MAXTPS));
        api.setGatewayVendor(artifact.getAttribute(APIConstants.API_GATEWAY_VENDOR));
        api.setAsyncTransportProtocols(artifact.getAttribute(APIConstants.ASYNC_API_TRANSPORT_PROTOCOLS));
        int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
        try {
            String strCacheTimeout = artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT);
            if (strCacheTimeout != null && !strCacheTimeout.isEmpty()) {
                cacheTimeout = Integer.parseInt(strCacheTimeout);
            }
        } catch (NumberFormatException e) {
            if (log.isWarnEnabled()) {
                log.warn("Error while retrieving cache timeout from the registry for " + apiIdentifier);
            }
        // ignore the exception and use default cache timeout value
        }
        api.setCacheTimeout(cacheTimeout);
        api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
        api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
        api.setApiExternalProductionEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_PRODUCTION_ENDPOINT));
        api.setApiExternalSandboxEndpoint(artifact.getAttribute(APIConstants.API_OVERVIEW_EXTERNAL_SANDBOX_ENDPOINT));
        api.setAdvertiseOnlyAPIVendor(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY_API_VENDOR));
        api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomainName);
        String tiers = artifact.getAttribute(APIConstants.API_OVERVIEW_TIER);
        Set<Tier> availableTiers = new HashSet<Tier>();
        if (tiers != null) {
            String[] tiersArray = tiers.split("\\|\\|");
            for (String tierName : tiersArray) {
                availableTiers.add(new Tier(tierName));
            }
        }
        api.setAvailableTiers(availableTiers);
        // This contains the resolved context
        api.setContext(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT));
        // We set the context template here
        api.setContextTemplate(artifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE));
        api.setLatest(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_LATEST)));
        api.setEnableSchemaValidation(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA)));
        api.setEnableStore(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE)));
        api.setTestKey(artifact.getAttribute(APIConstants.API_OVERVIEW_TESTKEY));
        Set<String> tags = new HashSet<String>();
        Tag[] tag = registry.getTags(artifactPath);
        for (Tag tag1 : tag) {
            tags.add(tag1.getTagName());
        }
        api.setTags(tags);
        api.setLastUpdated(apiResource.getLastModified());
        api.setCreatedTime(String.valueOf(apiResource.getCreatedTime().getTime()));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setEnvironments(getEnvironments(artifact.getAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS)));
        api.setCorsConfiguration(getCorsConfigurationFromArtifact(artifact));
        api.setWebsubSubscriptionConfiguration(getWebsubSubscriptionConfigurationFromArtifact(artifact));
        api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
        api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
        // set data and status related to monetization
        api.setMonetizationEnabled(Boolean.parseBoolean(artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS)));
        String monetizationInfo = artifact.getAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES);
        api.setWsUriMapping(getWsUriMappingFromArtifact(artifact));
        api.setAudience(artifact.getAttribute(APIConstants.API_OVERVIEW_AUDIENCE));
        api.setVersionTimestamp(artifact.getAttribute(APIConstants.API_OVERVIEW_VERSION_TIMESTAMP));
        // set selected clusters which API needs to be deployed
        String deployments = artifact.getAttribute(APIConstants.API_OVERVIEW_DEPLOYMENTS);
        if (StringUtils.isNotBlank(monetizationInfo)) {
            JSONParser parser = new JSONParser();
            JSONObject jsonObj = (JSONObject) parser.parse(monetizationInfo);
            api.setMonetizationProperties(jsonObj);
        }
        api.setApiCategories(getAPICategoriesFromAPIGovernanceArtifact(artifact, tenantId));
        // get endpoint config string from artifact, parse it as a json and set the environment list configured with
        // non empty URLs to API object
        String keyManagers = artifact.getAttribute(APIConstants.API_OVERVIEW_KEY_MANAGERS);
        if (StringUtils.isNotEmpty(keyManagers)) {
            api.setKeyManagers(new Gson().fromJson(keyManagers, List.class));
        } else {
            api.setKeyManagers(Arrays.asList(APIConstants.API_LEVEL_ALL_KEY_MANAGERS));
        }
        try {
            api.setEnvironmentList(extractEnvironmentListForAPI(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG)));
        } catch (ParseException e) {
            String msg = "Failed to parse endpoint config JSON of API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        } catch (ClassCastException e) {
            String msg = "Invalid endpoint config JSON found in API: " + apiName + " " + apiVersion;
            log.error(msg, e);
            throw new APIManagementException(msg, e);
        }
    } catch (GovernanceException e) {
        String msg = "Failed to get API for artifact ";
        throw new APIManagementException(msg, e);
    } catch (RegistryException e) {
        String msg = "Failed to get LastAccess time or Rating";
        throw new APIManagementException(msg, e);
    } catch (UserStoreException e) {
        String msg = "Failed to get User Realm of API Provider";
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Failed to get parse monetization information.";
        throw new APIManagementException(msg, e);
    }
    return api;
}
Also used : Tier(org.wso2.carbon.apimgt.api.model.Tier) Resource(org.wso2.carbon.registry.core.Resource) Gson(com.google.gson.Gson) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) DevPortalAPI(org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) JSONParser(org.json.simple.parser.JSONParser) List(java.util.List) ArrayList(java.util.ArrayList) Tag(org.wso2.carbon.registry.core.Tag) ParseException(org.json.simple.parser.ParseException) HashSet(java.util.HashSet)

Example 100 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class PersistenceHelper method getSampleAPIArtifactForTenant.

public static GenericArtifact getSampleAPIArtifactForTenant() throws GovernanceException {
    GenericArtifact artifact = new GenericArtifactImpl(new QName("", "PizzaShackAPI", ""), "application/vnd.wso2-api+xml");
    artifact.setAttribute("overview_endpointSecured", "false");
    artifact.setAttribute("overview_transports", "http,https");
    artifact.setAttribute("URITemplate_authType3", "Application & Application User");
    artifact.setAttribute("overview_wadl", null);
    artifact.setAttribute("URITemplate_authType4", "Application & Application User");
    artifact.setAttribute("overview_authorizationHeader", "Authorization");
    artifact.setAttribute("URITemplate_authType1", "Application & Application User");
    artifact.setAttribute("overview_visibleTenants", null);
    artifact.setAttribute("URITemplate_authType2", "Application & Application User");
    artifact.setAttribute("overview_wsdl", null);
    artifact.setAttribute("overview_apiSecurity", "oauth2,oauth_basic_auth_api_key_mandatory");
    artifact.setAttribute("URITemplate_authType0", "Application & Application User");
    artifact.setAttribute("overview_keyManagers", "[\"all\"]");
    artifact.setAttribute("overview_environments", "Default");
    artifact.setAttribute("overview_context", "/t/wso2.com/pizzashack/1.0.0");
    artifact.setAttribute("overview_visibility", "restricted");
    artifact.setAttribute("overview_isLatest", "true");
    artifact.setAttribute("overview_outSequence", "log_out_message");
    artifact.setAttribute("overview_provider", "admin-AT-wso2.com");
    artifact.setAttribute("apiCategories_categoryName", "testcategory");
    artifact.setAttribute("overview_thumbnail", "/t/wso2.com/t/wso2.com/registry/resource/_system/governance/apimgt/applicationdata/provider/admin-AT-wso2.com/PizzaShackAPI/1.0.0/icon");
    artifact.setAttribute("overview_contextTemplate", "/t/wso2.com/pizzashack/{version}");
    artifact.setAttribute("overview_description", "This is a simple API for Pizza Shack online pizza delivery store.");
    artifact.setAttribute("overview_technicalOwner", "John Doe");
    artifact.setAttribute("overview_type", "HTTP");
    artifact.setAttribute("overview_technicalOwnerEmail", "architecture@pizzashack.com");
    artifact.setAttribute("URITemplate_httpVerb4", "DELETE");
    artifact.setAttribute("overview_inSequence", "log_in_message");
    artifact.setAttribute("URITemplate_httpVerb2", "GET");
    artifact.setAttribute("URITemplate_httpVerb3", "PUT");
    artifact.setAttribute("URITemplate_httpVerb0", "POST");
    artifact.setAttribute("URITemplate_httpVerb1", "GET");
    artifact.setAttribute("labels_labelName", "gwlable");
    artifact.setAttribute("overview_businessOwner", "Jane Roe");
    artifact.setAttribute("overview_version", "1.0.0");
    artifact.setAttribute("overview_endpointConfig", "{\"endpoint_type\":\"http\",\"sandbox_endpoints\":{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\"}," + "\"endpoint_security\":{\"production\":{\"password\":\"admin\",\"tokenUrl\":null,\"clientId\":null," + "\"clientSecret\":null,\"customParameters\":\"{}\",\"additionalProperties\":{},\"type\":\"BASIC\"," + "\"grantType\":null,\"enabled\":true,\"uniqueIdentifier\":null,\"username\":\"admin\"}," + "\"sandbox\":{\"password\":null,\"tokenUrl\":null,\"clientId\":null,\"clientSecret\":null," + "\"customParameters\":\"{}\",\"additionalProperties\":{},\"type\":null,\"grantType\":null,\"enabled\":false," + "\"uniqueIdentifier\":null,\"username\":null}},\"production_endpoints\":" + "{\"url\":\"https://localhost:9443/am/sample/pizzashack/v1/api/\"}}");
    artifact.setAttribute("overview_tier", "Bronze||Silver||Gold||Unlimited");
    artifact.setAttribute("overview_sandboxTps", "1000");
    artifact.setAttribute("overview_apiOwner", "admin@wso2.com");
    artifact.setAttribute("overview_businessOwnerEmail", "marketing@pizzashack.com");
    artifact.setAttribute("isMonetizationEnabled", "false");
    artifact.setAttribute("overview_implementation", "ENDPOINT");
    artifact.setAttribute("overview_deployments", "null");
    artifact.setAttribute("overview_redirectURL", null);
    artifact.setAttribute("monetizationProperties", "{}");
    artifact.setAttribute("overview_name", "PizzaShackAPI");
    artifact.setAttribute("overview_subscriptionAvailability", "current_tenant");
    artifact.setAttribute("overview_productionTps", "1000");
    artifact.setAttribute("overview_cacheTimeout", "300");
    artifact.setAttribute("overview_visibleRoles", "admin,internal/subscriber");
    artifact.setAttribute("overview_testKey", null);
    artifact.setAttribute("overview_corsConfiguration", "{\"corsConfigurationEnabled\":true,\"accessControlAllowOrigins\":[\"*\"]," + "\"accessControlAllowCredentials\":false,\"accessControlAllowHeaders\":[\"authorization\"," + "\"Access-Control-Allow-Origin\",\"Content-Type\",\"SOAPAction\",\"apikey\",\"testKey\"]," + "\"accessControlAllowMethods\":[\"GET\",\"PUT\",\"POST\",\"DELETE\",\"PATCH\",\"OPTIONS\"]}");
    artifact.setAttribute("overview_advertiseOnly", "false");
    artifact.setAttribute("overview_versionType", "context");
    artifact.setAttribute("overview_status", "PUBLISHED");
    artifact.setAttribute("overview_endpointPpassword", null);
    artifact.setAttribute("overview_tenants", null);
    artifact.setAttribute("overview_endpointAuthDigest", "false");
    artifact.setAttribute("overview_faultSequence", "json_fault");
    artifact.setAttribute("overview_responseCaching", "Enabled");
    artifact.setAttribute("URITemplate_urlPattern4", "/order/{orderId}");
    artifact.setAttribute("overview_isDefaultVersion", "true");
    artifact.setAttribute("URITemplate_urlPattern2", "/order/{orderId}");
    artifact.setAttribute("URITemplate_urlPattern3", "/order/{orderId}");
    artifact.setAttribute("URITemplate_urlPattern0", "/order");
    artifact.setAttribute("URITemplate_urlPattern1", "/menu");
    artifact.setAttribute("overview_enableStore", "true");
    artifact.setAttribute("overview_enableSchemaValidation", "true");
    artifact.setAttribute("overview_endpointUsername", null);
    artifact.setAttribute("overview_status", "PUBLISHED");
    artifact.setId("88e758b7-6924-4e9f-8882-431070b6492b");
    return artifact;
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) QName(javax.xml.namespace.QName) GenericArtifactImpl(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifactImpl)

Aggregations

Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)118 Test (org.testng.annotations.Test)93 HashMap (java.util.HashMap)86 IOException (java.io.IOException)82 ArrayList (java.util.ArrayList)76 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)70 Test (org.junit.Test)62 API (org.wso2.carbon.apimgt.core.models.API)58 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)50 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)50 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)46 Map (java.util.Map)44 HashSet (java.util.HashSet)36 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)33 URL (java.net.URL)31 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)30 OMElement (org.apache.axiom.om.OMElement)28 Response (javax.ws.rs.core.Response)27 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)27 API (org.wso2.carbon.apimgt.api.model.API)26