Search in sources :

Example 16 with Wsdl

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

the class ApisApiServiceImplTestCase method testApisValidateDefinitionPostException.

@Test
public void testApisValidateDefinitionPostException() throws Exception {
    printTestMethodName();
    File file = new File(getClass().getClassLoader().getResource(WSDL_ZIP_LOCATION).getFile());
    FileInputStream fis = new FileInputStream(file);
    FileInfo fileInfo = new FileInfo();
    fileInfo.setFileName(WSDL_ZIP);
    ApisApiServiceImpl apisApiService = new ApisApiServiceImpl();
    APIPublisher apiPublisher = powerMockDefaultAPIPublisher();
    Mockito.doThrow(new APIMgtWSDLException("Error while validation", ExceptionCodes.INTERNAL_WSDL_EXCEPTION)).when(apiPublisher).extractAndValidateWSDLArchive(fis);
    Response response = apisApiService.apisValidateDefinitionPost(WSDL, fis, fileInfo, null, getRequest());
    fis.close();
    assertEquals(response.getStatus(), 500);
}
Also used : WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) Response(javax.ws.rs.core.Response) FileInfo(org.wso2.msf4j.formparam.FileInfo) APIMgtWSDLException(org.wso2.carbon.apimgt.core.exception.APIMgtWSDLException) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) File(java.io.File) FileInputStream(java.io.FileInputStream) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 17 with Wsdl

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

the class ApisApiServiceImplTestCase method testApisImportDefinitionPostWSDLArchive.

@Test
public void testApisImportDefinitionPostWSDLArchive() throws Exception {
    printTestMethodName();
    File file = new File(getClass().getClassLoader().getResource(WSDL_ZIP_LOCATION).getFile());
    FileInputStream fis = new FileInputStream(file);
    FileInfo fileInfo = new FileInfo();
    fileInfo.setFileName(WSDL_ZIP);
    ApisApiServiceImpl apisApiService = new ApisApiServiceImpl();
    APIPublisher apiPublisher = powerMockDefaultAPIPublisher();
    String apiId = UUID.randomUUID().toString();
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().id(apiId);
    API api = apiBuilder.build();
    APIDTO apiDto = MappingUtil.toAPIDto(api);
    ObjectMapper objectMapper = new ObjectMapper();
    String additionalProperties = objectMapper.writeValueAsString(apiDto);
    Mockito.doReturn(api).doThrow(new IllegalArgumentException()).when(apiPublisher).getAPIbyUUID(apiId);
    Mockito.doReturn(apiId).when(apiPublisher).addAPIFromWSDLArchive(Mockito.argThat(getAPIBuilderMatcher(apiBuilder)), Mockito.eq(fis), Mockito.eq(false));
    Response response = apisApiService.apisImportDefinitionPost(WSDL, fis, fileInfo, null, additionalProperties, null, null, null, getRequest());
    fis.close();
    assertEquals(response.getStatus(), 201);
    assertTrue(response.getEntity().toString().contains(apiId));
}
Also used : 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) FileInfo(org.wso2.msf4j.formparam.FileInfo) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) API(org.wso2.carbon.apimgt.core.models.API) File(java.io.File) FileInputStream(java.io.FileInputStream) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 18 with Wsdl

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

the class SampleTestObjectCreator method createDefaultAPI.

