org.wso2.carbon.apimgt.impl.utils.APIUtil Java Examples

The following examples show how to use org.wso2.carbon.apimgt.impl.utils.APIUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SearchResultMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get Document result representation for content search
 *
 * @param document Api Document
 * @return DocumentSearchResultDTO
 */
public static DocumentSearchResultDTO fromDocumentationToDocumentResultDTO(Documentation document, API api) {

    DocumentSearchResultDTO docResultDTO = new DocumentSearchResultDTO();
    docResultDTO.setId(document.getId());
    docResultDTO.setName(document.getName());
    docResultDTO.setDocType(DocumentSearchResultDTO.DocTypeEnum.valueOf(document.getType().toString()));
    docResultDTO.setType(SearchResultDTO.TypeEnum.DOC);
    docResultDTO.setSummary(document.getSummary());
    docResultDTO.associatedType(APIConstants.AuditLogConstants.API);
    docResultDTO.setVisibility(DocumentSearchResultDTO.VisibilityEnum.valueOf(document.getVisibility().toString()));
    docResultDTO.setSourceType(DocumentSearchResultDTO.SourceTypeEnum.valueOf(document.getSourceType().toString()));
    docResultDTO.setOtherTypeName(document.getOtherTypeName());
    APIIdentifier apiId = api.getId();
    docResultDTO.setApiName(apiId.getApiName());
    docResultDTO.setApiVersion(apiId.getVersion());
    docResultDTO.setApiProvider(APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
    docResultDTO.setApiUUID(api.getUUID());
    return docResultDTO;
}
 
Example #2
Source File: CustomAPIIndexerTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method checks the indexer's behaviour for new APIs which does not have the relevant properties.
 *
 * @throws RegistryException Registry Exception.
 * @throws APIManagementException API Management Exception.
 */
@Test
public void testIndexDocumentForNewAPI() throws APIManagementException, RegistryException {
    Resource resource = new ResourceImpl();
    PowerMockito.mockStatic(APIUtil.class);
    GenericArtifactManager artifactManager = Mockito.mock(GenericArtifactManager.class);
    PowerMockito.when(APIUtil.getArtifactManager((UserRegistry)(Mockito.anyObject()), Mockito.anyString())).
            thenReturn(artifactManager);
    GenericArtifact genericArtifact = Mockito.mock(GenericArtifact.class);
    Mockito.when(artifactManager.getGenericArtifact(Mockito.anyString())).thenReturn(genericArtifact);
    Mockito.when(genericArtifact.getAttribute(APIConstants.API_OVERVIEW_VISIBILITY)).thenReturn("public");
    PowerMockito.when(APIUtil.getAPI(genericArtifact, userRegistry))
            .thenReturn(Mockito.mock(API.class));
    resource.setProperty(APIConstants.ACCESS_CONTROL, APIConstants.NO_ACCESS_CONTROL);
    resource.setProperty(APIConstants.PUBLISHER_ROLES, APIConstants.NULL_USER_ROLE_LIST);
    resource.setProperty(APIConstants.STORE_VIEW_ROLES, APIConstants.NULL_USER_ROLE_LIST);
    Mockito.doReturn(resource).when(userRegistry).get(Mockito.anyString());
    indexer.getIndexedDocument(file2Index);
    Assert.assertNull(APIConstants.CUSTOM_API_INDEXER_PROPERTY + " property was set for the API which does not "
            + "require migration", resource.getProperty(APIConstants.CUSTOM_API_INDEXER_PROPERTY));
}
 
Example #3
Source File: TokenUtilTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void registerClient() throws Exception {
    Map<String, String> configMap = new HashMap<>();
    configMap.put(APIConstants.API_KEY_VALIDATOR_USERNAME, "Username");
    configMap.put(APIConstants.API_KEY_VALIDATOR_PASSWORD, "Password");
    mockAPIMConfiguration(configMap);
    mockAppCreationCall();
    PowerMockito.mockStatic(ConfigManager.class);
    PowerMockito.mockStatic(APIUtil.class);
    HttpClient httpClient = Mockito.mock(HttpClient.class);
    PowerMockito.when(APIUtil.getHttpClient(Mockito.anyInt(), Mockito.anyString())).thenReturn(httpClient);
    ConfigDTO configDTO = Mockito.mock(ConfigDTO.class);
    PowerMockito.when(ConfigManager.getConfigurationDTO()).thenReturn(configDTO);
    Mockito.when(ConfigManager.getConfigurationDTO().getUrl_publisher()).thenReturn("https" +
            "://localhost:9443");
    OAuthApplicationInfoDTO infoDTO = TokenUtil.registerClient();
    Assert.assertNotNull(infoDTO);
}
 
Example #4
Source File: APIGatewayManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * To update the database instance with the successfully removed client certificates from teh gateway.
 *
 * @param api          Relevant API related with teh removed certificate.
 * @param tenantDomain Tenant domain of the API.
 */
private void updateRemovedClientCertificates(API api, String tenantDomain) {

    if (!CertificateManagerImpl.getInstance().isClientCertificateBasedAuthenticationConfigured()) {
        return;
    }
    try {
        CertificateMgtDAO.getInstance().updateRemovedCertificatesFromGateways(api.getId(),
                APIUtil.getTenantIdFromTenantDomain(tenantDomain));
        /* The flow does not need to be blocked, as this failure do not related with updating client certificates
         in gateway, rather updating in database. There is no harm in database having outdated certificate
         information.*/
    } catch (CertificateManagementException e) {
        log.error("Certificate Management Exception while trying to update the remove certificate from gateways "
                + "for the api " + api.getId() + " for the tenant domain " + tenantDomain, e);
    }
}
 
Example #5
Source File: AbstractJWTGenerator.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Helper method to add public certificate to JWT_HEADER to signature verification.
 *
 * @param endUserName - The end user name
 * @throws APIManagementException
 */
protected String addCertToHeader(String endUserName) throws APIManagementException {

    try {
        //get tenant domain
        String tenantDomain = MultitenantUtils.getTenantDomain(endUserName);
        Certificate publicCert = CertificateMgtUtils.getInstance().getPublicCertificate(tenantDomain);

        //TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization
        if (publicCert == null) {
            throw new APIManagementException("Error in obtaining keystore for tenantDomain = " + tenantDomain);
        } else {
            return APIUtil.generateHeader(publicCert, signatureAlgorithm);
        }
    } catch (APIManagementException e) {
        String error = "Error in obtaining tenant's keystore";
        throw new APIManagementException(error, e);
    }
}
 
Example #6
Source File: StoreAlertConfigurator.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public void addAlertConfiguration(String userName, String alertName, Map<String, String> configProperties)
        throws APIManagementException {

    String applicationId = configProperties.get(AlertMgtConstants.APPLICATION_ID_KEY);
    String apiName = configProperties.get(AlertMgtConstants.API_NAME_KEY);
    String apiVersion = configProperties.get(AlertMgtConstants.API_VERSION_KEY);
        String thresholdRequestCountPerMin = configProperties.get(AlertMgtConstants.REQUEST_COUNT_KEY);
    String query =
            "select '" + applicationId + "' as applicationId, '" + userName + "' as subscriber, '" + apiName
                    + "' as apiName, '" + apiVersion + "' as apiVersion, "
                    + Integer.valueOf(thresholdRequestCountPerMin)
                    + " as thresholdRequestCountPerMin update or insert into ApiSubAlertConf "
                    + "set ApiSubAlertConf.thresholdRequestCountPerMin = thresholdRequestCountPerMin "
                    + "on ApiSubAlertConf.applicationId == applicationId and "
                    + "ApiSubAlertConf.subscriber == subscriber and "
                    + "ApiSubAlertConf.apiName == apiName and ApiSubAlertConf.apiVersion == apiVersion";
    APIUtil.executeQueryOnStreamProcessor(AlertMgtConstants.APIM_ALERT_CONFIG_APP, query);
}
 
Example #7
Source File: SubscriptionMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Convert Subscriber claims information into SubscriberInfoDTO
 *
 * @param subscriberClaims list of subscriber claims
 * @param subscriberName   subscriber name
 * @return SubscriberInfoDTO
 * @throws APIManagementException If an error occurs when getting display name of claim
 */
public static SubscriberInfoDTO fromSubscriberClaimsToDTO(Map<String, String> subscriberClaims,
                                                          String subscriberName) throws APIManagementException {
    SubscriberInfoDTO subscriberInfoDTO = new SubscriberInfoDTO();
    subscriberInfoDTO.setName(subscriberName);
    List<ClaimDTO> claimDTOList = new ArrayList<>();
    for (String key : subscriberClaims.keySet()) {
        ClaimDTO claimDTO = new ClaimDTO();
        claimDTO.setName(APIUtil.getClaimDisplayName(key, subscriberName));
        claimDTO.setURI(key);
        claimDTO.setValue(subscriberClaims.get(key));
        claimDTOList.add(claimDTO);
    }
    subscriberInfoDTO.setClaims(claimDTOList);
    return subscriberInfoDTO;
}
 
Example #8
Source File: APIAdminImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, List<KeyManagerConfigurationDTO>> getAllKeyManagerConfigurations()
        throws APIManagementException {

    List<KeyManagerConfigurationDTO> keyManagerConfigurations = apiMgtDAO.getKeyManagerConfigurations();
    Map<String, List<KeyManagerConfigurationDTO>> keyManagerConfigurationsByTenant = new HashMap<>();
    for (KeyManagerConfigurationDTO keyManagerConfiguration : keyManagerConfigurations) {
        List<KeyManagerConfigurationDTO> keyManagerConfigurationDTOS;
        if (keyManagerConfigurationsByTenant.containsKey(keyManagerConfiguration.getTenantDomain())) {
            keyManagerConfigurationDTOS =
                    keyManagerConfigurationsByTenant.get(keyManagerConfiguration.getTenantDomain());
        } else {
            keyManagerConfigurationDTOS = new ArrayList<>();
        }
        if (APIConstants.KeyManager.DEFAULT_KEY_MANAGER.equals(keyManagerConfiguration.getName())) {
            APIUtil.getAndSetDefaultKeyManagerConfiguration(keyManagerConfiguration);
        }
        keyManagerConfigurationDTOS.add(keyManagerConfiguration);
        keyManagerConfigurationsByTenant
                .put(keyManagerConfiguration.getTenantDomain(), keyManagerConfigurationDTOS);
    }
    return keyManagerConfigurationsByTenant;
}
 
Example #9
Source File: ScopesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the given scope already used in APIs.
 *
 * @param name           Base64 URL encoded form of scope name -Base64URLEncode{scope name}
 * @param messageContext
 * @return boolean to indicate existence
 */
@Override
public Response validateScope(String name, MessageContext messageContext) {

    boolean isScopeExist = false;
    String scopeName = new String(Base64.getUrlDecoder().decode(name));
    if (!APIUtil.isWhiteListedScope(scopeName)) {
        try {
            APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
            String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
            isScopeExist =
                    apiProvider.isScopeKeyExist(scopeName, APIUtil.getTenantIdFromTenantDomain(tenantDomain));
        } catch (APIManagementException e) {
            RestApiUtil.handleInternalServerError("Error occurred while checking scope name", e, log);
        }
    }

    if (isScopeExist) {
        return Response.status(Response.Status.OK).build();
    } else {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
}
 
Example #10
Source File: UserAwareAPIProviderTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method checks the behaviour of the checkAccessControlPermission when the user is not authorized to view
 * the specific API.
 *
 * @throws RegistryException Registry Exception.
 */
@Test
public void testCheckAccessControlPermissionForUnAuthorizedUser() throws RegistryException {
    try {
        PowerMockito.when(APIUtil.getAPIPath(apiIdentifier)).thenReturn(SAMPLE_IDENTIFIER);
        Mockito.doReturn(true).when(userRegistry).resourceExists(SAMPLE_IDENTIFIER);
        Mockito.doReturn(resource).when(userRegistry).get(SAMPLE_IDENTIFIER);
        Mockito.doReturn(APIConstants.API_RESTRICTED_VISIBILITY).when(resource)
                .getProperty(APIConstants.ACCESS_CONTROL);
        PowerMockito.when(APIUtil.hasPermission(ADMIN_ROLE_NAME, APIConstants.Permissions.APIM_ADMIN))
                .thenReturn(false);
        Mockito.doReturn(ADMIN_ROLE_NAME).when(resource).getProperty(APIConstants.DISPLAY_PUBLISHER_ROLES);
        PowerMockito.when(APIUtil.getListOfRoles(ADMIN_ROLE_NAME))
                .thenReturn(new String[] { "Internal/everyone" });
        userAwareAPIProvider.checkAccessControlPermission(apiIdentifier);
        Assert.fail("For a user, who is un-authorized access an API was able to successfully access the API");
    } catch (APIManagementException e) {
        Assert.assertNotNull("Exception is not thrown for an user who is trying to access an un-authorized API", e);
        Assert.assertTrue("Required error message is not present in exception error log",
                e.getMessage().contains(APIConstants.UN_AUTHORIZED_ERROR_MESSAGE));
    }
}
 
Example #11
Source File: APIMOAuthEventInterceptor.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
private void persistRevokedJWTSignature(String token, Long expiryTime) {

        ApiMgtDAO apiMgtDAO = ApiMgtDAO.getInstance();
        try {
            String tokenSignature = APIUtil.getSignatureIfJWT(token);
            String tenantDomain = APIUtil.getTenantDomainIfJWT(token);
            int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
            apiMgtDAO.addRevokedJWTSignature(tokenSignature, APIConstants.DEFAULT, expiryTime, tenantId);

            // Cleanup expired revoked tokens from db.
            Runnable expiredJWTCleaner = new ExpiredJWTCleaner();
            Thread cleanupThread = new Thread(expiredJWTCleaner);
            cleanupThread.start();
        } catch (APIManagementException e) {
            log.error("Unable to add revoked JWT signature to the database");
        }
    }
 
Example #12
Source File: APIImportUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Update API with the certificate.
 * If certificate alias already exists for tenant in database, certificate content will be
 * updated in trust store. If cert alias does not exits in database for that tenant, add the certificate to
 * publisher and gateway nodes. In such case if alias already exits in the trust store, update the certificate
 * content for that alias.
 *
 * @param certificate Certificate JSON element
 * @param apiProvider API Provider
 * @param importedApi API to import
 * @param tenantId    Tenant Id
 */
private static void updateAPIWithCertificate(JsonElement certificate, APIProvider apiProvider, API importedApi,
                                             int tenantId) {

    String certificateContent = certificate.getAsJsonObject()
            .get(APIImportExportConstants.CERTIFICATE_CONTENT_JSON_KEY).getAsString();
    String alias = certificate.getAsJsonObject().get(APIImportExportConstants.ALIAS_JSON_KEY).getAsString();
    String endpoint = certificate.getAsJsonObject().get(APIImportExportConstants.HOSTNAME_JSON_KEY)
            .getAsString();
    try {
        if (apiProvider.isCertificatePresent(tenantId, alias)
                || (ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE.getResponseCode() ==
                (apiProvider.addCertificate(APIUtil.replaceEmailDomainBack(importedApi.getId().getProviderName()),
                        certificateContent, alias, endpoint)))) {
            apiProvider.updateCertificate(certificateContent, alias);
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while importing certificate endpoint [" + endpoint + " ]" + "alias ["
                + alias + " ] tenant user ["
                + APIUtil.replaceEmailDomainBack(importedApi.getId().getProviderName()) + "]";
        log.error(errorMessage, e);
    }
}
 
Example #13
Source File: APIGatewayManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public void setProductResourceSequences(APIProviderImpl apiProvider, APIProduct apiProduct)
        throws APIManagementException {

    for (APIProductResource resource : apiProduct.getProductResources()) {
        APIIdentifier apiIdentifier = resource.getApiIdentifier();
        API api = apiProvider.getAPI(apiIdentifier);

        String inSequenceKey = APIUtil.getSequenceExtensionName(api) + APIConstants.API_CUSTOM_SEQ_IN_EXT;
        if (APIUtil.isSequenceDefined(api.getInSequence())) {
            resource.setInSequenceName(inSequenceKey);
        }

        String outSequenceKey = APIUtil.getSequenceExtensionName(api) + APIConstants.API_CUSTOM_SEQ_OUT_EXT;
        if (APIUtil.isSequenceDefined(api.getOutSequence())) {
            resource.setOutSequenceName(outSequenceKey);
        }

        String faultSequenceKey = APIUtil.getFaultSequenceName(api);
        if (APIUtil.isSequenceDefined(api.getFaultSequence())) {
            resource.setFaultSequenceName(faultSequenceKey);
        }
    }
}
 
Example #14
Source File: DefaultClaimsRetrieverTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetClaimsWhenCacheEmpty() throws Exception {

    DefaultClaimsRetriever defaultClaimsRetriever = new DefaultClaimsRetriever();
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.JWT_CLAIM_CACHE_EXPIRY)).thenReturn(null);
    Cache cache = Mockito.mock(Cache.class);
    Mockito.when(cacheManager.getCache(APIConstants.CLAIMS_APIM_CACHE)).thenReturn(cache);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getTenantId(USER_NAME)).thenReturn(TENANT_ID);

    Claim claim1 = new Claim();
    claim1.setClaimUri("http://wso2.org/claim1");
    Claim claim2 = new Claim();
    claim2.setClaimUri("http://wso2.com/claim2");

    SortedMap<String, String> claimValues = new TreeMap<String, String>();
    claimValues.put("claim1", "http://wso2.org/claim1");
    claimValues.put("claim2", "http://wso2.org/claim2");
    PowerMockito.when(APIUtil.getClaims(USER_NAME, TENANT_ID, DEFAULT_DIALECT_URI)).thenReturn(claimValues);
    SortedMap<String, String> claims = defaultClaimsRetriever.getClaims(USER_NAME);

    Assert.assertNotNull(claims);
    Assert.assertEquals(claimValues, claims);
}
 
Example #15
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public Documentation getDocumentation(APIIdentifier apiId, DocumentationType docType,
                                      String docName) throws APIManagementException {
    Documentation documentation = null;
    String docPath = APIUtil.getAPIDocPath(apiId) + docName;
    GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry,
            APIConstants.DOCUMENTATION_KEY);
    try {
        Resource docResource = registry.get(docPath);
        GenericArtifact artifact = artifactManager.getGenericArtifact(docResource.getUUID());
        documentation = APIUtil.getDocumentation(artifact);
    } catch (RegistryException e) {
        String msg = "Failed to get documentation details";
        throw new APIManagementException(msg, e);
    }
    return documentation;
}
 
