Search in sources :

Example 56 with Resource

use of org.wso2.carbon.registry.api.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 57 with Resource

use of org.wso2.carbon.registry.api.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 58 with Resource

use of org.wso2.carbon.registry.api.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)

Example 59 with Resource

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

the class APIStoreImpl method addCompositeApiFromDefinition.

/**
 * {@inheritDoc}
 */
@Override
public String addCompositeApiFromDefinition(String swaggerResourceUrl) throws APIManagementException {
    try {
        URL url = new URL(swaggerResourceUrl);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod(APIMgtConstants.HTTP_GET);
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            String responseStr = new String(IOUtils.toByteArray(urlConn.getInputStream()), StandardCharsets.UTF_8);
            CompositeAPI.Builder apiBuilder = apiDefinitionFromSwagger20.generateCompositeApiFromSwaggerResource(getUsername(), responseStr);
            apiBuilder.apiDefinition(responseStr);
            addCompositeApi(apiBuilder);
            return apiBuilder.getId();
        } else {
            throw new APIManagementException("Error while getting swagger resource from url : " + url, ExceptionCodes.API_DEFINITION_MALFORMED);
        }
    } catch (UnsupportedEncodingException e) {
        String msg = "Unsupported encoding exception while getting the swagger resource from url";
        log.error(msg, e);
        throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
    } catch (ProtocolException e) {
        String msg = "Protocol exception while getting the swagger resource from url";
        log.error(msg, e);
        throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
    } catch (MalformedURLException e) {
        String msg = "Malformed url while getting the swagger resource from url";
        log.error(msg, e);
        throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
    } catch (IOException e) {
        String msg = "Error while getting the swagger resource from url";
        log.error(msg, e);
        throw new APIManagementException(msg, ExceptionCodes.API_DEFINITION_MALFORMED);
    }
}
Also used : ProtocolException(java.net.ProtocolException) MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) URL(java.net.URL)

Example 60 with Resource

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

the class KubernetesGatewayImpl method createServiceResource.

/**
 * Create a service in cms
 *
 * @param serviceTemplate Service template as a String
 * @param serviceName     Name of the service
 * @throws ContainerBasedGatewayException if failed to create a service
 */
private void createServiceResource(String serviceTemplate, String serviceName) throws ContainerBasedGatewayException {
    HasMetadata resource = getResourcesFromTemplate(serviceTemplate);
    try {
        if (resource instanceof Service) {
            // check whether there are existing service already
            if (client.services().inNamespace(namespace).withName(serviceName).get() == null) {
                log.debug("Deploying in CMS type: {} and the Service resource definition: {} ", cmsType, serviceTemplate);
                Service service = (Service) resource;
                Service result = client.services().inNamespace(namespace).create(service);
                log.info("Created Service : " + result.getMetadata().getName() + " in Namespace : " + result.getMetadata().getNamespace() + " in " + cmsType);
            } else {
                log.info("There exist a service with the same name in " + cmsType + ". Service name : " + serviceName);
            }
        } else {
            throw new ContainerBasedGatewayException("Loaded Resource is not a Service in " + cmsType + "! " + resource, ExceptionCodes.LOADED_RESOURCE_DEFINITION_IS_NOT_VALID);
        }
    } catch (KubernetesClientException e) {
        throw new ContainerBasedGatewayException("Error while creating container based gateway service in " + cmsType + "!", e, ExceptionCodes.DEDICATED_CONTAINER_GATEWAY_CREATION_FAILED);
    }
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Service(io.fabric8.kubernetes.api.model.Service) ContainerBasedGatewayException(org.wso2.carbon.apimgt.core.exception.ContainerBasedGatewayException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

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