Search in sources :

Example 11 with APIIdentifier

use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.

the class UserAwareAPIConsumer method getLightweightAPI.

@Override
public API getLightweightAPI(APIIdentifier identifier, String orgId) throws APIManagementException {
    API api = super.getLightweightAPI(identifier, orgId);
    checkVisibilityPermission(userNameWithoutChange, api.getVisibility(), api.getVisibleRoles());
    return api;
}
Also used : SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) API(org.wso2.carbon.apimgt.api.model.API)

Example 12 with APIIdentifier

use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method complete.

/**
 * Complete the API state change workflow process.
 */
@Override
public WorkflowResponse complete(WorkflowDTO workflowDTO) throws WorkflowException {
    if (log.isDebugEnabled()) {
        log.debug("Completing API State change Workflow..");
        log.debug("response: " + workflowDTO.toString());
    }
    workflowDTO.setUpdatedTime(System.currentTimeMillis());
    super.complete(workflowDTO);
    String action = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_API_LC_ACTION);
    String apiName = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_APINAME);
    String providerName = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_APIPROVIDER);
    String version = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_APIVERSION);
    String invoker = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_INVOKER);
    String currentStatus = workflowDTO.getAttributes().get(PayloadConstants.VARIABLE_APISTATE);
    int tenantId = workflowDTO.getTenantId();
    ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
    try {
        // tenant flow is already started from the rest api service impl. no need to start from here
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(invoker);
        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceUserRegistry(invoker, tenantId);
        APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, version);
        GenericArtifact apiArtifact = APIUtil.getAPIArtifact(apiIdentifier, registry);
        if (WorkflowStatus.APPROVED.equals(workflowDTO.getStatus())) {
            String targetStatus;
            apiArtifact.invokeAction(action, APIConstants.API_LIFE_CYCLE);
            targetStatus = apiArtifact.getLifecycleState();
            if (!currentStatus.equals(targetStatus)) {
                apiMgtDAO.recordAPILifeCycleEvent(apiArtifact.getId(), currentStatus.toUpperCase(), targetStatus.toUpperCase(), invoker, tenantId);
            }
            if (log.isDebugEnabled()) {
                String logMessage = "API Status changed successfully. API Name: " + apiIdentifier.getApiName() + ", API Version " + apiIdentifier.getVersion() + ", New Status : " + targetStatus;
                log.debug(logMessage);
            }
        }
    } catch (RegistryException e) {
        String errorMsg = "Could not complete api state change workflow";
        log.error(errorMsg, e);
        throw new WorkflowException(errorMsg, e);
    } catch (APIManagementException e) {
        String errorMsg = "Could not complete api state change workflow";
        log.error(errorMsg, e);
        throw new WorkflowException(errorMsg, e);
    }
    return new GeneralWorkflowResponse();
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApiMgtDAO(org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException)

Example 13 with APIIdentifier

use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.

the class APIUtil method getReducedPublisherAPIForListing.

/**
 * Copy of the getAPI(GovernanceArtifact artifact, Registry registry) method with reduced DB calls for api
 * publisher list view listing.
 * @param artifact
 * @param registry
 * @return
 * @throws APIManagementException
 */
