Search in sources :

Example 1 with DocumentationContent

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

the class ApisApiServiceImpl method apisApiIdDocumentsDocumentIdContentGet.

/**
 * Retrieves the content of a particular document
 *
 * @param apiId           UUID of API
 * @param documentId      UUID of the document
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @param request         msf4j request object
 * @return Content of the document
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisApiIdDocumentsDocumentIdContentGet(String apiId, String documentId, String ifNoneMatch, String ifModifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        String existingFingerprint = apisApiIdDocumentsDocumentIdContentGetFingerprint(apiId, documentId, ifNoneMatch, ifModifiedSince, request);
        if (!StringUtils.isEmpty(ifNoneMatch) && !StringUtils.isEmpty(existingFingerprint) && ifNoneMatch.contains(existingFingerprint)) {
            return Response.notModified().build();
        }
        DocumentContent documentationContent = apiPublisher.getDocumentationContent(documentId);
        DocumentInfo documentInfo = documentationContent.getDocumentInfo();
        if (DocumentInfo.SourceType.FILE.equals(documentInfo.getSourceType())) {
            String filename = documentInfo.getFileName();
            return Response.ok(documentationContent.getFileContent()).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_TYPE).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"").header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").build();
        } else if (DocumentInfo.SourceType.INLINE.equals(documentInfo.getSourceType())) {
            String content = documentationContent.getInlineContent();
            return Response.ok(content).header(RestApiConstants.HEADER_CONTENT_TYPE, MediaType.TEXT_PLAIN).header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").build();
        } else if (DocumentInfo.SourceType.URL.equals(documentInfo.getSourceType())) {
            String sourceUrl = documentInfo.getSourceURL();
            return Response.seeOther(new URI(sourceUrl)).header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving document " + documentId + " of the API " + apiId;
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving source URI location of " + documentId;
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorMessage, 900313L, errorMessage);
        log.error(errorMessage, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) DocumentContent(org.wso2.carbon.apimgt.core.models.DocumentContent) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

Example 2 with DocumentationContent

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

the class APIProviderImplTest method testAddFileToDocumentation.

/**
 * This method tests adding file to documentation method.
 * @throws Exception
 *
 * @throws GovernanceException    Governance Exception.
 */
@Test
public void testAddFileToDocumentation() throws Exception {
    String apiUUID = "xxxxxxxx";
    String docUUID = "yyyyyyyy";
    APIIdentifier identifier = new APIIdentifier("admin-AT-carbon.super", "API1", "1.0.0");
    Set<String> environments = new HashSet<String>();
    Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
    Tier tier = new Tier("Gold");
    Map<String, Tier> tiers = new TreeMap<>();
    tiers.put("Gold", tier);
    URITemplate uriTemplate1 = new URITemplate();
    uriTemplate1.setHTTPVerb("POST");
    uriTemplate1.setAuthType("Application");
    uriTemplate1.setUriTemplate("/add");
    uriTemplate1.setThrottlingTier("Gold");
    uriTemplates.add(uriTemplate1);
    final API api = new API(identifier);
    api.setStatus(APIConstants.CREATED);
    api.setVisibility("public");
    api.setAccessControl("all");
    api.setTransports("http,https");
    api.setContext("/test");
    api.setEnvironments(environments);
    api.setUriTemplates(uriTemplates);
    api.setOrganization("carbon.super");
    List<Documentation> documentationList = getDocumentationList();
    final APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, documentationList, null);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
    ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    Mockito.when(APIUtil.getTiers(APIConstants.TIER_RESOURCE_TYPE, "carbon.super")).thenReturn(tiers);
    Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
    Mockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
    PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
    apiProvider.addAPI(api);
    String fileName = "test.txt";
    String contentType = "application/force-download";
    Documentation doc = new Documentation(DocumentationType.HOWTO, fileName);
    doc.setSourceType(DocumentSourceType.FILE);
    PowerMockito.when(APIUtil.getDocumentationFilePath(api.getId(), fileName)).thenReturn("filePath");
    InputStream inputStream = Mockito.mock(InputStream.class);
    // apiProvider.addFileToDocumentation(api.getId(), doc, fileName, inputStream, contentType);
    DocumentationContent content = new DocumentationContent();
    ResourceFile resourceFile = new ResourceFile(inputStream, contentType);
    content.setResourceFile(resourceFile);
    apiProvider.addDocumentationContent(apiUUID, docUUID, "carbon.super", content);
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Tier(org.wso2.carbon.apimgt.api.model.Tier) QName(javax.xml.namespace.QName) InputStream(java.io.InputStream) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) TreeMap(java.util.TreeMap) DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) RealmService(org.wso2.carbon.user.core.service.RealmService) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) TenantManager(org.wso2.carbon.user.core.tenant.TenantManager) HashSet(java.util.HashSet) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 3 with DocumentationContent

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

