Search in sources :

Example 71 with APIDTO

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

the class ApisApiServiceImpl method updateAPI.

@Override
public Response updateAPI(String apiId, APIDTO body, String ifMatch, MessageContext messageContext) {
    String[] tokenScopes = (String[]) PhaseInterceptorChain.getCurrentMessage().getExchange().get(RestApiConstants.USER_REST_API_SCOPES);
    String username = RestApiCommonUtil.getLoggedInUsername();
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // validate if api exists
        validateAPIExistence(apiId);
        // validate sandbox and production endpoints
        if (!PublisherCommonUtils.validateEndpoints(body)) {
            throw new APIManagementException("Invalid/Malformed endpoint URL(s) detected", ExceptionCodes.INVALID_ENDPOINT_URL);
        }
        APIProvider apiProvider = RestApiCommonUtil.getProvider(username);
        API originalAPI = apiProvider.getAPIbyUUID(apiId, organization);
        originalAPI.setOrganization(organization);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(originalAPI.getStatus());
        API updatedApi = PublisherCommonUtils.updateApi(originalAPI, body, apiProvider, tokenScopes);
        return Response.ok().entity(APIMappingUtil.fromAPItoDTO(updatedApi)).build();
    } catch (APIManagementException e) {
        // to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure("Authorization failure while updating API : " + apiId, e, log);
        } else {
            String errorMessage = "Error while updating the API : " + apiId + " - " + e.getMessage();
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    } catch (FaultGatewaysException e) {
        String errorMessage = "Error while updating API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (CryptoException e) {
        String errorMessage = "Error while encrypting the secret key of API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } catch (ParseException e) {
        String errorMessage = "Error while parsing endpoint config of API : " + apiId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ParseException(org.json.simple.parser.ParseException) CryptoException(org.wso2.carbon.core.util.CryptoException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider)

Example 72 with APIDTO

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

the class ApisApiServiceImpl method createAPIDTO.

private APIDTO createAPIDTO(API existingAPI, String newVersion) {
    APIDTO apidto = new APIDTO();
    apidto.setName(existingAPI.getId().getApiName());
    apidto.setContext(existingAPI.getContextTemplate());
    apidto.setVersion(newVersion);
    return apidto;
}
Also used : APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)

Example 73 with APIDTO

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

the class ExportUtils method exportApi.

/**
 * Exports an API from API Manager for a given API. Meta information, API icon, documentation,
 * WSDL and sequences are exported.
 *
 * @param apiProvider          API Provider
 * @param apiIdentifier        API Identifier
 * @param apiDtoToReturn       API DTO
 * @param userName             Username
 * @param exportFormat         Format of output documents. Can be YAML or JSON
 * @param preserveStatus       Preserve API status on export
 * @param preserveDocs         Preserve documentation on Export.
 * @param originalDevPortalUrl Original DevPortal URL (redirect URL) for the original Store
 *                             (This is used for advertise only APIs).
 * @param organization          Organization
 * @return
 * @throws APIManagementException If an error occurs while getting governance registry
 */
