Java Code Examples for org.wso2.carbon.apimgt.impl.APIConstants

The following examples show how to use org.wso2.carbon.apimgt.impl.APIConstants. These examples are extracted from open source projects. 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
private boolean validateSubscriptionDetails(String context, String version, String consumerKey, String keyManager,
        APIKeyValidationInfoDTO infoDTO) throws APIManagementException {
    boolean defaultVersionInvoked = false;
    String apiTenantDomain = MultitenantUtils.getTenantDomainFromRequestURL(context);
    if (apiTenantDomain == null) {
        apiTenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }
    int apiOwnerTenantId = APIUtil.getTenantIdFromTenantDomain(apiTenantDomain);
    // Check if the api version has been prefixed with _default_
    if (version != null && version.startsWith(APIConstants.DEFAULT_VERSION_PREFIX)) {
        defaultVersionInvoked = true;
        // Remove the prefix from the version.
        version = version.split(APIConstants.DEFAULT_VERSION_PREFIX)[1];
    }

    validateSubscriptionDetails(infoDTO, context, version, consumerKey, keyManager, defaultVersionInvoked);
    return infoDTO.isAuthorized();
}
 
Example 2
Source Project: carbon-apimgt   Source File: OAS2Parser.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Remove x-wso2-examples from all the paths from the swagger.
 *
 * @param swaggerString Swagger as String
 */
public String removeExamplesFromSwagger(String swaggerString) throws APIManagementException {
    try {
        SwaggerParser swaggerParser = new SwaggerParser();
        Swagger swagger = swaggerParser.parse(swaggerString);
        swagger.getPaths().values().forEach(path -> {
            path.getOperations().forEach(operation -> {
                if (operation.getVendorExtensions().keySet().contains(APIConstants.SWAGGER_X_EXAMPLES)) {
                    operation.getVendorExtensions().remove(APIConstants.SWAGGER_X_EXAMPLES);
                }
            });
        });
        return Yaml.pretty().writeValueAsString(swagger);
    } catch (JsonProcessingException e) {
        throw new APIManagementException("Error while removing examples from OpenAPI definition", e,
                ExceptionCodes.ERROR_REMOVING_EXAMPLES);
    }
}
 
Example 3
Source Project: carbon-apimgt   Source File: APIThrottleHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMsgThrottleOutWhenDomainBasedThrottlingAccessRateIsExceeded() throws XMLStreamException,
        ThrottleException {
    concurrentAccessController = new ConcurrentAccessController(100);
    configurationContext.setProperty(throttleKey, concurrentAccessController);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setConfigurationContext(configurationContext);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty("REMOTE_ADDR", IP);
    ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty("REMOTE_HOST", domain);
    //Set domain based throttling limits to be 1/60000
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "DOMAIN", domain, 1,
            60000, "true"),THROTTLE_POLICY_KEY, true, 0, messageContext);
    TestUtils.loadAPIThrottlingPolicyEntry(String.format(THROTTLING_POLICY_DEFINITION, "DOMAIN", domain, 1,
            60000, "true"),THROTTLE_POLICY_RESOURCE_KEY, true, 0, messageContext);
    messageContext.setProperty(RESPONSE, "false");
    messageContext.setProperty(APIConstants.VERB_INFO_DTO, verbInfoDTO);
    apiThrottleHandler.setPolicyKey(THROTTLE_POLICY_KEY);
    apiThrottleHandler.setPolicyKeyResource(THROTTLE_POLICY_RESOURCE_KEY);
    apiThrottleHandler.setId(throttleID);
    //First request should continue as the access rates are not exceeded yet (Access rate = 1 per 60000ms )
    Assert.assertTrue(apiThrottleHandler.handleRequest(messageContext));
    //Second request should throttle out as the access rate is exceeded
    Assert.assertFalse(apiThrottleHandler.handleRequest(messageContext));
}
 
Example 4
/**
 * Creates an archive of the contained application details.
 *
 * @param sourceDirectory Directory which contains source file
 * @param archiveLocation Directory to generate the zip archive
 * @param archiveName     Name of the zip archive
 * @return path to the created archive file
 * @throws APIManagementException if an error occurs while creating an archive from app details
 */
public String createArchiveFromExportedAppArtifacts(String sourceDirectory, String archiveLocation,
                                                    String archiveName) throws APIManagementException {
    String archivedFilePath;
    try {
        archiveDirectory(sourceDirectory, archiveLocation, archiveName);
    } catch (IOException e) {
        // cleanup the archive root directory
        try {
            FileUtils.deleteDirectory(new File(path));
        } catch (IOException e1) {
            log.warn("Unable to remove directory " + path);
        }
        String errorMsg = "Error while archiving directory " + sourceDirectory;
        throw new APIManagementException(errorMsg);
    }
    archivedFilePath = archiveLocation + File.separator + archiveName + APIConstants.ZIP_FILE_EXTENSION;
    return archivedFilePath;
}
 