public static API.APIBuilder createDefaultAPI() {
    Set<String> transport = new HashSet<>();
    transport.add(HTTP);
    transport.add(HTTPS);
    Set<String> tags = new HashSet<>();
    tags.add(TAG_CLIMATE);
    Set<Policy> policies = new HashSet<>();
    policies.add(goldSubscriptionPolicy);
    policies.add(silverSubscriptionPolicy);
    policies.add(bronzeSubscriptionPolicy);
    BusinessInformation businessInformation = new BusinessInformation();
    businessInformation.setBusinessOwner(NAME_BUSINESS_OWNER_1);
    businessInformation.setBusinessOwnerEmail(EMAIL_BUSINESS_OWNER_1);
    businessInformation.setTechnicalOwner(NAME_TECHNICAL_OWNER_1);
    businessInformation.setTechnicalOwnerEmail(EMAIL_TECHNICAL_OWNER_1);
    String permissionJson = "[{\"groupId\" : \"developer\", \"permission\" : " + "[\"READ\",\"UPDATE\"]},{\"groupId\" : \"admin\", \"permission\" : [\"READ\",\"UPDATE\"," + "\"DELETE\", \"MANAGE_SUBSCRIPTION\"]}]";
    Set<String> visibleRoles = new HashSet<>();
    visibleRoles.add("testRple");
    List<String> labels = new ArrayList<>();
    labels.add("testLabel");
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.setEnabled(true);
    corsConfiguration.setAllowMethods(Arrays.asList(APIMgtConstants.FunctionsConstants.GET, APIMgtConstants.FunctionsConstants.POST, APIMgtConstants.FunctionsConstants.DELETE));
    corsConfiguration.setAllowHeaders(Arrays.asList(ALLOWED_HEADER_AUTHORIZATION, ALLOWED_HEADER_CUSTOM));
    corsConfiguration.setAllowCredentials(true);
    corsConfiguration.setAllowOrigins(Arrays.asList("*"));
    Map<String, Endpoint> endpointMap = new HashMap<>();
    endpointMap.put("TestEndpoint", createMockEndpoint());
    API.APIBuilder apiBuilder = new API.APIBuilder(ADMIN, "WeatherAPI", API_VERSION).id(UUID.randomUUID().toString()).context("weather").description("Get Weather Info").lifeCycleStatus(APIStatus.CREATED.getStatus()).lifecycleInstanceId(UUID.randomUUID().toString()).endpoint(Collections.emptyMap()).wsdlUri("http://localhost:9443/echo?wsdl").isResponseCachingEnabled(false).cacheTimeout(60).isDefaultVersion(false).apiPolicy(unlimitedApiPolicy).transport(transport).tags(tags).policies(policies).visibility(API.Visibility.PUBLIC).visibleRoles(visibleRoles).businessInformation(businessInformation).corsConfiguration(corsConfiguration).createdTime(LocalDateTime.now()).createdBy(ADMIN).updatedBy(ADMIN).lastUpdatedTime(LocalDateTime.now()).apiPermission(permissionJson).uriTemplates(getMockUriTemplates()).apiDefinition(apiDefinition).workflowStatus(WORKFLOW_STATUS).labels(labels).endpoint(endpointMap);
    Map map = new HashMap();
    map.put(DEVELOPER_ROLE_ID, 6);
    map.put(ADMIN_ROLE_ID, 15);
    apiBuilder.permissionMap(map);
    return apiBuilder;
}
Also used : ApplicationPolicy(org.wso2.carbon.apimgt.core.models.policy.ApplicationPolicy) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) Policy(org.wso2.carbon.apimgt.core.models.policy.Policy) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) API(org.wso2.carbon.apimgt.core.models.API) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 19 with Wsdl

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

the class ApisApiServiceImpl method apisValidateDefinitionPost.

/**
 * Validates a provided API definition
 *
 * @param type            API definition type (SWAGGER or WSDL)
 * @param fileInputStream file content stream
 * @param fileDetail      file details
 * @param url             URL of the definition
 * @param request         msf4j request
 * @return API definition validation information
 * @throws NotFoundException
 */
