Search in sources :

Example 86 with InputStream

use of org.wso2.siddhi.query.api.execution.query.input.stream.InputStream in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdThumbnailPost.

/**
 * Updates the thumbnail image of an API
 *
 * @param apiId             UUID of API
 * @param fileInputStream   Image data stream
 * @param fileDetail        meta information of the image
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @param request           msf4j request object
 * @return meta info about the updated thumbnail image
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisApiIdThumbnailPost(String apiId, InputStream fileInputStream, FileInfo fileDetail, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        String existingFingerprint = apisApiIdThumbnailGetFingerprint(apiId, null, null, request);
        if (!StringUtils.isEmpty(ifMatch) && !StringUtils.isEmpty(existingFingerprint) && !ifMatch.contains(existingFingerprint)) {
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }
        apiPublisher.saveThumbnailImage(apiId, fileInputStream, fileDetail.getFileName());
        String uriString = RestApiConstants.RESOURCE_PATH_THUMBNAIL.replace(RestApiConstants.APIID_PARAM, apiId);
        FileInfoDTO infoDTO = new FileInfoDTO();
        infoDTO.setRelativePath(uriString);
        infoDTO.setMediaType(MediaType.APPLICATION_OCTET_STREAM);
        String newFingerprint = apisApiIdThumbnailGetFingerprint(apiId, null, null, request);
        return Response.status(Response.Status.CREATED).entity(infoDTO).header(HttpHeaders.ETAG, "\"" + newFingerprint + "\"").build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while uploading image" + 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) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) FileInfoDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.FileInfoDTO)

Example 87 with InputStream

use of org.wso2.siddhi.query.api.execution.query.input.stream.InputStream in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisImportDefinitionPost.

/**
 * Import an API from a Swagger or WSDL
 *
 * @param type                 definition type. If not specified, default will be SWAGGER
 * @param fileInputStream      file content stream, can be either archive or a single text file
 * @param fileDetail           file details
 * @param url                  URL of the definition
 * @param additionalProperties Additional attributes specified as a stringified JSON with API's schema
 * @param ifMatch              If-Match header value
 * @param ifUnmodifiedSince    If-Unmodified-Since header value
 * @param implementationType   WSDL based API implementation type (SOAP or HTTP_BINDING)
 * @param request              msf4j request object
 * @return Imported API
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisImportDefinitionPost(String type, InputStream fileInputStream, FileInfo fileDetail, String url, String additionalProperties, String implementationType, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        if (StringUtils.isBlank(type)) {
            type = APIDefinitionValidationResponseDTO.DefinitionTypeEnum.SWAGGER.toString();
        }
        Response response = buildResponseIfParamsInvalid(type, fileInputStream, url);
        if (response != null) {
            return response;
        }
        API.APIBuilder apiBuilder = null;
        APIDTO additionalPropertiesAPI = null;
        if (!StringUtils.isBlank(additionalProperties)) {
            if (log.isDebugEnabled()) {
                log.debug("Deseriallizing additionalProperties: " + additionalProperties);
            }
            ObjectMapper mapper = new ObjectMapper();
            additionalPropertiesAPI = mapper.readValue(additionalProperties, APIDTO.class);
            apiBuilder = MappingUtil.toAPI(additionalPropertiesAPI);
            if (log.isDebugEnabled()) {
                log.debug("Successfully deseriallized additionalProperties: " + additionalProperties);
            }
        }
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        String uuid = "";
        if (APIDefinitionValidationResponseDTO.DefinitionTypeEnum.SWAGGER.toString().equals(type)) {
            if (log.isDebugEnabled()) {
                log.debug("Adding an API by importing a swagger.");
            }
            if (fileInputStream != null) {
                uuid = apiPublisher.addApiFromDefinition(fileInputStream);
            } else {
                URL swaggerUrl = new URL(url);
                HttpURLConnection urlConn = (HttpURLConnection) swaggerUrl.openConnection();
                uuid = apiPublisher.addApiFromDefinition(urlConn);
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Adding an API by importing a WSDL.");
            }
            // context, version when creating an API from WSDL
            if (additionalPropertiesAPI != null) {
                final String soap = RestApiConstants.IMPORT_DEFINITION_WSDL_IMPL_TYPE_SOAP;
                final String httpBinding = RestApiConstants.IMPORT_DEFINITION_WSDL_IMPL_TYPE_HTTP;
                if (implementationType != null && !soap.equals(implementationType) && !httpBinding.equals(implementationType)) {
                    String msg = "Invalid implementation type. Should be one of '" + soap + "' or '" + httpBinding + "'";
                    log.error(msg);
                    ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900700L, msg);
                    return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
                }
                boolean isHttpBinding = httpBinding.equals(implementationType);
                if (fileInputStream != null) {
                    if (fileDetail.getFileName() == null) {
                        String msg = "File name cannot be null.";
                        log.error(msg);
                        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900700L, msg);
                        return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
                    }
                    if (fileDetail.getFileName().endsWith(".zip")) {
                        uuid = apiPublisher.addAPIFromWSDLArchive(apiBuilder, fileInputStream, isHttpBinding);
                        if (log.isDebugEnabled()) {
                            log.debug("Successfully added API with WSDL archive " + fileDetail.getFileName());
                        }
                    } else if (fileDetail.getFileName().endsWith(".wsdl")) {
                        uuid = apiPublisher.addAPIFromWSDLFile(apiBuilder, fileInputStream, isHttpBinding);
                        if (log.isDebugEnabled()) {
                            log.debug("Successfully added API with WSDL file " + fileDetail.getFileName());
                        }
                    } else {
                        String msg = "Unsupported extension type of file: " + fileDetail.getFileName();
                        log.error(msg);
                        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900700L, msg);
                        return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
                    }
                } else {
                    uuid = apiPublisher.addAPIFromWSDLURL(apiBuilder, url, isHttpBinding);
                    if (log.isDebugEnabled()) {
                        log.debug("Successfully added API with WSDL URL " + url);
                    }
                }
            } else {
                String msg = "'additionalProperties' should be specified when creating an API from WSDL";
                log.error(msg);
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900700L, msg);
                return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
            }
        }
        API returnAPI = apiPublisher.getAPIbyUUID(uuid);
        return Response.status(Response.Status.CREATED).entity(MappingUtil.toAPIDto(returnAPI)).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding new API";
        HashMap<String, String> paramList = new HashMap<String, String>();
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } catch (IOException e) {
        String errorMessage = "Error while adding new API";
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorMessage, 900313L, errorMessage);
        log.error(errorMessage, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
    }
}
Also used : HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) IOException(java.io.IOException) URL(java.net.URL) WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) Response(javax.ws.rs.core.Response) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO) HttpURLConnection(java.net.HttpURLConnection) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) API(org.wso2.carbon.apimgt.core.models.API) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 88 with InputStream

use of org.wso2.siddhi.query.api.execution.query.input.stream.InputStream 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 89 with InputStream

use of org.wso2.siddhi.query.api.execution.query.input.stream.InputStream 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 90 with InputStream

use of org.wso2.siddhi.query.api.execution.query.input.stream.InputStream in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdDocumentsDocumentIdContentPost.

/**
 * Uploads a document's content and attach to particular document
 *
 * @param apiId             UUID of API
 * @param documentId        UUID of the document
 * @param fileInputStream   file content stream
 * @param fileDetail        meta infomation about the file
 * @param inlineContent     inline documentation content
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @param request           msf4j request object
 * @return updated document meta information
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisApiIdDocumentsDocumentIdContentPost(String apiId, String documentId, InputStream fileInputStream, FileInfo fileDetail, String inlineContent, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    try {
        String username = RestApiUtil.getLoggedInUsername(request);
        APIPublisher apiProvider = RestAPIPublisherUtil.getApiPublisher(username);
        String existingFingerprint = apisApiIdDocumentsDocumentIdContentGetFingerprint(apiId, documentId, null, null, request);
        if (!StringUtils.isEmpty(ifMatch) && !StringUtils.isEmpty(existingFingerprint) && !ifMatch.contains(existingFingerprint)) {
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }
        if (fileInputStream != null && inlineContent != null) {
            String msg = "Only one of 'file' and 'inlineContent' should be specified";
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900314L, msg);
            log.error(msg);
            return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
        }
        // retrieves the document and send 404 if not found
        DocumentInfo documentation = apiProvider.getDocumentationSummary(documentId);
        if (documentation == null) {
            String msg = "Documentation not found " + documentId;
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900314L, msg);
            log.error(msg);
            return Response.status(Response.Status.NOT_FOUND).entity(errorDTO).build();
        }
        // add content depending on the availability of either input stream or inline content
        if (fileInputStream != null) {
            if (!documentation.getSourceType().equals(DocumentInfo.SourceType.FILE)) {
                String msg = "Source type of document " + documentId + " is not FILE";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900314L, msg);
                log.error(msg);
                return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
            }
            apiProvider.uploadDocumentationFile(documentId, fileInputStream, fileDetail.getContentType());
        } else if (inlineContent != null) {
            if (!documentation.getSourceType().equals(DocumentInfo.SourceType.INLINE)) {
                String msg = "Source type of document " + documentId + " is not INLINE";
                log.error(msg);
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900976L, msg);
                return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
            }
            apiProvider.addDocumentationContent(documentId, inlineContent);
        } else {
            String msg = "Either 'file' or 'inlineContent' should be specified";
            log.error(msg);
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(msg, 900976L, msg);
            return Response.status(Response.Status.BAD_REQUEST).entity(errorDTO).build();
        }
        String newFingerprint = apisApiIdDocumentsDocumentIdContentGetFingerprint(apiId, documentId, null, null, request);
        return Response.status(Response.Status.CREATED).header(HttpHeaders.ETAG, "\"" + newFingerprint + "\"").build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding content to document" + documentId;
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        paramList.put(APIMgtConstants.ExceptionsConstants.DOC_ID, documentId);
        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) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) DocumentInfo(org.wso2.carbon.apimgt.core.models.DocumentInfo)

Aggregations

Test (org.testng.annotations.Test)80 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)67 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)58 InputStream (java.io.InputStream)54 InputHandler (org.wso2.siddhi.core.stream.input.InputHandler)54 Event (org.wso2.siddhi.core.event.Event)48 QueryCallback (org.wso2.siddhi.core.query.output.callback.QueryCallback)47 IOException (java.io.IOException)32 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)24 ByteArrayInputStream (java.io.ByteArrayInputStream)20 API (org.wso2.carbon.apimgt.core.models.API)18 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)17 FileInputStream (java.io.FileInputStream)15 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)13 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)12 Response (javax.ws.rs.core.Response)11 HashMap (java.util.HashMap)9 APIMgtWSDLException (org.wso2.carbon.apimgt.core.exception.APIMgtWSDLException)8 File (java.io.File)7 Connection (java.sql.Connection)7