Search in sources :

Example 11 with APIInfo

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

the class ApiMgtDAO method getAPIInfoByUUID.

/**
 * Retrieve basic information about the given API by the UUID quering only from AM_API
 *
 * @param apiId UUID of the API
 * @return basic information about the API
 * @throws APIManagementException error while getting the API information from AM_API
 */
public APIInfo getAPIInfoByUUID(String apiId) throws APIManagementException {
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        APIRevision apiRevision = getRevisionByRevisionUUID(connection, apiId);
        String sql = SQLConstants.RETRIEVE_API_INFO_FROM_UUID;
        try (PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            if (apiRevision != null) {
                preparedStatement.setString(1, apiRevision.getApiUUID());
            } else {
                preparedStatement.setString(1, apiId);
            }
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                if (resultSet.next()) {
                    APIInfo.Builder apiInfoBuilder = new APIInfo.Builder();
                    apiInfoBuilder = apiInfoBuilder.id(resultSet.getString("API_UUID")).name(resultSet.getString("API_NAME")).version(resultSet.getString("API_VERSION")).provider(resultSet.getString("API_PROVIDER")).context(resultSet.getString("CONTEXT")).contextTemplate(resultSet.getString("CONTEXT_TEMPLATE")).status(APIUtil.getApiStatus(resultSet.getString("STATUS"))).apiType(resultSet.getString("API_TYPE")).createdBy(resultSet.getString("CREATED_BY")).createdTime(resultSet.getString("CREATED_TIME")).updatedBy(resultSet.getString("UPDATED_BY")).updatedTime(resultSet.getString("UPDATED_TIME")).revisionsCreated(resultSet.getInt("REVISIONS_CREATED")).isRevision(apiRevision != null);
                    if (apiRevision != null) {
                        apiInfoBuilder = apiInfoBuilder.apiTier(getAPILevelTier(connection, apiRevision.getApiUUID(), apiId));
                    } else {
                        apiInfoBuilder = apiInfoBuilder.apiTier(resultSet.getString("API_TIER"));
                    }
                    return apiInfoBuilder.build();
                }
            }
        }
    } catch (SQLException e) {
        throw new APIManagementException("Error while retrieving apimgt connection", e, ExceptionCodes.INTERNAL_ERROR);
    }
    return null;
}
Also used : DeployedAPIRevision(org.wso2.carbon.apimgt.api.model.DeployedAPIRevision) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) PreparedStatement(java.sql.PreparedStatement)

Example 12 with APIInfo

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

the class APIProviderImpl method generateApiKey.

@Override
public String generateApiKey(String apiId) throws APIManagementException {
    APIInfo apiInfo = apiMgtDAO.getAPIInfoByUUID(apiId);
    if (apiInfo == null) {
        throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with ID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
    }
    SubscribedApiDTO subscribedApiInfo = new SubscribedApiDTO();
    subscribedApiInfo.setName(apiInfo.getName());
    subscribedApiInfo.setContext(apiInfo.getContext());
    subscribedApiInfo.setPublisher(apiInfo.getProvider());
    subscribedApiInfo.setVersion(apiInfo.getVersion());
    JwtTokenInfoDTO jwtTokenInfoDTO = new JwtTokenInfoDTO();
    jwtTokenInfoDTO.setEndUserName(username);
    jwtTokenInfoDTO.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
    jwtTokenInfoDTO.setSubscribedApiDTOList(Arrays.asList(subscribedApiInfo));
    jwtTokenInfoDTO.setExpirationTime(60 * 1000);
    ApiKeyGenerator apiKeyGenerator = new InternalAPIKeyGenerator();
    return apiKeyGenerator.generateToken(jwtTokenInfoDTO);
}
Also used : SubscribedApiDTO(org.wso2.carbon.apimgt.impl.dto.SubscribedApiDTO) InternalAPIKeyGenerator(org.wso2.carbon.apimgt.impl.token.InternalAPIKeyGenerator) JwtTokenInfoDTO(org.wso2.carbon.apimgt.impl.dto.JwtTokenInfoDTO) PublisherAPIInfo(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIInfo) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) ApiKeyGenerator(org.wso2.carbon.apimgt.impl.token.ApiKeyGenerator) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)

Example 13 with APIInfo

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

the class ApisApiServiceImpl method apisApiIdAsyncapiPut.