public static API getReducedPublisherAPIForListing(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);
        api = new API(apiIdentifier);
        // set description
        api.setDescription(artifact.getAttribute(APIConstants.API_OVERVIEW_DESCRIPTION));
        // set uuid
        api.setUUID(artifact.getId());
        // set url
        api.setStatus(getLcStateFromArtifact(artifact));
        api.setType(artifact.getAttribute(APIConstants.API_OVERVIEW_TYPE));
        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(getActualEpPswdFromHiddenProperty(api, registry));
        }
        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.setProductionMaxTps(artifact.getAttribute(APIConstants.API_PRODUCTION_THROTTLE_MAXTPS));
        int cacheTimeout = APIConstants.API_RESPONSE_CACHE_TIMEOUT;
        try {
            cacheTimeout = Integer.parseInt(artifact.getAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT));
        } catch (NumberFormatException e) {
        // ignore
        }
        api.setCacheTimeout(cacheTimeout);
        api.setEndpointConfig(artifact.getAttribute(APIConstants.API_OVERVIEW_ENDPOINT_CONFIG));
        api.setRedirectURL(artifact.getAttribute(APIConstants.API_OVERVIEW_REDIRECT_URL));
        api.setApiOwner(artifact.getAttribute(APIConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_ADVERTISE_ONLY)));
        api.setSubscriptionAvailability(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(artifact.getAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));
        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.setAsDefaultVersion(Boolean.parseBoolean(artifact.getAttribute(APIConstants.API_OVERVIEW_IS_DEFAULT_VERSION)));
        api.setImplementation(artifact.getAttribute(APIConstants.PROTOTYPE_OVERVIEW_IMPLEMENTATION));
        api.setAuthorizationHeader(artifact.getAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER));
        api.setApiSecurity(artifact.getAttribute(APIConstants.API_OVERVIEW_API_SECURITY));
    } 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);
    }
    return api;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Endpoint(org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint)

Example 14 with APIIdentifier

use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.

the class APIUtil method getMediationPolicyAttributes.

/**
 * Returns attributes correspond to the given mediation policy name and direction
 *
 * @param policyName name of the  sequence
 * @param tenantId   logged in user's tenantId
 * @param direction  in/out/fault
 * @param identifier API identifier
 * @return attributes(path, uuid) of the given mediation sequence or null
 * @throws APIManagementException If failed to get the uuid of the mediation sequence
 */
