use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.
the class ApiMgtDAO method updateSubscription.
/**
* This method is used to update the subscription
*
* @param identifier APIIdentifier
* @param subStatus Subscription Status[BLOCKED/UNBLOCKED]
* @param applicationId Application id
* @param organization Organization
* @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to update subscriber
*/
public void updateSubscription(APIIdentifier identifier, String subStatus, int applicationId, String organization) throws APIManagementException {
Connection conn = null;
ResultSet resultSet = null;
PreparedStatement ps = null;
PreparedStatement updatePs = null;
int apiId = -1;
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(false);
String getApiQuery = SQLConstants.GET_API_ID_SQL;
ps = conn.prepareStatement(getApiQuery);
ps.setString(1, APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
ps.setString(2, identifier.getApiName());
ps.setString(3, identifier.getVersion());
resultSet = ps.executeQuery();
if (resultSet.next()) {
apiId = resultSet.getInt("API_ID");
}
if (apiId == -1) {
String msg = "Unable to get the API ID for: " + identifier;
log.error(msg);
throw new APIManagementException(msg);
}
String subsCreateStatus = getSubscriptionCreaeteStatus(identifier, applicationId, organization, conn);
if (APIConstants.SubscriptionCreatedStatus.UN_SUBSCRIBE.equals(subsCreateStatus)) {
deleteSubscriptionByApiIDAndAppID(apiId, applicationId, conn);
}
// This query to update the AM_SUBSCRIPTION table
String sqlQuery = SQLConstants.UPDATE_SUBSCRIPTION_OF_APPLICATION_SQL;
// Updating data to the AM_SUBSCRIPTION table
updatePs = conn.prepareStatement(sqlQuery);
updatePs.setString(1, subStatus);
updatePs.setString(2, identifier.getProviderName());
updatePs.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
updatePs.setInt(4, apiId);
updatePs.setInt(5, applicationId);
updatePs.execute();
// finally commit transaction
conn.commit();
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException e1) {
log.error("Failed to rollback the add subscription ", e1);
}
}
handleException("Failed to update subscription data ", e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
APIMgtDBUtil.closeAllConnections(updatePs, null, null);
}
}
use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.
the class ApiMgtDAO method removeSubscription.
/**
* Removes the subscription entry from AM_SUBSCRIPTIONS for identifier.
*
* @param identifier Identifier
* @param applicationId ID of the application which has the subscription
* @throws APIManagementException
*/
public void removeSubscription(Identifier identifier, int applicationId) throws APIManagementException {
Connection conn = null;
ResultSet resultSet = null;
PreparedStatement ps = null;
int id = -1;
String uuid;
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(false);
String subscriptionUUIDQuery = SQLConstants.GET_SUBSCRIPTION_UUID_SQL;
if (identifier.getId() > 0) {
id = identifier.getId();
} else if (identifier instanceof APIIdentifier) {
String apiUuid;
if (identifier.getUUID() != null) {
apiUuid = identifier.getUUID();
} else {
apiUuid = getUUIDFromIdentifier((APIIdentifier) identifier);
}
id = getAPIID(apiUuid, conn);
} else if (identifier instanceof APIProductIdentifier) {
id = ((APIProductIdentifier) identifier).getProductId();
}
ps = conn.prepareStatement(subscriptionUUIDQuery);
ps.setInt(1, id);
ps.setInt(2, applicationId);
resultSet = ps.executeQuery();
if (resultSet.next()) {
uuid = resultSet.getString("UUID");
SubscribedAPI subscribedAPI = new SubscribedAPI(uuid);
removeSubscription(subscribedAPI, conn);
} else {
throw new APIManagementException("UUID does not exist for the given apiId:" + id + " and " + "application id:" + applicationId);
}
conn.commit();
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException ex) {
log.error("Failed to rollback the add subscription ", ex);
}
}
handleException("Failed to add subscriber data ", e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, resultSet);
}
}
use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.
the class APIProviderImplTest method testDeleteWorkflowTask.
@Test
public void testDeleteWorkflowTask() throws APIManagementException, WorkflowException {
APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
Mockito.when(apimgtDAO.getAPIID(apiUUID)).thenReturn(1111);
WorkflowExecutorFactory wfe = PowerMockito.mock(WorkflowExecutorFactory.class);
Mockito.when(WorkflowExecutorFactory.getInstance()).thenReturn(wfe);
WorkflowExecutor apiStateChangeWFExecutor = Mockito.mock(WorkflowExecutor.class);
Mockito.when(wfe.getWorkflowExecutor(WorkflowConstants.WF_TYPE_AM_API_STATE)).thenReturn(apiStateChangeWFExecutor);
WorkflowDTO workflowDTO = Mockito.mock(WorkflowDTO.class);
Mockito.when(apimgtDAO.retrieveWorkflowFromInternalReference(Integer.toString(1111), WorkflowConstants.WF_TYPE_AM_API_STATE)).thenReturn(workflowDTO);
APIIdentifier identifier = new APIIdentifier("admin", "API1", "1.0.0", apiUUID);
apiProvider.deleteWorkflowTask(identifier);
Mockito.verify(apimgtDAO, Mockito.times(1)).getAPIID(apiUUID);
}
use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.
the class APIProviderImplTest method testUpdateAPI_InCreatedState.
@Test
public void testUpdateAPI_InCreatedState() throws Exception {
APIIdentifier identifier = new APIIdentifier("admin-AT-carbon.super", "API1", "1.0.0");
Set<String> environments = new HashSet<String>();
Set<URITemplate> uriTemplates = new HashSet<URITemplate>();
Set<URITemplate> newUriTemplates = new HashSet<URITemplate>();
Tier tier = new Tier("Gold");
Map<String, Tier> tiers = new TreeMap<>();
tiers.put("Gold", tier);
URITemplate uriTemplate1 = new URITemplate();
uriTemplate1.setHTTPVerb("POST");
uriTemplate1.setAuthType("Application");
uriTemplate1.setUriTemplate("/add");
uriTemplate1.setThrottlingTier("Gold");
uriTemplates.add(uriTemplate1);
URITemplate uriTemplate2 = new URITemplate();
uriTemplate2.setHTTPVerb("PUT");
uriTemplate2.setAuthType("Application");
uriTemplate2.setUriTemplate("/update");
uriTemplate2.setThrottlingTier("Gold");
newUriTemplates.add(uriTemplate1);
newUriTemplates.add(uriTemplate2);
final API api = new API(identifier);
api.setStatus(APIConstants.CREATED);
api.setVisibility("public");
api.setAccessControl("all");
api.setTransports("http,https");
api.setContext("/test");
api.setEnvironments(environments);
api.setUriTemplates(newUriTemplates);
api.setOrganization("carbon.super");
API oldApi = new API(identifier);
oldApi.setStatus(APIConstants.CREATED);
oldApi.setVisibility("public");
oldApi.setAccessControl("all");
oldApi.setContext("/test");
oldApi.setEnvironments(environments);
api.setUriTemplates(uriTemplates);
oldApi.setOrganization("carbon.super");
List<Documentation> documentationList = getDocumentationList();
Documentation documentation = documentationList.get(1);
Mockito.when(APIUtil.getAPIDocPath(api.getId())).thenReturn(documentation.getFilePath());
APIProviderImplWrapper apiProviderImplWrapper = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO);
Resource docResource = Mockito.mock(Resource.class);
Mockito.when(docResource.getUUID()).thenReturn(documentation.getId());
Mockito.when(apiProviderImplWrapper.registry.get(documentation.getFilePath())).thenReturn(docResource);
GenericArtifact docArtifact = Mockito.mock(GenericArtifact.class);
Mockito.when(artifactManager.getGenericArtifact(documentation.getId())).thenReturn(docArtifact);
Mockito.when(APIUtil.getDocumentation(docArtifact)).thenReturn(documentation);
Mockito.when(docArtifact.getPath()).thenReturn(artifactPath);
PowerMockito.doNothing().when(APIUtil.class, "clearResourcePermissions", Mockito.any(), Mockito.any(), Mockito.anyInt());
String[] roles = { "admin", "subscriber" };
APIUtil.setResourcePermissions("admin", "Public", roles, artifactPath);
Mockito.when(docArtifact.getAttribute(APIConstants.DOC_FILE_PATH)).thenReturn("docFilePath");
final APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, scopesDAO, documentationList, null);
RegistryService registryService = Mockito.mock(RegistryService.class);
UserRegistry userRegistry = Mockito.mock(UserRegistry.class);
ServiceReferenceHolder serviceReferenceHolder = TestUtils.getServiceReferenceHolder();
RealmService realmService = Mockito.mock(RealmService.class);
TenantManager tenantManager = Mockito.mock(TenantManager.class);
Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
Mockito.when(APIUtil.createAPIArtifactContent(artifact, oldApi)).thenReturn(artifact);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
Mockito.when(registryService.getConfigSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
PublisherAPI publisherAPI = Mockito.mock(PublisherAPI.class);
PowerMockito.when(apiPersistenceInstance.addAPI(any(Organization.class), any(PublisherAPI.class))).thenReturn(publisherAPI);
apiProvider.addAPI(oldApi);
// mock has permission
Resource apiSourceArtifact = Mockito.mock(Resource.class);
Mockito.when(apiSourceArtifact.getUUID()).thenReturn("12640983654");
String apiSourcePath = "path";
PowerMockito.when(APIUtil.getAPIPath(api.getId())).thenReturn(apiSourcePath);
PowerMockito.when(APIUtil.getAPIPath(oldApi.getId())).thenReturn(apiSourcePath);
PowerMockito.when(apiProvider.registry.get(apiSourcePath)).thenReturn(apiSourceArtifact);
// API Status is CREATED and user has permission
Mockito.when(artifact.getAttribute(APIConstants.API_OVERVIEW_STATUS)).thenReturn("CREATED");
Mockito.when(artifactManager.getGenericArtifact(apiSourceArtifact.getUUID())).thenReturn(artifact);
PowerMockito.when(APIUtil.hasPermission(null, APIConstants.Permissions.API_PUBLISH)).thenReturn(true);
PowerMockito.when(APIUtil.hasPermission(null, APIConstants.Permissions.API_CREATE)).thenReturn(true);
Mockito.when(apimgtDAO.getDefaultVersion(identifier)).thenReturn("1.0.0");
Mockito.when(apimgtDAO.getPublishedDefaultVersion(identifier)).thenReturn("1.0.0");
// updateDefaultAPIInRegistry
String defaultAPIPath = APIConstants.API_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + APIConstants.API_RESOURCE_NAME;
Resource defaultAPISourceArtifact = Mockito.mock(Resource.class);
String defaultAPIUUID = "12640983600";
Mockito.when(defaultAPISourceArtifact.getUUID()).thenReturn(defaultAPIUUID);
Mockito.when(apiProvider.registry.get(defaultAPIPath)).thenReturn(defaultAPISourceArtifact);
GenericArtifact defaultAPIArtifact = Mockito.mock(GenericArtifact.class);
Mockito.when(artifactManager.getGenericArtifact(defaultAPIUUID)).thenReturn(defaultAPIArtifact);
Mockito.doNothing().when(artifactManager).updateGenericArtifact(defaultAPIArtifact);
TestUtils.mockAPIMConfiguration(APIConstants.API_GATEWAY_TYPE, APIConstants.API_GATEWAY_TYPE_SYNAPSE, -1234);
// updateApiArtifact
PowerMockito.when(APIUtil.createAPIArtifactContent(artifact, api)).thenReturn(artifact);
Mockito.when(artifact.getId()).thenReturn("12640983654");
PowerMockito.when(GovernanceUtils.getArtifactPath(apiProvider.registry, "12640983654")).thenReturn(apiSourcePath);
// Mock Updating API
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
apiProvider.createAPI(api);
return null;
}
}).when(artifactManager).updateGenericArtifact(artifact);
APIManagerConfiguration config = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
GatewayArtifactSynchronizerProperties synchronizerProperties = new GatewayArtifactSynchronizerProperties();
Mockito.when(config.getGatewayArtifactSynchronizerProperties()).thenReturn(synchronizerProperties);
PowerMockito.when(apiPersistenceInstance.getPublisherAPI(any(Organization.class), any(String.class))).thenReturn(publisherAPI);
Mockito.when(APIUtil.getTiers(APIConstants.TIER_RESOURCE_TYPE, "carbon.super")).thenReturn(tiers);
apiProvider.updateAPI(api, oldApi);
Assert.assertEquals(0, api.getEnvironments().size());
tiers.remove("Gold", tier);
tier = new Tier("Unlimited");
tiers.put("Unlimited", tier);
try {
apiProvider.updateAPI(api, oldApi);
} catch (APIManagementException ex) {
Assert.assertTrue(ex.getMessage().contains("Invalid x-throttling tier Gold found in api definition for " + "resource POST /add"));
}
}
use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-apimgt by wso2.
the class AbstractAPIManagerTestCase method testGetAllApiSpecificMediationPolicies.
@Test
public void testGetAllApiSpecificMediationPolicies() throws RegistryException, APIManagementException, IOException, XMLStreamException {
APIIdentifier identifier = getAPIIdentifier(SAMPLE_API_NAME, API_PROVIDER, SAMPLE_API_VERSION);
String parentCollectionPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + identifier.getProviderName() + RegistryConstants.PATH_SEPARATOR + identifier.getApiName() + RegistryConstants.PATH_SEPARATOR + identifier.getVersion() + APIConstants.API_RESOURCE_NAME;
parentCollectionPath = parentCollectionPath.substring(0, parentCollectionPath.lastIndexOf("/"));
Collection parentCollection = new CollectionImpl();
parentCollection.setChildren(new String[] { parentCollectionPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN, parentCollectionPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_OUT, parentCollectionPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_FAULT });
Collection childCollection = new CollectionImpl();
childCollection.setChildren(new String[] { "mediation1" });
Mockito.when(registry.get(parentCollectionPath)).thenThrow(RegistryException.class).thenReturn(parentCollection);
Mockito.when(registry.get(parentCollectionPath + RegistryConstants.PATH_SEPARATOR + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN)).thenReturn(childCollection);
Resource resource = new ResourceImpl();
resource.setUUID(SAMPLE_RESOURCE_ID);
String mediationPolicyContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<sequence xmlns=\"http://ws.apache.org/ns/synapse\" name=\"default-endpoint\">\n</sequence>";
resource.setContent(mediationPolicyContent);
Mockito.when(registry.get("mediation1")).thenReturn(resource);
AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(registry);
try {
abstractAPIManager.getAllApiSpecificMediationPolicies(identifier);
Assert.fail("Registry exception not thrown for error scenario");
} catch (APIManagementException e) {
Assert.assertTrue(e.getMessage().contains("Error occurred while getting Api Specific mediation policies "));
}
Assert.assertEquals(abstractAPIManager.getAllApiSpecificMediationPolicies(identifier).size(), 1);
PowerMockito.mockStatic(IOUtils.class);
PowerMockito.mockStatic(AXIOMUtil.class);
PowerMockito.when(IOUtils.toString((InputStream) Mockito.any(), Mockito.anyString())).thenThrow(IOException.class).thenReturn(mediationPolicyContent);
PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())).thenThrow(XMLStreamException.class);
// covers exception which is only logged
abstractAPIManager.getAllApiSpecificMediationPolicies(identifier);
// covers exception which is only logged
abstractAPIManager.getAllApiSpecificMediationPolicies(identifier);
}
Aggregations