Search in sources :

Example 16 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO in project carbon-apimgt by wso2.

the class CompositeApisApiServiceImpl method compositeApisApiIdPut.

/**
 * Updates an API by UUID
 *
 * @param apiId             UUID of API
 * @param body              Updated API details
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @param request           msf4j request object
 * @return Updated API
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response compositeApisApiIdPut(String apiId, CompositeAPIDTO body, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIStore apiStore = RestApiUtil.getConsumer(username);
        String existingFingerprint = compositeApisApiIdGetFingerprint(apiId, null, null, request);
        if (!StringUtils.isEmpty(ifMatch) && !StringUtils.isEmpty(existingFingerprint) && !ifMatch.contains(existingFingerprint)) {
            return Response.status(Response.Status.PRECONDITION_FAILED).build();
        }
        CompositeAPI.Builder api = CompositeAPIMappingUtil.toAPI(body).id(apiId);
        apiStore.updateCompositeApi(api);
        String newFingerprint = compositeApisApiIdGetFingerprint(apiId, null, null, request);
        CompositeAPIDTO apidto = CompositeAPIMappingUtil.toCompositeAPIDTO(apiStore.getCompositeAPIbyId(apiId));
        return Response.ok().header(HttpHeaders.ETAG, "\"" + newFingerprint + "\"").entity(apidto).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) CompositeAPIDTO(org.wso2.carbon.apimgt.rest.api.store.dto.CompositeAPIDTO) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Example 17 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO in project carbon-apimgt by wso2.

the class APIMappingUtil method toAPIDTO.

/**
 * Converts {@link APIDTO} to a {@link API}.
 *
 * @param api API
 * @return API DTO
 */
public static APIDTO toAPIDTO(API api) {
    APIDTO apiDTO = new APIDTO();
    apiDTO.setId(api.getId());
    apiDTO.setName(api.getName());
    apiDTO.setProvider(api.getProvider());
    apiDTO.setLifeCycleStatus(api.getLifeCycleStatus());
    apiDTO.setVersion(api.getVersion());
    apiDTO.setContext(api.getContext());
    apiDTO.setDescription(api.getDescription());
    api.getPolicies().forEach(policy -> apiDTO.addPoliciesItem(policy.getPolicyName()));
    apiDTO.setLabels(new ArrayList<>(api.getLabels()));
    return apiDTO;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.store.dto.APIDTO)

Example 18 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO 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 19 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisPost.

/**
 * Creates a new API
 *
 * @param body    DTO model including the API details
 * @param request msf4j request object
 * @return Newly created API
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response apisPost(APIDTO body, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        API.APIBuilder apiBuilder = MappingUtil.toAPI(body);
        APIPublisher apiPublisher = RestAPIPublisherUtil.getApiPublisher(username);
        apiPublisher.addAPI(apiBuilder);
        API returnAPI = apiPublisher.getAPIbyUUID(apiBuilder.getId());
        return Response.status(Response.Status.CREATED).entity(MappingUtil.toAPIDto(returnAPI)).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding new API : " + body.getProvider() + "-" + body.getName() + "-" + body.getVersion();
        HashMap<String, String> paramList = new HashMap<String, String>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_NAME, body.getName());
        paramList.put(APIMgtConstants.ExceptionsConstants.API_VERSION, body.getVersion());
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } catch (JsonProcessingException 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();
    } 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 : 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) API(org.wso2.carbon.apimgt.core.models.API) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 20 with APIDTO

use of org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO in project carbon-apimgt by wso2.

the class ApisApiServiceImplTestCase method testApisApiIdPutException.

@Test
public void testApisApiIdPutException() throws Exception {
    printTestMethodName();
    ApisApiServiceImpl apisApiService = new ApisApiServiceImpl();
    APIPublisher apiPublisher = Mockito.mock(APIPublisherImpl.class);
    PowerMockito.mockStatic(RestAPIPublisherUtil.class);
    PowerMockito.when(RestAPIPublisherUtil.getApiPublisher(USER)).thenReturn(apiPublisher);
    String apiId = UUID.randomUUID().toString();
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI();
    API api = apiBuilder.id(apiId).build();
    APIDTO apidto = MappingUtil.toAPIDto(api);
    Mockito.when(apiPublisher.getApiSwaggerDefinition(apiId)).thenReturn(SampleTestObjectCreator.apiDefinition);
    Mockito.doNothing().doThrow(new IllegalArgumentException()).when(apiPublisher).updateAPI(apiBuilder);
    Mockito.doThrow(new APIManagementException("Error occurred", ExceptionCodes.API_TYPE_INVALID)).when(apiPublisher).getAPIbyUUID(apiId);
    Response response = apisApiService.apisApiIdPut(apiId, apidto, null, null, getRequest());
    assertEquals(response.getStatus(), 400);
    assertTrue(response.getEntity().toString().contains("API Type specified is invalid"));
}
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) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIPublisher(org.wso2.carbon.apimgt.core.api.APIPublisher) API(org.wso2.carbon.apimgt.core.models.API) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

API (org.wso2.carbon.apimgt.core.models.API)17 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO)15 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)11 Response (javax.ws.rs.core.Response)10 Test (org.junit.Test)10 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)10 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)10 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)10 HashMap (java.util.HashMap)9 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)8 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)6 File (java.io.File)5 FileInputStream (java.io.FileInputStream)5 IOException (java.io.IOException)5 FileInfo (org.wso2.msf4j.formparam.FileInfo)5 APIDTO (org.wso2.carbon.apimgt.rest.api.store.dto.APIDTO)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 ArrayList (java.util.ArrayList)2 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)2