Search in sources :

Example 76 with APIProduct

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

the class APIConfigContext method setApiProductVelocityContext.

private void setApiProductVelocityContext(APIProduct apiProduct, VelocityContext context) {
    APIProductIdentifier id = apiProduct.getId();
    // set the api name version and context
    context.put("apiName", id.getName());
    context.put("apiVersion", "1.0.0");
    // We set the context pattern now to support plugable version strategy
    // context.put("apiContext", api.getContext());
    context.put("apiContext", apiProduct.getContext());
    // the api object will be passed on to the template so it properties can be used to
    // customise how the synapse config is generated.
    context.put("apiObj", apiProduct);
    context.put("apiIsBlocked", Boolean.FALSE);
    String apiSecurity = apiProduct.getApiSecurity();
    if (apiSecurity == null || apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2)) {
        context.put("apiIsOauthProtected", Boolean.TRUE);
    } else {
        context.put("apiIsOauthProtected", Boolean.FALSE);
    }
    if (apiProduct.isEnabledSchemaValidation()) {
        context.put("enableSchemaValidation", Boolean.TRUE);
    } else {
        context.put("enableSchemaValidation", Boolean.FALSE);
    }
    if (apiProduct.isEnableStore()) {
        context.put("enableStore", Boolean.TRUE);
    } else {
        context.put("enableStore", Boolean.FALSE);
    }
    // API test key
    context.put("testKey", apiProduct.getTestKey());
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier)

Example 77 with APIProduct

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

the class SecurityConfigContext method getContext.

public VelocityContext getContext() {
    VelocityContext context = super.getContext();
    boolean isSecureVaultEnabled = Boolean.parseBoolean(getApiManagerConfiguration().getFirstProperty(APIConstants.API_SECUREVAULT_ENABLE));
    if (api != null) {
        Map<String, EndpointSecurityModel> endpointSecurityModelMap = new HashMap<>();
        endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_PRODUCTION, new EndpointSecurityModel());
        endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_SANDBOX, new EndpointSecurityModel());
        if (StringUtils.isNotEmpty(api.getEndpointConfig())) {
            if (productionEndpointSecurity != null) {
                EndpointSecurityModel endpointSecurityModel = new ObjectMapper().convertValue(productionEndpointSecurity, EndpointSecurityModel.class);
                endpointSecurityModel = retrieveEndpointSecurityModel(endpointSecurityModel, api.getId().getApiName(), api.getId().getVersion(), api.getUuid(), APIConstants.ENDPOINT_SECURITY_PRODUCTION, null);
                if (endpointSecurityModel != null) {
                    endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_PRODUCTION, endpointSecurityModel);
                }
            }
            if (sandboxEndpointSecurity != null) {
                EndpointSecurityModel endpointSecurityModel = new ObjectMapper().convertValue(sandboxEndpointSecurity, EndpointSecurityModel.class);
                endpointSecurityModel = retrieveEndpointSecurityModel(endpointSecurityModel, api.getId().getApiName(), api.getId().getVersion(), api.getUuid(), APIConstants.ENDPOINT_SECURITY_SANDBOX, null);
                if (endpointSecurityModel != null) {
                    endpointSecurityModelMap.put(APIConstants.ENDPOINT_SECURITY_SANDBOX, endpointSecurityModel);
                }
            }
        }
        context.put("endpoint_security", endpointSecurityModelMap);
    } else if (apiProduct != null) {
        Map<String, Map<String, EndpointSecurityModel>> endpointSecurityModelMap = new HashMap<>();
        for (APIProductResource apiProductResource : apiProduct.getProductResources()) {
            APIDTO apidto = associatedAPIMap.get(apiProductResource.getApiId());
            String alias = apiProduct.getId().getName() + "--v" + apiProduct.getId().getVersion();
            Map<String, EndpointSecurityModel> stringEndpointSecurityModelMap = new HashMap<>();
            Map<String, EndpointSecurity> endpointSecurityMap = apiProductResource.getEndpointSecurityMap();
            for (Map.Entry<String, EndpointSecurity> endpointSecurityEntry : endpointSecurityMap.entrySet()) {
                EndpointSecurityModel endpointSecurityModel = new EndpointSecurityModel(endpointSecurityEntry.getValue());
                endpointSecurityModel = retrieveEndpointSecurityModel(endpointSecurityModel, apidto.getName(), apidto.getVersion(), apidto.getId(), endpointSecurityEntry.getKey(), alias);
                stringEndpointSecurityModelMap.put(endpointSecurityEntry.getKey(), endpointSecurityModel);
            }
            endpointSecurityModelMap.put(apiProductResource.getApiId(), stringEndpointSecurityModelMap);
        }
        context.put("endpoint_security", endpointSecurityModelMap);
    }
    context.put("isSecureVaultEnabled", isSecureVaultEnabled);
    return context;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) HashMap(java.util.HashMap) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) VelocityContext(org.apache.velocity.VelocityContext) HashMap(java.util.HashMap) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 78 with APIProduct

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