@Override
public Response apisValidateDefinitionPost(String type, InputStream fileInputStream, FileInfo fileDetail, String url, Request request) throws NotFoundException {
    String errorMessage = "Error while validating the definition";
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        if (StringUtils.isBlank(type)) {
            type = APIDefinitionValidationResponseDTO.DefinitionTypeEnum.SWAGGER.toString();
        }
        Response responseIfParamsInvalid = buildResponseIfParamsInvalid(type, fileInputStream, url);
        if (responseIfParamsInvalid != null) {
            return responseIfParamsInvalid;
        }
        if (APIDefinitionValidationResponseDTO.DefinitionTypeEnum.SWAGGER.toString().equals(type)) {
            if (log.isDebugEnabled()) {
                log.debug("Validating a swagger file.");
            }
            // TODO implement swagger validation
            return Response.noContent().build();
        } else {
            // WSDL type
            WSDLProcessor processor = null;
            WSDLInfo info = null;
            if (!StringUtils.isBlank(url)) {
                processor = WSDLProcessFactory.getInstance().getWSDLProcessor(url);
                info = processor.getWsdlInfo();
                if (log.isDebugEnabled()) {
                    log.debug("Successfully validated WSDL URL " + url);
                }
            } else {
                if (fileDetail.getFileName().endsWith(".zip")) {
                    WSDLArchiveInfo archiveInfo = apiPublisher.extractAndValidateWSDLArchive(fileInputStream);
                    info = archiveInfo.getWsdlInfo();
                    if (log.isDebugEnabled()) {
                        log.debug("Successfully validated WSDL archive " + fileDetail.getFileName());
                    }
                } else if (fileDetail.getFileName().endsWith(".wsdl")) {
                    byte[] wsdlContent = IOUtils.toByteArray(fileInputStream);
                    processor = WSDLProcessFactory.getInstance().getWSDLProcessor(wsdlContent);
                    info = processor.getWsdlInfo();
                    if (log.isDebugEnabled()) {
                        log.debug("Successfully validated 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();
                }
            }
            if (info != null) {
                APIDefinitionValidationResponseDTO responseDTO = MappingUtil.toWSDLValidationResponseDTO(info);
                return Response.ok(responseDTO).build();
            }
            APIDefinitionValidationResponseDTO responseDTO = new APIDefinitionValidationResponseDTO();
            responseDTO.isValid(false);
            return Response.ok().entity(responseDTO).build();
        }
    } catch (APIManagementException e) {
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } catch (IOException e) {
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorMessage, 900313L, errorMessage);
        log.error(errorMessage, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorDTO).build();
    }
}
Also used : WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) Response(javax.ws.rs.core.Response) WSDLProcessor(org.wso2.carbon.apimgt.core.api.WSDLProcessor) WSDLInfo(org.wso2.carbon.apimgt.core.models.WSDLInfo) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) WSDLArchiveInfo(org.wso2.carbon.apimgt.core.models.WSDLArchiveInfo) IOException(java.io.IOException) APIDefinitionValidationResponseDTO(org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDefinitionValidationResponseDTO)

Example 20 with Wsdl

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

the class ApisApiServiceImplTestCase method testApisApiIdWsdlGetException.

@Test
public void testApisApiIdWsdlGetException() throws Exception {
    printTestMethodName();
    final String uuid = "11112222-3333-4444-5555-666677778888";
    ApisApiServiceImpl apisApiService = new ApisApiServiceImpl();
    APIStore apiStore = Mockito.mock(APIStoreImpl.class);
    PowerMockito.mockStatic(RestApiUtil.class);
    PowerMockito.when(RestApiUtil.getConsumer(USER)).thenReturn(apiStore);
    Request request = getRequest();
    PowerMockito.when(RestApiUtil.getLoggedInUsername(request)).thenReturn(USER);
    Mockito.doReturn(true).when(apiStore).isWSDLExists(uuid);
    Mockito.doReturn(false).when(apiStore).isWSDLArchiveExists(uuid);
    Mockito.doThrow(new APIMgtWSDLException("Error while retrieving WSDL", ExceptionCodes.INTERNAL_WSDL_EXCEPTION)).when(apiStore).getAPIWSDL(uuid, "Sample");
    Response response = apisApiService.apisApiIdWsdlGet(uuid, "Sample", null, null, request);
    assertEquals(response.getStatus(), 500);
}
Also used : Response(javax.ws.rs.core.Response) APIMgtWSDLException(org.wso2.carbon.apimgt.core.exception.APIMgtWSDLException) Request(org.wso2.msf4j.Request) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)64 IOException (java.io.IOException)42 APIMgtWSDLException (org.wso2.carbon.apimgt.impl.wsdl.exceptions.APIMgtWSDLException)33 Test (org.junit.Test)30 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)29 API (org.wso2.carbon.apimgt.core.models.API)28 File (java.io.File)27 APIMgtWSDLException (org.wso2.carbon.apimgt.core.exception.APIMgtWSDLException)24 ByteArrayInputStream (java.io.ByteArrayInputStream)23 FileInputStream (java.io.FileInputStream)23 InputStream (java.io.InputStream)22 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)22 WSDLException (javax.wsdl.WSDLException)21 HashMap (java.util.HashMap)20 Resource (org.wso2.carbon.registry.core.Resource)20 MalformedURLException (java.net.MalformedURLException)18 Map (java.util.Map)16 Response (javax.ws.rs.core.Response)16 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)16 SAXException (org.xml.sax.SAXException)16