Example 5
Source Project: carbon-apimgt   Source File: InMemoryAPIDeployer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * UnDeploy an API in the gateway using the uneployAPI method in gateway admin
 *
 * @param apiId        - UUID of the API
 * @param gatewayLabel - Label of the Gateway
 * @return True if API artifact retrieved from the storage and successfully undeployed without any error. else false
 */
public boolean unDeployAPI(String apiId, String gatewayLabel) {

    if (gatewayArtifactSynchronizerProperties.isRetrieveFromStorageEnabled() &&
            gatewayArtifactSynchronizerProperties.getGatewayLabels().contains(gatewayLabel)) {
        if (artifactRetriever != null) {
            try {
                String gatewayRuntimeArtifact = artifactRetriever
                        .retrieveArtifact(apiId, gatewayLabel,
                                APIConstants.GatewayArtifactSynchronizer.GATEWAY_INSTRUCTION_REMOVE);
                if (gatewayRuntimeArtifact != null) {
                    GatewayAPIDTO gatewayAPIDTO = new Gson().fromJson(gatewayRuntimeArtifact, GatewayAPIDTO.class);
                    apiGatewayAdmin.unDeployAPI(gatewayAPIDTO);
                    return true;
                } else {
                    log.error("Error retrieving artifacts for API " + apiId + ". Storage returned null");
                }
            } catch (AxisFault | ArtifactSynchronizerException e) {
                log.error("Error undeploying " + apiId + " in Gateway", e);
            }
        } else {
            log.error("Artifact retriever not found");
        }
    }
    return false;
}
 
Example 6
Source Project: carbon-apimgt   Source File: ImportApiServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This extracts information for creating an APIKey from an OAuthApplication
 * @param type Type of the OAuthApp(SANDBOX or PRODUCTION)
 * @param keyManagerName
 * @param oAuthApplicationInfo OAuth Application information
 * @return An APIKey containing keys from OAuthApplication
 */
private APIKey getAPIKeyFromOauthApp(String type, String keyManagerName,
                                     OAuthApplicationInfo oAuthApplicationInfo){
    APIKey apiKey = new APIKey();
    apiKey.setType(type);
    apiKey.setConsumerKey(oAuthApplicationInfo.getClientId());
    apiKey.setConsumerSecret(oAuthApplicationInfo.getClientSecret());
    apiKey.setGrantTypes((String) oAuthApplicationInfo.getParameter(GRANT_TYPES));
    apiKey.setKeyManager(keyManagerName);
    if (apiKey.getGrantTypes().contains(GRANT_TYPE_IMPLICIT) && apiKey.getGrantTypes().contains(GRANT_TYPE_CODE)){
        apiKey.setCallbackUrl((String) oAuthApplicationInfo.getParameter(REDIRECT_URIS));
    }

    long validityPeriod = OAuthServerConfiguration.getInstance().getApplicationAccessTokenValidityPeriodInSeconds();
    apiKey.setValidityPeriod(validityPeriod);
    apiKey.setTokenScope(DEFAULT_TOKEN_SCOPE);
    apiKey.setAdditionalProperties(oAuthApplicationInfo.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES));
    return apiKey;
}
 
Example 7
Source Project: carbon-apimgt   Source File: GatewayUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Map<String, Set<IPRange>> generateIpRangeMap(List<IPRange> ipRangeList) {

        Map<String, Set<IPRange>> ipRangeMap = new HashMap<>();
        for (IPRange ipRange : ipRangeList) {
            Set<IPRange> tenantWiseIpRangeList;
            if (!ipRangeMap.containsKey(ipRange.getTenantDomain())) {
                tenantWiseIpRangeList = new HashSet<>();
            } else {
                tenantWiseIpRangeList = ipRangeMap.get(ipRange.getTenantDomain());
            }
            if (APIConstants.BLOCK_CONDITION_IP_RANGE.equals(ipRange.getType())) {
                convertIpRangeBigIntValue(ipRange);
            }
            tenantWiseIpRangeList.add(ipRange);
            ipRangeMap.put(ipRange.getTenantDomain(), tenantWiseIpRangeList);
        }
        return ipRangeMap;
    }
 
Example 8
/**
 * To get the fully qualified username with the user store domain.
 *
 * @param username         Name of the User.
 * @param userStoreManager User store manager, which the user is belong to.
 * @return fully qualified username.
 */