the class APIProviderImpl method createNewAPIVersion.

public API createNewAPIVersion(String existingApiId, String newVersion, Boolean isDefaultVersion, String organization) throws APIManagementException {
    API existingAPI = getAPIbyUUID(existingApiId, organization);
    if (existingAPI == null) {
        throw new APIMgtResourceNotFoundException("API not found for id " + existingApiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, existingApiId));
    }
    if (newVersion.equals(existingAPI.getId().getVersion())) {
        throw new APIMgtResourceAlreadyExistsException("Version " + newVersion + " exists for api " + existingAPI.getId().getApiName());
    }
    existingAPI.setOrganization(organization);
    APIIdentifier existingAPIId = existingAPI.getId();
    String existingAPICreatedTime = existingAPI.getCreatedTime();
    String existingAPIStatus = existingAPI.getStatus();
    boolean isExsitingAPIdefaultVersion = existingAPI.isDefaultVersion();
    String existingContext = existingAPI.getContext();
    String existingVersionTimestamp = existingAPI.getVersionTimestamp();
    APIIdentifier newApiId = new APIIdentifier(existingAPI.getId().getProviderName(), existingAPI.getId().getApiName(), newVersion);
    existingAPI.setUuid(null);
    existingAPI.setId(newApiId);
    existingAPI.setStatus(APIConstants.CREATED);
    existingAPI.setDefaultVersion(isDefaultVersion);
    existingAPI.setVersionTimestamp("");
    // We need to change the context by setting the new version
    // This is a change that is coming with the context version strategy
    String existingAPIContextTemplate = existingAPI.getContextTemplate();
    existingAPI.setContext(existingAPIContextTemplate.replace("{version}", newVersion));
    Map<String, List<OperationPolicy>> operationPoliciesMap = extractAndDropOperationPoliciesFromURITemplate(existingAPI.getUriTemplates());
    API newAPI = addAPI(existingAPI);
    String newAPIId = newAPI.getUuid();
    if (!operationPoliciesMap.isEmpty()) {
        // clone common or API specific operation policy.
        Map<String, String> clonedOperationPolicyMap = cloneOperationPoliciesToAPI(existingApiId, newAPI, operationPoliciesMap);
        // attach policy to uri template.
        attachOperationPoliciesToAPI(newAPI, clonedOperationPolicyMap, operationPoliciesMap);
    }
    // copy docs
    List<Documentation> existingDocs = getAllDocumentation(existingApiId, organization);
    if (existingDocs != null) {
        for (Documentation documentation : existingDocs) {
            Documentation newDoc = addDocumentation(newAPIId, documentation, organization);
            DocumentationContent content = getDocumentationContent(existingApiId, documentation.getId(), // TODO see whether we can optimize this
            organization);
            if (content != null) {
                addDocumentationContent(newAPIId, newDoc.getId(), organization, content);
            }
        }
    }
    // copy icon
    ResourceFile icon = getIcon(existingApiId, organization);
    if (icon != null) {
        setThumbnailToAPI(newAPIId, icon, organization);
    }
    // copy sequences
    List<Mediation> mediationPolicies = getAllApiSpecificMediationPolicies(existingApiId, organization);
    if (mediationPolicies != null) {
        for (Mediation mediation : mediationPolicies) {
            Mediation policy = getApiSpecificMediationPolicyByPolicyId(existingApiId, mediation.getUuid(), organization);
            addApiSpecificMediationPolicy(newAPIId, policy, organization);
        }
    }
    // copy wsdl
    if (!APIConstants.API_TYPE_SOAPTOREST.equals(existingAPI.getType()) && existingAPI.getWsdlUrl() != null) {
        ResourceFile wsdl = getWSDL(existingApiId, organization);
        if (wsdl != null) {
            addWSDLResource(newAPIId, wsdl, null, organization);
        }
    }
    // copy graphql definition
    String graphQLSchema = getGraphqlSchemaDefinition(existingApiId, organization);
    if (graphQLSchema != null) {
        saveGraphqlSchemaDefinition(newAPIId, graphQLSchema, organization);
    }
    // update old api
    // revert back to old values before update.
    existingAPI.setUuid(existingApiId);
    existingAPI.setStatus(existingAPIStatus);
    existingAPI.setId(existingAPIId);
    existingAPI.setContext(existingContext);
    existingAPI.setCreatedTime(existingAPICreatedTime);
    // update existing api with the original timestamp
    existingAPI.setVersionTimestamp(existingVersionTimestamp);
    if (isDefaultVersion) {
        existingAPI.setDefaultVersion(false);
    } else {
        existingAPI.setDefaultVersion(isExsitingAPIdefaultVersion);
    }
    try {
        apiPersistenceInstance.updateAPI(new Organization(organization), APIMapper.INSTANCE.toPublisherApi(existingAPI));
    } catch (APIPersistenceException e) {
        throw new APIManagementException("Error while updating API details", e);
    }
    return getAPIbyUUID(newAPIId, organization);
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) Mediation(org.wso2.carbon.apimgt.api.model.Mediation) DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ArrayList(java.util.ArrayList) List(java.util.List)

