Search in sources :

Example 36 with Attachment

use of org.wso2.carbon.attachment.mgt.api.attachment.Attachment in project carbon-apimgt by wso2.

the class ExportApiServiceImpl method exportPoliciesThrottleGet.

/**
 * Export throttle policies containing zip.
 *
 * @param accept  Accept header value
 * @param request msf4j request object
 * @return Response object
 * @throws NotFoundException if an error occurred when particular resource does not exits in the system.
 */
@Override
public Response exportPoliciesThrottleGet(String accept, Request request) throws NotFoundException {
    String archiveName = "exported-policies";
    // files will be written to following directory
    String exportedPoliciesDirName = "exported-policies";
    // archive will be here at following location tmp directory
    String archiveDir = System.getProperty("java.io.tmpdir");
    if (log.isDebugEnabled()) {
        log.debug("Received export policies GET request ");
    }
    try {
        APIMgtAdminService apiMgtAdminService = APIManagerFactory.getInstance().getAPIMgtAdminService();
        PolicyExportManager policyExportManager = new PolicyExportManager(apiMgtAdminService);
        // create archive and get the archive location
        String zippedFilePath = policyExportManager.createArchiveFromExecutionPlans(exportedPoliciesDirName, archiveDir, archiveName);
        APIFileUtils.deleteDirectory(exportedPoliciesDirName);
        File exportedApiArchiveFile = new File(zippedFilePath);
        Response.ResponseBuilder responseBuilder = Response.status(Response.Status.OK).entity(exportedApiArchiveFile);
        responseBuilder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM).header("Content-Disposition", "attachment; filename=\"" + exportedApiArchiveFile.getName() + "\"");
        Response response = responseBuilder.build();
        return response;
    } catch (APIManagementException e) {
        String errorMessage = "Error while exporting policies";
        log.error(errorMessage, e);
        org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : Response(javax.ws.rs.core.Response) APIMgtAdminService(org.wso2.carbon.apimgt.core.api.APIMgtAdminService) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) PolicyExportManager(org.wso2.carbon.apimgt.rest.api.core.utils.PolicyExportManager) File(java.io.File)

Example 37 with Attachment

use of org.wso2.carbon.attachment.mgt.api.attachment.Attachment in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdWsdlGet.

/**
 * Retrieves the WSDL of the particular API. If the WSDL is added as a single file/URL, the text content of the WSDL
 * will be retrived. If the WSDL is added as an archive, the binary content of the archive will be retrieved.
 *
 * @param apiId           UUID of API
 * @param labelName       Name of the label
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @param request         msf4j request
 * @return WSDL archive/file content
 * @throws NotFoundException
 */
@Override
public Response apisApiIdWsdlGet(String apiId, String labelName, String ifNoneMatch, String ifModifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    WSDLArchiveInfo wsdlArchiveInfo = null;
    try {
        APIStore apiStore = RestApiUtil.getConsumer(username);
        String wsdlString;
        if (!apiStore.isWSDLExists(apiId)) {
            if (log.isDebugEnabled()) {
                log.debug("WSDL has no content for API: " + apiId);
            }
            return Response.noContent().build();
        }
        if (StringUtils.isBlank(labelName)) {
            if (log.isDebugEnabled()) {
                log.debug("Label not provided since retrieving WSDL archive for default label. API: " + apiId);
            }
            labelName = APIMgtConstants.LabelConstants.DEFAULT;
        }
        boolean isWSDLArchiveExists = apiStore.isWSDLArchiveExists(apiId);
        if (log.isDebugEnabled()) {
            log.debug("API has WSDL archive?: " + isWSDLArchiveExists);
        }
        if (isWSDLArchiveExists) {
            wsdlArchiveInfo = apiStore.getAPIWSDLArchive(apiId, labelName);
            if (log.isDebugEnabled()) {
                log.debug("Successfully retrieved WSDL archive for API: " + apiId);
            }
            // wsdlArchiveInfo will not be null all the time so no need null check
            File archive = new File(wsdlArchiveInfo.getAbsoluteFilePath());
            return Response.ok(archive).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_TYPE).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + wsdlArchiveInfo.getFileName() + "\"").build();
        } else {
            wsdlString = apiStore.getAPIWSDL(apiId, labelName);
            if (log.isDebugEnabled()) {
                log.debug("Successfully retrieved WSDL for API: " + apiId);
            }
            return Response.ok(wsdlString).header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN).build();
        }
    } catch (APIManagementException e) {
        Map<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error("Error while getting WSDL for API:" + apiId + " and label:" + labelName, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } finally {
    // Commented below since MSFJ fails to reply when the files are already deleted. Need to fix this properly
    /*
            if (wsdlArchiveInfo != null) {
                try {
                    APIFileUtils.deleteDirectory(wsdlArchiveInfo.getLocation());
                } catch (APIMgtDAOException e) {
                    //This is not a blocker. Give a warning and continue
                    log.warn("Error occured while deleting processed WSDL artifacts folder : " + wsdlArchiveInfo
                            .getLocation());
                }
            }*/
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) WSDLArchiveInfo(org.wso2.carbon.apimgt.core.models.WSDLArchiveInfo) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Example 38 with Attachment

use of org.wso2.carbon.attachment.mgt.api.attachment.Attachment in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdWsdlGet.

/**
 * Retrieves the WSDL of the particular API. If the WSDL is added as a single file/URL, the text content of the WSDL
 * will be retrived. If the WSDL is added as an archive, the binary content of the archive will be retrieved.
 *
 * @param apiId           UUID of API
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @param request         msf4j request
 * @return WSDL archive/file content
 * @throws NotFoundException
 */
@Override
public Response apisApiIdWsdlGet(String apiId, String ifNoneMatch, String ifModifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        InputStream wsdlStream = null;
        if (!apiPublisher.isWSDLExists(apiId)) {
            if (log.isDebugEnabled()) {
                log.debug("WSDL has no content for API: " + apiId);
            }
            return Response.noContent().build();
        }
        boolean isWSDLArchiveExists = apiPublisher.isWSDLArchiveExists(apiId);
        if (log.isDebugEnabled()) {
            log.debug("API has WSDL archive?: " + isWSDLArchiveExists);
        }
        if (isWSDLArchiveExists) {
            wsdlStream = apiPublisher.getAPIWSDLArchive(apiId);
            API api = apiPublisher.getAPIbyUUID(apiId);
            String wsdlFileName = api.getProvider() + "-" + api.getName() + "-" + api.getVersion() + "-wsdl-archive.zip";
            return Response.ok(wsdlStream).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_TYPE).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + wsdlFileName + "\"").build();
        } else {
            String wsdlText = apiPublisher.getAPIWSDL(apiId);
            // TODO need to use text/xml content type. It does not work due to an issue with MSF4J -malinthaa
            return Response.ok(wsdlText, MediaType.TEXT_PLAIN).build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving WSDL of 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();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) InputStream(java.io.InputStream) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) API(org.wso2.carbon.apimgt.core.models.API)