private String getUserName(String username, UserStoreManager userStoreManager) {

    String userStoreDomain = getUserStoreDomainName(userStoreManager);
    String tenantDomain = getTenantDomain();

    username = UserCoreUtil.addDomainToName(username, userStoreDomain);
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain) ||
            (!MultitenantUtils.isEmailUserName() &&
            username.indexOf(APIConstants.EMAIL_DOMAIN_SEPARATOR) > 0)) {
        username = UserCoreUtil.addTenantDomainToEntry(username, tenantDomain);
    }

    //If the username is not case sensitive
    if (!isUserStoreInUsernameCaseSensitive(username)) {
        username = username.toLowerCase();
    }
    return username;
}
 
Example 9
Source Project: carbon-apimgt   Source File: APIUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetOAuthConfigurationFromAPIMConfig () throws Exception {
    String property = "AuthorizationHeader";
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    APIManagerConfigurationService apiManagerConfigurationService =
            Mockito.mock(APIManagerConfigurationService.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService())
            .thenReturn(apiManagerConfigurationService);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.OAUTH_CONFIGS + property))
            .thenReturn("APIM_AUTH");

    String authHeader = getOAuthConfigurationFromAPIMConfig(property);
    Assert.assertEquals("APIM_AUTH", authHeader);
}
 
Example 10
Source Project: carbon-apimgt   Source File: DefaultMonetizationImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Update info about monetization usage publish job
 *
 * @param monetizationUsagePublishInfo
 * @return boolean always return true if there is no exception
 * @throws MonetizationException
 */
@Override
public boolean publishMonetizationUsageRecords(MonetizationUsagePublishInfo monetizationUsagePublishInfo)
        throws MonetizationException {

    APIAdmin apiAdmin = new APIAdminImpl();
    monetizationUsagePublishInfo.setState(APIConstants.Monetization.COMPLETED);
    monetizationUsagePublishInfo.setStatus(APIConstants.Monetization.SUCCESSFULL);
    DateFormat df = new SimpleDateFormat(APIConstants.Monetization.USAGE_PUBLISH_TIME_FORMAT);
    Date dateobj = new Date();
    //get the time in UTC format
    df.setTimeZone(TimeZone.getTimeZone(APIConstants.Monetization.USAGE_PUBLISH_TIME_ZONE));
    String currentDate = df.format(dateobj);
    long currentTimestamp = apiAdmin.getTimestamp(currentDate);
    monetizationUsagePublishInfo.setLastPublishTime(currentTimestamp);
    try {
        apiAdmin.updateMonetizationUsagePublishInfo(monetizationUsagePublishInfo);
    } catch (APIManagementException e) {
        throw new MonetizationException("Failed to update the monetization usage publish info", e);
    }
    return true;
}
 
Example 11
Source Project: carbon-apimgt   Source File: OASParserUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static void setScopes(final OpenAPI destOpenAPI, final Set<Scope> aggregatedScopes) {
    Map<String, SecurityScheme> securitySchemes;
    SecurityScheme securityScheme;
    OAuthFlow oAuthFlow;
    Scopes scopes = new Scopes();
    if (destOpenAPI.getComponents() != null &&
            (securitySchemes = destOpenAPI.getComponents().getSecuritySchemes()) != null &&
            (securityScheme = securitySchemes.get(OAS3Parser.OPENAPI_SECURITY_SCHEMA_KEY)) != null &&
            (oAuthFlow = securityScheme.getFlows().getImplicit()) != null) {

        Map<String, String> scopeBindings = new HashMap<>();

        for (Scope scope : aggregatedScopes) {
            scopes.addString(scope.getKey(), scope.getDescription());
            scopeBindings.put(scope.getKey(), scope.getRoles());
        }

        oAuthFlow.setScopes(scopes);

        Map<String, Object> extensions = new HashMap<>();
        extensions.put(APIConstants.SWAGGER_X_SCOPES_BINDINGS, scopeBindings);
        oAuthFlow.setExtensions(extensions);
    }
}
 
