use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class TemplateBuilderUtil method getAPITemplateBuilder.
public static APITemplateBuilderImpl getAPITemplateBuilder(APIProduct apiProduct, String tenantDomain, List<ClientCertificateDTO> clientCertificateDTOS, Map<String, APIDTO> associatedAPIMap) throws APIManagementException {
int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
APITemplateBuilderImpl vtb = new APITemplateBuilderImpl(apiProduct, associatedAPIMap);
Map<String, String> latencyStatsProperties = new HashMap<String, String>();
latencyStatsProperties.put(APIConstants.API_UUID, apiProduct.getUuid());
if (!APIUtil.isStreamingApi(apiProduct)) {
vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.common.APIMgtLatencyStatsHandler", latencyStatsProperties);
}
Map<String, String> corsProperties = new HashMap<>();
corsProperties.put(APIConstants.CORSHeaders.IMPLEMENTATION_TYPE_HANDLER_VALUE, APIConstants.IMPLEMENTATION_TYPE_ENDPOINT);
// Get authorization header from the API object or from the tenant registry
String authorizationHeader;
if (!StringUtils.isBlank(apiProduct.getAuthorizationHeader())) {
authorizationHeader = apiProduct.getAuthorizationHeader();
} else {
// Retrieves the auth configuration from tenant registry or api-manager.xml if not available
// in tenant registry
authorizationHeader = APIUtil.getOAuthConfiguration(tenantDomain, APIConstants.AUTHORIZATION_HEADER);
}
if (!StringUtils.isBlank(authorizationHeader)) {
corsProperties.put(APIConstants.AUTHORIZATION_HEADER, authorizationHeader);
}
if (apiProduct.getCorsConfiguration() != null && apiProduct.getCorsConfiguration().isCorsConfigurationEnabled()) {
CORSConfiguration corsConfiguration = apiProduct.getCorsConfiguration();
if (corsConfiguration.getAccessControlAllowHeaders() != null) {
StringBuilder allowHeaders = new StringBuilder();
for (String header : corsConfiguration.getAccessControlAllowHeaders()) {
allowHeaders.append(header).append(',');
}
if (allowHeaders.length() != 0) {
allowHeaders.deleteCharAt(allowHeaders.length() - 1);
corsProperties.put(APIConstants.CORSHeaders.ALLOW_HEADERS_HANDLER_VALUE, allowHeaders.toString());
}
}
if (corsConfiguration.getAccessControlAllowOrigins() != null) {
StringBuilder allowOrigins = new StringBuilder();
for (String origin : corsConfiguration.getAccessControlAllowOrigins()) {
allowOrigins.append(origin).append(',');
}
if (allowOrigins.length() != 0) {
allowOrigins.deleteCharAt(allowOrigins.length() - 1);
corsProperties.put(APIConstants.CORSHeaders.ALLOW_ORIGIN_HANDLER_VALUE, allowOrigins.toString());
}
}
if (corsConfiguration.getAccessControlAllowMethods() != null) {
StringBuilder allowedMethods = new StringBuilder();
for (String methods : corsConfiguration.getAccessControlAllowMethods()) {
allowedMethods.append(methods).append(',');
}
if (allowedMethods.length() != 0) {
allowedMethods.deleteCharAt(allowedMethods.length() - 1);
corsProperties.put(APIConstants.CORSHeaders.ALLOW_METHODS_HANDLER_VALUE, allowedMethods.toString());
}
}
if (corsConfiguration.isAccessControlAllowCredentials()) {
corsProperties.put(APIConstants.CORSHeaders.ALLOW_CREDENTIALS_HANDLER_VALUE, String.valueOf(corsConfiguration.isAccessControlAllowCredentials()));
}
vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler", corsProperties);
} else if (APIUtil.isCORSEnabled()) {
vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler", corsProperties);
}
vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.common.APIStatusHandler", Collections.emptyMap());
Map<String, String> clientCertificateObject = null;
CertificateMgtUtils certificateMgtUtils = CertificateMgtUtils.getInstance();
if (clientCertificateDTOS != null) {
clientCertificateObject = new HashMap<>();
for (ClientCertificateDTO clientCertificateDTO : clientCertificateDTOS) {
clientCertificateObject.put(certificateMgtUtils.getUniqueIdentifierOfCertificate(clientCertificateDTO.getCertificate()), clientCertificateDTO.getTierName());
}
}
Map<String, String> authProperties = new HashMap<String, String>();
if (!StringUtils.isBlank(authorizationHeader)) {
authProperties.put(APIConstants.AUTHORIZATION_HEADER, authorizationHeader);
}
String apiSecurity = apiProduct.getApiSecurity();
String apiLevelPolicy = apiProduct.getProductLevelPolicy();
authProperties.put(APIConstants.API_SECURITY, apiSecurity);
authProperties.put(APIConstants.API_LEVEL_POLICY, apiLevelPolicy);
if (clientCertificateObject != null) {
authProperties.put(APIConstants.CERTIFICATE_INFORMATION, clientCertificateObject.toString());
}
// Get RemoveHeaderFromOutMessage from tenant registry or api-manager.xml
String removeHeaderFromOutMessage = APIUtil.getOAuthConfiguration(tenantDomain, APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE);
if (!StringUtils.isBlank(removeHeaderFromOutMessage)) {
authProperties.put(APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE, removeHeaderFromOutMessage);
} else {
authProperties.put(APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE, APIConstants.REMOVE_OAUTH_HEADER_FROM_OUT_MESSAGE_DEFAULT);
}
authProperties.put("apiType", APIConstants.ApiTypes.PRODUCT_API.name());
vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler", authProperties);
Map<String, String> properties = new HashMap<String, String>();
if (apiProduct.getProductionMaxTps() != null) {
properties.put("productionMaxCount", apiProduct.getProductionMaxTps());
}
if (apiProduct.getSandboxMaxTps() != null) {
properties.put("sandboxMaxCount", apiProduct.getSandboxMaxTps());
}
if (!APIUtil.isStreamingApi(apiProduct)) {
vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.throttling.ThrottleHandler", properties);
properties = new HashMap<String, String>();
properties.put("configKey", APIConstants.GA_CONF_KEY);
vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.analytics.APIMgtGoogleAnalyticsTrackingHandler", properties);
String extensionHandlerPosition = getExtensionHandlerPosition(tenantDomain);
if ("top".equalsIgnoreCase(extensionHandlerPosition)) {
vtb.addHandlerPriority("org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler", Collections.emptyMap(), 2);
} else {
vtb.addHandler("org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler", Collections.emptyMap());
}
}
return vtb;
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class TemplateBuilderUtil method retrieveOperationPolicySequenceForProducts.
private static GatewayContentDTO retrieveOperationPolicySequenceForProducts(APIProduct apiProduct, API api, String extractedLocation, String flow) throws APIManagementException {
Set<URITemplate> applicableURITemplates = new HashSet<>();
for (APIProductResource productResource : apiProduct.getProductResources()) {
if (productResource.getApiIdentifier().equals(api.getId())) {
applicableURITemplates.add(productResource.getUriTemplate());
}
}
String policySequence = null;
APIProductIdentifier apiProductIdentifier = apiProduct.getId();
String seqExt = APIUtil.getSequenceExtensionName(apiProductIdentifier.getName(), apiProductIdentifier.getVersion()).concat("--").concat(api.getUuid()).concat(SynapsePolicyAggregator.getSequenceExtensionFlow(flow));
try {
policySequence = SynapsePolicyAggregator.generatePolicySequenceForUriTemplateSet(applicableURITemplates, seqExt, flow, extractedLocation);
} catch (IOException e) {
throw new APIManagementException(e);
}
GatewayContentDTO operationPolicySequenceContentDto = new GatewayContentDTO();
if (StringUtils.isNotEmpty(policySequence)) {
try {
OMElement omElement = APIUtil.buildOMElement(new ByteArrayInputStream(policySequence.getBytes()));
if (omElement != null) {
if (omElement.getAttribute(new QName("name")) != null) {
omElement.getAttribute(new QName("name")).setAttributeValue(seqExt);
}
operationPolicySequenceContentDto.setName(seqExt);
operationPolicySequenceContentDto.setContent(APIUtil.convertOMtoString(omElement));
for (APIProductResource productResource : apiProduct.getProductResources()) {
if (productResource.getApiIdentifier().equals(api.getId())) {
switch(flow) {
case APIConstants.OPERATION_SEQUENCE_TYPE_REQUEST:
productResource.setInSequenceName(seqExt);
break;
case APIConstants.OPERATION_SEQUENCE_TYPE_RESPONSE:
productResource.setOutSequenceName(seqExt);
break;
case APIConstants.OPERATION_SEQUENCE_TYPE_FAULT:
productResource.setFaultSequenceName(seqExt);
break;
}
}
}
return operationPolicySequenceContentDto;
}
} catch (Exception e) {
throw new APIManagementException(e);
}
}
return null;
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class TemplateBuilderUtil method retrieveGatewayAPIDto.
public static GatewayAPIDTO retrieveGatewayAPIDto(APIProduct apiProduct, Environment environment, String tenantDomain, String extractedFolderPath) throws APIManagementException, XMLStreamException, APITemplateException {
List<ClientCertificateDTO> clientCertificatesDTOList = ImportUtils.retrieveClientCertificates(extractedFolderPath);
Map<String, APIDTO> apidtoMap = retrieveAssociatedApis(extractedFolderPath);
Map<String, APIDTO> associatedAPIsMap = convertAPIIdToDto(apidtoMap.values());
for (APIProductResource productResource : apiProduct.getProductResources()) {
String apiId = productResource.getApiId();
APIDTO apidto = associatedAPIsMap.get(apiId);
if (apidto != null) {
API api = APIMappingUtil.fromDTOtoAPI(apidto, apidto.getProvider());
productResource.setApiIdentifier(api.getId());
if (api.isAdvertiseOnly()) {
productResource.setEndpointConfig(APIUtil.generateEndpointConfigForAdvertiseOnlyApi(api));
} else {
productResource.setEndpointConfig(api.getEndpointConfig());
}
if (StringUtils.isNotEmpty(api.getInSequence())) {
String sequenceName = APIUtil.getSequenceExtensionName(apiProduct.getId().getName(), apiProduct.getId().getVersion()).concat("--").concat(productResource.getApiId()) + APIConstants.API_CUSTOM_SEQ_IN_EXT;
productResource.setInSequenceName(sequenceName);
}
if (StringUtils.isNotEmpty(api.getOutSequence())) {
String sequenceName = APIUtil.getSequenceExtensionName(apiProduct.getId().getName(), apiProduct.getId().getVersion()).concat("--").concat(productResource.getApiId()) + APIConstants.API_CUSTOM_SEQ_OUT_EXT;
productResource.setOutSequenceName(sequenceName);
}
if (StringUtils.isNotEmpty(api.getFaultSequence())) {
String sequenceName = APIUtil.getSequenceExtensionName(apiProduct.getId().getName(), apiProduct.getId().getVersion()).concat("--").concat(productResource.getApiId()) + APIConstants.API_CUSTOM_SEQ_FAULT_EXT;
productResource.setFaultSequenceName(sequenceName);
}
productResource.setProductIdentifier(apiProduct.getId());
productResource.setEndpointSecurityMap(APIUtil.setEndpointSecurityForAPIProduct(api));
}
}
APITemplateBuilder apiTemplateBuilder = TemplateBuilderUtil.getAPITemplateBuilder(apiProduct, tenantDomain, clientCertificatesDTOList, convertAPIIdToDto(associatedAPIsMap.values()));
return createAPIGatewayDTOtoPublishAPI(environment, apiProduct, apiTemplateBuilder, tenantDomain, apidtoMap, clientCertificatesDTOList);
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class TemplateBuilderUtil method createAPIGatewayDTOtoPublishAPI.
private static GatewayAPIDTO createAPIGatewayDTOtoPublishAPI(Environment environment, APIProduct apiProduct, APITemplateBuilder builder, String tenantDomain, Map<String, APIDTO> associatedAPIsMap, List<ClientCertificateDTO> clientCertificatesDTOList) throws APITemplateException, XMLStreamException, APIManagementException {
APIProductIdentifier id = apiProduct.getId();
GatewayAPIDTO productAPIDto = new GatewayAPIDTO();
productAPIDto.setProvider(id.getProviderName());
productAPIDto.setApiId(apiProduct.getUuid());
productAPIDto.setName(id.getName());
productAPIDto.setVersion(id.getVersion());
productAPIDto.setTenantDomain(tenantDomain);
productAPIDto.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
String definition = apiProduct.getDefinition();
productAPIDto.setLocalEntriesToBeRemove(GatewayUtils.addStringToList(apiProduct.getUuid(), productAPIDto.getLocalEntriesToBeRemove()));
GatewayContentDTO productLocalEntry = new GatewayContentDTO();
productLocalEntry.setName(apiProduct.getUuid());
productLocalEntry.setContent("<localEntry key=\"" + apiProduct.getUuid() + "\">" + definition.replaceAll("&(?!amp;)", "&").replaceAll("<", "<").replaceAll(">", ">") + "</localEntry>");
productAPIDto.setLocalEntriesToBeAdd(addGatewayContentToList(productLocalEntry, productAPIDto.getLocalEntriesToBeAdd()));
setClientCertificatesToBeAdded(tenantDomain, productAPIDto, clientCertificatesDTOList);
for (Map.Entry<String, APIDTO> apidtoEntry : associatedAPIsMap.entrySet()) {
String apiExtractedPath = apidtoEntry.getKey();
APIDTO apidto = apidtoEntry.getValue();
API api = APIMappingUtil.fromDTOtoAPI(apidto, apidto.getProvider());
api.setUuid(apidto.getId());
GatewayUtils.setCustomSequencesToBeRemoved(apiProduct.getId(), api.getUuid(), productAPIDto);
APITemplateBuilder apiTemplateBuilder = new APITemplateBuilderImpl(api, apiProduct);
addEndpoints(api, apiTemplateBuilder, productAPIDto);
setCustomSequencesToBeAdded(apiProduct, api, productAPIDto, apiExtractedPath, apidto);
setAPIFaultSequencesToBeAdded(api, productAPIDto, apiExtractedPath, apidto);
String prefix = id.getName() + "--v" + id.getVersion();
setSecureVaultPropertyToBeAdded(prefix, api, productAPIDto);
}
productAPIDto.setApiDefinition(builder.getConfigStringForTemplate(environment));
return productAPIDto;
}
use of org.wso2.carbon.apimgt.api.model.APIProduct in project carbon-apimgt by wso2.
the class ImportUtils method importSubscriptions.
/**
* Import and add subscriptions of a particular application for the available APIs and API products
*
* @param subscribedAPIs Subscribed APIs
* @param userId Username of the subscriber
* @param application Application
* @param update Whether to update the application or not
* @param apiConsumer API Consumer
* @param organization Organization
* @return a list of APIIdentifiers of the skipped subscriptions
* @throws APIManagementException if an error occurs while importing and adding subscriptions
* @throws UserStoreException if an error occurs while checking whether the tenant domain exists
*/
public static List<APIIdentifier> importSubscriptions(Set<ExportedSubscribedAPI> subscribedAPIs, String userId, Application application, Boolean update, APIConsumer apiConsumer, String organization) throws APIManagementException, UserStoreException {
List<APIIdentifier> skippedAPIList = new ArrayList<>();
for (ExportedSubscribedAPI subscribedAPI : subscribedAPIs) {
APIIdentifier apiIdentifier = subscribedAPI.getApiId();
String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
if (!StringUtils.isEmpty(tenantDomain) && APIUtil.isTenantAvailable(tenantDomain)) {
String name = apiIdentifier.getApiName();
String version = apiIdentifier.getVersion();
// Creating a solr compatible search query, here we will execute a search query without wildcard *s
StringBuilder searchQuery = new StringBuilder();
String[] searchCriteria = { name, "version:" + version };
for (int i = 0; i < searchCriteria.length; i++) {
if (i == 0) {
searchQuery = new StringBuilder(APIUtil.getSingleSearchCriteria(searchCriteria[i]).replace("*", ""));
} else {
searchQuery.append(APIConstants.SEARCH_AND_TAG).append(APIUtil.getSingleSearchCriteria(searchCriteria[i]).replace("*", ""));
}
}
Map matchedAPIs;
matchedAPIs = apiConsumer.searchPaginatedAPIs(searchQuery.toString(), tenantDomain, 0, Integer.MAX_VALUE, false);
Set<Object> apiSet = (Set<Object>) matchedAPIs.get("apis");
if (apiSet != null && !apiSet.isEmpty()) {
Object type = apiSet.iterator().next();
ApiTypeWrapper apiTypeWrapper = null;
String apiOrApiProductUuid;
// Check whether the object is ApiProduct
if (isApiProduct(type)) {
APIProduct apiProduct = (APIProduct) apiSet.iterator().next();
apiOrApiProductUuid = APIUtil.getUUIDFromIdentifier(apiProduct.getId(), organization);
} else {
API api = (API) apiSet.iterator().next();
apiOrApiProductUuid = APIUtil.getUUIDFromIdentifier(api.getId(), organization);
}
apiTypeWrapper = apiConsumer.getAPIorAPIProductByUUID(apiOrApiProductUuid, organization);
// Tier of the imported subscription
String targetTier = subscribedAPI.getThrottlingPolicy();
// Checking whether the target tier is available
if (isTierAvailable(targetTier, apiTypeWrapper) && apiTypeWrapper.getStatus() != null && APIConstants.PUBLISHED.equals(apiTypeWrapper.getStatus())) {
apiTypeWrapper.setTier(targetTier);
// It will throw an error if subscriber already exists
if (update == null || !update) {
apiConsumer.addSubscription(apiTypeWrapper, userId, application);
} else if (!apiConsumer.isSubscribedToApp(subscribedAPI.getApiId(), userId, application.getId())) {
// on update skip subscriptions that already exists
apiConsumer.addSubscription(apiTypeWrapper, userId, application);
}
} else {
log.error("Failed to import Subscription as API/API Product " + name + "-" + version + " as one or more tiers may be unavailable or the API/API Product may not have been published ");
skippedAPIList.add(subscribedAPI.getApiId());
}
} else {
log.error("Failed to import Subscription as API " + name + "-" + version + " is not available");
skippedAPIList.add(subscribedAPI.getApiId());
}
} else {
log.error("Failed to import Subscription as Tenant domain: " + tenantDomain + " is not available");
skippedAPIList.add(subscribedAPI.getApiId());
}
}
return skippedAPIList;
}
Aggregations