the class ApiProductsApiServiceImpl method updateAPIProductThumbnail.

@Override
public Response updateAPIProductThumbnail(String apiProductId, InputStream fileInputStream, Attachment fileDetail, String ifMatch, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String tenantDomain = RestApiCommonUtil.getLoggedInUserTenantDomain();
        String fileName = fileDetail.getDataHandler().getName();
        String extension = FilenameUtils.getExtension(fileName);
        if (!RestApiConstants.ALLOWED_THUMBNAIL_EXTENSIONS.contains(extension.toLowerCase())) {
            RestApiUtil.handleBadRequest("Unsupported Thumbnail File Extension. Supported extensions are .jpg, .png, .jpeg .svg " + "and .gif", log);
        }
        String fileContentType = URLConnection.guessContentTypeFromName(fileName);
        if (org.apache.commons.lang3.StringUtils.isBlank(fileContentType)) {
            fileContentType = fileDetail.getContentType().toString();
        }
        // this will fail if user does not have access to the API or the API does not exist
        APIProduct apiProduct = apiProvider.getAPIProductbyUUID(apiProductId, tenantDomain);
        ResourceFile apiImage = new ResourceFile(fileInputStream, fileContentType);
        apiProvider.setThumbnailToAPI(apiProductId, apiImage, tenantDomain);
        /*
            String thumbPath = APIUtil.getProductIconPath(apiProduct.getId());
            String thumbnailUrl = apiProvider.addProductResourceFile(apiProduct.getId(), thumbPath, apiImage);
            apiProduct.setThumbnailUrl(APIUtil.prependTenantPrefix(thumbnailUrl, apiProduct.getId().getProviderName()));
            APIUtil.setResourcePermissions(apiProduct.getId().getProviderName(), null, null, thumbPath);

            //need to set product resource mappings before updating product, otherwise existing mappings will be lost
            List<APIProductResource> resources = apiProvider.getResourcesOfAPIProduct(apiProduct.getId());
            apiProduct.setProductResources(resources);
            apiProvider.updateAPIProduct(apiProduct);
            */
        String uriString = RestApiConstants.RESOURCE_PATH_THUMBNAIL.replace(RestApiConstants.APIID_PARAM, apiProductId);
        URI uri = new URI(uriString);
        FileInfoDTO infoDTO = new FileInfoDTO();
        infoDTO.setRelativePath(uriString);
        infoDTO.setMediaType(apiImage.getContentType());
        return Response.created(uri).entity(infoDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while updating API Product : " + apiProductId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving thumbnail location of API Product : " + apiProductId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) FileInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.FileInfoDTO)

Example 79 with APIProduct

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

the class ApiProductsApiServiceImpl method getAPIProductLifecycleHistory.

