Search in sources :

Example 91 with APIProduct

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

the class ApisApiServiceImpl method updateAPIClientCertificateByAlias.

@Override
public Response updateAPIClientCertificateByAlias(String alias, String apiId, InputStream certificateInputStream, Attachment certificateDetail, String tier, MessageContext messageContext) {
    try {
        // validate if api exists
        validateAPIExistence(apiId);
        ContentDisposition contentDisposition;
        String fileName;
        String base64EncodedCert = null;
        APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        API api = apiProvider.getAPIbyUUID(apiId, organization);
        api.setOrganization(organization);
        // validate API update operation permitted based on the LC state
        validateAPIOperationsPerLC(api.getStatus());
        String userName = RestApiCommonUtil.getLoggedInUsername();
        int tenantId = APIUtil.getInternalOrganizationId(organization);
        ClientCertificateDTO clientCertificateDTO = CertificateRestApiUtils.preValidateClientCertificate(alias, api.getId(), organization);
        if (certificateDetail != null) {
            contentDisposition = certificateDetail.getContentDisposition();
            fileName = contentDisposition.getParameter(RestApiConstants.CONTENT_DISPOSITION_FILENAME);
            if (StringUtils.isNotBlank(fileName)) {
                base64EncodedCert = CertificateRestApiUtils.generateEncodedCertificate(certificateInputStream);
            }
        }
        if (StringUtils.isEmpty(base64EncodedCert) && StringUtils.isEmpty(tier)) {
            return Response.ok().entity("Client Certificate is not updated for alias " + alias).build();
        }
        int responseCode = apiProvider.updateClientCertificate(base64EncodedCert, alias, clientCertificateDTO.getApiIdentifier(), tier, tenantId, organization);
        if (ResponseCode.SUCCESS.getResponseCode() == responseCode) {
            // Handle api product case.
            if (API_PRODUCT_TYPE.equals(api.getType())) {
                APIIdentifier apiIdentifier = api.getId();
                APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(apiIdentifier.getProviderName(), apiIdentifier.getApiName(), apiIdentifier.getVersion());
                APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
                apiProduct.setOrganization(organization);
                apiProvider.updateAPIProduct(apiProduct);
            } else {
                apiProvider.updateAPI(api);
            }
            ClientCertMetadataDTO clientCertMetadataDTO = new ClientCertMetadataDTO();
            clientCertMetadataDTO.setAlias(alias);
            clientCertMetadataDTO.setApiId(api.getUUID());
            clientCertMetadataDTO.setTier(clientCertificateDTO.getTierName());
            URI updatedCertUri = new URI(RestApiConstants.CLIENT_CERTS_BASE_PATH + "?alias=" + alias);
            return Response.ok(updatedCertUri).entity(clientCertMetadataDTO).build();
        } else if (ResponseCode.INTERNAL_SERVER_ERROR.getResponseCode() == responseCode) {
            RestApiUtil.handleInternalServerError("Error while updating the client certificate for the alias " + alias + " due to an internal " + "server error", log);
        } else if (ResponseCode.CERTIFICATE_NOT_FOUND.getResponseCode() == responseCode) {
            RestApiUtil.handleResourceNotFoundError("", log);
        } else if (ResponseCode.CERTIFICATE_EXPIRED.getResponseCode() == responseCode) {
            RestApiUtil.handleBadRequest("Error while updating the client certificate for the alias " + alias + " Certificate Expired.", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while updating the client certificate for the alias " + alias + " due to an internal " + "server error", e, log);
    } catch (IOException e) {
        RestApiUtil.handleInternalServerError("Error while encoding client certificate for the alias " + alias, e, log);
    } catch (URISyntaxException e) {
        RestApiUtil.handleInternalServerError("Error while generating the resource location URI for alias '" + alias + "'", e, log);
    } catch (FaultGatewaysException e) {
        RestApiUtil.handleInternalServerError("Error while publishing the certificate change to gateways for the alias " + alias, e, log);
    }
    return null;
}
Also used : FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) URI(java.net.URI) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) ContentDisposition(org.apache.cxf.jaxrs.ext.multipart.ContentDisposition) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ClientCertMetadataDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.ClientCertMetadataDTO) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 92 with APIProduct

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

the class SearchApiServiceImpl method search.