Example 12
Source Project: carbon-apimgt   Source File: SearchResultMappingUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static DocumentSearchResultDTO fromDocumentationToProductDocumentResultDTO(Documentation document,
                                                                                  APIProduct apiProduct) {

    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.associatedType(APIConstants.AuditLogConstants.API_PRODUCT);
    docResultDTO.setSummary(document.getSummary());
    docResultDTO.setVisibility(DocumentSearchResultDTO.VisibilityEnum.valueOf(document.getVisibility().toString()));
    docResultDTO.setSourceType(DocumentSearchResultDTO.SourceTypeEnum.valueOf(document.getSourceType().toString()));
    docResultDTO.setOtherTypeName(document.getOtherTypeName());
    APIProductIdentifier apiId = apiProduct.getId();
    docResultDTO.setApiName(apiId.getName());
    docResultDTO.setApiVersion(apiId.getVersion());
    docResultDTO.setApiProvider(APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
    docResultDTO.setApiUUID(apiProduct.getUuid());
    return docResultDTO;
}
 
Example 13
Source Project: carbon-apimgt   Source File: APIConfigContext.java    License: Apache License 2.0 5 votes vote down vote up
private void setApiProductVelocityContext(APIProduct apiProduct, VelocityContext context) {
    APIProductIdentifier id = apiProduct.getId();
    //set the api name version and context
    context.put("apiName", PRODUCT_PREFIX + "--" + id.getName());
    context.put("apiVersion", "1.0.0");

    // We set the context pattern now to support plugable version strategy
    // context.put("apiContext", api.getContext());
    context.put("apiContext", apiProduct.getContext());

    //the api object will be passed on to the template so it properties can be used to
    // customise how the synapse config is generated.
    context.put("apiObj", apiProduct);

    context.put("apiIsBlocked", Boolean.FALSE);

    String apiSecurity = apiProduct.getApiSecurity();
    if (apiSecurity == null || apiSecurity.contains(APIConstants.DEFAULT_API_SECURITY_OAUTH2)) {
        context.put("apiIsOauthProtected", Boolean.TRUE);
    } else {
        context.put("apiIsOauthProtected", Boolean.FALSE);
    }
    if (apiProduct.isEnabledSchemaValidation()) {
        context.put("enableSchemaValidation", Boolean.TRUE);
    } else {
        context.put("enableSchemaValidation", Boolean.FALSE);
    }
}
 
Example 14
Source Project: carbon-apimgt   Source File: OASParserUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static void populateEndpointSecurity(API api, ObjectNode endpointResult) {
    if (api.isEndpointSecured()) {
        ObjectNode securityConfigObj = objectMapper.createObjectNode();
        if (api.isEndpointAuthDigest()) {
            securityConfigObj.put(APIConstants.ENDPOINT_SECURITY_TYPE, APIConstants.ENDPOINT_SECURITY_TYPE_DIGEST);
        } else {
            securityConfigObj.put(APIConstants.ENDPOINT_SECURITY_TYPE, APIConstants.ENDPOINT_SECURITY_TYPE_BASIC);
        }
        if (!StringUtils.isEmpty(api.getEndpointUTUsername())) {
            securityConfigObj.put(APIConstants.ENDPOINT_SECURITY_USERNAME, api.getEndpointUTUsername());
        }
        endpointResult.set(APIConstants.ENDPOINT_SECURITY_CONFIG, securityConfigObj);
    }
}
 
Example 15
private void handleScopes(OAuth2IntrospectionResponseDTO responseDTO, AccessTokenInfo tokenInfo) {

        String[] scopes = OAuth2Util.buildScopeArray(responseDTO.getScope());
        String applicationTokenScope = getConfigurationElementValue(APIConstants.APPLICATION_TOKEN_SCOPE);
        if (scopes != null && applicationTokenScope != null && !applicationTokenScope.isEmpty()) {
            if (Arrays.asList(scopes).contains(applicationTokenScope)) {
                tokenInfo.setApplicationToken(true);
            }
        }
    }
 
Example 16
Source Project: carbon-apimgt   Source File: JMSMessageListener.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized void handleKeyTemplateMessage(Map<String, Object> map) {

        if (log.isDebugEnabled()) {
            log.debug("Received Key -  KeyTemplate : " + map.get(APIConstants.POLICY_TEMPLATE_KEY).toString());
        }
        String keyTemplateValue = map.get(APIConstants.POLICY_TEMPLATE_KEY).toString();
        String keyTemplateState = map.get(APIConstants.TEMPLATE_KEY_STATE).toString();
        if (APIConstants.AdvancedThrottleConstants.ADD.equals(keyTemplateState)) {
            ServiceReferenceHolder.getInstance().getAPIThrottleDataService()
                    .addKeyTemplate(keyTemplateValue, keyTemplateValue);
        } else {
            ServiceReferenceHolder.getInstance().getAPIThrottleDataService()
                    .removeKeyTemplate(keyTemplateValue);
        }
    }
 
Example 17
Source Project: carbon-apimgt   Source File: GraphQLSchemaDefinition.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method saves schema definition of GraphQL APIs in the registry
 *
 * @param api               API to be saved
 * @param schemaDefinition  Graphql API definition as String
 * @param registry          user registry
 * @throws APIManagementException
 */
public void saveGraphQLSchemaDefinition(API api, String schemaDefinition, Registry registry)
        throws APIManagementException {
    String apiName = api.getId().getApiName();
    String apiVersion = api.getId().getVersion();
    String apiProviderName = api.getId().getProviderName();
    String resourcePath = APIUtil.getGraphqlDefinitionFilePath(apiName, apiVersion, apiProviderName);
    try {
        String saveResourcePath = resourcePath + apiProviderName + APIConstants.GRAPHQL_SCHEMA_PROVIDER_SEPERATOR +
                apiName + apiVersion + APIConstants.GRAPHQL_SCHEMA_FILE_EXTENSION;
        Resource resource;
        if (!registry.resourceExists(saveResourcePath)) {
            resource = registry.newResource();
        } else {
            resource = registry.get(saveResourcePath);
        }

        resource.setContent(schemaDefinition);
        resource.setMediaType(String.valueOf(ContentType.TEXT_PLAIN));
        registry.put(saveResourcePath, resource);
        if (log.isDebugEnabled()) {
            log.debug("Successfully imported the schema: " + schemaDefinition );
        }

        String[] visibleRoles = null;
        if (api.getVisibleRoles() != null) {
            visibleRoles = api.getVisibleRoles().split(",");
        }

        //Need to set anonymous if the visibility is public
        APIUtil.clearResourcePermissions(resourcePath, api.getId(), ((UserRegistry) registry).getTenantId());
        APIUtil.setResourcePermissions(apiProviderName, api.getVisibility(), visibleRoles, resourcePath);

    } catch (RegistryException e) {
        String errorMessage = "Error while adding Graphql Definition for " + apiName + '-' + apiVersion;
        log.error(errorMessage, e);
        handleException(errorMessage, e);
    }
}
 
Example 18
Source Project: carbon-apimgt   Source File: APIExportUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve API Specific sequence details from the registry.
 *
 * @param sequenceName Name of the sequence
 * @param type         Sequence type
 * @param registry     Current tenant registry
 * @return Registry resource name of the sequence and its content
 * @throws APIImportExportException If an error occurs while retrieving registry elements
 */
private static AbstractMap.SimpleEntry<String, OMElement> getAPISpecificSequence(APIIdentifier api,
                                                                                 String sequenceName, String type,
                                                                                 Registry registry)
        throws APIImportExportException {

    String regPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR + api.getProviderName()
            + RegistryConstants.PATH_SEPARATOR + api.getApiName() + RegistryConstants.PATH_SEPARATOR
            + api.getVersion() + RegistryConstants.PATH_SEPARATOR + type;
    return getSeqDetailsFromRegistry(sequenceName, regPath, registry);
}
 
Example 19
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    if (callbacks != null && callbacks.length > 0){
        OAuthCallback oauthCallback = (OAuthCallback) callbacks[0];
        if (OAuthCallback.OAuthCallbackType.ACCESS_DELEGATION_AUTHZ.equals(
                oauthCallback.getCallbackType())){
            oauthCallback.setAuthorized(true);
        }
        if (OAuthCallback.OAuthCallbackType.ACCESS_DELEGATION_TOKEN.equals(
                oauthCallback.getCallbackType())){
            oauthCallback.setAuthorized(true);
        }
        if (OAuthCallback.OAuthCallbackType.SCOPE_VALIDATION_AUTHZ.equals(
                oauthCallback.getCallbackType())){
            //Validate scopes in callback using scope issuers
            ScopesIssuer.getInstance().setScopes(oauthCallback);
            oauthCallback.setValidScope(true);
        }
        if (OAuthCallback.OAuthCallbackType.SCOPE_VALIDATION_TOKEN.equals(
                oauthCallback.getCallbackType())){
            String[] scopes = oauthCallback.getRequestedScope();
            //If no scopes have been requested.
            if(scopes == null || scopes.length == 0){
               //Issue a default scope. The default scope can only be used to access resources which are
               // not associated to a scope
               scopes = new String[]{APIConstants.OAUTH2_DEFAULT_SCOPE};
            }
            oauthCallback.setApprovedScope(scopes);
            oauthCallback.setValidScope(true);
        }
    }
}
 