Example #16
Source File: AbstractAPIManager.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public APIProduct getAPIProduct(String productPath) throws APIManagementException {
    try {
        GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry,
                APIConstants.API_KEY);
        Resource productResource = registry.get(productPath);
        String artifactId = productResource.getUUID();
        if (artifactId == null) {
            throw new APIManagementException("artifact id is null for : " + productPath);
        }
        GenericArtifact productArtifact = artifactManager.getGenericArtifact(artifactId);
        return APIUtil.getAPIProduct(productArtifact, registry);

    } catch (RegistryException e) {
        String msg = "Failed to get API Product from : " + productPath;
        throw new APIManagementException(msg, e);
    }
}
 
Example #17
Source File: RolesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the given role exists in the system
 *
 * @param roleId Base64 URL encoded form of role name -Base64URLEncode{user-store-name/role-name}
 * @return 200 if the given role exists
 */
public Response validateSystemRole(String roleId, MessageContext messageContext) {
    Boolean isRoleExist = false;
    String username = RestApiUtil.getLoggedInUsername();
    if (roleId != null) {
        try {
            String roleName =  new String(Base64.getUrlDecoder().decode(roleId));
            log.debug("Checking whether the role : " + roleName + "exists");
            isRoleExist = APIUtil.isRoleNameExist(username, roleName);
        } catch (APIManagementException e) {
            RestApiUtil.handleInternalServerError(e.getMessage(), e, log);
        }
    }
    if (isRoleExist) {
        return Response.status(Response.Status.OK).build();
    } else {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
}
 
Example #18
Source File: ApikeyApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Response apikeyRevokePost(RevokeAPIKeyDTO body, MessageContext messageContext)
        throws APIManagementException {
    String username = RestApiUtil.getLoggedInUsername();
    try {
        boolean hasPermission = APIUtil.hasPermission(username, APIConstants.Permissions.APIM_ADMIN);
        if(hasPermission) {
            APIKeyRevokeService apiKeyRevokeService = APIKeyRevokeServiceImpl.getInstance();
            apiKeyRevokeService.revokeAPIKey(body.getApiKey(), body.getExpiryTime().longValue(),
                    body.getTenantId().intValue());
        } else {
            RestApiUtil.handleAuthorizationFailure("User doesn't have sufficient permissions", username,log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while checking permissions", e, log);
    }
    return Response.ok().build();
}
 
Example #19
Source File: SequenceUtilsTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws UserStoreException, RegistryException {
    userRegistry = Mockito.mock(UserRegistry.class);
    serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    registryService = Mockito.mock(RegistryService.class);
    realmService = Mockito.mock(RealmService.class);
    tenantManager = Mockito.mock(TenantManager.class);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.mockStatic(RegistryUtils.class);

    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(Mockito.anyInt())).thenReturn(userRegistry);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
}
 
Example #20
Source File: APIAdminImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public List<BotDetectionData> retrieveBotDetectionData() throws APIManagementException {

    List<BotDetectionData> botDetectionDatalist = new ArrayList<>();
    String appName = AlertMgtConstants.APIM_ALERT_BOT_DETECTION_APP;
    String query = SQLConstants.BotDataConstants.GET_BOT_DETECTED_DATA;

    JSONObject botDataJsonObject = APIUtil.executeQueryOnStreamProcessor(appName, query);
    if (botDataJsonObject != null) {
        JSONArray botDataJsonArray = (JSONArray) botDataJsonObject.get("records");
        if (botDataJsonArray != null && botDataJsonArray.size() != 0) {
            for (Object botData : botDataJsonArray) {
                JSONArray values = (JSONArray) botData;
                BotDetectionData botDetectionData = new BotDetectionData();
                botDetectionData.setCurrentTime((Long) values.get(0));
                botDetectionData.setMessageID((String) values.get(1));
                botDetectionData.setApiMethod((String) values.get(2));
                botDetectionData.setHeaderSet((String) values.get(3));
                botDetectionData.setMessageBody(extractBotDetectionDataContent((String) values.get(4)));
                botDetectionData.setClientIp((String) values.get(5));
                botDetectionDatalist.add(botDetectionData);
            }
        }
    }
    return botDetectionDatalist;
}
 
Example #21
Source File: APIAdminImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public List<KeyManagerConfigurationDTO> getKeyManagerConfigurationsByTenant(String tenantDomain)
        throws APIManagementException {

    KeyMgtRegistrationService.registerDefaultKeyManager(tenantDomain);
    List<KeyManagerConfigurationDTO> keyManagerConfigurationsByTenant =
            apiMgtDAO.getKeyManagerConfigurationsByTenant(tenantDomain);
    Iterator<KeyManagerConfigurationDTO> iterator = keyManagerConfigurationsByTenant.iterator();
    KeyManagerConfigurationDTO defaultKeyManagerConfiguration = null;
    while (iterator.hasNext()) {
        KeyManagerConfigurationDTO keyManagerConfigurationDTO = iterator.next();
        if (APIConstants.KeyManager.DEFAULT_KEY_MANAGER.equals(keyManagerConfigurationDTO.getName())) {
            defaultKeyManagerConfiguration = keyManagerConfigurationDTO;
            iterator.remove();
            break;
        }
    }
    if (defaultKeyManagerConfiguration != null) {
        APIUtil.getAndSetDefaultKeyManagerConfiguration(defaultKeyManagerConfiguration);
        keyManagerConfigurationsByTenant.add(defaultKeyManagerConfiguration);
    }
    return keyManagerConfigurationsByTenant;
}
 
Example #22
Source File: ApiProductsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Override public Response apiProductsApiProductIdDelete(String apiProductId, String ifMatch,
        MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String username = RestApiUtil.getLoggedInUsername();
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
        APIProductIdentifier apiProductIdentifier = APIMappingUtil.getAPIProductIdentifierFromUUID(apiProductId, tenantDomain);
        if (log.isDebugEnabled()) {
            log.debug("Delete API Product request: Id " +apiProductId + " by " + username);
        }
        APIProduct apiProduct = apiProvider.getAPIProductbyUUID(apiProductId, tenantDomain);
        if (apiProduct == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API_PRODUCT, apiProductId, log);
        }

        List<SubscribedAPI> apiUsages = apiProvider.getAPIProductUsageByAPIProductId(apiProductIdentifier);
        if (apiUsages != null && apiUsages.size() > 0) {
            RestApiUtil.handleConflict("Cannot remove the API " + apiProductIdentifier + " as active subscriptions exist", log);
        }

        apiProvider.deleteAPIProduct(apiProduct.getId(), apiProductId);
        return Response.ok().build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while deleting API Product : " + apiProductId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example #23
Source File: SwaggerYamlApi.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves swagger definition of Store REST API and returns
 * 
 * @return swagger definition of Store REST API in yaml format
 */
@GET
@Consumes({ "text/yaml" })
@Produces({ "text/yaml" })
@io.swagger.annotations.ApiOperation(value = "Get Swagger Definition", notes = "Get Swagger Definition of Store REST API.", response = Void.class)
@io.swagger.annotations.ApiResponses(value = {
        @io.swagger.annotations.ApiResponse(code = 200, message = "OK.\nSwagger Definition is returned."),

        @io.swagger.annotations.ApiResponse(code = 304, message = "Not Modified.\nEmpty body because the client has already the latest version of the requested resource."),

        @io.swagger.annotations.ApiResponse(code = 406, message = "Not Acceptable.\nThe requested media type is not supported") })

public Response swaggerYamlGet() throws APIManagementException {
    try {
        if (openAPIDef == null) {
            synchronized (LOCK_STORE_OPENAPI_DEF) {
                if (openAPIDef == null) {
                    String definition = IOUtils
                            .toString(this.getClass().getResourceAsStream("/store-api.yaml"), "UTF-8");
                    openAPIDef = new OAS2Parser().removeExamplesFromSwagger(definition);
                }
            }
        }
        RESTAPICacheConfiguration restapiCacheConfiguration = APIUtil.getRESTAPICacheConfig();
        if (restapiCacheConfiguration.isCacheControlHeadersEnabled()) {
            CacheControl cacheControl = new CacheControl();
            cacheControl.setMaxAge(restapiCacheConfiguration.getCacheControlHeadersMaxAge());
            cacheControl.setPrivate(true);
            return Response.ok().entity(openAPIDef).cacheControl(cacheControl).build();
        } else {
            return Response.ok().entity(openAPIDef).build();
        }
    } catch (IOException e) {
        String errorMessage = "Error while retrieving the swagger definition of the Store API";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example #24
Source File: APIExportUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Clean api by removing unnecessary details.
 *
 * @param api API to be exported
 */
private static void cleanApiDataToExport(API api) throws APIManagementException {
    // Thumbnail will be set according to the importing environment. Therefore current URL is removed
    api.setThumbnailUrl(null);
    // WSDL file path will be set according to the importing environment. Therefore current path is removed
    api.setWsdlUrl(null);
    // If Secure Endpoint is enabled and "ExposeEndpointPassword" is 'false' in tenant-conf.json in registry,
    // secure endpoint password is removed, as it causes security issues. Need to add it manually when importing.
    String tenantDomain = MultitenantUtils
            .getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
    if (api.isEndpointSecured() && api.getEndpointUTPassword() != null && !isExposeEndpointPasswordEnabled(
            tenantDomain)) {
        api.setEndpointUTPassword(StringUtils.EMPTY);
    }
}
 
Example #25
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructor() throws Exception {

    ServiceReferenceHolderMockCreator holderMockCreator = new ServiceReferenceHolderMockCreator(1);
    ServiceReferenceHolderMockCreator.initContextService();
    holderMockCreator.initRegistryServiceMockCreator(false, new Object());
    RegistryAuthorizationManager registryAuthorizationManager = Mockito.mock(RegistryAuthorizationManager.class);
    Mockito.doThrow(UserStoreException.class).doNothing().when(registryAuthorizationManager)
            .authorizeRole(Mockito.anyString(), Mockito.anyString(), Mockito.anyString());
    PowerMockito.whenNew(RegistryAuthorizationManager.class).withAnyArguments()
            .thenReturn(registryAuthorizationManager);
    PowerMockito.mockStatic(RegistryUtils.class);
    PowerMockito.when(RegistryUtils.getAbsolutePath((RegistryContext) Mockito.any(), Mockito.anyString()))
            .thenReturn("/test");
    try {
        new AbstractAPIManager(null) {
            @Override
            public String getGraphqlSchema(APIIdentifier apiId) throws APIManagementException {
                return null;
            }
        };
        Assert.fail("User store exception not thrown for error scenario");
    } catch (APIManagementException e) {
        Assert.assertTrue(e.getMessage().contains("Error while setting the permissions"));
    }

    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.doNothing().when(APIUtil.class, "loadTenantRegistry", Mockito.anyInt());
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.when(MultitenantUtils.getTenantDomain(Mockito.anyString())).thenReturn(SAMPLE_TENANT_DOMAIN_1);
    String userName = "admin";

    Mockito.verify(
            holderMockCreator.getRegistryServiceMockCreator().getMock().getConfigSystemRegistry(Mockito.anyInt()),
            Mockito.atLeastOnce());
}
 
Example #26
Source File: WorkflowExecutor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method is to publish workflow events
 *
 * @param workflowDTO workflow DTO
 */
public void publishEvents(WorkflowDTO workflowDTO) {
    boolean enabled = APIUtil.isAnalyticsEnabled();
    if (enabled) {
        APIMgtWorkflowDataPublisher publisher = ServiceReferenceHolder.getInstance()
                .getApiMgtWorkflowDataPublisher();
        publisher.publishEvent(workflowDTO);
    }
}
 
Example #27
Source File: ThrottleDataHolder.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private IPRange convertValueToIPRange(String tenantDomain, int conditionId, String value, String type) {

        IPRange ipRange = new IPRange();
        ipRange.setId(conditionId);
        ipRange.setTenantDomain(tenantDomain);
        JsonObject ipLevelJson = (JsonObject) new JsonParser().parse(value);
        if (APIConstants.BLOCKING_CONDITIONS_IP.equals(type)) {
            ipRange.setType(APIConstants.BLOCKING_CONDITIONS_IP);
            JsonElement fixedIpElement = ipLevelJson.get(APIConstants.BLOCK_CONDITION_FIXED_IP);
            if (fixedIpElement != null && StringUtils.isNotEmpty(fixedIpElement.getAsString())) {
                ipRange.setFixedIp(fixedIpElement.getAsString());
            }
        } else if (APIConstants.BLOCK_CONDITION_IP_RANGE.equals(type)) {
            ipRange.setType(APIConstants.BLOCK_CONDITION_IP_RANGE);
            JsonElement startingIpElement = ipLevelJson.get(APIConstants.BLOCK_CONDITION_START_IP);
            if (startingIpElement != null && StringUtils.isNotEmpty(startingIpElement.getAsString())) {
                ipRange.setStartingIP(startingIpElement.getAsString());
                ipRange.setStartingIpBigIntValue(APIUtil.ipToBigInteger(startingIpElement.getAsString()));
            }
            JsonElement endingIpElement = ipLevelJson.get(APIConstants.BLOCK_CONDITION_ENDING_IP);
            if (endingIpElement != null && StringUtils.isNotEmpty(endingIpElement.getAsString())) {
                ipRange.setEndingIp(endingIpElement.getAsString());
                ipRange.setEndingIpBigIntValue(APIUtil.ipToBigInteger(endingIpElement.getAsString()));
            }
        }
        if (ipLevelJson.has(APIConstants.BLOCK_CONDITION_INVERT)) {
            ipRange.setInvert(ipLevelJson.get(APIConstants.BLOCK_CONDITION_INVERT).getAsBoolean());
        }
        return ipRange;
    }
 
Example #28
Source File: AbstractAPIManagerTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetPolicies() throws APIManagementException, org.wso2.carbon.user.api.UserStoreException,
        RegistryException {
    APIPolicy[] policies1 = { new APIPolicy("policy1") };
    ApplicationPolicy[] policies2 = { new ApplicationPolicy("policy2"), new ApplicationPolicy("policy3") };
    SubscriptionPolicy[] policies3 = { new SubscriptionPolicy("policy4"), new SubscriptionPolicy("policy5"),
            new SubscriptionPolicy("policy6") };
    GlobalPolicy[] policies4 = { new GlobalPolicy("policy7"), new GlobalPolicy("policy8"),
            new GlobalPolicy("policy9"), new GlobalPolicy("policy0") };
    PowerMockito.mockStatic(APIUtil.class);
    BDDMockito.when(APIUtil.getTenantId(Mockito.anyString())).thenReturn(-1234);
    PowerMockito.when(APIUtil.replaceSystemProperty(Mockito.anyString())).thenAnswer((Answer<String>) invocation -> {
        Object[] args = invocation.getArguments();
        return (String) args[0];
    });
    AbstractAPIManager abstractAPIManager = new AbstractAPIManagerWrapper(apiMgtDAO);
    Mockito.when(apiMgtDAO.getAPIPolicies(Mockito.anyInt())).thenReturn(policies1);
    Mockito.when(apiMgtDAO.getApplicationPolicies(Mockito.anyInt())).thenReturn(policies2);
    Mockito.when(apiMgtDAO.getSubscriptionPolicies(Mockito.anyInt())).thenReturn(policies3);
    Mockito.when(apiMgtDAO.getGlobalPolicies(Mockito.anyInt())).thenReturn(policies4);

    ServiceReferenceHolder sh = mockRegistryAndUserRealm(-1234);
    APIManagerConfigurationService amConfigService = Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration amConfig = Mockito.mock(APIManagerConfiguration.class);
    ThrottleProperties throttleProperties = Mockito.mock(ThrottleProperties.class, Mockito.RETURNS_MOCKS);

    PowerMockito.when(sh.getAPIManagerConfigurationService()).thenReturn(amConfigService);
    PowerMockito.when(amConfigService.getAPIManagerConfiguration()).thenReturn(amConfig);
    PowerMockito.when(amConfig.getThrottleProperties()).thenReturn(throttleProperties);

    Assert.assertEquals(abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_API).length, 1);
    Assert.assertEquals(abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_APP).length, 2);

    PowerMockito.when(throttleProperties.isEnableUnlimitedTier()).thenReturn(false);

    Assert.assertEquals(3, abstractAPIManager.getPolicies(API_PROVIDER, PolicyConstants.POLICY_LEVEL_SUB).length);
    Assert.assertEquals(4, abstractAPIManager.getPolicies(API_PROVIDER,
            PolicyConstants.POLICY_LEVEL_GLOBAL).length);
    Assert.assertEquals(0, abstractAPIManager.getPolicies(API_PROVIDER, "Test").length);
}
 
Example #29
Source File: APIGatewayManager.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Undeploy the sequences deployed in synapse
 *
 * @param api
 * @throws APIManagementException
 */
private void setCustomSequencesToBeRemoved(API api, GatewayAPIDTO gatewayAPIDTO) {

    String inSequence = APIUtil.getSequenceExtensionName(api) + APIConstants.API_CUSTOM_SEQ_IN_EXT;
    gatewayAPIDTO.setSequencesToBeRemove(addStringToList(inSequence, gatewayAPIDTO.getSequencesToBeRemove()));
    String outSequence = APIUtil.getSequenceExtensionName(api) + APIConstants.API_CUSTOM_SEQ_OUT_EXT;
    gatewayAPIDTO.setSequencesToBeRemove(addStringToList(outSequence, gatewayAPIDTO.getSequencesToBeRemove()));
    String faultSequence = APIUtil.getSequenceExtensionName(api) + APIConstants.API_CUSTOM_SEQ_FAULT_EXT;
    gatewayAPIDTO.setSequencesToBeRemove(addStringToList(faultSequence, gatewayAPIDTO.getSequencesToBeRemove()));
}
 
Example #30
Source File: RecommenderDetailsExtractor.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
public void run() {

        if (tenantDomain == null) {
            tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        }
        startTenantFlow(tenantDomain);
        tenantFlowStarted = true;
        try {
            if (APIUtil.isRecommendationEnabled(tenantDomain)) {
                if (APIConstants.ADD_API.equals(publishingDetailType)) {
                    publishAPIDetails(api, tenantDomain);
                } else if (APIConstants.ADD_NEW_APPLICATION.equals(publishingDetailType)) {
                    publishApplicationDetails(application, userName, applicationId);
                } else if (APIConstants.UPDATED_APPLICATION.equals(publishingDetailType)) {
                    publishApplicationDetails(application, userName, applicationId);
                } else if (APIConstants.DELETE_APPLICATION.equals(publishingDetailType)) {
                    publishDeletedApplication(applicationId);
                } else if (APIConstants.ADD_USER_CLICKED_API.equals(publishingDetailType)) {
                    publishClickedApi(clickedApi, userName);
                } else if (APIConstants.ADD_USER_SEARCHED_QUERY.equals(publishingDetailType)) {
                    publishSearchQueries(searchQuery, userName);
                }

                if (!APIConstants.ADD_API.equals(publishingDetailType) && userName != null
                        && userName != APIConstants.WSO2_ANONYMOUS_USER && requestTenantDomain != null) {
                    updateRecommendationsCache(userName, requestTenantDomain);
                }
            }
        } catch (IOException e) {
            log.error("When extracting data for the recommendation system !", e);
        } finally {
            if (tenantFlowStarted) {
                endTenantFlow();
            }
        }
    }