Example 4 with DocumentationContent

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

the class PublisherCommonUtils method addDocumentationContentForFile.

/**
 * Add documentation content of files.
 *
 * @param inputStream  Input Stream
 * @param mediaType    Media type of the document
 * @param filename     File name
 * @param apiProvider  API Provider
 * @param apiId        API/API Product UUID
 * @param documentId   Document ID
 * @param organization organization of the API
 * @throws APIManagementException If an error occurs while adding the documentation file
 */
public static void addDocumentationContentForFile(InputStream inputStream, String mediaType, String filename, APIProvider apiProvider, String apiId, String documentId, String organization) throws APIManagementException {
    DocumentationContent content = new DocumentationContent();
    ResourceFile resourceFile = new ResourceFile(inputStream, mediaType);
    resourceFile.setName(filename);
    content.setResourceFile(resourceFile);
    content.setSourceType(DocumentationContent.ContentSourceType.FILE);
    apiProvider.addDocumentationContent(apiId, documentId, organization, content);
}
Also used : DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile)

Example 5 with DocumentationContent

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

the class ApiProductsApiServiceImpl method getAPIProductDocumentContent.

@Override
public Response getAPIProductDocumentContent(String apiProductId, String documentId, String accept, String ifNoneMatch, MessageContext messageContext) {
    Documentation documentation;
    try {
        String username = RestApiCommonUtil.getLoggedInUsername();
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // this will fail if user does not have access to the API Product or the API Product does not exist
        APIProductIdentifier productIdentifier = APIMappingUtil.getAPIProductIdentifierFromUUID(apiProductId, organization);
        // documentation = apiProvider.getProductDocumentation(documentId, tenantDomain);
        DocumentationContent docContent = apiProvider.getDocumentationContent(apiProductId, documentId, organization);
        if (docContent == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PRODUCT_DOCUMENTATION, documentId, log);
            return null;
        }
        // gets the content depending on the type of the document
        if (docContent.getSourceType().equals(DocumentationContent.ContentSourceType.FILE)) {
            String contentType = docContent.getResourceFile().getContentType();
            contentType = contentType == null ? RestApiConstants.APPLICATION_OCTET_STREAM : contentType;
            String name = docContent.getResourceFile().getName();
            return Response.ok(docContent.getResourceFile().getContent()).header(RestApiConstants.HEADER_CONTENT_TYPE, contentType).header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\"" + name + "\"").build();
        } else if (docContent.getSourceType().equals(DocumentationContent.ContentSourceType.INLINE) || docContent.getSourceType().equals(DocumentationContent.ContentSourceType.MARKDOWN)) {
            String content = docContent.getTextContent();
            return Response.ok(content).header(RestApiConstants.HEADER_CONTENT_TYPE, DOCUMENTATION_INLINE_CONTENT_TYPE).build();
        } else if (docContent.getSourceType().equals(DocumentationContent.ContentSourceType.URL)) {
            String sourceUrl = docContent.getTextContent();
            return Response.seeOther(new URI(sourceUrl)).build();
        }
    } catch (APIManagementException e) {
        // Auth failure occurs when cross tenant accessing APIs. Sends 404, since we don't need to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_PRODUCT_DOCUMENTATION, apiProductId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while retrieving document : " + documentId + " of API Product " + apiProductId, e, log);
        } else {
            String errorMessage = "Error while retrieving document " + documentId + " of the API Product" + apiProductId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving source URI location of " + documentId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : DocumentationContent(org.wso2.carbon.apimgt.api.model.DocumentationContent) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI)

Aggregations

DocumentationContent (org.wso2.carbon.apimgt.api.model.DocumentationContent)9 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)6 URI (java.net.URI)5 URISyntaxException (java.net.URISyntaxException)5 Documentation (org.wso2.carbon.apimgt.api.model.Documentation)4 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)4 ResourceFile (org.wso2.carbon.apimgt.api.model.ResourceFile)3 InputStream (java.io.InputStream)2 HashMap (java.util.HashMap)2 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)2 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)2 API (org.wso2.carbon.apimgt.api.model.API)2 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)2 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)2 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)2 DocumentContent (org.wso2.carbon.apimgt.core.models.DocumentContent)2 DocumentInfo (org.wso2.carbon.apimgt.core.models.DocumentInfo)2 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)2 DocumentContent (org.wso2.carbon.apimgt.persistence.dto.DocumentContent)2 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)2