Example 20
@Test
public void testWorkflowExecuteFailWhenMessageProcessingFailed() throws Exception {
	ApplicationWorkflowDTO workflowDTO = new ApplicationWorkflowDTO();
	PowerMockito.mockStatic(AXIOMUtil.class);
	PowerMockito.when(AXIOMUtil.stringToOM(Mockito.anyString())).thenThrow(new XMLStreamException("Error " +
			"converting String to OMElement"));
	Application application = new Application("TestAPP", new Subscriber(null));

	application.setTier("Gold");
	application.setCallbackUrl("www.wso2.com");
	application.setDescription("Description");
	workflowDTO.setApplication(application);
	workflowDTO.setTenantDomain("wso2");
	workflowDTO.setUserName("admin");
	workflowDTO.setCallbackUrl("http://localhost:8280/workflow-callback");
	workflowDTO.setWorkflowReference("1");
	workflowDTO.setExternalWorkflowReference(UUID.randomUUID().toString());

	PowerMockito.doNothing().when(apiMgtDAO).updateSubscriptionStatus(
			Integer.parseInt(workflowDTO.getWorkflowReference()), APIConstants.SubscriptionStatus.REJECTED);

	ServiceReferenceHolderMockCreator serviceRefMock = new ServiceReferenceHolderMockCreator(-1234);
	ServiceReferenceHolderMockCreator.initContextService();

	PowerMockito.whenNew(ServiceClient.class)
			.withArguments(Mockito.any(ConfigurationContext.class), Mockito.any(AxisService.class))
			.thenReturn(serviceClient);
	try {
		applicationCreationWSWorkflowExecutor.execute(workflowDTO);
		Assert.fail("Unexpected WorkflowException occurred while executing Application creation ws workflow");
	} catch (WorkflowException e) {
		Assert.assertEquals(e.getMessage(), "Error converting String to OMElement");
	}
}
 