public static File exportApi(APIProvider apiProvider, APIIdentifier apiIdentifier, APIDTO apiDtoToReturn, API api, String userName, ExportFormat exportFormat, boolean preserveStatus, boolean preserveDocs, String originalDevPortalUrl, String organization) throws APIManagementException, APIImportExportException {
    int tenantId;
    // If explicitly advertise only property has been specified as true, make it true and update the API DTO.
    if (StringUtils.isNotBlank(originalDevPortalUrl)) {
        setAdvertiseOnlySpecificPropertiesToDTO(apiDtoToReturn, originalDevPortalUrl);
    }
    // Create temp location for storing API data
    File exportFolder = CommonUtil.createTempDirectory(apiIdentifier);
    String exportAPIBasePath = exportFolder.toString();
    String archivePath = exportAPIBasePath.concat(File.separator + apiIdentifier.getApiName() + "-" + apiIdentifier.getVersion());
    tenantId = APIUtil.getTenantId(userName);
    CommonUtil.createDirectory(archivePath);
    if (preserveDocs) {
        addThumbnailToArchive(archivePath, apiIdentifier, apiProvider);
        addDocumentationToArchive(archivePath, apiIdentifier, exportFormat, apiProvider, APIConstants.API_IDENTIFIER_TYPE);
    } else {
        if (StringUtils.equals(apiDtoToReturn.getType().toString().toLowerCase(), APIConstants.API_TYPE_SOAPTOREST.toLowerCase())) {
            addSOAPToRESTMediationToArchive(archivePath, api);
        }
    }
    if (StringUtils.equals(apiDtoToReturn.getType().toString().toLowerCase(), APIConstants.API_TYPE_SOAP.toLowerCase()) && preserveDocs) {
        addWSDLtoArchive(archivePath, apiIdentifier, apiProvider);
    } else if (log.isDebugEnabled()) {
        log.debug("No WSDL URL found for API: " + apiIdentifier + ". Skipping WSDL export.");
    }
    // Set API status to created if the status is not preserved
    if (!preserveStatus) {
        apiDtoToReturn.setLifeCycleStatus(APIConstants.CREATED);
    }
    String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
    addOperationPoliciesToArchive(archivePath, apiDtoToReturn.getId(), tenantDomain, exportFormat, apiProvider, api);
    addGatewayEnvironmentsToArchive(archivePath, apiDtoToReturn.getId(), exportFormat, apiProvider);
    if (!ImportUtils.isAdvertiseOnlyAPI(apiDtoToReturn)) {
        addEndpointCertificatesToArchive(archivePath, apiDtoToReturn, tenantId, exportFormat);
        addRuntimeSequencesToArchive(archivePath, api);
        if (preserveDocs) {
            addMultipleAPISpecificSequencesToArchive(archivePath, api, apiProvider);
        }
        // Export mTLS authentication related certificates
        if (log.isDebugEnabled()) {
            log.debug("Mutual SSL enabled. Exporting client certificates.");
        }
        addClientCertificatesToArchive(archivePath, apiIdentifier, tenantId, apiProvider, exportFormat, organization);
    }
    addAPIMetaInformationToArchive(archivePath, apiDtoToReturn, exportFormat, apiProvider, apiIdentifier, organization);
    CommonUtil.archiveDirectory(exportAPIBasePath);
    FileUtils.deleteQuietly(new File(exportAPIBasePath));
    return new File(exportAPIBasePath + APIConstants.ZIP_FILE_EXTENSION);
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Example 74 with APIDTO

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

the class ImportUtils method validateWSDLFromArchive.

/**
 * Validate WSDL definition from the archive directory and return it.
 *
 * @param pathToArchive Path to API archive
 * @throws APIImportExportException If an error due to an invalid WSDL definition
 */
private static void validateWSDLFromArchive(String pathToArchive, APIDTO apiDto) throws APIManagementException {
    try {
        byte[] wsdlDefinition = loadWsdlFile(pathToArchive, apiDto);
        WSDLValidationResponse wsdlValidationResponse = APIMWSDLReader.getWsdlValidationResponse(APIMWSDLReader.getWSDLProcessor(wsdlDefinition));
        if (!wsdlValidationResponse.isValid()) {
            throw new APIManagementException("Error occurred while importing the API. Invalid WSDL definition found. " + wsdlValidationResponse.getError());
        }
    } catch (IOException | APIManagementException e) {
        throw new APIManagementException("Error while reading API meta information from path: " + pathToArchive, e, ExceptionCodes.ERROR_READING_META_DATA);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) WSDLValidationResponse(org.wso2.carbon.apimgt.impl.wsdl.model.WSDLValidationResponse) IOException(java.io.IOException)

Example 75 with APIDTO

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

the class APIControllerUtil method injectEnvParamsToAPI.

/**
 * This method will be used to add Extracted environment parameters to the imported Api object.
 *
 * @param pathToArchive  Path to API or API Product archive
 * @param importedApiDto APIDTO object to be imported
 * @param envParams      Env params object with required parameters
 * @return API Updated API Object
 * @throws APIManagementException If an error occurs merging env parameters with api
 */
public static APIDTO injectEnvParamsToAPI(APIDTO importedApiDto, JsonObject envParams, String pathToArchive) throws APIManagementException {
    if (envParams == null || envParams.isJsonNull()) {
        return importedApiDto;
    }
    API importedApi = APIMappingUtil.fromDTOtoAPI(importedApiDto, importedApiDto.getProvider());
    // if endpointType field is not specified in the params file, it will be considered as HTTP/REST
    JsonElement endpointTypeElement = envParams.get(ImportExportConstants.ENDPOINT_TYPE_FIELD);
    String endpointType = null;
    if (endpointTypeElement != null) {
        endpointType = endpointTypeElement.getAsString();
    } else {
        endpointType = ImportExportConstants.REST_TYPE_ENDPOINT;
    }
    // Handle multiple end points
    JsonObject jsonObject = setupMultipleEndpoints(envParams, endpointType);
    // Handle endpoint security configs
    if (envParams.get(ImportExportConstants.ENDPOINT_SECURITY_FIELD) != null) {
        handleEndpointSecurityConfigs(envParams, jsonObject);
    }
    ObjectMapper mapper = new ObjectMapper();
    HashMap<String, Object> endpointConfig;
    try {
        endpointConfig = mapper.readValue(jsonObject.toString(), HashMap.class);
        convertValuesToStrings(endpointConfig);
    } catch (JsonProcessingException e) {
        String errorMessage = "Error while reading endpointConfig information in the params file.";
        throw new APIManagementException(errorMessage, e, ExceptionCodes.ERROR_READING_PARAMS_FILE);
    }
    importedApiDto.setEndpointConfig(endpointConfig);
    // handle mutualSSL certificates
    handleMutualSslCertificates(envParams, importedApiDto, null, importedApi.getId(), pathToArchive);
    // handle endpoint certificates
    JsonElement endpointCertificates = envParams.get(ImportExportConstants.ENDPOINT_CERTIFICATES_FIELD);
    if (endpointCertificates != null) {
        try {
            String jsonString = endpointCertificates.toString();
            handleEndpointCertificates(new JsonParser().parse(jsonString).getAsJsonArray(), pathToArchive);
        } catch (IOException e) {
            // Error is logged and when generating certificate details and certs in the archive
            String errorMessage = "Error while generating meta information of client certificates from path.";
            throw new APIManagementException(errorMessage, e, ExceptionCodes.ERROR_READING_PARAMS_FILE);
        }
    }
    // handle available subscription policies
    JsonElement policies = envParams.get(ImportExportConstants.POLICIES_FIELD);
    if (policies != null && !policies.isJsonNull()) {
        handleSubscriptionPolicies(policies, importedApiDto, null);
    }
    return importedApiDto;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HashMap(java.util.HashMap) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject) API(org.wso2.carbon.apimgt.api.model.API) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonParser(com.google.gson.JsonParser)

Aggregations

APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)29 HashMap (java.util.HashMap)28 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)27 ArrayList (java.util.ArrayList)25 API (org.wso2.carbon.apimgt.api.model.API)25 IOException (java.io.IOException)18 API (org.wso2.carbon.apimgt.core.models.API)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)15 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.dto.APIDTO)15 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)14 File (java.io.File)12 Response (javax.ws.rs.core.Response)12 Map (java.util.Map)11 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)11 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)11 Test (org.junit.Test)10 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)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