org.wso2.carbon.apimgt.api.APIProvider Java Examples

The following examples show how to use org.wso2.carbon.apimgt.api.APIProvider. 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: ExportApiUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Exports an API from API Manager for a given API using the ApiId. ID. Meta information, API icon, documentation,
 * WSDL and sequences are exported. This service generates a zipped archive which contains all the above mentioned
 * resources for a given API.
 *
 * @param apiIdentifier
 * @param preserveStatus Preserve API status on export
 * @return Zipped file containing exported API
 */
public Response exportApiById(APIIdentifier apiIdentifier, Boolean preserveStatus) {
    ExportFormat exportFormat;
    APIProvider apiProvider;
    String userName;
    File file;
    try {
        exportFormat = ExportFormat.YAML;
        apiProvider = RestApiUtil.getLoggedInUserProvider();
        userName = RestApiUtil.getLoggedInUsername();
        file = APIExportUtil.exportApi(apiProvider, apiIdentifier, userName, exportFormat, preserveStatus);
        return Response.ok(file)
                .header(RestApiConstants.HEADER_CONTENT_DISPOSITION, "attachment; filename=\""
                        + file.getName() + "\"")
                .build();
    } catch (APIManagementException | APIImportExportException e) {
        RestApiUtil.handleInternalServerError("Error while exporting " + RestApiConstants.RESOURCE_API, e, log);
    }
    return null;
}
 
Example #2
Source File: ThrottlingApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves all Global level policies
 *
 * @param accept          Accept header value
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @return All matched Global Throttle policies to the given request
 */