Example 39 with Attachment

use of org.wso2.carbon.attachment.mgt.api.attachment.Attachment in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdThumbnailGet.

/**
 * Retrives the thumbnail of an API
 *
 * @param apiId           UUID of API
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @param request         msf4j request object
 * @return the thumbnail image of an API
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisApiIdThumbnailGet(String apiId, String ifNoneMatch, String ifModifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        String existingFingerprint = apisApiIdThumbnailGetFingerprint(apiId, ifNoneMatch, ifModifiedSince, request);
        if (!StringUtils.isEmpty(ifNoneMatch) && !StringUtils.isEmpty(existingFingerprint) && ifNoneMatch.contains(existingFingerprint)) {
            return Response.notModified().build();
        }
        InputStream imageInputStream = apiPublisher.getThumbnailImage(apiId);
        if (imageInputStream != null) {
            return Response.ok(imageInputStream, MediaType.APPLICATION_OCTET_STREAM_TYPE).header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"icon\"").header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").build();
        } else {
            return Response.noContent().build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving thumbnail of 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();
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) InputStream(java.io.InputStream) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher)

Example 40 with Attachment

use of org.wso2.carbon.attachment.mgt.api.attachment.Attachment in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdDocumentsDocumentIdContentGet.

/**
 * Retrieves the content of the document
 *
 * @param apiId           API ID
 * @param documentId      Document ID
 * @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 {
        APIStore apiStore = RestApiUtil.getConsumer(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 = apiStore.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) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

Aggregations

HashMap (java.util.HashMap)11 AttachmentMgtException (org.wso2.carbon.attachment.mgt.skeleton.AttachmentMgtException)11 TAttachment (org.wso2.carbon.attachment.mgt.skeleton.types.TAttachment)10 DataHandler (javax.activation.DataHandler)9 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)9 ArrayList (java.util.ArrayList)8 BLangRecordLiteral (org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral)8 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)8 File (java.io.File)7 Response (javax.ws.rs.core.Response)7 DiagnosticPos (org.wso2.ballerinalang.compiler.util.diagnotic.DiagnosticPos)7 RestResponseFactory (org.wso2.carbon.bpmn.rest.common.RestResponseFactory)7 TopLevelNode (org.ballerinalang.model.tree.TopLevelNode)6 AttachmentDAO (org.wso2.carbon.attachment.mgt.core.dao.AttachmentDAO)6 BaseTaskService (org.wso2.carbon.bpmn.rest.service.base.BaseTaskService)5 IOException (java.io.IOException)4 List (java.util.List)4 BLangExpression (org.wso2.ballerinalang.compiler.tree.expressions.BLangExpression)4 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)4 Attachment (org.wso2.carbon.attachment.mgt.api.attachment.Attachment)4