@Override
public Response getAPIProductLifecycleHistory(String apiProductId, String ifNoneMatch, MessageContext messageContext) {
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        APIProduct product;
        APIRevision apiRevision = ApiMgtDAO.getInstance().checkAPIUUIDIsARevisionUUID(apiProductId);
        if (apiRevision != null && apiRevision.getApiUUID() != null) {
            product = apiProvider.getAPIProductbyUUID(apiRevision.getApiUUID(), organization);
        } else {
            product = apiProvider.getAPIProductbyUUID(apiProductId, organization);
        }
        return Response.ok().entity(PublisherCommonUtils.getLifecycleHistoryDTO(product.getUuid(), apiProvider)).build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API_PRODUCT, apiProductId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving the " + "lifecycle history of the API Product with id : " + apiProductId, e, log);
        } else {
            String errorMessage = "Error while retrieving the lifecycle history of  API Product with id : " + apiProductId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 80 with APIProduct

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

the class RegistryPersistenceImpl method searchContentForPublisher.

@Override
public PublisherContentSearchResult searchContentForPublisher(Organization org, String searchQuery, int start, int offset, UserContext ctx) throws APIPersistenceException {
    log.debug("Requested query for publisher content search: " + searchQuery);
    Map<String, String> attributes = RegistrySearchUtil.getPublisherSearchAttributes(searchQuery, ctx);
    if (log.isDebugEnabled()) {
        log.debug("Search attributes : " + attributes);
    }
    boolean isTenantFlowStarted = false;
    PublisherContentSearchResult result = null;
    try {
        RegistryHolder holder = getRegistry(org.getName());
        Registry registry = holder.getRegistry();
        isTenantFlowStarted = holder.isTenantFlowStarted();
        String requestedTenantDomain = org.getName();
        String tenantAwareUsername = getTenantAwareUsername(RegistryPersistenceUtil.getTenantAdminUserName(requestedTenantDomain));
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(tenantAwareUsername);
        GenericArtifactManager apiArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.API_KEY);
        GenericArtifactManager docArtifactManager = RegistryPersistenceUtil.getArtifactManager(registry, APIConstants.DOCUMENTATION_KEY);
        int maxPaginationLimit = getMaxPaginationLimit();
        PaginationContext.init(start, offset, "ASC", APIConstants.API_OVERVIEW_NAME, maxPaginationLimit);
        int tenantId = holder.getTenantId();
        if (tenantId == -1) {
            tenantId = MultitenantConstants.SUPER_TENANT_ID;
        }
        UserRegistry systemUserRegistry = ServiceReferenceHolder.getInstance().getRegistryService().getRegistry(CarbonConstants.REGISTRY_SYSTEM_USERNAME, tenantId);
        ContentBasedSearchService contentBasedSearchService = new ContentBasedSearchService();
        SearchResultsBean resultsBean = contentBasedSearchService.searchByAttribute(attributes, systemUserRegistry);
        String errorMsg = resultsBean.getErrorMessage();
        if (errorMsg != null) {
            throw new APIPersistenceException("Error while searching " + errorMsg);
        }
        ResourceData[] resourceData = resultsBean.getResourceDataList();
        int totalLength = PaginationContext.getInstance().getLength();
        if (resourceData != null) {
            result = new PublisherContentSearchResult();
            List<SearchContent> contentData = new ArrayList<SearchContent>();
            if (log.isDebugEnabled()) {
                log.debug("Number of records Found: " + resourceData.length);
            }
            for (ResourceData data : resourceData) {
                String resourcePath = data.getResourcePath();
                if (resourcePath.contains(APIConstants.APIMGT_REGISTRY_LOCATION)) {
                    int index = resourcePath.indexOf(APIConstants.APIMGT_REGISTRY_LOCATION);
                    resourcePath = resourcePath.substring(index);
                    Resource resource = registry.get(resourcePath);
                    if (APIConstants.DOCUMENT_RXT_MEDIA_TYPE.equals(resource.getMediaType()) || APIConstants.DOCUMENTATION_INLINE_CONTENT_TYPE.equals(resource.getMediaType())) {
                        if (resourcePath.contains(APIConstants.INLINE_DOCUMENT_CONTENT_DIR)) {
                            int indexOfContents = resourcePath.indexOf(APIConstants.INLINE_DOCUMENT_CONTENT_DIR);
                            resourcePath = resourcePath.substring(0, indexOfContents) + data.getName();
                        }
                        DocumentSearchContent docSearch = new DocumentSearchContent();
                        Resource docResource = registry.get(resourcePath);
                        String docArtifactId = docResource.getUUID();
                        GenericArtifact docArtifact = docArtifactManager.getGenericArtifact(docArtifactId);
                        Documentation doc = RegistryPersistenceDocUtil.getDocumentation(docArtifact);
                        // API associatedAPI = null;
                        // APIProduct associatedAPIProduct = null;
                        int indexOfDocumentation = resourcePath.indexOf(APIConstants.DOCUMENTATION_KEY);
                        String apiPath = resourcePath.substring(0, indexOfDocumentation) + APIConstants.API_KEY;
                        Resource apiResource = registry.get(apiPath);
                        String apiArtifactId = apiResource.getUUID();
                        PublisherAPI pubAPI;
                        if (apiArtifactId != null) {
                            GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                            String accociatedType;
                            if (apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE).equals(APIConstants.AuditLogConstants.API_PRODUCT)) {
                                // associatedAPIProduct = APIUtil.getAPIProduct(apiArtifact, registry);
                                accociatedType = APIConstants.API_PRODUCT;
                            } else {
                                // associatedAPI = APIUtil.getAPI(apiArtifact, registry);
                                accociatedType = APIConstants.API;
                            }
                            pubAPI = RegistryPersistenceUtil.getAPIForSearch(apiArtifact);
                            docSearch.setApiName(pubAPI.getApiName());
                            docSearch.setApiProvider(pubAPI.getProviderName());
                            docSearch.setApiVersion(pubAPI.getVersion());
                            docSearch.setApiUUID(pubAPI.getId());
                            docSearch.setAssociatedType(accociatedType);
                            docSearch.setDocType(doc.getType());
                            docSearch.setId(doc.getId());
                            docSearch.setSourceType(doc.getSourceType());
                            docSearch.setVisibility(doc.getVisibility());
                            docSearch.setName(doc.getName());
                            contentData.add(docSearch);
                        } else {
                            throw new GovernanceException("artifact id is null of " + apiPath);
                        }
                    } else {
                        String apiArtifactId = resource.getUUID();
                        // API api;
                        // APIProduct apiProduct;
                        String type;
                        if (apiArtifactId != null) {
                            GenericArtifact apiArtifact = apiArtifactManager.getGenericArtifact(apiArtifactId);
                            if (apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE).equals(APIConstants.API_PRODUCT)) {
                                // apiProduct = APIUtil.getAPIProduct(apiArtifact, registry);
                                // apiProductSet.add(apiProduct);
                                type = APIConstants.API_PRODUCT;
                            } else {
                                // api = APIUtil.getAPI(apiArtifact, registry);
                                // apiSet.add(api);
                                type = APIConstants.API;
                            }
                            PublisherAPI pubAPI = RegistryPersistenceUtil.getAPIForSearch(apiArtifact);
                            PublisherSearchContent content = new PublisherSearchContent();
                            content.setContext(pubAPI.getContext());
                            content.setDescription(pubAPI.getDescription());
                            content.setId(pubAPI.getId());
                            content.setName(pubAPI.getApiName());
                            content.setProvider(RegistryPersistenceUtil.replaceEmailDomainBack(pubAPI.getProviderName()));
                            content.setType(type);
                            content.setVersion(pubAPI.getVersion());
                            content.setStatus(pubAPI.getStatus());
                            content.setAdvertiseOnly(pubAPI.isAdvertiseOnly());
                            contentData.add(content);
                        } else {
                            throw new GovernanceException("artifact id is null for " + resourcePath);
                        }
                    }
                }
            }
            result.setTotalCount(totalLength);
            result.setReturnedCount(contentData.size());
            result.setResults(contentData);
        }
    } catch (RegistryException | IndexerException | DocumentationPersistenceException | APIManagementException e) {
        throw new APIPersistenceException("Error while searching for content ", e);
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
    return result;
}
Also used : DocumentationPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.DocumentationPersistenceException) ArrayList(java.util.ArrayList) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) SearchResultsBean(org.wso2.carbon.registry.indexing.service.SearchResultsBean) IndexerException(org.wso2.carbon.registry.indexing.indexer.IndexerException) DevPortalSearchContent(org.wso2.carbon.apimgt.persistence.dto.DevPortalSearchContent) DocumentSearchContent(org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent) PublisherSearchContent(org.wso2.carbon.apimgt.persistence.dto.PublisherSearchContent) SearchContent(org.wso2.carbon.apimgt.persistence.dto.SearchContent) GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) ResourceData(org.wso2.carbon.registry.common.ResourceData) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) DocumentSearchContent(org.wso2.carbon.apimgt.persistence.dto.DocumentSearchContent) PublisherSearchContent(org.wso2.carbon.apimgt.persistence.dto.PublisherSearchContent) Documentation(org.wso2.carbon.apimgt.persistence.dto.Documentation) Resource(org.wso2.carbon.registry.core.Resource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) ContentBasedSearchService(org.wso2.carbon.registry.indexing.service.ContentBasedSearchService) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) PublisherContentSearchResult(org.wso2.carbon.apimgt.persistence.dto.PublisherContentSearchResult)

Aggregations

APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)71 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)52 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)51 API (org.wso2.carbon.apimgt.api.model.API)37 ArrayList (java.util.ArrayList)31 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)22 PublisherAPIProduct (org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct)22 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)21 Tier (org.wso2.carbon.apimgt.api.model.Tier)21 HashMap (java.util.HashMap)19 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)19 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)18 JSONObject (org.json.simple.JSONObject)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)17 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)16 HashSet (java.util.HashSet)15 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)15 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)14 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)14 ParseException (org.json.simple.parser.ParseException)12