use of org.wso2.carbon.apimgt.api.model.subscription.URLMapping in project carbon-apimgt by wso2.
the class ApiMgtDAO method restoreAPIRevision.
/**
* Restore API revision database records as the Current API of an API
*
* @param apiRevision content of the revision
* @throws APIManagementException if an error occurs when restoring an API revision
*/
public void restoreAPIRevision(APIRevision apiRevision) throws APIManagementException {
try (Connection connection = APIMgtDBUtil.getConnection()) {
try {
connection.setAutoCommit(false);
// Retrieve API ID
APIIdentifier apiIdentifier = APIUtil.getAPIIdentifierFromUUID(apiRevision.getApiUUID());
int apiId = getAPIID(apiRevision.getApiUUID(), connection);
int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
String tenantDomain = APIUtil.getTenantDomainFromTenantId(tenantId);
// Removing related Current API entries from AM_API_URL_MAPPING table
PreparedStatement removeURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.REMOVE_CURRENT_API_ENTRIES_IN_AM_API_URL_MAPPING_BY_API_ID);
removeURLMappingsStatement.setInt(1, apiId);
removeURLMappingsStatement.executeUpdate();
// Restoring to AM_API_URL_MAPPING table
PreparedStatement getURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_URL_MAPPINGS_WITH_SCOPE_AND_PRODUCT_ID_BY_REVISION_UUID);
getURLMappingsStatement.setInt(1, apiId);
getURLMappingsStatement.setString(2, apiRevision.getRevisionUUID());
List<URITemplate> urlMappingList = new ArrayList<>();
try (ResultSet rs = getURLMappingsStatement.executeQuery()) {
while (rs.next()) {
String script = null;
URITemplate uriTemplate = new URITemplate();
uriTemplate.setHTTPVerb(rs.getString(1));
uriTemplate.setAuthType(rs.getString(2));
uriTemplate.setUriTemplate(rs.getString(3));
uriTemplate.setThrottlingTier(rs.getString(4));
InputStream mediationScriptBlob = rs.getBinaryStream(5);
if (mediationScriptBlob != null) {
script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
}
uriTemplate.setMediationScript(script);
if (!StringUtils.isEmpty(rs.getString(6))) {
Scope scope = new Scope();
scope.setKey(rs.getString(6));
uriTemplate.setScope(scope);
}
if (rs.getInt(7) != 0) {
// Adding product id to uri template id just to store value
uriTemplate.setId(rs.getInt(7));
}
urlMappingList.add(uriTemplate);
}
}
Map<String, URITemplate> uriTemplateMap = new HashMap<>();
for (URITemplate urlMapping : urlMappingList) {
if (urlMapping.getScope() != null) {
URITemplate urlMappingNew = urlMapping;
URITemplate urlMappingExisting = uriTemplateMap.get(urlMapping.getUriTemplate() + urlMapping.getHTTPVerb());
if (urlMappingExisting != null && urlMappingExisting.getScopes() != null) {
if (!urlMappingExisting.getScopes().contains(urlMapping.getScope())) {
urlMappingExisting.setScopes(urlMapping.getScope());
uriTemplateMap.put(urlMappingExisting.getUriTemplate() + urlMappingExisting.getHTTPVerb(), urlMappingExisting);
}
} else {
urlMappingNew.setScopes(urlMapping.getScope());
uriTemplateMap.put(urlMappingNew.getUriTemplate() + urlMappingNew.getHTTPVerb(), urlMappingNew);
}
} else {
uriTemplateMap.put(urlMapping.getUriTemplate() + urlMapping.getHTTPVerb(), urlMapping);
}
}
setOperationPoliciesToURITemplatesMap(apiRevision.getRevisionUUID(), uriTemplateMap);
PreparedStatement insertURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_URL_MAPPINGS_CURRENT_API);
for (URITemplate urlMapping : uriTemplateMap.values()) {
insertURLMappingsStatement.setInt(1, apiId);
insertURLMappingsStatement.setString(2, urlMapping.getHTTPVerb());
insertURLMappingsStatement.setString(3, urlMapping.getAuthType());
insertURLMappingsStatement.setString(4, urlMapping.getUriTemplate());
insertURLMappingsStatement.setString(5, urlMapping.getThrottlingTier());
insertURLMappingsStatement.addBatch();
}
insertURLMappingsStatement.executeBatch();
// Add to AM_API_RESOURCE_SCOPE_MAPPING table and to AM_API_PRODUCT_MAPPING
PreparedStatement getCurrentAPIURLMappingsStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_CURRENT_API_URL_MAPPINGS_ID);
PreparedStatement insertScopeResourceMappingStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_SCOPE_RESOURCE_MAPPING);
PreparedStatement insertProductResourceMappingStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_PRODUCT_RESOURCE_MAPPING);
PreparedStatement insertOperationPolicyMappingStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.ADD_API_OPERATION_POLICY_MAPPING);
PreparedStatement deleteOutdatedOperationPolicyStatement = connection.prepareStatement(SQLConstants.OperationPolicyConstants.DELETE_OPERATION_POLICY_BY_POLICY_ID);
Map<String, String> restoredPolicyMap = new HashMap<>();
Set<String> usedClonedPolicies = new HashSet<String>();
for (URITemplate urlMapping : uriTemplateMap.values()) {
if (urlMapping.getScopes() != null) {
getCurrentAPIURLMappingsStatement.setInt(1, apiId);
getCurrentAPIURLMappingsStatement.setString(2, urlMapping.getHTTPVerb());
getCurrentAPIURLMappingsStatement.setString(3, urlMapping.getAuthType());
getCurrentAPIURLMappingsStatement.setString(4, urlMapping.getUriTemplate());
getCurrentAPIURLMappingsStatement.setString(5, urlMapping.getThrottlingTier());
try (ResultSet rs = getCurrentAPIURLMappingsStatement.executeQuery()) {
while (rs.next()) {
for (Scope scope : urlMapping.getScopes()) {
insertScopeResourceMappingStatement.setString(1, scope.getKey());
insertScopeResourceMappingStatement.setInt(2, rs.getInt(1));
insertScopeResourceMappingStatement.setInt(3, tenantId);
insertScopeResourceMappingStatement.addBatch();
}
}
}
}
if (urlMapping.getId() != 0) {
getCurrentAPIURLMappingsStatement.setInt(1, apiId);
getCurrentAPIURLMappingsStatement.setString(2, urlMapping.getHTTPVerb());
getCurrentAPIURLMappingsStatement.setString(3, urlMapping.getAuthType());
getCurrentAPIURLMappingsStatement.setString(4, urlMapping.getUriTemplate());
getCurrentAPIURLMappingsStatement.setString(5, urlMapping.getThrottlingTier());
try (ResultSet rs = getCurrentAPIURLMappingsStatement.executeQuery()) {
while (rs.next()) {
insertProductResourceMappingStatement.setInt(1, urlMapping.getId());
insertProductResourceMappingStatement.setInt(2, rs.getInt(1));
insertProductResourceMappingStatement.addBatch();
}
}
}
if (!urlMapping.getOperationPolicies().isEmpty()) {
getCurrentAPIURLMappingsStatement.setInt(1, apiId);
getCurrentAPIURLMappingsStatement.setString(2, urlMapping.getHTTPVerb());
getCurrentAPIURLMappingsStatement.setString(3, urlMapping.getAuthType());
getCurrentAPIURLMappingsStatement.setString(4, urlMapping.getUriTemplate());
getCurrentAPIURLMappingsStatement.setString(5, urlMapping.getThrottlingTier());
try (ResultSet rs = getCurrentAPIURLMappingsStatement.executeQuery()) {
while (rs.next()) {
for (OperationPolicy policy : urlMapping.getOperationPolicies()) {
if (!restoredPolicyMap.keySet().contains(policy.getPolicyName())) {
String restoredPolicyId = restoreOperationPolicyRevision(connection, apiRevision.getApiUUID(), policy.getPolicyId(), apiRevision.getId(), tenantDomain);
// policy ID is stored in a map as same policy can be applied to multiple operations
// and we only need to create the policy once.
restoredPolicyMap.put(policy.getPolicyName(), restoredPolicyId);
usedClonedPolicies.add(restoredPolicyId);
}
Gson gson = new Gson();
String paramJSON = gson.toJson(policy.getParameters());
insertOperationPolicyMappingStatement.setInt(1, rs.getInt(1));
insertOperationPolicyMappingStatement.setString(2, restoredPolicyMap.get(policy.getPolicyName()));
insertOperationPolicyMappingStatement.setString(3, policy.getDirection());
insertOperationPolicyMappingStatement.setString(4, paramJSON);
insertOperationPolicyMappingStatement.setInt(5, policy.getOrder());
insertOperationPolicyMappingStatement.addBatch();
}
}
}
}
}
insertScopeResourceMappingStatement.executeBatch();
insertProductResourceMappingStatement.executeBatch();
insertOperationPolicyMappingStatement.executeBatch();
deleteOutdatedOperationPolicyStatement.executeBatch();
cleanUnusedClonedOperationPolicies(connection, usedClonedPolicies, apiRevision.getApiUUID());
// Restoring AM_API_CLIENT_CERTIFICATE table entries
PreparedStatement removeClientCertificatesStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.REMOVE_CURRENT_API_ENTRIES_IN_AM_API_CLIENT_CERTIFICATE_BY_API_ID);
removeClientCertificatesStatement.setInt(1, apiId);
removeClientCertificatesStatement.executeUpdate();
PreparedStatement getClientCertificatesStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_CLIENT_CERTIFICATES_BY_REVISION_UUID);
getClientCertificatesStatement.setInt(1, apiId);
getClientCertificatesStatement.setString(2, apiRevision.getRevisionUUID());
List<ClientCertificateDTO> clientCertificateDTOS = new ArrayList<>();
try (ResultSet rs = getClientCertificatesStatement.executeQuery()) {
while (rs.next()) {
ClientCertificateDTO clientCertificateDTO = new ClientCertificateDTO();
clientCertificateDTO.setAlias(rs.getString(1));
clientCertificateDTO.setCertificate(APIMgtDBUtil.getStringFromInputStream(rs.getBinaryStream(2)));
clientCertificateDTO.setTierName(rs.getString(3));
clientCertificateDTOS.add(clientCertificateDTO);
}
}
PreparedStatement insertClientCertificateStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_CLIENT_CERTIFICATES_AS_CURRENT_API);
for (ClientCertificateDTO clientCertificateDTO : clientCertificateDTOS) {
insertClientCertificateStatement.setInt(1, tenantId);
insertClientCertificateStatement.setString(2, clientCertificateDTO.getAlias());
insertClientCertificateStatement.setInt(3, apiId);
insertClientCertificateStatement.setBinaryStream(4, getInputStream(clientCertificateDTO.getCertificate()));
insertClientCertificateStatement.setBoolean(5, false);
insertClientCertificateStatement.setString(6, clientCertificateDTO.getTierName());
insertClientCertificateStatement.setString(7, "Current API");
insertClientCertificateStatement.addBatch();
}
insertClientCertificateStatement.executeBatch();
// Restoring AM_GRAPHQL_COMPLEXITY table
PreparedStatement removeGraphQLComplexityStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.REMOVE_CURRENT_API_ENTRIES_IN_AM_GRAPHQL_COMPLEXITY_BY_API_ID);
removeGraphQLComplexityStatement.setInt(1, apiId);
removeGraphQLComplexityStatement.executeUpdate();
PreparedStatement getGraphQLComplexityStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_GRAPHQL_COMPLEXITY_BY_REVISION_UUID);
List<CustomComplexityDetails> customComplexityDetailsList = new ArrayList<>();
getGraphQLComplexityStatement.setInt(1, apiId);
getGraphQLComplexityStatement.setString(2, apiRevision.getRevisionUUID());
try (ResultSet rs1 = getGraphQLComplexityStatement.executeQuery()) {
while (rs1.next()) {
CustomComplexityDetails customComplexityDetails = new CustomComplexityDetails();
customComplexityDetails.setType(rs1.getString("TYPE"));
customComplexityDetails.setField(rs1.getString("FIELD"));
customComplexityDetails.setComplexityValue(rs1.getInt("COMPLEXITY_VALUE"));
customComplexityDetailsList.add(customComplexityDetails);
}
}
PreparedStatement insertGraphQLComplexityStatement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.INSERT_GRAPHQL_COMPLEXITY_AS_CURRENT_API);
for (CustomComplexityDetails customComplexityDetails : customComplexityDetailsList) {
insertGraphQLComplexityStatement.setString(1, UUID.randomUUID().toString());
insertGraphQLComplexityStatement.setInt(2, apiId);
insertGraphQLComplexityStatement.setString(3, customComplexityDetails.getType());
insertGraphQLComplexityStatement.setString(4, customComplexityDetails.getField());
insertGraphQLComplexityStatement.setInt(5, customComplexityDetails.getComplexityValue());
insertGraphQLComplexityStatement.addBatch();
}
insertGraphQLComplexityStatement.executeBatch();
restoreAPIRevisionMetaDataToWorkingCopy(connection, apiRevision.getApiUUID(), apiRevision.getRevisionUUID());
connection.commit();
} catch (SQLException e) {
connection.rollback();
handleException("Failed to restore API Revision entry of API UUID " + apiRevision.getApiUUID(), e);
}
} catch (SQLException e) {
handleException("Failed to restore API Revision entry of API UUID " + apiRevision.getApiUUID(), e);
}
}
use of org.wso2.carbon.apimgt.api.model.subscription.URLMapping in project carbon-apimgt by wso2.
the class DefaultKeyValidationHandlerTest method testValidateScopes.
@Test
public void testValidateScopes() throws APIKeyMgtException {
API api = new API();
api.setApiId(1);
api.setApiProvider(USER_NAME);
api.setApiName(API_NAME);
api.setApiVersion(API_VERSION);
api.setContext(API_CONTEXT);
URLMapping urlMapping = new URLMapping();
urlMapping.addScope(SCOPES);
urlMapping.setHttpMethod(HTTP_VERB);
urlMapping.setUrlPattern(RESOURCE);
api.addResource(urlMapping);
Map<String, API> apiMap = new HashMap<>();
String key = API_CONTEXT + ":" + API_VERSION;
apiMap.put(key, api);
APIKeyValidationInfoDTO dto = new APIKeyValidationInfoDTO();
dto.setSubscriber(SUBSCRIBER);
dto.setApplicationName(APPLICATION_NAME);
dto.setApplicationId(APPLICATION_ID);
dto.setApplicationTier(TIER);
Set<String> scopeSet = new HashSet<>();
scopeSet.add(SCOPES);
dto.setScopes(scopeSet);
dto.setSubscriberTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
dto.setUserType(APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
// TokenValidationContext for non default API
TokenValidationContext param1 = new TokenValidationContext();
param1.setValidationInfoDTO(dto);
param1.setContext(API_CONTEXT);
param1.setVersion(API_VERSION);
param1.setAccessToken(ACCESS_TOKEN);
param1.setMatchingResource(RESOURCE);
param1.setHttpVerb(HTTP_VERB);
// TokenValidationContext for default API version
TokenValidationContext param2 = new TokenValidationContext();
param2.setValidationInfoDTO(dto);
param2.setContext(API_CONTEXT);
param2.setVersion(DEFAULT_API_VERSION);
param2.setAccessToken(ACCESS_TOKEN);
param2.setMatchingResource(RESOURCE);
param2.setHttpVerb(HTTP_VERB);
Mockito.when(SubscriptionDataHolder.getInstance()).thenReturn(subscriptionDataHolder);
Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
Mockito.when(subscriptionDataHolder.getTenantSubscriptionStore(eq(TENANT_DOMAIN))).thenReturn(tenantSubscriptionStore);
Mockito.when(tenantSubscriptionStore.getApiByContextAndVersion(eq(API_CONTEXT), eq(API_VERSION))).thenReturn(api);
DefaultKeyValidationHandler defaultKeyValidationHandler = new DefaultKeyValidationHandler();
boolean isScopeValidated = defaultKeyValidationHandler.validateScopes(param1);
boolean isScopeValidated_default = defaultKeyValidationHandler.validateScopes(param2);
Assert.assertTrue("Scope validation fails for API " + API_NAME, isScopeValidated);
Assert.assertTrue("Scope validation fails for default API " + API_NAME, isScopeValidated_default);
}
use of org.wso2.carbon.apimgt.api.model.subscription.URLMapping in project carbon-apimgt by wso2.
the class DefaultKeyValidationHandlerTest method testInvalidSubscription.
@Test
public void testInvalidSubscription() throws APIKeyMgtException {
DefaultKeyValidationHandler defaultKeyValidationHandler = new DefaultKeyValidationHandler();
API api = new API();
api.setApiId(1);
api.setApiProvider(USER_NAME);
api.setApiName(API_NAME);
api.setApiVersion(API_VERSION);
api.setContext(API_CONTEXT);
URLMapping urlMapping = new URLMapping();
urlMapping.addScope(SCOPES);
urlMapping.setHttpMethod(HTTP_VERB);
urlMapping.setUrlPattern(RESOURCE);
api.addResource(urlMapping);
Mockito.when(SubscriptionDataHolder.getInstance()).thenReturn(subscriptionDataHolder);
Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
Mockito.when(subscriptionDataHolder.getTenantSubscriptionStore(eq(TENANT_DOMAIN))).thenReturn(tenantSubscriptionStore);
Mockito.when(tenantSubscriptionStore.getApiByContextAndVersion(eq(API_CONTEXT), eq(API_VERSION))).thenReturn(api);
APIKeyValidationInfoDTO info = defaultKeyValidationHandler.validateSubscription(API_CONTEXT, API_VERSION, "xxxxxx", "default");
Assert.assertEquals("Invalid error message status code ", APIConstants.KeyValidationStatus.API_AUTH_RESOURCE_FORBIDDEN, info.getValidationStatus());
}
use of org.wso2.carbon.apimgt.api.model.subscription.URLMapping in project carbon-apimgt by wso2.
the class HandshakeProcessorTest method handleSuccessfulHandshake.
@Test
public void handleSuccessfulHandshake() throws Exception {
InboundMessageContext inboundMessageContext = new InboundMessageContext();
URLMapping urlMapping = new URLMapping();
urlMapping.setHttpMethod("SUBSCRIPTION");
urlMapping.setThrottlingPolicy("Unlimited");
urlMapping.setUrlPattern("liftStatusChange");
org.wso2.carbon.apimgt.keymgt.model.entity.API api = new API();
api.addResource(urlMapping);
inboundMessageContext.setElectedAPI(api);
PowerMockito.mockStatic(InboundWebsocketProcessorUtil.class);
PowerMockito.when(InboundWebsocketProcessorUtil.isAuthenticated(inboundMessageContext)).thenReturn(true);
HandshakeProcessor handshakeProcessor = new HandshakeProcessor();
InboundProcessorResponseDTO inboundProcessorResponseDTO = handshakeProcessor.processHandshake(inboundMessageContext);
Assert.assertFalse(inboundProcessorResponseDTO.isError());
Assert.assertNull(inboundProcessorResponseDTO.getErrorMessage());
Assert.assertFalse(inboundProcessorResponseDTO.isCloseConnection());
}
use of org.wso2.carbon.apimgt.api.model.subscription.URLMapping in project carbon-apimgt by wso2.
the class SubscriptionValidationDataUtil method fromAPItoDTO.
private static APIDTO fromAPItoDTO(API model) {
APIDTO apidto = null;
if (model != null) {
apidto = new APIDTO();
apidto.setUuid(model.getApiUUID());
apidto.setApiId(model.getApiId());
apidto.setVersion(model.getVersion());
apidto.setName(model.getName());
apidto.setContext(model.getContext());
apidto.setPolicy(model.getPolicy());
apidto.setProvider(model.getProvider());
apidto.setApiType(model.getApiType());
apidto.setName(model.getName());
apidto.setStatus(model.getStatus());
apidto.setIsDefaultVersion(model.isDefaultVersion());
Map<String, URLMapping> urlMappings = model.getAllResources();
List<URLMappingDTO> urlMappingsDTO = new ArrayList<>();
for (URLMapping urlMapping : urlMappings.values()) {
URLMappingDTO urlMappingDTO = new URLMappingDTO();
urlMappingDTO.setAuthScheme(urlMapping.getAuthScheme());
urlMappingDTO.setHttpMethod(urlMapping.getHttpMethod());
urlMappingDTO.setThrottlingPolicy(urlMapping.getThrottlingPolicy());
urlMappingDTO.setUrlPattern(urlMapping.getUrlPattern());
urlMappingDTO.setScopes(urlMapping.getScopes());
urlMappingsDTO.add(urlMappingDTO);
}
apidto.setUrlMappings(urlMappingsDTO);
}
return apidto;
}
Aggregations