@Override
public Response apisApiIdAsyncapiPut(String apiId, String ifMatch, String apiDefinition, String url, InputStream fileInputStream, Attachment fileDetail, MessageContext messageContext) throws APIManagementException {
    try {
        String updatedAsyncAPIDefinition;
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        // validate if api exists
        APIInfo apiInfo = validateAPIExistence(apiId);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(apiInfo.getStatus().toString());
        // Handle URL and file based definition imports
        if (url != null || fileInputStream != null) {
            // Validate and retrieve the AsyncAPI definition
            Map validationResponseMap = validateAsyncAPISpecification(url, fileInputStream, fileDetail, true, false);
            APIDefinitionValidationResponse validationResponse = (APIDefinitionValidationResponse) validationResponseMap.get(RestApiConstants.RETURN_MODEL);
            if (!validationResponse.isValid()) {
                RestApiUtil.handleBadRequest(validationResponse.getErrorItems(), log);
            }
            updatedAsyncAPIDefinition = PublisherCommonUtils.updateAsyncAPIDefinition(apiId, validationResponse, organization);
        } else {
            updatedAsyncAPIDefinition = updateAsyncAPIDefinition(apiId, apiDefinition, organization);
        }
        return Response.ok().entity(updatedAsyncAPIDefinition).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 AsyncAPI definition of API: " + apiId, e, log);
        } else {
            String errorMessage = "Error while updating the AsyncAPI definition of 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);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)

Example 14 with APIInfo

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

the class ApisApiServiceImpl method addAPIDocumentContent.

/**
 * Add content to a document. Content can be inline or File
 *
 * @param apiId         API identifier
 * @param documentId    document identifier
 * @param inputStream   file input stream
 * @param fileDetail    file details as Attachment
 * @param inlineContent inline content for the document
 * @param ifMatch       If-match header value
 * @return updated document as DTO
 */
@Override
public Response addAPIDocumentContent(String apiId, String documentId, String ifMatch, InputStream inputStream, Attachment fileDetail, String inlineContent, MessageContext messageContext) {
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        // validate if api exists
        APIInfo apiInfo = validateAPIExistence(apiId);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(apiInfo.getStatus().toString());
        if (inputStream != null && inlineContent != null) {
            RestApiUtil.handleBadRequest("Only one of 'file' and 'inlineContent' should be specified", log);
        }
        // retrieves the document and send 404 if not found
        Documentation documentation = apiProvider.getDocumentation(apiId, documentId, organization);
        if (documentation == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_DOCUMENTATION, documentId, log);
            return null;
        }
        // add content depending on the availability of either input stream or inline content
        if (inputStream != null) {
            if (!documentation.getSourceType().equals(Documentation.DocumentSourceType.FILE)) {
                RestApiUtil.handleBadRequest("Source type of document " + documentId + " is not FILE", log);
            }
            String filename = fileDetail.getContentDisposition().getFilename();
            if (APIUtil.isSupportedFileType(filename)) {
                RestApiPublisherUtils.attachFileToDocument(apiId, documentation, inputStream, fileDetail, organization);
            } else {
                RestApiUtil.handleBadRequest("Unsupported extension type of document file: " + filename, log);
            }
        } else if (inlineContent != null) {
            if (!documentation.getSourceType().equals(Documentation.DocumentSourceType.INLINE) && !documentation.getSourceType().equals(Documentation.DocumentSourceType.MARKDOWN)) {
                RestApiUtil.handleBadRequest("Source type of document " + documentId + " is not INLINE " + "or MARKDOWN", log);
            }
            PublisherCommonUtils.addDocumentationContent(documentation, apiProvider, apiId, documentId, organization, inlineContent);
        } else {
            RestApiUtil.handleBadRequest("Either 'file' or 'inlineContent' should be specified", log);
        }
        // retrieving the updated doc and the URI
        Documentation updatedDoc = apiProvider.getDocumentation(apiId, documentId, organization);
        DocumentDTO documentDTO = DocumentationMappingUtil.fromDocumentationToDTO(updatedDoc);
        String uriString = RestApiConstants.RESOURCE_PATH_DOCUMENT_CONTENT.replace(RestApiConstants.APIID_PARAM, apiId).replace(RestApiConstants.DOCUMENTID_PARAM, documentId);
        URI uri = new URI(uriString);
        return Response.created(uri).entity(documentDTO).build();
    } catch (APIManagementException e) {
        // Auth failure occurs when cross tenant accessing APIs. Sends 404, since we don't need 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 adding content to the document: " + documentId + " of API " + apiId, e, log);
        } else {
            RestApiUtil.handleInternalServerError("Failed to add content to the document " + documentId, e, log);
        }
    } catch (URISyntaxException e) {
        String errorMessage = "Error while retrieving document content location : " + documentId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) DocumentDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.DocumentDTO) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI)

Example 15 with APIInfo

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