public static Map<String, String> getMediationPolicyAttributes(String policyName, int tenantId, String direction, APIIdentifier identifier) throws APIManagementException {
    org.wso2.carbon.registry.api.Collection seqCollection = null;
    String seqCollectionPath = "";
    Map<String, String> mediationPolicyAttributes = new HashMap<>(3);
    try {
        UserRegistry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
        if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN.equals(direction)) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + "/" + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN);
        } else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT.equals(direction)) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + "/" + APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT);
        } else if (APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT.equals(direction)) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(APIConstants.API_CUSTOM_SEQUENCE_LOCATION + "/" + APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT);
        }
        if (seqCollection == null) {
            seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier, direction));
        }
        if (seqCollection != null) {
            String[] childPaths = seqCollection.getChildren();
            for (String childPath : childPaths) {
                Resource mediationPolicy = registry.get(childPath);
                OMElement seqElment = APIUtil.buildOMElement(mediationPolicy.getContentStream());
                String seqElmentName = seqElment.getAttributeValue(new QName("name"));
                if (policyName.equals(seqElmentName)) {
                    mediationPolicyAttributes.put("path", childPath);
                    mediationPolicyAttributes.put("uuid", mediationPolicy.getUUID());
                    mediationPolicyAttributes.put("name", policyName);
                    return mediationPolicyAttributes;
                }
            }
        }
        // If the sequence not found the default sequences, check in custom sequences
        seqCollection = (org.wso2.carbon.registry.api.Collection) registry.get(getSequencePath(identifier, direction));
        if (seqCollection != null) {
            String[] childPaths = seqCollection.getChildren();
            for (String childPath : childPaths) {
                Resource mediationPolicy = registry.get(childPath);
                OMElement seqElment = APIUtil.buildOMElement(mediationPolicy.getContentStream());
                if (policyName.equals(seqElment.getAttributeValue(new QName("name")))) {
                    mediationPolicyAttributes.put("path", childPath);
                    mediationPolicyAttributes.put("uuid", mediationPolicy.getUUID());
                    mediationPolicyAttributes.put("name", policyName);
                    return mediationPolicyAttributes;
                }
            }
        }
    } catch (Exception e) {
        String msg = "Issue is in accessing the Registry";
        log.error(msg);
        throw new APIManagementException(msg, e);
    }
    return mediationPolicyAttributes;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) QName(javax.xml.namespace.QName) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) OMElement(org.apache.axiom.om.OMElement) KeyStoreException(java.security.KeyStoreException) JSONException(org.json.JSONException) XMLStreamException(javax.xml.stream.XMLStreamException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ExceptionException(org.wso2.carbon.core.commons.stub.loggeduserinfo.ExceptionException) APIMgtInternalException(org.wso2.carbon.apimgt.api.APIMgtInternalException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URISyntaxException(java.net.URISyntaxException) SignatureException(java.security.SignatureException) RemoteException(java.rmi.RemoteException) CertificateEncodingException(javax.security.cert.CertificateEncodingException) AuthorizationFailedException(org.wso2.carbon.registry.core.secure.AuthorizationFailedException) EventPublisherException(org.wso2.carbon.apimgt.eventing.EventPublisherException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) ValidationException(org.everit.json.schema.ValidationException) CryptoException(org.wso2.carbon.core.util.CryptoException) NotifierException(org.wso2.carbon.apimgt.impl.notifier.exceptions.NotifierException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) SocketException(java.net.SocketException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) SAXException(org.xml.sax.SAXException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) APIMgtAuthorizationFailedException(org.wso2.carbon.apimgt.api.APIMgtAuthorizationFailedException) ParseException(org.json.simple.parser.ParseException) MalformedURLException(java.net.MalformedURLException) CertificateException(java.security.cert.CertificateException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Collection(java.util.Collection)

Example 15 with APIIdentifier

use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.

the class RegistryPersistenceImpl method saveAsyncDefinition.

@Override
public void saveAsyncDefinition(Organization org, String apiId, String apiDefinition) throws AsyncSpecPersistenceException {
    boolean isTenantFlowStarted = false;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        GenericArtifactManager artifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        if (artifactManager == null) {
            String errorMessage = "Failed to retrieve artifact manager when deleting API " + apiId;
            log.error(errorMessage);
            throw new AsyncSpecPersistenceException(errorMessage);
        }
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiId);
        String apiProviderName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
        String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
        String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
        String visibility = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY);
        String visibleRoles = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES);
        String apiPath = GovernanceUtils.getArtifactPath(registry, apiId);
        int prependIndex = apiPath.lastIndexOf("/api");
        String apiSourcePath = apiPath.substring(0, prependIndex);
        String resourcePath = apiSourcePath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_ASYNC_API_DEFINITION_RESOURCE_NAME;
        Resource resource;
        if (!registry.resourceExists(resourcePath)) {
            resource = registry.newResource();
        } else {
            resource = registry.get(resourcePath);
        }
        resource.setContent(apiDefinition);
        // add a constant for app.json
        resource.setMediaType(APIConstants.APPLICATION_JSON_MEDIA_TYPE);
        registry.put(resourcePath, resource);
        String[] visibleRolesArr = null;
        if (visibleRoles != null) {
            visibleRolesArr = visibleRoles.split(",");
        }
        RegistryPersistenceUtil.clearResourcePermissions(resourcePath, new APIIdentifier(apiProviderName, apiName, apiVersion), ((UserRegistry) registry).getTenantId());
        RegistryPersistenceUtil.setResourcePermissions(apiProviderName, visibility, visibleRolesArr, resourcePath);
    } catch (RegistryException | APIPersistenceException | APIManagementException e) {
        throw new AsyncSpecPersistenceException("Error while adding AsyncApi Definition for " + apiId, e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) AsyncSpecPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.AsyncSpecPersistenceException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Aggregations

APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)305 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)171 API (org.wso2.carbon.apimgt.api.model.API)160 Test (org.junit.Test)155 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)119 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)105 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)85 Resource (org.wso2.carbon.registry.core.Resource)79 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)69 ArrayList (java.util.ArrayList)68 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)56 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)48 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)46 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)46 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)44 HashSet (java.util.HashSet)41 HashMap (java.util.HashMap)40 IOException (java.io.IOException)37 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)37 JSONObject (org.json.simple.JSONObject)36