use of org.wso2.carbon.governance.api.exception.GovernanceException in project carbon-apimgt by wso2.
the class APIProviderImplTest method testChangeLifeCycleStatus_FaultyGWException.
@Test(expected = FaultGatewaysException.class)
public void testChangeLifeCycleStatus_FaultyGWException() throws RegistryException, UserStoreException, APIManagementException, FaultGatewaysException, WorkflowException, XMLStreamException {
APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.0");
APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
prepareForChangeLifeCycleStatus(apiProvider, apimgtDAO, apiId, artifact);
GovernanceException exception = new GovernanceException(new APIManagementException("FaultGatewaysException:" + "{\"PUBLISHED\":{\"PROD\":\"Error\"}}"));
Mockito.when(artifact.getLifecycleState()).thenThrow(exception);
apiProvider.changeLifeCycleStatus(apiId, APIConstants.API_LC_ACTION_DEPRECATE, "org1");
}
use of org.wso2.carbon.governance.api.exception.GovernanceException in project carbon-apimgt by wso2.
the class APIProviderImpl method getAPIsByProvider.
/**
* Get a list of APIs published by the given provider. If a given API has multiple APIs,
* only the latest version will
* be included in this list.
*
* @param providerId , provider id
* @return set of API
* @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get set of API
*/
@Override
public List<API> getAPIsByProvider(String providerId) throws APIManagementException {
List<API> apiSortedList = new ArrayList<API>();
try {
providerId = APIUtil.replaceEmailDomain(providerId);
String providerPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + providerId;
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
Association[] associations = registry.getAssociations(providerPath, APIConstants.PROVIDER_ASSOCIATION);
for (Association association : associations) {
String apiPath = association.getDestinationPath();
if (registry.resourceExists(apiPath)) {
Resource resource = registry.get(apiPath);
String apiArtifactId = resource.getUUID();
if (apiArtifactId != null) {
GenericArtifact apiArtifact = artifactManager.getGenericArtifact(apiArtifactId);
if (apiArtifact != null) {
String type = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE);
if (!APIConstants.API_PRODUCT.equals(type)) {
apiSortedList.add(getAPI(apiArtifact));
}
}
} else {
throw new GovernanceException("artifact id is null of " + apiPath);
}
}
}
} catch (RegistryException e) {
handleException("Failed to get APIs for provider : " + providerId, e);
}
Collections.sort(apiSortedList, new APINameComparator());
return apiSortedList;
}
use of org.wso2.carbon.governance.api.exception.GovernanceException in project carbon-apimgt by wso2.
the class APIProviderImpl method changeLifeCycleStatus.
public APIStateChangeResponse changeLifeCycleStatus(APIIdentifier apiIdentifier, String action, String organization) throws APIManagementException, FaultGatewaysException {
APIStateChangeResponse response = new APIStateChangeResponse();
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(this.tenantDomain, true);
GenericArtifact apiArtifact = getAPIArtifact(apiIdentifier);
String targetStatus;
if (apiArtifact != null) {
String providerName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_PROVIDER);
String apiName = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_NAME);
String apiContext = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_CONTEXT);
String apiType = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE);
String apiVersion = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_VERSION);
String currentStatus = apiArtifact.getLifecycleState();
String uuid = apiMgtDAO.getUUIDFromIdentifier(apiIdentifier, organization);
String gatewayVendor = apiMgtDAO.getGatewayVendorByAPIUUID(uuid);
int apiId = apiMgtDAO.getAPIID(uuid);
WorkflowStatus apiWFState = null;
WorkflowDTO wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(apiId), WorkflowConstants.WF_TYPE_AM_API_STATE);
if (wfDTO != null) {
apiWFState = wfDTO.getStatus();
}
// if the workflow has started, then executor should not fire again
if (!WorkflowStatus.CREATED.equals(apiWFState)) {
try {
WorkflowProperties workflowProperties = getAPIManagerConfiguration().getWorkflowProperties();
WorkflowExecutor apiStateWFExecutor = WorkflowExecutorFactory.getInstance().getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_API_STATE);
APIStateWorkflowDTO apiStateWorkflow = new APIStateWorkflowDTO();
apiStateWorkflow.setApiCurrentState(currentStatus);
apiStateWorkflow.setApiLCAction(action);
apiStateWorkflow.setApiName(apiName);
apiStateWorkflow.setApiContext(apiContext);
apiStateWorkflow.setApiType(apiType);
apiStateWorkflow.setApiVersion(apiVersion);
apiStateWorkflow.setApiProvider(providerName);
apiStateWorkflow.setGatewayVendor(gatewayVendor);
apiStateWorkflow.setCallbackUrl(workflowProperties.getWorkflowCallbackAPI());
apiStateWorkflow.setExternalWorkflowReference(apiStateWFExecutor.generateUUID());
apiStateWorkflow.setTenantId(tenantId);
apiStateWorkflow.setTenantDomain(this.tenantDomain);
apiStateWorkflow.setWorkflowType(WorkflowConstants.WF_TYPE_AM_API_STATE);
apiStateWorkflow.setStatus(WorkflowStatus.CREATED);
apiStateWorkflow.setCreatedTime(System.currentTimeMillis());
apiStateWorkflow.setWorkflowReference(Integer.toString(apiId));
apiStateWorkflow.setInvoker(this.username);
apiStateWorkflow.setApiUUID(uuid);
String workflowDescription = "Pending lifecycle state change action: " + action;
apiStateWorkflow.setWorkflowDescription(workflowDescription);
WorkflowResponse workflowResponse = apiStateWFExecutor.execute(apiStateWorkflow);
response.setWorkflowResponse(workflowResponse);
} catch (WorkflowException e) {
handleException("Failed to execute workflow for life cycle status change : " + e.getMessage(), e);
}
// get the workflow state once the executor is executed.
wfDTO = apiMgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(apiId), WorkflowConstants.WF_TYPE_AM_API_STATE);
if (wfDTO != null) {
apiWFState = wfDTO.getStatus();
response.setStateChangeStatus(apiWFState.toString());
} else {
response.setStateChangeStatus(WorkflowStatus.APPROVED.toString());
}
}
// apiWFState is null when simple wf executor is used because wf state is not stored in the db.
if (WorkflowStatus.APPROVED.equals(apiWFState) || apiWFState == null) {
targetStatus = "";
apiArtifact.invokeAction(action, APIConstants.API_LIFE_CYCLE);
targetStatus = apiArtifact.getLifecycleState();
if (!currentStatus.equals(targetStatus)) {
apiMgtDAO.recordAPILifeCycleEvent(apiId, currentStatus.toUpperCase(), targetStatus.toUpperCase(), this.username, this.tenantId);
}
if (log.isDebugEnabled()) {
String logMessage = "API Status changed successfully. API Name: " + apiIdentifier.getApiName() + ", API Version " + apiIdentifier.getVersion() + ", New Status : " + targetStatus;
log.debug(logMessage);
}
APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_LIFECYCLE_CHANGE.name(), tenantId, tenantDomain, apiName, apiId, uuid, apiVersion, apiType, apiContext, providerName, targetStatus);
APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
return response;
}
}
} catch (GovernanceException e) {
String cause = e.getCause().getMessage();
if (!StringUtils.isEmpty(cause)) {
if (cause.contains("FaultGatewaysException:")) {
Map<String, Map<String, String>> faultMap = new HashMap<String, Map<String, String>>();
String faultJsonString;
if (!StringUtils.isEmpty(cause) && cause.split("FaultGatewaysException:").length > 1) {
faultJsonString = cause.split("FaultGatewaysException:")[1];
try {
JSONObject faultGatewayJson = (JSONObject) new JSONParser().parse(faultJsonString);
faultMap.putAll(faultGatewayJson);
throw new FaultGatewaysException(faultMap);
} catch (ParseException e1) {
log.error("Couldn't parse the Failed Environment json", e);
handleException("Couldn't parse the Failed Environment json : " + e.getMessage(), e);
}
}
} else if (cause.contains("APIManagementException:")) {
// This exception already logged from APIExecutor class hence this no need to logged again
handleException("Failed to change the life cycle status : " + cause.split("APIManagementException:")[1], e);
} else {
/* This exception already logged from APIExecutor class hence this no need to logged again
This block handles the all the exception which not have custom cause message*/
handleException("Failed to change the life cycle status : " + e.getMessage(), e);
}
}
return response;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return response;
}
use of org.wso2.carbon.governance.api.exception.GovernanceException in project carbon-apimgt by wso2.
the class APIConsumerImpl method getPublishedAPIsByProvider.
@Override
public Set<API> getPublishedAPIsByProvider(String providerId, String loggedUsername, int limit, String apiOwner, String apiBizOwner) throws APIManagementException {
try {
Boolean allowMultipleVersions = APIUtil.isAllowDisplayMultipleVersions();
Boolean showAllAPIs = APIUtil.isAllowDisplayAPIsWithMultipleStatus();
String providerDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(providerId));
int tenantId = getTenantId(providerDomain);
final Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry(tenantId);
GenericArtifactManager artifactManager = APIUtil.getArtifactManager(registry, APIConstants.API_KEY);
if (artifactManager == null) {
String errorMessage = "Artifact manager is null when retrieving all published APIs by provider ID " + providerId;
log.error(errorMessage);
throw new APIManagementException(errorMessage);
}
int publishedAPICount = 0;
Map<String, API> apiCollection = new HashMap<String, API>();
if (apiBizOwner != null && !apiBizOwner.isEmpty()) {
try {
final String bizOwner = apiBizOwner;
Map<String, List<String>> listMap = new HashMap<String, List<String>>();
listMap.put(APIConstants.API_OVERVIEW_BUSS_OWNER, new ArrayList<String>() {
{
add(bizOwner);
}
});
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(this.username);
GenericArtifact[] genericArtifacts = artifactManager.findGenericArtifacts(listMap);
if (genericArtifacts != null && genericArtifacts.length > 0) {
for (GenericArtifact artifact : genericArtifacts) {
if (publishedAPICount >= limit) {
break;
}
if (isCandidateAPI(artifact.getPath(), loggedUsername, artifactManager, tenantId, showAllAPIs, allowMultipleVersions, apiOwner, providerId, registry, apiCollection)) {
publishedAPICount += 1;
}
}
}
} catch (GovernanceException e) {
log.error("Error while finding APIs by business owner " + apiBizOwner, e);
return null;
}
} else {
String providerPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + providerId;
Association[] associations = registry.getAssociations(providerPath, APIConstants.PROVIDER_ASSOCIATION);
for (Association association : associations) {
if (publishedAPICount >= limit) {
break;
}
String apiPath = association.getDestinationPath();
if (isCandidateAPI(apiPath, loggedUsername, artifactManager, tenantId, showAllAPIs, allowMultipleVersions, apiOwner, providerId, registry, apiCollection)) {
publishedAPICount += 1;
}
}
}
return new HashSet<API>(apiCollection.values());
} catch (RegistryException e) {
handleException("Failed to get Published APIs for provider : " + providerId, e);
return null;
} catch (org.wso2.carbon.user.core.UserStoreException e) {
handleException("Failed to get Published APIs for provider : " + providerId, e);
return null;
} catch (UserStoreException e) {
handleException("Failed to get Published APIs for provider : " + providerId, e);
return null;
}
}
use of org.wso2.carbon.governance.api.exception.GovernanceException in project carbon-apimgt by wso2.
the class APIUtil method createAPIProductArtifactContent.
/**
* Create Governance artifact from given attributes
*
* @param artifact initial governance artifact
* @param apiProduct APIProduct object with the attributes value
* @return GenericArtifact
* @throws APIManagementException if failed to create API Product
*/
public static GenericArtifact createAPIProductArtifactContent(GenericArtifact artifact, APIProduct apiProduct) throws APIManagementException {
try {
// todo : review and add missing fields
artifact.setAttribute(APIConstants.API_OVERVIEW_NAME, apiProduct.getId().getName());
artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION, apiProduct.getId().getVersion());
artifact.setAttribute(APIConstants.API_OVERVIEW_PROVIDER, apiProduct.getId().getProviderName());
artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT, apiProduct.getContext());
artifact.setAttribute(APIConstants.API_OVERVIEW_DESCRIPTION, apiProduct.getDescription());
artifact.setAttribute(APIConstants.API_OVERVIEW_TYPE, APIConstants.AuditLogConstants.API_PRODUCT);
artifact.setAttribute(APIConstants.API_OVERVIEW_STATUS, apiProduct.getState());
artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBILITY, apiProduct.getVisibility());
artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_ROLES, apiProduct.getVisibleRoles());
artifact.setAttribute(APIConstants.API_OVERVIEW_VISIBLE_TENANTS, apiProduct.getVisibleTenants());
artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER, apiProduct.getBusinessOwner());
artifact.setAttribute(APIConstants.API_OVERVIEW_BUSS_OWNER_EMAIL, apiProduct.getBusinessOwnerEmail());
artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER, apiProduct.getTechnicalOwner());
artifact.setAttribute(APIConstants.API_OVERVIEW_TEC_OWNER_EMAIL, apiProduct.getTechnicalOwnerEmail());
artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY, apiProduct.getSubscriptionAvailability());
artifact.setAttribute(APIConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS, apiProduct.getSubscriptionAvailableTenants());
artifact.setAttribute(APIConstants.API_OVERVIEW_THUMBNAIL_URL, apiProduct.getThumbnailUrl());
artifact.setAttribute(APIConstants.API_OVERVIEW_CACHE_TIMEOUT, Integer.toString(apiProduct.getCacheTimeout()));
StringBuilder policyBuilder = new StringBuilder();
for (Tier tier : apiProduct.getAvailableTiers()) {
policyBuilder.append(tier.getName());
policyBuilder.append("||");
}
String policies = policyBuilder.toString();
if (!"".equals(policies)) {
policies = policies.substring(0, policies.length() - 2);
artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, policies);
} else {
artifact.setAttribute(APIConstants.API_OVERVIEW_TIER, policies);
}
artifact.setAttribute(APIConstants.API_OVERVIEW_ENVIRONMENTS, writeEnvironmentsToArtifact(apiProduct));
artifact.setAttribute(APIConstants.API_OVERVIEW_TRANSPORTS, apiProduct.getTransports());
artifact.setAttribute(APIConstants.API_OVERVIEW_CORS_CONFIGURATION, APIUtil.getCorsConfigurationJsonFromDto(apiProduct.getCorsConfiguration()));
artifact.setAttribute(APIConstants.API_OVERVIEW_AUTHORIZATION_HEADER, apiProduct.getAuthorizationHeader());
artifact.setAttribute(APIConstants.API_OVERVIEW_API_SECURITY, apiProduct.getApiSecurity());
// Validate if the API has an unsupported context before setting it in the artifact
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
if (APIConstants.SUPER_TENANT_DOMAIN.equals(tenantDomain)) {
String invalidContext = File.separator + APIConstants.VERSION_PLACEHOLDER;
if (invalidContext.equals(apiProduct.getContextTemplate())) {
throw new APIManagementException("API : " + apiProduct.getId() + " has an unsupported context : " + apiProduct.getContextTemplate());
}
} else {
String invalidContext = APIConstants.TENANT_PREFIX + tenantDomain + File.separator + APIConstants.VERSION_PLACEHOLDER;
if (invalidContext.equals(apiProduct.getContextTemplate())) {
throw new APIManagementException("API : " + apiProduct.getId() + " has an unsupported context : " + apiProduct.getContextTemplate());
}
}
artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_JSON_SCHEMA, Boolean.toString(apiProduct.isEnabledSchemaValidation()));
artifact.setAttribute(APIConstants.API_OVERVIEW_ENABLE_STORE, Boolean.toString(apiProduct.isEnableStore()));
artifact.setAttribute(APIConstants.API_OVERVIEW_RESPONSE_CACHING, apiProduct.getResponseCache());
// This is to support the pluggable version strategy.
artifact.setAttribute(APIConstants.API_OVERVIEW_CONTEXT_TEMPLATE, apiProduct.getContextTemplate());
artifact.setAttribute(APIConstants.API_OVERVIEW_VERSION_TYPE, "context");
// set monetization status (i.e - enabled or disabled)
artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_STATUS, Boolean.toString(apiProduct.getMonetizationStatus()));
// set additional monetization data
if (apiProduct.getMonetizationProperties() != null) {
artifact.setAttribute(APIConstants.Monetization.API_MONETIZATION_PROPERTIES, apiProduct.getMonetizationProperties().toJSONString());
}
// attaching api categories to the API
List<APICategory> attachedApiCategories = apiProduct.getApiCategories();
artifact.removeAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME);
if (attachedApiCategories != null) {
for (APICategory category : attachedApiCategories) {
artifact.addAttribute(APIConstants.API_CATEGORIES_CATEGORY_NAME, category.getName());
}
}
} catch (GovernanceException e) {
String msg = "Failed to create API for : " + apiProduct.getId().getName();
log.error(msg, e);
throw new APIManagementException(msg, e);
}
return artifact;
}
Aggregations