use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.
the class APIProviderImplTest method testGetCustomInSequences1.
@Test
public void testGetCustomInSequences1() throws Exception {
APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.1");
APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
mockSequences(APIConstants.API_CUSTOM_INSEQUENCE_LOCATION, APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN, apiId);
List<String> sequenceList = apiProvider.getCustomInSequences();
Assert.assertNotNull(sequenceList);
Assert.assertEquals(1, sequenceList.size());
// OMException when building OMElement
PowerMockito.when(APIUtil.buildOMElement(any(InputStream.class))).thenThrow(new OMException());
apiProvider.getCustomOutSequences(apiId);
// org.wso2.carbon.registry.api.RegistryException
ServiceReferenceHolder sh = PowerMockito.mock(ServiceReferenceHolder.class);
PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(sh);
RegistryService registryService = Mockito.mock(RegistryService.class);
PowerMockito.when(sh.getRegistryService()).thenReturn(registryService);
UserRegistry registry = Mockito.mock(UserRegistry.class);
PowerMockito.when(registryService.getGovernanceSystemRegistry(Matchers.anyInt())).thenReturn(registry);
Mockito.when(registry.resourceExists(APIConstants.API_CUSTOM_INSEQUENCE_LOCATION)).thenThrow(org.wso2.carbon.registry.api.RegistryException.class);
String msg = "Error while processing the in in the registry";
try {
apiProvider.getCustomInSequences();
} catch (APIManagementException e) {
Assert.assertEquals(msg, e.getMessage());
}
// Registry Exception
PowerMockito.when(registryService.getGovernanceSystemRegistry(Matchers.anyInt())).thenThrow(RegistryException.class);
String msg1 = "Error while retrieving registry for tenant -1";
try {
apiProvider.getCustomInSequences();
} catch (APIManagementException e) {
Assert.assertEquals(msg1, e.getMessage());
}
}
use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.
the class APIProviderImplTest method testAddFileToDocumentation.
/**
* This method tests adding file to documentation method.
* @throws Exception
*
* @throws GovernanceException Governance Exception.
*/
@Test
public void testAddFileToDocumentation() throws Exception {
String apiUUID = "xxxxxxxx";
String docUUID = "yyyyyyyy";
APIIdentifier identifier = new APIIdentifier("admin-AT-carbon.super", "API1", "1.0.0");
Set<String> environments = new HashSet<String>();
Set<URITemplate> uriTemplates = 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);
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(uriTemplates);
api.setOrganization("carbon.super");
List<Documentation> documentationList = getDocumentationList();
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(APIUtil.getTiers(APIConstants.TIER_RESOURCE_TYPE, "carbon.super")).thenReturn(tiers);
Mockito.when(artifactManager.newGovernanceArtifact(any(QName.class))).thenReturn(artifact);
Mockito.when(APIUtil.createAPIArtifactContent(artifact, api)).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(api);
String fileName = "test.txt";
String contentType = "application/force-download";
Documentation doc = new Documentation(DocumentationType.HOWTO, fileName);
doc.setSourceType(DocumentSourceType.FILE);
PowerMockito.when(APIUtil.getDocumentationFilePath(api.getId(), fileName)).thenReturn("filePath");
InputStream inputStream = Mockito.mock(InputStream.class);
// apiProvider.addFileToDocumentation(api.getId(), doc, fileName, inputStream, contentType);
DocumentationContent content = new DocumentationContent();
ResourceFile resourceFile = new ResourceFile(inputStream, contentType);
content.setResourceFile(resourceFile);
apiProvider.addDocumentationContent(apiUUID, docUUID, "carbon.super", content);
}
use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.
the class ApiMgtDAO method getSubscribedAPIs.
/**
* This method returns the set of APIs for given subscriber, subscribed under the specified application.
*
* @param subscriber subscriber
* @param applicationName Application Name
* @return Set<API>
* @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get SubscribedAPIs
*/
public Set<SubscribedAPI> getSubscribedAPIs(Subscriber subscriber, String applicationName, String groupingId) throws APIManagementException {
Set<SubscribedAPI> subscribedAPIs = new LinkedHashSet<SubscribedAPI>();
Connection connection = null;
PreparedStatement ps = null;
ResultSet result = null;
String sqlQuery = SQLConstants.GET_SUBSCRIBED_APIS_SQL;
String whereClauseWithGroupId = " AND (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)" + " AND SUB.USER_ID = ?))";
String whereClauseWithGroupIdorceCaseInsensitiveComp = " AND (APP.GROUP_ID = ?" + " OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL) AND LOWER(SUB.USER_ID) = LOWER(?)))";
String whereClause = " AND SUB.USER_ID = ? ";
String whereClauseCaseSensitive = " AND LOWER(SUB.USER_ID) = LOWER(?) ";
String whereClauseWithMultiGroupId = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM " + "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR ( SUB.USER_ID = ? ))";
String whereClauseWithMultiGroupIdCaseInsensitive = " AND ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID " + "FROM AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) OR ( LOWER(SUB" + ".USER_ID) = LOWER" + "(?) ))";
try {
connection = APIMgtDBUtil.getConnection();
if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
if (multiGroupAppSharingEnabled) {
if (forceCaseInsensitiveComparisons) {
sqlQuery += whereClauseWithMultiGroupIdCaseInsensitive;
} else {
sqlQuery += whereClauseWithMultiGroupId;
}
String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
String[] groupIdArr = groupingId.split(",");
ps = fillQueryParams(connection, sqlQuery, groupIdArr, 3);
int tenantId = APIUtil.getTenantId(subscriber.getName());
ps.setInt(1, tenantId);
ps.setString(2, applicationName);
int paramIndex = groupIdArr.length + 2;
ps.setString(++paramIndex, tenantDomain);
ps.setString(++paramIndex, subscriber.getName());
} else {
if (forceCaseInsensitiveComparisons) {
sqlQuery += whereClauseWithGroupIdorceCaseInsensitiveComp;
} else {
sqlQuery += whereClauseWithGroupId;
}
ps = connection.prepareStatement(sqlQuery);
int tenantId = APIUtil.getTenantId(subscriber.getName());
ps.setInt(1, tenantId);
ps.setString(2, applicationName);
ps.setString(3, groupingId);
ps.setString(4, subscriber.getName());
}
} else {
if (forceCaseInsensitiveComparisons) {
sqlQuery += whereClauseCaseSensitive;
} else {
sqlQuery += whereClause;
}
ps = connection.prepareStatement(sqlQuery);
int tenantId = APIUtil.getTenantId(subscriber.getName());
ps.setInt(1, tenantId);
ps.setString(2, applicationName);
ps.setString(3, subscriber.getName());
}
result = ps.executeQuery();
while (result.next()) {
APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(result.getString("API_PROVIDER")), result.getString("API_NAME"), result.getString("API_VERSION"));
apiIdentifier.setUuid(result.getString("API_UUID"));
SubscribedAPI subscribedAPI = new SubscribedAPI(subscriber, apiIdentifier);
subscribedAPI.setSubscriptionId(result.getInt("SUBS_ID"));
subscribedAPI.setSubStatus(result.getString("SUB_STATUS"));
subscribedAPI.setSubCreatedStatus(result.getString("SUBS_CREATE_STATE"));
subscribedAPI.setUUID(result.getString("SUB_UUID"));
subscribedAPI.setTier(new Tier(result.getString(APIConstants.SUBSCRIPTION_FIELD_TIER_ID)));
Application application = new Application(result.getString("APP_NAME"), subscriber);
application.setUUID(result.getString("APP_UUID"));
subscribedAPI.setApplication(application);
subscribedAPIs.add(subscribedAPI);
}
} catch (SQLException e) {
handleException("Failed to get SubscribedAPI of :" + subscriber.getName(), e);
} finally {
APIMgtDBUtil.closeAllConnections(ps, connection, result);
}
return subscribedAPIs;
}
use of org.wso2.carbon.apimgt.api.model.APIIdentifier in project carbon-apimgt by wso2.
the class ApiMgtDAO method deleteExternalAPIStoresDetails.
/**
* Delete the records of external APIStore details.
*
* @param uuid API uuid
* @param apiStoreSet APIStores set
* @return added/failed
* @throws APIManagementException
*/
public boolean deleteExternalAPIStoresDetails(String uuid, Set<APIStore> apiStoreSet) throws APIManagementException {
Connection conn = null;
PreparedStatement ps = null;
boolean state = false;
try {
conn = APIMgtDBUtil.getConnection();
conn.setAutoCommit(false);
String sqlQuery = SQLConstants.REMOVE_EXTERNAL_API_STORE_SQL;
// Get API Id
int apiIdentifier;
apiIdentifier = getAPIID(uuid, conn);
if (apiIdentifier == -1) {
String msg = "Could not load API record for API with UUID: " + uuid;
log.error(msg);
}
ps = conn.prepareStatement(sqlQuery);
for (Object storeObject : apiStoreSet) {
APIStore store = (APIStore) storeObject;
ps.setInt(1, apiIdentifier);
ps.setString(2, store.getName());
ps.setString(3, store.getType());
ps.addBatch();
}
ps.executeBatch();
conn.commit();
state = true;
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();
} catch (SQLException e1) {
log.error("Failed to rollback deleting external apistore details ", e1);
}
}
log.error("Failed to delete external apistore details", e);
state = false;
} catch (APIManagementException e) {
log.error("Failed to delete external apistore details", e);
state = false;
} finally {
APIMgtDBUtil.closeAllConnections(ps, conn, null);
}
return state;
}
use of org.wso2.carbon.apimgt.api.model.APIIdentifier 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);
}
}
Aggregations