@Override
public Response throttlingPoliciesCustomGet(String accept, String ifNoneMatch, String ifModifiedSince,
                                            MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String userName = RestApiUtil.getLoggedInUsername();

        //only super tenant is allowed to access global policies/custom rules
        checkTenantDomainForCustomRules();

        GlobalPolicy[] globalPolicies = (GlobalPolicy[]) apiProvider.getPolicies(userName,
                PolicyConstants.POLICY_LEVEL_GLOBAL);
        CustomRuleListDTO listDTO = GlobalThrottlePolicyMappingUtil.fromGlobalPolicyArrayToListDTO(globalPolicies);
        return Response.ok().entity(listDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving Global level policies";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example #3
Source File: PoliciesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Returns list of global Mediation policies
 *
 * @param limit       maximum number of mediation returns
 * @param offset      starting index
 * @param query       search condition
 * @param accept      accept header value
 * @param ifNoneMatch If-None-Match header value
 * @return Matched global mediation policies for given search condition
 */
@Override
public Response policiesMediationGet(Integer limit, Integer offset, String query, String accept,
                                     String ifNoneMatch, MessageContext messageContext) {
    //pre-processing
    //setting default limit and offset values if they are not set
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        List<Mediation> mediationList = apiProvider.getAllGlobalMediationPolicies();
        MediationListDTO mediationListDTO = MediationMappingUtil.fromMediationListToDTO(mediationList, offset,
                limit);
        return Response.ok().entity(mediationListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving all global mediation policies";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
        return null;
    }
}
 
Example #4
Source File: PoliciesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Returns list of global Mediation policies
 *
 * @param limit       maximum number of mediation returns
 * @param offset      starting index
 * @param query       search condition
 * @param accept      accept header value
 * @param ifNoneMatch If-None-Match header value
 * @return Matched global mediation policies for given search condition
 */
@Override
public Response policiesMediationGet(Integer limit, Integer offset, String query, String accept,
                                     String ifNoneMatch) {
    //pre-processing
    //setting default limit and offset values if they are not set
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        List<Mediation> mediationList = apiProvider.getAllGlobalMediationPolicies();
        MediationListDTO mediationListDTO =
                MediationMappingUtil.fromMediationListToDTO(mediationList, offset, limit);
        return Response.ok().entity(mediationListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving all global mediation policies";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
        return null;
    }
}
 
Example #5
Source File: ThrottlingApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves all Subscription level policies
 *
 * @param accept          Accept header value
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @return All matched Subscription Throttle policies to the given request
 */
@Override
public Response throttlingPoliciesSubscriptionGet(String accept, String ifNoneMatch, String ifModifiedSince,
                                                  MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String userName = RestApiUtil.getLoggedInUsername();
        SubscriptionPolicy[] subscriptionPolicies = (SubscriptionPolicy[]) apiProvider.getPolicies(userName,
                PolicyConstants.POLICY_LEVEL_SUB);
        SubscriptionThrottlePolicyListDTO listDTO =
                SubscriptionThrottlePolicyMappingUtil.fromSubscriptionPolicyArrayToListDTO(subscriptionPolicies);
        return Response.ok().entity(listDTO).build();
    } catch (APIManagementException | ParseException e) {
        String errorMessage = "Error while retrieving Subscription level policies";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example #6
Source File: ThrottlingApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get a specific Advanced Level Policy
 *
 * @param policyId      uuid of the policy
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @return Required policy specified by name
 */
@Override
public Response throttlingPoliciesAdvancedPolicyIdGet(String policyId, String ifNoneMatch, String ifModifiedSince) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String username = RestApiUtil.getLoggedInUsername();
        
        //This will give PolicyNotFoundException if there's no policy exists with UUID
        APIPolicy apiPolicy = apiProvider.getAPIPolicyByUUID(policyId);
        if (!RestApiAdminUtils.isPolicyAccessibleToUser(username, apiPolicy)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_ADVANCED_POLICY, policyId, log);
        }
        AdvancedThrottlePolicyDTO policyDTO = AdvancedThrottlePolicyMappingUtil.fromAdvancedPolicyToDTO(apiPolicy);
        return Response.ok().entity(policyDTO).build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_ADVANCED_POLICY, policyId, e, log);
        } else {
            String errorMessage = "Error while retrieving Advanced level policy : " + policyId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
 
Example #7
Source File: ThrottlingApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves all Application Throttle Policies
 *
 * @param accept          Accept header value
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @return Retrieves all Application Throttle Policies
 */
@Override
public Response throttlingPoliciesApplicationGet(String accept, String ifNoneMatch, String ifModifiedSince,
                                                 MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String userName = RestApiUtil.getLoggedInUsername();
        ApplicationPolicy[] appPolicies = (ApplicationPolicy[]) apiProvider.getPolicies(userName,
                PolicyConstants.POLICY_LEVEL_APP);
        ApplicationThrottlePolicyListDTO listDTO =
                ApplicationThrottlePolicyMappingUtil.fromApplicationPolicyArrayToListDTO(appPolicies);
        return Response.ok().entity(listDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving Application level policies";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example #8
Source File: PoliciesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a specific global mediation policy by identifier
 *
 * @param mediationPolicyId Mediation policy uuid
 * @param accept            Accept header value
 * @param ifNoneMatch       If-None-Match header value
 * @param ifModifiedSince   If-Modified-Since header value
 * @return returns the matched mediation
 */
@Override
public Response policiesMediationMediationPolicyIdGet(String mediationPolicyId, String accept, String ifNoneMatch
        , String ifModifiedSince, MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        //Get given global mediation policy
        Mediation mediation = apiProvider.getGlobalMediationPolicy(mediationPolicyId);
        if (mediation != null) {
            MediationDTO mediationDTO = MediationMappingUtil.fromMediationToDTO(mediation);
            return Response.ok().entity(mediationDTO).build();
        } else {
            //If global mediation policy not exists
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_POLICY, mediationPolicyId, log);
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving the global mediation policy with id " + mediationPolicyId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example #9
Source File: ThrottlingApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves all Advanced level policies
 *
 * @param accept          Accept header value
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @return All matched Advanced Throttle policies to the given request
 */
@Override
public Response throttlingPoliciesAdvancedGet(String accept, String ifNoneMatch, String ifModifiedSince,
                                              MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String userName = RestApiUtil.getLoggedInUsername();
        APIPolicy[] apiPolicies = (APIPolicy[]) apiProvider.getPolicies(userName, PolicyConstants.POLICY_LEVEL_API);
        AdvancedThrottlePolicyListDTO listDTO =
                AdvancedThrottlePolicyMappingUtil.fromAPIPolicyArrayToListDTO(apiPolicies);
        return Response.ok().entity(listDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving Advanced level policies";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example #10
Source File: ThrottlingApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get a specific Advanced Level Policy
 *
 * @param policyId        uuid of the policy
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @return Required policy specified by name
 */
@Override
public Response throttlingPoliciesAdvancedPolicyIdGet(String policyId, String ifNoneMatch, String ifModifiedSince
        , MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String username = RestApiUtil.getLoggedInUsername();

        //This will give PolicyNotFoundException if there's no policy exists with UUID
        APIPolicy apiPolicy = apiProvider.getAPIPolicyByUUID(policyId);
        if (!RestApiAdminUtils.isPolicyAccessibleToUser(username, apiPolicy)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_ADVANCED_POLICY, policyId, log);
        }
        AdvancedThrottlePolicyDTO policyDTO = AdvancedThrottlePolicyMappingUtil.fromAdvancedPolicyToDTO(apiPolicy);
        return Response.ok().entity(policyDTO).build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_ADVANCED_POLICY, policyId, e, log);
        } else {
            String errorMessage = "Error while retrieving Advanced level policy : " + policyId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
 
Example #11
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 #12
Source File: CellerySignedJWTGenerator.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private String getDestinationCell(TokenValidationContext validationContext) throws APIManagementException {

        String providerName = validationContext.getValidationInfoDTO().getApiPublisher();
        String apiName = validationContext.getValidationInfoDTO().getApiName();
        String apiVersion = removeDefaultVersion(validationContext);

        APIIdentifier apiIdentifier = new APIIdentifier(providerName, apiName, apiVersion);
        APIProvider apiProvider = APIManagerFactory.getInstance().getAPIProvider(providerName);
        API api = apiProvider.getAPI(apiIdentifier);

        Object cellName = api.getAdditionalProperties().get(CELL_NAME);
        if (cellName instanceof String) {
            String destinationCell = String.valueOf(cellName);
            log.debug("Destination Cell for API call is '" + destinationCell + "'");
            return destinationCell;
        } else {
            log.debug("Property:" + CELL_NAME + " was not found for the API. This API call is going to an API not " +
                    "published by a Cellery Cell.");
            return null;
        }
    }
 
Example #13
Source File: ThrottlingApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves all Block Conditions
 *
 * @param accept          Accept header value
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @return All matched block conditions to the given request
 */
@Override
public Response throttlingBlacklistGet(String accept, String ifNoneMatch, String ifModifiedSince,
                                       MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        List<BlockConditionsDTO> blockConditions = apiProvider.getBlockConditions();
        BlockingConditionListDTO listDTO =
                BlockingConditionMappingUtil.fromBlockConditionListToListDTO(blockConditions);
        return Response.ok().entity(listDTO).build();
    } catch (APIManagementException | ParseException e) {
        String errorMessage = "Error while retrieving Block Conditions";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example #14
Source File: ThrottlingApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Delete a block condition specified by the condition Id
 *
 * @param conditionId       Id of the block condition
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @return 200 OK response if successfully deleted the block condition
 */
@Override
public Response throttlingBlacklistConditionIdDelete(String conditionId, String ifMatch, String ifUnmodifiedSince
        , MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String username = RestApiUtil.getLoggedInUsername();

        //This will give BlockConditionNotFoundException if there's no block condition exists with UUID
        BlockConditionsDTO existingCondition = apiProvider.getBlockConditionByUUID(conditionId);
        if (!RestApiAdminUtils.isBlockConditionAccessibleToUser(username, existingCondition)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_BLOCK_CONDITION, conditionId, log);
        }
        apiProvider.deleteBlockConditionByUUID(conditionId);
        return Response.ok().build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_BLOCK_CONDITION, conditionId, e, log);
        } else {
            String errorMessage = "Error while deleting Block Condition. Id : " + conditionId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
 
Example #15
Source File: ThrottlingApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Delete a block condition specified by the condition Id
 *
 * @param conditionId       Id of the block condition
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @return 200 OK response if successfully deleted the block condition
 */
@Override
public Response throttlingBlacklistConditionIdDelete(String conditionId, String ifMatch,
        String ifUnmodifiedSince) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String username = RestApiUtil.getLoggedInUsername();

        //This will give BlockConditionNotFoundException if there's no block condition exists with UUID
        BlockConditionsDTO existingCondition = apiProvider.getBlockConditionByUUID(conditionId);
        if (!RestApiAdminUtils.isBlockConditionAccessibleToUser(username, existingCondition)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_BLOCK_CONDITION, conditionId, log);
        }
        apiProvider.deleteBlockConditionByUUID(conditionId);
        return Response.ok().build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_BLOCK_CONDITION, conditionId, e, log);
        } else {
            String errorMessage = "Error while deleting Block Condition. Id : " + conditionId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
 
Example #16
Source File: DefaultMonetizationImplTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws Exception {

    monetizationImpl = Mockito.mock(DefaultMonetizationImpl.class);
    subPolicy = Mockito.mock(SubscriptionPolicy.class);
    api = Mockito.mock(API.class);
    apiProvider = Mockito.mock(APIProvider.class);
    monetizationUsagePublishInfo = Mockito.mock(MonetizationUsagePublishInfo.class);
    Mockito.when(monetizationImpl.createBillingPlan(subPolicy)).thenReturn(true);
    Mockito.when(monetizationImpl.updateBillingPlan(subPolicy)).thenReturn(true);
    Mockito.when(monetizationImpl.deleteBillingPlan(subPolicy)).thenReturn(true);
    Mockito.when(monetizationImpl.enableMonetization(tenantDomain, api, dataMap)).thenReturn(true);
    Mockito.when(monetizationImpl.disableMonetization(tenantDomain, api, dataMap)).thenReturn(true);
    Mockito.when(monetizationImpl.getMonetizedPoliciesToPlanMapping(api)).thenReturn(dataMap);
    Mockito.when(monetizationImpl.getCurrentUsageForSubscription(subscriptionUUID, apiProvider)).thenReturn(dataMap);
    Mockito.when(monetizationImpl.getTotalRevenue(api, apiProvider)).thenReturn(dataMap);
    Mockito.when(monetizationImpl.publishMonetizationUsageRecords(monetizationUsagePublishInfo)).thenReturn(true);
}
 
Example #17
Source File: CertificateRestApiUtils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * To pre validate client certificate given for an alias
 *
 * @param alias Alias of the certificate.
 * @return Client certificate
 * @throws APIManagementException API Management Exception.
 */
public static ClientCertificateDTO preValidateClientCertificate(String alias, APIIdentifier apiIdentifier)
        throws APIManagementException {
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    if (StringUtils.isEmpty(alias)) {
        RestApiUtil.handleBadRequest("The alias cannot be empty", log);
    }
    APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
    if (!apiProvider.isClientCertificateBasedAuthenticationConfigured()) {
        RestApiUtil.handleBadRequest(
                "The client certificate based authentication is not configured for this server", log);
    }
    ClientCertificateDTO clientCertificate = apiProvider.getClientCertificate(tenantId, alias, apiIdentifier);
    if (clientCertificate == null) {
        if (log.isDebugEnabled()) {
            log.debug(String.format("Could not find a client certificate in truststore which belongs to "
                    + "tenant : %d and with alias : %s. Hence the operation is terminated.", tenantId, alias));
        }
        String message = "Certificate for alias '" + alias + "' is not found.";
        RestApiUtil.handleResourceNotFoundError(message, log);
    }
    return clientCertificate;
}
 
Example #18
Source File: SettingsMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method returns the Security Audit properties from the configuration
 *
 * @return SecurityAuditAttributeDTO Security Audit Attributes
 * @throws APIManagementException
 */
private SecurityAuditAttributeDTO getSecurityAuditProperties() throws APIManagementException {
    SecurityAuditAttributeDTO properties = new SecurityAuditAttributeDTO();

    String username = RestApiUtil.getLoggedInUsername();
    APIProvider apiProvider = RestApiUtil.getProvider(username);

    JSONObject securityAuditPropertyObject = apiProvider.getSecurityAuditAttributesFromConfig(username);
    if (securityAuditPropertyObject != null) {
        String apiToken = (String) securityAuditPropertyObject.get(APIConstants.SECURITY_AUDIT_API_TOKEN);
        String collectionId = (String) securityAuditPropertyObject.get(APIConstants.SECURITY_AUDIT_COLLECTION_ID);
        String baseUrl = (String) securityAuditPropertyObject.get(APIConstants.SECURITY_AUDIT_BASE_URL);

        properties.setApiToken(apiToken);
        properties.setCollectionId(collectionId);
        properties.setBaseUrl(baseUrl);
    }
    return properties;
}
 
Example #19
Source File: APIMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * This method creates the API monetization information DTO
 *
 * @param apiIdentifier API identifier
 * @return monetization information DTO
 * @throws APIManagementException if failed to construct the DTO
 */
public static APIMonetizationInfoDTO getMonetizationInfoDTO(APIIdentifier apiIdentifier)
        throws APIManagementException {

    APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
    API api = apiProvider.getAPI(apiIdentifier);
    APIMonetizationInfoDTO apiMonetizationInfoDTO = new APIMonetizationInfoDTO();
    //set the information relatated to monetization to the DTO
    apiMonetizationInfoDTO.setEnabled(api.getMonetizationStatus());
    Map<String, String> monetizationPropertiesMap = new HashMap<>();

    if (api.getMonetizationProperties() != null) {
        JSONObject monetizationProperties = api.getMonetizationProperties();
        for (Object propertyKey : monetizationProperties.keySet()) {
            String key = (String) propertyKey;
            monetizationPropertiesMap.put(key, (String) monetizationProperties.get(key));
        }
    }
    apiMonetizationInfoDTO.setProperties(monetizationPropertiesMap);
    return apiMonetizationInfoDTO;
}
 
Example #20
Source File: APIMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public static APIMonetizationInfoDTO getMonetizationInfoDTO(APIProductIdentifier apiProductIdentifier)
        throws APIManagementException {

    APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
    APIProduct apiProduct = apiProvider.getAPIProduct(apiProductIdentifier);
    APIMonetizationInfoDTO apiMonetizationInfoDTO = new APIMonetizationInfoDTO();
    //set the information related to monetization to the DTO
    apiMonetizationInfoDTO.setEnabled(apiProduct.getMonetizationStatus());
    Map<String, String> monetizationPropertiesMap = new HashMap<>();
    if (apiProduct.getMonetizationProperties() != null) {
        JSONObject monetizationProperties = apiProduct.getMonetizationProperties();
        for (Object propertyKey : monetizationProperties.keySet()) {
            String key = (String) propertyKey;
            monetizationPropertiesMap.put(key, (String) monetizationProperties.get(key));
        }
    }
    apiMonetizationInfoDTO.setProperties(monetizationPropertiesMap);
    return apiMonetizationInfoDTO;
}
 
Example #21
Source File: ScopesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get all shared scopes for tenant.
 *
 * @param messageContext CXF Message Context
 * @return Shared Scopes DTO List
 * @throws APIManagementException if an error occurs while retrieving shared scope
 */
@Override
public Response getSharedScopes(Integer limit, Integer offset, MessageContext messageContext)
        throws APIManagementException {

    // pre-processing
    // setting default limit and offset values if they are not set
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();

    List<Scope> scopeList = apiProvider.getAllSharedScopes(tenantDomain);
    ScopeListDTO sharedScopeListDTO = SharedScopeMappingUtil.fromScopeListToDTO(scopeList, offset, limit);
    SharedScopeMappingUtil
            .setPaginationParams(sharedScopeListDTO, limit, offset, scopeList.size());
    return Response.ok().entity(sharedScopeListDTO).build();
}
 
Example #22
Source File: APIMappingUtil.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the API given the uuid or the id in {provider}-{api}-{version} format
 *
 * @param apiId                 uuid or the id in {provider}-{api}-{version} format
 * @param requestedTenantDomain tenant domain of the API
 * @return API which represents the given id
 * @throws APIManagementException
 */
public static API getAPIFromApiIdOrUUID(String apiId, String requestedTenantDomain)
        throws APIManagementException {

    API api;
    APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
    if (RestApiUtil.isUUID(apiId)) {
        api = apiProvider.getAPIbyUUID(apiId, requestedTenantDomain);
    } else {
        APIIdentifier apiIdentifier = getAPIIdentifierFromApiId(apiId);
        //Checks whether the logged in user's tenant and the API's tenant is equal
        RestApiUtil.validateUserTenantWithAPIIdentifier(apiIdentifier);
        api = apiProvider.getAPI(apiIdentifier);
    }
    return api;
}
 
Example #23
Source File: PublisherAlertsAPIUtils.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the provided configuration id.
 *
 * @param configId : The configuration id
 * @return true if the validation is successful. Error response otherwise.
 * */
public static boolean validateConfigParameters(String configId) {
    String decodedConfigurationId = new String(Base64.getDecoder().decode(configId.getBytes()));
    String[] parameters = decodedConfigurationId.split("#");
    if (parameters.length < 2) {
        RestApiUtil.handleBadRequest(
                "The configuration id validation failed. Should be {apiName}#{apiVersion}#{tenantDomain}",
                log);
    }

    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        if (!apiProvider.isApiNameExist(parameters[0])) {
            RestApiUtil.handleBadRequest("Invalid API Name", log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while validating payload", e, log);
    }
    return true;
}
 
Example #24
Source File: ThrottlingApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Get a specific Application Policy by its uuid
 *
 * @param policyId      uuid of the policy
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @return Matched Application Throttle Policy by the given name
 */
@Override
public Response throttlingPoliciesApplicationPolicyIdGet(String policyId, String ifNoneMatch,
        String ifModifiedSince) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String username = RestApiUtil.getLoggedInUsername();

        //This will give PolicyNotFoundException if there's no policy exists with UUID
        ApplicationPolicy appPolicy = apiProvider.getApplicationPolicyByUUID(policyId);
        if (!RestApiAdminUtils.isPolicyAccessibleToUser(username, appPolicy)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APP_POLICY, policyId, log);
        }
        ApplicationThrottlePolicyDTO policyDTO = ApplicationThrottlePolicyMappingUtil
                .fromApplicationThrottlePolicyToDTO(appPolicy);
        return Response.ok().entity(policyDTO).build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APP_POLICY, policyId, e, log);
        } else {
            String errorMessage = "Error while retrieving Application level policy: " + policyId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
 
Example #25
Source File: ThrottlingApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves all Subscription level policies
 *
 * @param accept           Accept header value
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @return All matched Subscription Throttle policies to the given request
 */
@Override
public Response throttlingPoliciesSubscriptionGet(String accept, String ifNoneMatch, String ifModifiedSince) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String userName = RestApiUtil.getLoggedInUsername();
        SubscriptionPolicy[] subscriptionPolicies = (SubscriptionPolicy[]) apiProvider
                .getPolicies(userName, PolicyConstants.POLICY_LEVEL_SUB);
        SubscriptionThrottlePolicyListDTO listDTO = SubscriptionThrottlePolicyMappingUtil
                .fromSubscriptionPolicyArrayToListDTO(subscriptionPolicies);
        return Response.ok().entity(listDTO).build();
    } catch (APIManagementException | ParseException e) {
        String errorMessage = "Error while retrieving Subscription level policies";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example #26
Source File: ScopesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Delete shared scope.
 *
 * @param scopeId        Scope UUID
 * @param messageContext CXF Message Context
 * @return Deletion Response
 * @throws APIManagementException If an error occurs while deleting shared scope
 */
@Override
public Response deleteSharedScope(String scopeId, MessageContext messageContext) throws APIManagementException {

    APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    if (StringUtils.isEmpty(scopeId)) {
        throw new APIManagementException("Scope Id cannot be null or empty",
                ExceptionCodes.SHARED_SCOPE_ID_NOT_SPECIFIED);
    }
    Scope existingScope = apiProvider.getSharedScopeByUUID(scopeId, tenantDomain);
    if (apiProvider.isScopeKeyAssignedToAPI(existingScope.getKey(), tenantDomain)) {
        throw new APIManagementException("Cannot remove the Shared Scope " + scopeId + " as it is used by one "
                + "or more APIs", ExceptionCodes.from(ExceptionCodes.SHARED_SCOPE_ALREADY_ATTACHED, scopeId));
    }
    apiProvider.deleteSharedScope(existingScope.getKey(), tenantDomain);
    return Response.ok().build();
}
 
Example #27
Source File: MediationPoliciesApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Returns list of global Mediation policies
 *
 * @param limit       maximum number of mediation returns
 * @param offset      starting index
 * @param query       search condition
 * @param ifNoneMatch If-None-Match header value
 * @return Matched global mediation policies for given search condition
 */
@Override
public Response getAllGlobalMediationPolicies(Integer limit, Integer offset, String query, String ifNoneMatch, MessageContext messageContext) throws APIManagementException {
    //pre-processing
    //setting default limit and offset values if they are not set
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        List<Mediation> mediationList = apiProvider.getAllGlobalMediationPolicies();
        MediationListDTO mediationListDTO =
                MediationMappingUtil.fromMediationListToDTO(mediationList, offset, limit);
        return Response.ok().entity(mediationListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving global mediation policies";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
        return null;
    }
}
 
Example #28
Source File: ApiProductsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override public Response apiProductsApiProductIdGet(String apiProductId, String accept, String ifNoneMatch,
        MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        String username = RestApiUtil.getLoggedInUsername();
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(username));
        if (log.isDebugEnabled()) {
            log.debug("API Product request: Id " +apiProductId + " by " + username);
        }
        APIProduct apiProduct = apiProvider.getAPIProductbyUUID(apiProductId, tenantDomain);
        if (apiProduct == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API_PRODUCT, apiProductId, log);
        }

        APIProductDTO createdApiProductDTO = APIMappingUtil.fromAPIProducttoDTO(apiProduct);
        return Response.ok().entity(createdApiProductDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving API Product from Id  : " + apiProductId ;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example #29
Source File: APIManagerFactory.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
public void clearAll() {
    consumers.exclusiveLock();
    try {
        for (APIConsumer consumer : consumers.values()) {
            cleanupSilently(consumer);
        }
        consumers.clear();
    } finally {
        consumers.release();
    }

    providers.exclusiveLock();
    try {
        for (APIProvider provider : providers.values()) {
            cleanupSilently(provider);
        }
        providers.clear();
    } finally {
        providers.release();
    }
}
 
Example #30
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();
    }
}