the class ApisApiServiceImpl method deployAPIRevision.

/**
 * Deploy a revision
 *
 * @param apiId             UUID of the API
 * @param revisionId     Revision ID of the API
 * @param messageContext    message context object
 * @return response with 200 status code
 */
@Override
public Response deployAPIRevision(String apiId, String revisionId, List<APIRevisionDeploymentDTO> apIRevisionDeploymentDTOList, MessageContext messageContext) throws APIManagementException {
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    // validate if api exists
    APIInfo apiInfo = validateAPIExistence(apiId);
    // validate API update operation permitted based on the LC state
    validateAPIOperationsPerLC(apiInfo.getStatus().toString());
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    // validate whether the API is advertise only
    APIDTO apiDto = getAPIByID(apiId, apiProvider, organization);
    if (apiDto != null && apiDto.getAdvertiseInfo() != null && apiDto.getAdvertiseInfo().isAdvertised()) {
        throw new APIManagementException("Deploying API Revisions is not supported for third party APIs: " + apiId);
    }
    Map<String, Environment> environments = APIUtil.getEnvironments(organization);
    List<APIRevisionDeployment> apiRevisionDeployments = new ArrayList<>();
    for (APIRevisionDeploymentDTO apiRevisionDeploymentDTO : apIRevisionDeploymentDTOList) {
        APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
        apiRevisionDeployment.setRevisionUUID(revisionId);
        String environment = apiRevisionDeploymentDTO.getName();
        if (environments.get(environment) == null) {
            RestApiUtil.handleBadRequest("Gateway environment not found: " + environment, log);
        }
        apiRevisionDeployment.setDeployment(environment);
        apiRevisionDeployment.setVhost(apiRevisionDeploymentDTO.getVhost());
        if (StringUtils.isEmpty(apiRevisionDeploymentDTO.getVhost())) {
            // vhost is only required when deploying an revision, not required when un-deploying a revision
            // since the same scheme 'APIRevisionDeployment' is used for deploy and undeploy, handle it here.
            RestApiUtil.handleBadRequest("Required field 'vhost' not found in deployment", log);
        }
        apiRevisionDeployment.setDisplayOnDevportal(apiRevisionDeploymentDTO.isDisplayOnDevportal());
        apiRevisionDeployments.add(apiRevisionDeployment);
    }
    apiProvider.deployAPIRevision(apiId, revisionId, apiRevisionDeployments, organization);
    List<APIRevisionDeployment> apiRevisionDeploymentsResponse = apiProvider.getAPIRevisionsDeploymentList(apiId);
    List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOS = new ArrayList<>();
    for (APIRevisionDeployment apiRevisionDeployment : apiRevisionDeploymentsResponse) {
        apiRevisionDeploymentDTOS.add(APIMappingUtil.fromAPIRevisionDeploymenttoDTO(apiRevisionDeployment));
    }
    Response.Status status = Response.Status.CREATED;
    return Response.status(status).entity(apiRevisionDeploymentDTOS).build();
}
Also used : APIInfo(org.wso2.carbon.apimgt.api.model.APIInfo) ArrayList(java.util.ArrayList) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) HttpResponse(org.apache.http.HttpResponse) WSDLValidationResponse(org.wso2.carbon.apimgt.impl.wsdl.model.WSDLValidationResponse) Response(javax.ws.rs.core.Response) APIDefinitionValidationResponse(org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse) APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) APIDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIRevisionDeploymentDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIRevisionDeploymentDTO) Environment(org.wso2.carbon.apimgt.api.model.Environment)

Aggregations

APIInfo (org.wso2.carbon.apimgt.api.model.APIInfo)20 ArrayList (java.util.ArrayList)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)17 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)16 HashMap (java.util.HashMap)7 APIDefinitionValidationResponse (org.wso2.carbon.apimgt.api.APIDefinitionValidationResponse)7 APIInfo (org.wso2.carbon.apimgt.core.models.analytics.APIInfo)7 API (org.wso2.carbon.apimgt.core.models.API)5 WSDLValidationResponse (org.wso2.carbon.apimgt.impl.wsdl.model.WSDLValidationResponse)5 URI (java.net.URI)4 URISyntaxException (java.net.URISyntaxException)4 Response (javax.ws.rs.core.Response)4 HttpResponse (org.apache.http.HttpResponse)4 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)4 APIStateChangeResponse (org.wso2.carbon.apimgt.api.model.APIStateChangeResponse)4 Documentation (org.wso2.carbon.apimgt.api.model.Documentation)4 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)4 Tier (org.wso2.carbon.apimgt.api.model.Tier)4 APIDTO (org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO)4 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)3