Example 21
Source Project: carbon-apimgt   Source File: RecommenderDetailsExtractor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void publishDeletedApplication(int appId) {

    JSONObject obj = new JSONObject();
    obj.put("appid", appId);

    JSONObject payload = new JSONObject();
    payload.put(APIConstants.ACTION_STRING, APIConstants.DELETE_APPLICATION);
    payload.put(APIConstants.PAYLOAD_STRING, obj);
    publishEvent(payload.toString());
}
 
Example 22
Source Project: carbon-apimgt   Source File: APIUtilTierTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testAddDefaultTenantAdvancedThrottlePoliciesApiLevelAlreadyAdded() throws Exception {
    int tenantId = 1;
    String tenantDomain = "test.com";

    ApiMgtDAOMockCreator daoMockHolder = new ApiMgtDAOMockCreator(tenantId);
    ApiMgtDAO apiMgtDAO = daoMockHolder.getMock();

    ThrottlePolicyTemplateBuilder templateBuilder = Mockito.mock(ThrottlePolicyTemplateBuilder.class);
    PowerMockito.whenNew(ThrottlePolicyTemplateBuilder.class).withNoArguments().thenReturn(templateBuilder);

    String[] policies = new String[]{APIConstants.DEFAULT_API_POLICY_FIFTY_THOUSAND_REQ_PER_MIN,
            APIConstants.DEFAULT_API_POLICY_TWENTY_THOUSAND_REQ_PER_MIN,
            APIConstants.DEFAULT_API_POLICY_TEN_THOUSAND_REQ_PER_MIN, APIConstants.DEFAULT_API_POLICY_UNLIMITED};

    for (String policy : policies) {
        Mockito.when(
                apiMgtDAO.isPolicyExist(eq(PolicyConstants.POLICY_LEVEL_API), eq(tenantId),
                        eq(policy))).thenReturn(true);
        Mockito.when(
                apiMgtDAO.isPolicyDeployed(eq(PolicyConstants.POLICY_LEVEL_API), eq(tenantId),
                        eq(policy))).thenReturn(true);
    }

    APIUtil.addDefaultTenantAdvancedThrottlePolicies(tenantDomain, tenantId);
    Mockito.verify(apiMgtDAO, Mockito.never()).
            addAPIPolicy(Mockito.any(APIPolicy.class));
    Mockito.verify(apiMgtDAO, Mockito.never()).
            setPolicyDeploymentStatus(eq(PolicyConstants.POLICY_LEVEL_API), Mockito.anyString(), eq(tenantId), eq(true));
}
 
Example 23
Source Project: carbon-apimgt   Source File: OAuthMediator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method returns the OAuthEndpointSecurity Properties from the API Manager Configuration
 * @return JSONObject OAuthEndpointSecurity properties
 */
public JSONObject getOAuthEndpointSecurityProperties() {
    APIManagerConfiguration configuration = ServiceReferenceHolder.getInstance()
            .getAPIManagerConfigurationService().getAPIManagerConfiguration();
    String tokenRefreshInterval = configuration.getFirstProperty(APIConstants
            .OAuthConstants.OAUTH_TOKEN_REFRESH_INTERVAL);

    JSONObject configProperties = new JSONObject();

    if (StringUtils.isNotEmpty(tokenRefreshInterval)) {
        configProperties.put(APIConstants.OAuthConstants.TOKEN_REFRESH_INTERVAL, tokenRefreshInterval);
        return configProperties;
    }
    return null;
}
 