public Response search(Integer limit, Integer offset, String query, String ifNoneMatch, MessageContext messageContext) throws APIManagementException {
    SearchResultListDTO resultListDTO = new SearchResultListDTO();
    List<SearchResultDTO> allmatchedResults = new ArrayList<>();
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    query = query == null ? "*" : query;
    if (!query.contains(":")) {
        query = (APIConstants.CONTENT_SEARCH_TYPE_PREFIX + ":" + query);
    }
    APIProvider apiProvider = RestApiCommonUtil.getLoggedInUserProvider();
    String organization = RestApiUtil.getOrganization(messageContext);
    Map<String, Object> result = null;
    if (query.startsWith(APIConstants.CONTENT_SEARCH_TYPE_PREFIX)) {
        result = apiProvider.searchPaginatedContent(query, organization, offset, limit);
    } else {
        result = apiProvider.searchPaginatedAPIs(query, organization, offset, limit, null, null);
    }
    ArrayList<Object> apis;
    /* Above searchPaginatedAPIs method underneath calls searchPaginatedAPIsByContent method,searchPaginatedAPIs
        method and searchAPIDoc method in AbstractApiManager. And those methods respectively returns ArrayList,
        TreeSet and a HashMap.
        Hence the below logic.
        */
    Object apiSearchResults = result.get("apis");
    if (apiSearchResults instanceof List<?>) {
        apis = (ArrayList<Object>) apiSearchResults;
    } else if (apiSearchResults instanceof HashMap) {
        Collection<String> values = ((HashMap) apiSearchResults).values();
        apis = new ArrayList<Object>(values);
    } else {
        apis = new ArrayList<Object>();
        apis.addAll((Collection<?>) apiSearchResults);
    }
    for (Object searchResult : apis) {
        if (searchResult instanceof API) {
            API api = (API) searchResult;
            SearchResultDTO apiResult = SearchResultMappingUtil.fromAPIToAPIResultDTO(api);
            allmatchedResults.add(apiResult);
        } else if (searchResult instanceof APIProduct) {
            APIProduct apiproduct = (APIProduct) searchResult;
            SearchResultDTO apiResult = SearchResultMappingUtil.fromAPIProductToAPIResultDTO(apiproduct);
            allmatchedResults.add(apiResult);
        } else if (searchResult instanceof Map.Entry) {
            Map.Entry pair = (Map.Entry) searchResult;
            SearchResultDTO docResult;
            if (pair.getValue() instanceof API) {
                docResult = SearchResultMappingUtil.fromDocumentationToDocumentResultDTO((Documentation) pair.getKey(), (API) pair.getValue());
            } else {
                docResult = SearchResultMappingUtil.fromDocumentationToProductDocumentResultDTO((Documentation) pair.getKey(), (APIProduct) pair.getValue());
            }
            allmatchedResults.add(docResult);
        }
    }
    Object totalLength = result.get("length");
    Integer length = 0;
    if (totalLength != null) {
        length = (Integer) totalLength;
    }
    List<Object> allmatchedObjectResults = new ArrayList<>(allmatchedResults);
    resultListDTO.setList(allmatchedObjectResults);
    resultListDTO.setCount(allmatchedResults.size());
    SearchResultMappingUtil.setPaginationParams(resultListDTO, query, offset, limit, length);
    return Response.ok().entity(resultListDTO).build();
}
Also used : HashMap(java.util.HashMap) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) ArrayList(java.util.ArrayList) APIProvider(org.wso2.carbon.apimgt.api.APIProvider) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) SearchResultDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.SearchResultDTO) SearchResultListDTO(org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.SearchResultListDTO) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) API(org.wso2.carbon.apimgt.api.model.API) HashMap(java.util.HashMap) Map(java.util.Map)

Example 93 with APIProduct

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

the class APIProviderImplTest method testChangeLifeCycleStatusOfAPIProduct.

@Test
public void testChangeLifeCycleStatusOfAPIProduct() throws APIManagementException, FaultGatewaysException {
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    String provider = "admin";
    PrivilegedCarbonContext carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.doNothing().when(carbonContext).setUsername(Mockito.anyString());
    PowerMockito.doNothing().when(carbonContext).setTenantDomain(Mockito.anyString(), Mockito.anyBoolean());
    APIProduct product = createMockAPIProduct(provider);
    Mockito.when(apimgtDAO.getAPIProductId(product.getId())).thenReturn(1);
    WorkflowDTO workflowDTO = Mockito.mock(WorkflowDTO.class);
    Mockito.when(workflowDTO.getStatus()).thenReturn(WorkflowStatus.CREATED);
    Mockito.when(apimgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(1), WorkflowConstants.WF_TYPE_AM_API_PRODUCT_STATE)).thenReturn(workflowDTO);
    APIStateChangeResponse response = apiProvider.changeLifeCycleStatus("carbon.super", new ApiTypeWrapper(product), "Publish", null);
    Assert.assertNotNull(response);
}
Also used : PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) WorkflowDTO(org.wso2.carbon.apimgt.impl.dto.WorkflowDTO) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) APIStateChangeResponse(org.wso2.carbon.apimgt.api.model.APIStateChangeResponse) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 94 with APIProduct

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

