Search in sources :

Example 56 with Resource

use of org.wso2.carbon.registry.core.Resource in project carbon-apimgt by wso2.

the class SubscriptionsApiServiceImpl method subscriptionsPost.

/**
 * Adds a new subscription
 *
 * @param body        Subscription details to be added
 * @param request     msf4j request object
 * @return Newly added subscription as the response
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response subscriptionsPost(SubscriptionDTO body, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    SubscriptionDTO subscriptionDTO = null;
    URI location = null;
    try {
        APIStore apiStore = RestApiUtil.getConsumer(username);
        String applicationId = body.getApplicationId();
        String apiId = body.getApiIdentifier();
        String tier = body.getPolicy();
        Application application = apiStore.getApplicationByUuid(applicationId);
        if (application != null && !ApplicationStatus.APPLICATION_APPROVED.equals(application.getStatus())) {
            String errorMessage = "Application " + applicationId + " is not active";
            ExceptionCodes exceptionCode = ExceptionCodes.APPLICATION_INACTIVE;
            APIManagementException e = new APIManagementException(errorMessage, exceptionCode);
            Map<String, String> paramList = new HashMap<>();
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
            log.error(errorMessage, e);
            return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
        }
        if (application != null) {
            SubscriptionResponse addSubResponse = apiStore.addApiSubscription(apiId, applicationId, tier);
            String subscriptionId = addSubResponse.getSubscriptionUUID();
            Subscription subscription = apiStore.getSubscriptionByUUID(subscriptionId);
            location = new URI(RestApiConstants.RESOURCE_PATH_SUBSCRIPTION + "/" + subscriptionId);
            subscriptionDTO = SubscriptionMappingUtil.fromSubscriptionToDTO(subscription);
            // be in either pending or approved state) send back the workflow response
            if (SubscriptionStatus.ON_HOLD == subscription.getStatus()) {
                WorkflowResponseDTO workflowResponse = MiscMappingUtil.fromWorkflowResponseToDTO(addSubResponse.getWorkflowResponse());
                return Response.status(Response.Status.ACCEPTED).header(RestApiConstants.LOCATION_HEADER, location).entity(workflowResponse).build();
            }
        } else {
            String errorMessage = null;
            ExceptionCodes exceptionCode = null;
            exceptionCode = ExceptionCodes.APPLICATION_NOT_FOUND;
            errorMessage = "Application not found";
            APIMgtResourceNotFoundException e = new APIMgtResourceNotFoundException(errorMessage, exceptionCode);
            Map<String, String> paramList = new HashMap<>();
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
            log.error(errorMessage, e);
            return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
        }
    } catch (GatewayException e) {
        String errorMessage = "Failed to add subscription of API : " + body.getApiIdentifier() + " to gateway";
        log.error(errorMessage, e);
        return Response.status(Response.Status.ACCEPTED).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while adding subscriptions";
        Map<String, String> paramList = new HashMap<>();
        paramList.put(APIMgtConstants.ExceptionsConstants.API_ID, body.getApiIdentifier());
        paramList.put(APIMgtConstants.ExceptionsConstants.APPLICATION_ID, body.getApplicationId());
        paramList.put(APIMgtConstants.ExceptionsConstants.TIER, body.getPolicy());
        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 adding location header in response for subscription : " + body.getSubscriptionId();
        Map<String, String> paramList = new HashMap<>();
        paramList.put(APIMgtConstants.ExceptionsConstants.SUBSCRIPTION_ID, body.getSubscriptionId());
        ErrorHandler errorHandler = ExceptionCodes.LOCATION_HEADER_INCORRECT;
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorHandler, paramList);
        log.error(errorMessage, e);
        return Response.status(errorHandler.getHttpStatusCode()).entity(errorDTO).build();
    }
    return Response.status(Response.Status.CREATED).header(RestApiConstants.LOCATION_HEADER, location).entity(subscriptionDTO).build();
}
Also used : ErrorHandler(org.wso2.carbon.apimgt.core.exception.ErrorHandler) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) URISyntaxException(java.net.URISyntaxException) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException) URI(java.net.URI) WorkflowResponseDTO(org.wso2.carbon.apimgt.rest.api.store.dto.WorkflowResponseDTO) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) SubscriptionResponse(org.wso2.carbon.apimgt.core.models.SubscriptionResponse) ExceptionCodes(org.wso2.carbon.apimgt.core.exception.ExceptionCodes) Subscription(org.wso2.carbon.apimgt.core.models.Subscription) SubscriptionDTO(org.wso2.carbon.apimgt.rest.api.store.dto.SubscriptionDTO) Application(org.wso2.carbon.apimgt.core.models.Application) HashMap(java.util.HashMap) Map(java.util.Map) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Example 57 with Resource

use of org.wso2.carbon.registry.core.Resource in project carbon-apimgt by wso2.

the class TagsApiServiceImpl method tagsGet.

/**
 * Retrieve tags of APIs
 *
 * @param limit       Maximum number of tags to return
 * @param offset      Starting position of the pagination
 * @param ifNoneMatch If-None-Match header value
 * @param request     msf4j request object
 * @return A list of qualifying tags as the response
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response tagsGet(Integer limit, Integer offset, String ifNoneMatch, Request request) throws NotFoundException {
    TagListDTO tagListDTO = null;
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        APIStore apiStore = RestApiUtil.getConsumer(username);
        List<Tag> tagList = apiStore.getAllTags();
        tagListDTO = TagMappingUtil.fromTagListToDTO(tagList, limit, offset);
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving tags";
        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();
    }
    return Response.ok().entity(tagListDTO).build();
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) TagListDTO(org.wso2.carbon.apimgt.rest.api.store.dto.TagListDTO) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) Tag(org.wso2.carbon.apimgt.core.models.Tag) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Example 58 with Resource

use of org.wso2.carbon.registry.core.Resource in project carbon-apimgt by wso2.

the class CompositeApisApiServiceImpl method compositeApisApiIdGet.

/**
 * Retrives an API by UUID
 *
 * @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 API which is identified by the given UUID
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response compositeApisApiIdGet(String apiId, String ifNoneMatch, String ifModifiedSince, Request request) throws NotFoundException {
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        if (!RestApiUtil.getConsumer(username).isCompositeAPIExist(apiId)) {
            String errorMessage = "API not found : " + apiId;
            APIMgtResourceNotFoundException e = new APIMgtResourceNotFoundException(errorMessage, ExceptionCodes.API_NOT_FOUND);
            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();
        }
        String existingFingerprint = compositeApisApiIdGetFingerprint(apiId, ifNoneMatch, ifModifiedSince, request);
        if (!StringUtils.isEmpty(ifNoneMatch) && !StringUtils.isEmpty(existingFingerprint) && ifNoneMatch.contains(existingFingerprint)) {
            return Response.notModified().build();
        }
        CompositeAPIDTO apidto = CompositeAPIMappingUtil.toCompositeAPIDTO(RestApiUtil.getConsumer(username).getCompositeAPIbyId(apiId));
        return Response.ok().header(HttpHeaders.ETAG, "\"" + existingFingerprint + "\"").entity(apidto).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving 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) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) CompositeAPIDTO(org.wso2.carbon.apimgt.rest.api.store.dto.CompositeAPIDTO) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.core.exception.APIMgtResourceNotFoundException)

Example 59 with Resource

use of org.wso2.carbon.registry.core.Resource in project carbon-apimgt by wso2.

the class ExportApiServiceImpl method exportApplicationsGet.

/**
 * Export an existing Application
 *
 * @param appId   Search query
 * @param request msf4j request object
 * @return Zip file containing exported Applications
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response exportApplicationsGet(String appId, Request request) throws NotFoundException {
    APIStore consumer = null;
    String exportedFilePath, zippedFilePath = null;
    Application applicationDetails;
    String exportedAppDirName = "exported-application";
    String pathToExportDir = System.getProperty("java.io.tmpdir") + File.separator + "exported-app-archives-" + // creates a directory in default temporary-file directory
    UUID.randomUUID().toString();
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        consumer = RestApiUtil.getConsumer(username);
        FileBasedApplicationImportExportManager importExportManager = new FileBasedApplicationImportExportManager(consumer, pathToExportDir);
        applicationDetails = importExportManager.getApplicationDetails(appId, username);
        if (applicationDetails == null) {
            // 404
            String errorMsg = "No application found for query " + appId;
            log.error(errorMsg);
            HashMap<String, String> paramList = new HashMap<>();
            paramList.put("query", appId);
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(ExceptionCodes.APPLICATION_NOT_FOUND, paramList);
            return Response.status(Response.Status.NOT_FOUND).entity(errorDTO).build();
        }
        exportedFilePath = importExportManager.exportApplication(applicationDetails, exportedAppDirName);
        zippedFilePath = importExportManager.createArchiveFromExportedAppArtifacts(exportedFilePath, pathToExportDir, exportedAppDirName);
    } catch (APIManagementException e) {
        String errorMessage = "Error while exporting Application";
        log.error(errorMessage, e);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
    File exportedApplicationArchiveFile = new File(zippedFilePath);
    Response.ResponseBuilder responseBuilder = Response.status(Response.Status.OK).entity(exportedApplicationArchiveFile);
    responseBuilder.header("Content-Disposition", "attachment; filename=\"" + exportedApplicationArchiveFile.getName() + "\"");
    Response response = responseBuilder.build();
    return response;
}
Also used : Response(javax.ws.rs.core.Response) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) FileBasedApplicationImportExportManager(org.wso2.carbon.apimgt.rest.api.store.utils.FileBasedApplicationImportExportManager) Application(org.wso2.carbon.apimgt.core.models.Application) File(java.io.File) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Example 60 with Resource

use of org.wso2.carbon.registry.core.Resource in project carbon-apimgt by wso2.

the class ImportApiServiceImpl method importApplicationsPost.

/**
 * Import an Application which has been exported to a zip file
 *
 * @param fileInputStream content stream of the zip file which contains exported Application
 * @param fileDetail      meta information of the zip file
 * @param request         msf4j request object
 * @return Application that was imported
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response importApplicationsPost(InputStream fileInputStream, FileInfo fileDetail, Request request) throws NotFoundException {
    APIStore consumer = null;
    String username = RestApiUtil.getLoggedInUsername(request);
    try {
        consumer = RestApiUtil.getConsumer(username);
        FileBasedApplicationImportExportManager importExportManager = new FileBasedApplicationImportExportManager(consumer, System.getProperty("java.io.tmpdir") + File.separator + "exported-app-archives-" + UUID.randomUUID().toString());
        Application applicationDetails = importExportManager.importApplication(fileInputStream);
        applicationDetails.setCreatedUser(username);
        applicationDetails.setUpdatedUser(username);
        ApplicationCreationResponse response = consumer.addApplication(applicationDetails);
        return Response.status(Response.Status.OK).entity(response).build();
    } catch (APIManagementException e) {
        String errorMsg = "Error while importing the Applications";
        log.error(errorMsg, e);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : ApplicationCreationResponse(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) FileBasedApplicationImportExportManager(org.wso2.carbon.apimgt.rest.api.store.utils.FileBasedApplicationImportExportManager) Application(org.wso2.carbon.apimgt.core.models.Application) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)111 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)102 HashMap (java.util.HashMap)91 Test (org.testng.annotations.Test)64 HTTPCarbonMessage (org.wso2.transport.http.netty.message.HTTPCarbonMessage)59 HTTPTestRequest (org.ballerinalang.test.services.testutils.HTTPTestRequest)56 HttpMessageDataStreamer (org.wso2.transport.http.netty.message.HttpMessageDataStreamer)53 BJSON (org.ballerinalang.model.values.BJSON)46 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)38 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)29 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)27 APIMgtAdminService (org.wso2.carbon.apimgt.core.api.APIMgtAdminService)24 CharonException (org.wso2.charon3.core.exceptions.CharonException)24 IOException (java.io.IOException)23 Map (java.util.Map)20 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)20 NotFoundException (org.wso2.charon3.core.exceptions.NotFoundException)17 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)17 ArrayList (java.util.ArrayList)15 InternalErrorException (org.wso2.charon3.core.exceptions.InternalErrorException)15