Example 24
Source Project: carbon-apimgt   Source File: CacheProvider.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create and return RESOURCE_CACHE
 */
public static Cache createResourceCache() {
    APIManagerConfiguration config = getApiManagerConfiguration();
    String gatewayResourceCacheExpiry = config.getFirstProperty(APIConstants.GATEWAY_RESOURCE_CACHE_TIMEOUT);
    if (gatewayResourceCacheExpiry != null) {
        return getCache(APIConstants.API_MANAGER_CACHE_MANAGER, APIConstants.RESOURCE_CACHE_NAME,
                Long.parseLong(gatewayResourceCacheExpiry), Long.parseLong(gatewayResourceCacheExpiry));
    } else {
        long defaultCacheTimeout = getDefaultCacheTimeout();
        return getCache(APIConstants.API_MANAGER_CACHE_MANAGER, APIConstants.RESOURCE_CACHE_NAME,
                defaultCacheTimeout, defaultCacheTimeout);
    }
}
 
Example 25
Source Project: carbon-apimgt   Source File: MethodTimeLogger.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * If the pointcuts results true, this method is invoked every time a method satisfies the
 * criteria given in the pointcut.
 *
 * @param point The JoinPoint before method execution
 * @return result of method execution
 * @throws Throwable
 */
@Around("isConfigEnabled() && (pointCut() || pointCutAll())")
public Object log(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Object result = point.proceed();
    String[] args = signature.getParameterNames();

    String argString;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[");
    if (args != null && args.length != 0) {
        String delimiter = "";
        for (String arg : args) {
            stringBuilder.append(delimiter);
            delimiter = ", ";
            stringBuilder.append(arg);
        }
    }
    stringBuilder.append("]");
    argString = stringBuilder.toString();
    MessageContext messageContext = MessageContext.getCurrentMessageContext();
    if(MDC.get(APIConstants.CORRELATION_ID) == null) {
        if (messageContext != null) {
            Map headers =
                    (Map) messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            if (headers != null) {
                String correlationId = (String) headers.get(APIConstants.AM_ACTIVITY_ID);
                if (correlationId != null) {
                    MDC.put(APIConstants.CORRELATION_ID, correlationId);
                }
            }
        }
    }
    log.info((System.currentTimeMillis() - start) + "|METHOD|" +
            MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName() + "|" +
            MethodSignature.class.cast(point.getSignature()).getMethod().getName()+ "|" + argString);
    return result;
}
 
Example 26
Source Project: carbon-apimgt   Source File: APIImportUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This method adds API sequences to the imported API. If the sequence is a newly defined one, it is added.
 *
 * @param pathToArchive location of the extracted folder of the API
 * @param importedApi   the imported API object
 */
private static void addAPISequences(String pathToArchive, API importedApi, Registry registry) {

    String inSequenceFileName = importedApi.getInSequence() + APIConstants.XML_EXTENSION;
    String inSequenceFileLocation = pathToArchive + APIImportExportConstants.IN_SEQUENCE_LOCATION
            + inSequenceFileName;
    String regResourcePath;

    //Adding in-sequence, if any
    if (CommonUtil.checkFileExistence(inSequenceFileLocation)) {
        regResourcePath = APIConstants.API_CUSTOM_INSEQUENCE_LOCATION + inSequenceFileName;
        addSequenceToRegistry(false, registry, inSequenceFileLocation, regResourcePath);
    }

    String outSequenceFileName = importedApi.getOutSequence() + APIConstants.XML_EXTENSION;
    String outSequenceFileLocation = pathToArchive + APIImportExportConstants.OUT_SEQUENCE_LOCATION
            + outSequenceFileName;

    //Adding out-sequence, if any
    if (CommonUtil.checkFileExistence(outSequenceFileLocation)) {
        regResourcePath = APIConstants.API_CUSTOM_OUTSEQUENCE_LOCATION + outSequenceFileName;
        addSequenceToRegistry(false, registry, outSequenceFileLocation, regResourcePath);
    }

    String faultSequenceFileName = importedApi.getFaultSequence() + APIConstants.XML_EXTENSION;
    String faultSequenceFileLocation = pathToArchive + APIImportExportConstants.FAULT_SEQUENCE_LOCATION
            + faultSequenceFileName;

    //Adding fault-sequence, if any
    if (CommonUtil.checkFileExistence(faultSequenceFileLocation)) {
        regResourcePath = APIConstants.API_CUSTOM_FAULTSEQUENCE_LOCATION + faultSequenceFileName;
        addSequenceToRegistry(false, registry, faultSequenceFileLocation, regResourcePath);
    }
}
 
Example 27
@Override
public boolean publishEvent(Event event) throws NotifierException {
    try {
        ApplicationRegistrationEvent appRegEvent = (ApplicationRegistrationEvent) event;
        byte[] bytesEncoded = Base64.encodeBase64(new Gson().toJson(appRegEvent).getBytes());
        Object[] objects = new Object[]{appRegEvent.getType(), appRegEvent.getTimeStamp(), new String(bytesEncoded)};
        org.wso2.carbon.databridge.commons.Event payload = new org.wso2.carbon.databridge.commons.Event(
                APIConstants.NOTIFICATION_STREAM_ID, System.currentTimeMillis(),
                null, null, objects);
        APIUtil.publishEventToEventHub(null, payload);
        return true;
    } catch (Exception e) {
        throw new NotifierException(e);
    }
}
 
Example 28
Source Project: carbon-apimgt   Source File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isClientCertificateValidationEnabled() {

        APIManagerConfiguration apiManagerConfiguration =
                ServiceReferenceHolder.getInstance().getAPIManagerConfiguration();
        if (apiManagerConfiguration != null) {
            String firstProperty = apiManagerConfiguration
                    .getFirstProperty(APIConstants.MutualSSL.ENABLE_CLIENT_CERTIFICATE_VALIDATION);
            return Boolean.parseBoolean(firstProperty);
        }
        return false;
    }
 
Example 29
Source Project: carbon-apimgt   Source File: APIMappingUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts a URI template object to a REST API DTO
 *
 * @param uriTemplate URI Template object
 * @return REST API DTO representing URI template object
 */
private static APIOperationsDTO getOperationFromURITemplate(URITemplate uriTemplate) {

    APIOperationsDTO operationsDTO = new APIOperationsDTO();
    operationsDTO.setId(""); //todo: Set ID properly
    if (APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN.equals(uriTemplate.getAuthType())) {
        operationsDTO.setAuthType(APIConstants.OASResourceAuthTypes.APPLICATION_OR_APPLICATION_USER);
    } else if (APIConstants.AUTH_APPLICATION_USER_LEVEL_TOKEN.equals(uriTemplate.getAuthType())) {
        operationsDTO.setAuthType(APIConstants.OASResourceAuthTypes.APPLICATION_USER);
    } else if (APIConstants.AUTH_NO_AUTHENTICATION.equals(uriTemplate.getAuthType())) {
        operationsDTO.setAuthType(APIConstants.OASResourceAuthTypes.NONE);
    } else if (APIConstants.AUTH_APPLICATION_LEVEL_TOKEN.equals(uriTemplate.getAuthType())) {
        operationsDTO.setAuthType(APIConstants.OASResourceAuthTypes.APPLICATION);
    } else {
        operationsDTO.setAuthType(APIConstants.OASResourceAuthTypes.APPLICATION_OR_APPLICATION_USER);
    }
    operationsDTO.setVerb(uriTemplate.getHTTPVerb());
    operationsDTO.setTarget(uriTemplate.getUriTemplate());
    operationsDTO.setScopes(uriTemplate.retrieveAllScopes().stream().map(Scope::getKey).collect(
            Collectors.toList()));
    operationsDTO.setThrottlingPolicy(uriTemplate.getThrottlingTier());
    Set<APIProductIdentifier> usedByProducts = uriTemplate.retrieveUsedByProducts();
    List<String> usedProductIds = new ArrayList<>();

    for (APIProductIdentifier usedByProduct : usedByProducts) {
        usedProductIds.add(usedByProduct.getUUID());
    }

    if (!usedProductIds.isEmpty()) {
        operationsDTO.setUsedProductIds(usedProductIds);
    }

    return operationsDTO;
}
 
Example 30
Source Project: carbon-apimgt   Source File: RestApiUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a JAXRS Response object based on the provided ResourceFile
 *
 * @param fileNameWithoutExtension Filename without the extension. The extension is determined from the method
 * @param resourceFile ResourceFile object
 * @return JAXRS Response object
 */
public static Response getResponseFromResourceFile(String fileNameWithoutExtension, ResourceFile resourceFile) {
    String contentType;
    String extension;
    if (resourceFile.getContentType().contains(APIConstants.APPLICATION_ZIP)) {
        contentType = APIConstants.APPLICATION_ZIP;
        extension = APIConstants.ZIP_FILE_EXTENSION;
    } else {
        contentType = APIConstants.APPLICATION_WSDL_MEDIA_TYPE;
        extension = APIConstants.WSDL_FILE_EXTENSION;
    }
    String filename = fileNameWithoutExtension + extension;
    return Response.ok(resourceFile.getContent(), contentType).header("Content-Disposition",
            "attachment; filename=\"" + filename + "\"" ).build();
}