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;
}
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();
}
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);
}
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;
}
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);
}
Aggregations