Search in sources :

Example 16 with FileInfo

use of org.wso2.msf4j.formparam.FileInfo in project carbon-apimgt by wso2.

the class ImportApiServiceImplTestCase method testImportApplicationsPost.

@Test
public void testImportApplicationsPost() throws Exception {
    printTestMethodName();
    ClassLoader classLoader = getClass().getClassLoader();
    File file = new File(classLoader.getResource("sampleApp.zip").getFile());
    FileInputStream fis = null;
    fis = new FileInputStream(file);
    ImportApiServiceImpl importApiService = new ImportApiServiceImpl();
    APIStore apiStore = Mockito.mock(APIStore.class);
    PowerMockito.mockStatic(RestApiUtil.class);
    PowerMockito.when(RestApiUtil.getConsumer(USER)).thenReturn(apiStore);
    Request request = getRequest();
    PowerMockito.when(RestApiUtil.getLoggedInUsername(request)).thenReturn(USER);
    FileInfo fileInfo = new FileInfo();
    fileInfo.setFileName("sampleApp.zip");
    fileInfo.setContentType("application/zip");
    Response response = importApiService.importApplicationsPost(fis, fileInfo, request);
    assertEquals(response.getStatus(), 200);
}
Also used : Response(javax.ws.rs.core.Response) FileInfo(org.wso2.msf4j.formparam.FileInfo) Request(org.wso2.msf4j.Request) File(java.io.File) FileInputStream(java.io.FileInputStream) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 17 with FileInfo

use of org.wso2.msf4j.formparam.FileInfo in project carbon-apimgt by wso2.

the class CompositeApisApiServiceImplTestCase method testCompositeApisApiIdPut.

@Test
public void testCompositeApisApiIdPut() throws APIManagementException, NotFoundException {
    TestUtil.printTestMethodName();
    String apiID = UUID.randomUUID().toString();
    CompositeApisApiServiceImpl compositeApisApiService = new CompositeApisApiServiceImpl();
    APIStore apiStore = Mockito.mock(APIStoreImpl.class);
    PowerMockito.mockStatic(RestApiUtil.class);
    PowerMockito.when(RestApiUtil.getConsumer(USER)).thenReturn(apiStore);
    Request request = TestUtil.getRequest();
    PowerMockito.when(RestApiUtil.getLoggedInUsername(request)).thenReturn(USER);
    CompositeAPI.Builder builder = null;
    InputStream implmentation = null;
    FileInfo fileInfo = new FileInfo();
    fileInfo.setFileName("sample.txt");
    fileInfo.setContentType(contentType);
    Mockito.doNothing().doThrow(new IllegalArgumentException()).when(apiStore).updateCompositeApi(builder);
    Response response = compositeApisApiService.compositeApisApiIdImplementationPut(apiID, implmentation, fileInfo, null, null, request);
    Assert.assertEquals(200, response.getStatus());
}
Also used : Response(javax.ws.rs.core.Response) FileInfo(org.wso2.msf4j.formparam.FileInfo) InputStream(java.io.InputStream) Request(org.wso2.msf4j.Request) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 18 with FileInfo

use of org.wso2.msf4j.formparam.FileInfo in project carbon-apimgt by wso2.

the class CompositeApisApiServiceImpl method compositeApisApiIdImplementationPut.

@Override
public Response compositeApisApiIdImplementationPut(String apiId, InputStream apiImplementationInputStream, FileInfo apiImplementationDetail, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIStore apiStore = RestApiUtil.getConsumer(username);
        String existingFingerprint = compositeApisApiIdImplementationGetFingerprint(apiId, null, null, request);
        if (!StringUtils.isEmpty(ifMatch) && !StringUtils.isEmpty(existingFingerprint) && ifMatch.contains(existingFingerprint)) {
            return Response.notModified().build();
        }
        apiStore.updateCompositeApiImplementation(apiId, apiImplementationInputStream);
        String uriString = RestApiConstants.RESOURCE_PATH_IMPLEMENTATION.replace(RestApiConstants.APIID_PARAM, apiId);
        FileInfoDTO infoDTO = new FileInfoDTO();
        infoDTO.setRelativePath(uriString);
        infoDTO.setMediaType(MediaType.APPLICATION_OCTET_STREAM);
        String newFingerprint = compositeApisApiIdImplementationGetFingerprint(apiId, null, null, request);
        return Response.ok().header(HttpHeaders.ETAG, "\"" + newFingerprint + "\"").entity(infoDTO).build();
    } catch (APIManagementException e) {
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, apiId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        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) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) FileInfoDTO(org.wso2.carbon.apimgt.rest.api.store.dto.FileInfoDTO)

Example 19 with FileInfo

use of org.wso2.msf4j.formparam.FileInfo 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 20 with FileInfo

use of org.wso2.msf4j.formparam.FileInfo 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)

Aggregations

Response (javax.ws.rs.core.Response)24 Test (org.junit.Test)22 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)22 FileInfo (org.wso2.msf4j.formparam.FileInfo)22 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)21 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)21 File (java.io.File)19 FileInputStream (java.io.FileInputStream)19 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)17 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)10 API (org.wso2.carbon.apimgt.core.models.API)10 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)9 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)6 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)6 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO)6 InputStream (java.io.InputStream)4 HashMap (java.util.HashMap)4 DocumentInfo (org.wso2.carbon.apimgt.core.models.DocumentInfo)3 Request (org.wso2.msf4j.Request)3 IOException (java.io.IOException)2