the class ImportUtils method updateApiProductSwagger.

/**
 * This method updates the API Product and the swagger with the correct scopes.
 *
 * @param pathToArchive      Path to the extracted folder
 * @param importedApiProduct Imported API Product
 * @param apiProvider        API Provider
 * @throws APIManagementException If an error occurs when retrieving the parser and updating the API Product
 * @throws FaultGatewaysException If an error occurs when updating the API to overwrite
 * @throws IOException            If an error occurs when loading the swagger file
 */
private static APIProduct updateApiProductSwagger(String pathToArchive, String apiProductId, APIProduct importedApiProduct, APIProvider apiProvider, String orgId) throws APIManagementException, FaultGatewaysException, IOException {
    String swaggerContent = loadSwaggerFile(pathToArchive);
    // Load required properties from swagger to the API Product
    APIDefinition apiDefinition = OASParserUtil.getOASParser(swaggerContent);
    Set<Scope> scopes = apiDefinition.getScopes(swaggerContent);
    importedApiProduct.setScopes(scopes);
    importedApiProduct.setOrganization(orgId);
    // This is required to make scopes get effected
    Map<API, List<APIProductResource>> apiToProductResourceMapping = apiProvider.updateAPIProduct(importedApiProduct);
    apiProvider.updateAPIProductSwagger(apiProductId, apiToProductResourceMapping, importedApiProduct, orgId);
    return importedApiProduct;
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) APIDefinition(org.wso2.carbon.apimgt.api.APIDefinition) API(org.wso2.carbon.apimgt.api.model.API) ArrayList(java.util.ArrayList) List(java.util.List) NodeList(org.w3c.dom.NodeList)

Example 95 with APIProduct

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

the class ImportUtils method retrieveApiProductToOverwrite.

/**
 * This method retrieves an API Product to overwrite in the current tenant domain.
 *
 * @param apiProductName      API Product Name
 * @param currentTenantDomain Current tenant domain
 * @param apiProvider         API Provider
 * @param ignoreAndImport     This should be true if the exception should be ignored
 * @param organization        Identifier of the organization
 * @throws APIManagementException If an error occurs when retrieving the API to overwrite
 */
private static APIProduct retrieveApiProductToOverwrite(String apiProductName, String currentTenantDomain, APIProvider apiProvider, Boolean ignoreAndImport, String organization) throws APIManagementException {
    String provider = APIUtil.getAPIProviderFromAPINameVersionTenant(apiProductName, ImportExportConstants.DEFAULT_API_PRODUCT_VERSION, currentTenantDomain);
    APIProductIdentifier apiProductIdentifier = new APIProductIdentifier(APIUtil.replaceEmailDomain(provider), apiProductName, ImportExportConstants.DEFAULT_API_PRODUCT_VERSION);
    // Checking whether the API exists
    if (!apiProvider.isAPIProductAvailable(apiProductIdentifier, organization)) {
        if (ignoreAndImport) {
            return null;
        }
        throw new APIMgtResourceNotFoundException("Error occurred while retrieving the API Product. API Product: " + apiProductName + StringUtils.SPACE + APIConstants.API_DATA_VERSION + ": " + ImportExportConstants.DEFAULT_API_PRODUCT_VERSION + " not found");
    }
    return apiProvider.getAPIProduct(apiProductIdentifier);
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)

Aggregations

APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)71 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)52 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)51 API (org.wso2.carbon.apimgt.api.model.API)37 ArrayList (java.util.ArrayList)31 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)22 PublisherAPIProduct (org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct)22 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)21 Tier (org.wso2.carbon.apimgt.api.model.Tier)21 HashMap (java.util.HashMap)19 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)19 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)18 JSONObject (org.json.simple.JSONObject)17 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)17 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)16 HashSet (java.util.HashSet)15 GenericArtifactManager (org.wso2.carbon.governance.api.generic.GenericArtifactManager)15 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)14 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)14 ParseException (org.json.simple.parser.ParseException)12