org.wso2.carbon.apimgt.impl.APIManagerFactory Java Examples

The following examples show how to use org.wso2.carbon.apimgt.impl.APIManagerFactory. 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: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Response applicationsApplicationIdChangeOwnerPost(String owner, String applicationId,
                                                         MessageContext messageContext) {

    APIConsumer apiConsumer = null;
    try {
        apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(owner);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        boolean applicationUpdated = apiConsumer.updateApplicationOwner(owner, application);
        if (applicationUpdated) {
            return Response.ok().build();
        } else {
            RestApiUtil.handleInternalServerError("Error while updating application owner " + applicationId, log);
        }

    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while updating application owner " + applicationId, e, log);
    }

    return null;
}
 
Example #2
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Response applicationsApplicationIdChangeOwnerPost(String owner, String applicationId) {

    APIConsumer apiConsumer = null;
    try {
        apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(owner);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        boolean applicationUpdated = apiConsumer.updateApplicationOwner(owner, application);
        if (applicationUpdated) {
            return Response.ok().build();
        } else {
            RestApiUtil.handleInternalServerError("Error while updating application owner " + applicationId, log);
        }

    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while updating application owner " + applicationId, e, log);
    }

    return null;
}
 
Example #3
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Response applicationsApplicationIdOauthKeysKeyMappingIdRegenerateSecretPost(String applicationId,
                                                                                   String keyMappingId,
                                                                                   MessageContext messageContext)
        throws APIManagementException {

    String username = RestApiUtil.getLoggedInUsername();
        Set<APIKey> applicationKeys = getApplicationKeys(applicationId);
        if (applicationKeys == null) {
            return null;
        }
        ApplicationKeyDTO applicationKeyDTO = getApplicationKeyByAppIDAndKeyMapping(applicationId, keyMappingId);
        if (applicationKeyDTO != null) {
            APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
            String clientId = applicationKeyDTO.getConsumerKey();
            String clientSecret = apiConsumer.renewConsumerSecret(clientId, applicationKeyDTO.getKeyManager());

            ApplicationKeyDTO retrievedApplicationKet = new ApplicationKeyDTO();
            applicationKeyDTO.setConsumerKey(clientId);
            applicationKeyDTO.setConsumerSecret(clientSecret);

            return Response.ok().entity(retrievedApplicationKet).build();
        }
    return null;
}
 
Example #4
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Response applicationsApplicationIdOauthKeysKeyMappingIdCleanUpPost(String applicationId, String keyMappingId,
                                                                          String ifMatch,
                                                                          MessageContext messageContext)
        throws APIManagementException {

    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        Application application = apiConsumer.getLightweightApplicationByUUID(applicationId);
        apiConsumer.cleanUpApplicationRegistrationByApplicationIdAndKeyMappingId(application.getId(), keyMappingId);
        return Response.ok().build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error occurred while application key cleanup process", e, log);
    }
    return null;
}
 
Example #5
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Used to get all keys of an application
 *
 * @param applicationUUID Id of the application
 * @return List of application keys
 */
private Set<APIKey> getApplicationKeys(String applicationUUID) {

    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        Application application = apiConsumer.getLightweightApplicationByUUID(applicationUUID);
        if (application != null) {
            if (RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
                return apiConsumer.getApplicationKeysOfApplication(application.getId());
            } else {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationUUID, log);
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationUUID, log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while retrieving application " + applicationUUID, e, log);
    }
    return null;
}
 
Example #6
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Clean up application keys
 * @param applicationId Application Id
 * @param keyType Key Type whether PRODUCTION or SANDBOX
 * @param ifMatch
 * @param messageContext
 * @return
 */
@Override
public Response applicationsApplicationIdKeysKeyTypeCleanUpPost(String applicationId, String keyType, String ifMatch,
                         MessageContext messageContext) {

    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        Application application = apiConsumer.getLightweightApplicationByUUID(applicationId);
        apiConsumer.cleanUpApplicationRegistrationByApplicationId(application.getId(), keyType);
        return Response.ok().build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error occurred while application key cleanup process", e, log);
    }
    return null;
}
 
Example #7
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes an application by id
 *
 * @param applicationId     application identifier
 * @param ifMatch           If-Match header value
 * @return 200 Response if successfully deleted the application
 */
@Override
public Response applicationsApplicationIdDelete(String applicationId, String ifMatch, MessageContext messageContext) {
    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        if (application != null) {
            if (RestAPIStoreUtils.isUserOwnerOfApplication(application)) {
                apiConsumer.removeApplication(application, username);
                return Response.ok().build();
            } else {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while deleting application " + applicationId, e, log);
    }
    return null;
}
 
Example #8
Source File: SettingsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public Response settingsApplicationAttributesGet(String ifNoneMatch, MessageContext messageContext) {
    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        List<ApplicationAttributeDTO> applicationAttributeDTOList = new ArrayList<>();
        JSONArray attributeArray = apiConsumer.getAppAttributesFromConfig(username);
        for (int i = 0; i < attributeArray.size(); i++) {
            JSONObject obj = (JSONObject) attributeArray.get(i);
            ApplicationAttributeDTO applicationAttributeDTO = ApplicationMappingUtil
                    .fromApplicationAttributeJsonToDTO(obj);
            applicationAttributeDTOList.add(applicationAttributeDTO);
        }
        ApplicationAttributeListDTO applicationAttributeListDTO = ApplicationMappingUtil
                .fromApplicationAttributeListToDTO(applicationAttributeDTOList);
        return Response.ok().entity(applicationAttributeListDTO).build();
    } catch (APIManagementException e) {
        RestApiUtil
                .handleInternalServerError("Error occurred in reading application attributes from config", e, log);
    }
    return null;
}
 
Example #9
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 #10
Source File: APIManagerComponent.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Deactivate
protected void deactivate(ComponentContext componentContext) {
    if (log.isDebugEnabled()) {
        log.debug("Deactivating API manager component");
    }
    CertificateReLoaderUtil.shutDownCertificateReLoader();
    registration.unregister();
    APIManagerFactory.getInstance().clearAll();
    org.wso2.carbon.apimgt.impl.utils.AuthorizationManager.getInstance().destroy();
}
 
Example #11
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Generate keys using existing consumer key and consumer secret
 *
 * @param applicationId Application id
 * @param body          Contains consumer key, secret and key type information
 * @return A response object containing application keys
 */
@Override
public Response applicationsApplicationIdMapKeysPost(String applicationId, ApplicationKeyMappingRequestDTO body,
                                                     MessageContext messageContext) throws APIManagementException {

    String username = RestApiUtil.getLoggedInUsername();
    JSONObject jsonParamObj = new JSONObject();
    APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
    Application application = apiConsumer.getApplicationByUUID(applicationId);
    String keyManagerName = APIConstants.KeyManager.DEFAULT_KEY_MANAGER;
    if (StringUtils.isNotEmpty(body.getKeyManager())) {
        keyManagerName = body.getKeyManager();
    }
    if (application != null) {
        if (RestAPIStoreUtils.isUserOwnerOfApplication(application)) {
            String clientId = body.getConsumerKey();
            String keyType = body.getKeyType().toString();
            String tokenType = APIConstants.DEFAULT_TOKEN_TYPE;
            jsonParamObj.put(APIConstants.SUBSCRIPTION_KEY_TYPE, body.getKeyType().toString());
            jsonParamObj.put(APIConstants.JSON_CLIENT_SECRET, body.getConsumerSecret());
            Map<String, Object> keyDetails = apiConsumer
                    .mapExistingOAuthClient(jsonParamObj.toJSONString(), username, clientId,
                            application.getName(), keyType, tokenType, keyManagerName);
            ApplicationKeyDTO applicationKeyDTO = ApplicationKeyMappingUtil
                    .fromApplicationKeyToDTO(keyDetails, body.getKeyType().toString());
            applicationKeyDTO.setKeyManager(keyManagerName);
            return Response.ok().entity(applicationKeyDTO).build();
        } else {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
    } else {
        RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
    }
    return null;
}
 
Example #12
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Re generate consumer secret.
 *
 * @param applicationId Application Id
 * @param keyType       Key Type (Production | Sandbox)
 * @return A response object containing application keys.
 */
@Override
public Response applicationsApplicationIdKeysKeyTypeRegenerateSecretPost(String applicationId,
        String keyType, MessageContext messageContext) {
    String username = RestApiUtil.getLoggedInUsername();
    try {
        Set<APIKey> applicationKeys = getApplicationKeys(applicationId);
        if (applicationKeys == null){
            return null;
        }
        for (APIKey apiKey : applicationKeys) {
            if (keyType != null && keyType.equals(apiKey.getType()) &&
                    APIConstants.KeyManager.DEFAULT_KEY_MANAGER.equals(apiKey.getKeyManager())) {
                APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
                String clientId = apiKey.getConsumerKey();
                String clientSecret =
                        apiConsumer.renewConsumerSecret(clientId, APIConstants.KeyManager.DEFAULT_KEY_MANAGER);

                ApplicationKeyDTO applicationKeyDTO = new ApplicationKeyDTO();
                applicationKeyDTO.setConsumerKey(clientId);
                applicationKeyDTO.setConsumerSecret(clientSecret);

                return Response.ok().entity(applicationKeyDTO).build();
            }
        }

    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while re generating the consumer secret ", e, log);
    }
    return null;
}
 
Example #13
Source File: APIConsumerAdminTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testResumeWorkflow() throws Exception {
    APIManagerFactory apiManagerFactory = Mockito.mock(APIManagerFactory.class);
    PowerMockito.mockStatic(APIManagerFactory.class);
    Mockito.when(APIManagerFactory.getInstance()).thenReturn(apiManagerFactory);

    APIConsumer consumer = Mockito.mock(APIConsumer.class);
    Mockito.when(apiManagerFactory.getAPIConsumer("")).thenReturn(consumer);
    APIConsumerAdmin apiConsumerAdmin = new APIConsumerAdmin();
    apiConsumerAdmin.resumeWorkflow(null, "");
    Mockito.verify(consumer, Mockito.times(1)).resumeWorkflow(null);
}
 
Example #14
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new application
 *
 * @param body        request body containing application details
 * @return 201 response if successful
 */
@Override
public Response applicationsPost(ApplicationDTO body, MessageContext messageContext){
    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();

        //validate the tier specified for the application
        String tierName = body.getThrottlingPolicy();
        if (tierName == null) {
            RestApiUtil.handleBadRequest("Throttling tier cannot be null", log);
        }

        Map<String, Tier> appTierMap = APIUtil.getTiers(APIConstants.TIER_APPLICATION_TYPE, tenantDomain);
        if (appTierMap == null || RestApiUtil.findTier(appTierMap.values(), tierName) == null) {
            RestApiUtil.handleBadRequest("Specified tier " + tierName + " is invalid", log);
        }

        Object applicationAttributesFromUser = body.getAttributes();
        Map<String, String> applicationAttributes =
                new ObjectMapper().convertValue(applicationAttributesFromUser, Map.class);
        if (applicationAttributes != null) {
            body.setAttributes(applicationAttributes);
        }

        //subscriber field of the body is not honored. It is taken from the context
        Application application = ApplicationMappingUtil.fromDTOtoApplication(body, username);

        int applicationId = apiConsumer.addApplication(application, username);

        //retrieves the created application and send as the response
        Application createdApplication = apiConsumer.getApplicationById(applicationId);
        ApplicationDTO createdApplicationDTO = ApplicationMappingUtil.fromApplicationtoDTO(createdApplication);

        //to be set as the Location header
        URI location = new URI(RestApiConstants.RESOURCE_PATH_APPLICATIONS + "/" +
                createdApplicationDTO.getApplicationId());
        return Response.created(location).entity(createdApplicationDTO).build();
    } catch (APIManagementException | URISyntaxException e) {
        if (RestApiUtil.isDueToResourceAlreadyExists(e)) {
            RestApiUtil.handleResourceAlreadyExistsError(
                    "An application already exists with name " + body.getName(), e,
                    log);
        } else if (RestApiUtil.isDueToApplicationNameWhiteSpaceValidation(e)) {
            RestApiUtil.handleBadRequest("Application name cannot contain leading or trailing white spaces", log);
        } else if (RestApiUtil.isDueToApplicationNameWithInvalidCharacters(e)) {
            RestApiUtil.handleBadRequest("Application name cannot contain invalid characters", log);
        } else {
            RestApiUtil.handleInternalServerError("Error while adding a new application for the user " + username,
                    e, log);
        }
    }
    return null;
}
 
Example #15
Source File: APIConsumerAdmin.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public JSONObject resumeWorkflow(Object[] args, String username) throws APIManagementException {
	APIConsumer consumer = APIManagerFactory.getInstance().getAPIConsumer(username);
	return consumer.resumeWorkflow(args);
}
 
Example #16
Source File: RestApiUtil.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public static APIProvider getLoggedInUserProvider() throws APIManagementException {
    return APIManagerFactory.getInstance().getAPIProvider(getLoggedInUsername());
}
 
Example #17
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Override
public Response applicationsApplicationIdOauthKeysKeyMappingIdPut(String applicationId, String keyMappingId,
                                                                  ApplicationKeyDTO body,
                                                                  MessageContext messageContext)
        throws APIManagementException {

    String username = RestApiUtil.getLoggedInUsername();
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        if (application != null) {
            ApplicationKeyDTO appKey = getApplicationKeyByAppIDAndKeyMapping(applicationId, keyMappingId);
            if (RestAPIStoreUtils.isUserOwnerOfApplication(application) && appKey != null) {
                String grantTypes = StringUtils.join(body.getSupportedGrantTypes(), ',');
                JsonObject jsonParams = new JsonObject();
                jsonParams.addProperty(APIConstants.JSON_GRANT_TYPES, grantTypes);
                jsonParams.addProperty(APIConstants.JSON_USERNAME, username);
                if (body.getAdditionalProperties() != null) {
                    if (body.getAdditionalProperties() instanceof String &&
                            StringUtils.isNotEmpty((String) body.getAdditionalProperties())) {
                        jsonParams.addProperty(APIConstants.JSON_ADDITIONAL_PROPERTIES,
                                (String) body.getAdditionalProperties());
                    } else if (body.getAdditionalProperties() instanceof Map) {
                        String jsonContent = new Gson().toJson(body.getAdditionalProperties());
                        jsonParams.addProperty(APIConstants.JSON_ADDITIONAL_PROPERTIES, jsonContent);
                    }
                }
                OAuthApplicationInfo updatedData = apiConsumer.updateAuthClient(username, application.getName(),
                        appKey.getKeyType().value(), body.getCallbackUrl(), null, null, null,
                        body.getGroupId(),new Gson().toJson(jsonParams),appKey.getKeyManager());
                ApplicationKeyDTO applicationKeyDTO = new ApplicationKeyDTO();
                applicationKeyDTO.setCallbackUrl(updatedData.getCallBackURL());
                JsonObject json = new Gson().fromJson(updatedData.getJsonString(), JsonObject.class);
                if (json.get(APIConstants.JSON_GRANT_TYPES) != null) {
                    String[] updatedGrantTypes = json.get(APIConstants.JSON_GRANT_TYPES).getAsString().split(" ");
                    applicationKeyDTO.setSupportedGrantTypes(Arrays.asList(updatedGrantTypes));
                }
                applicationKeyDTO.setConsumerKey(updatedData.getClientId());
                applicationKeyDTO.setConsumerSecret(updatedData.getClientSecret());
                applicationKeyDTO.setKeyType(appKey.getKeyType());
                Object additionalProperties = updatedData.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES);
                if (additionalProperties != null) {
                    applicationKeyDTO.setAdditionalProperties(additionalProperties);
                }
                applicationKeyDTO.setKeyMappingId(body.getKeyMappingId());
                applicationKeyDTO.setKeyManager(body.getKeyManager());
                return Response.ok().entity(applicationKeyDTO).build();
            } else {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }

    return null;    }
 
Example #18
Source File: RestApiUtil.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public static APIProvider getProvider(String username) throws APIManagementException {
    return APIManagerFactory.getInstance().getAPIProvider(username);
}
 
Example #19
Source File: APIExecutorTestCase.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Before
public void setup() throws Exception {

    System.setProperty(CARBON_HOME, "");
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    Mockito.when(privilegedCarbonContext.getUsername()).thenReturn(USER_NAME);

    PowerMockito.mockStatic(CarbonContext.class);
    CarbonContext carbonContext = Mockito.mock(CarbonContext.class);
    PowerMockito.when(CarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    Mockito.when(carbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);

    Mockito.when(resource.getUUID()).thenReturn(ARTIFACT_ID);
    Mockito.when(requestContext.getResource()).thenReturn(resource);
    Mockito.when(genericArtifactManager.getGenericArtifact(ARTIFACT_ID)).thenReturn(genericArtifact);
    Mockito.when(genericArtifact.getLifecycleState()).thenReturn("CREATED");

    Mockito.when(apiProvider.propergateAPIStatusChangeToGateways(apiIdentifier, APIConstants.PUBLISHED))
            .thenReturn(new HashMap<>());
    Mockito.when(apiProvider.updateAPIforStateChange(apiIdentifier, APIConstants.PUBLISHED, new HashMap<>())).thenReturn
            (true);
    Mockito.when(userRegistry.get("/apimgt/applicationdata/provider/john/pizza-shack/2.0.0/api"))
            .thenReturn(resource);

    Mockito.when(api.getId()).thenReturn(apiIdentifier);
    Mockito.when(apiIdentifier.getProviderName()).thenReturn(USER_NAME);
    Mockito.when(apiIdentifier.getApiName()).thenReturn(API_NAME);
    Mockito.when(apiIdentifier.getVersion()).thenReturn(API_VERSION);
    Mockito.when(api.getEndpointConfig()).thenReturn("http://bar.com");

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    TestTenantManager tenantManager = new TestTenantManager();
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    PowerMockito.mockStatic(APIUtil.class);
    PowerMockito.when(APIUtil.getArtifactManager(requestContext.getSystemRegistry(),APIConstants.API_KEY)).thenReturn(genericArtifactManager);

    PowerMockito.when(APIUtil.replaceEmailDomainBack(tenantAwareUserName)).thenReturn(tenantAwareUserName);
    PowerMockito.when(APIUtil.replaceEmailDomain(USER_NAME)).thenReturn(USER_NAME);
    PowerMockito.when(APIUtil.getAPIPath(apiIdentifier)).thenCallRealMethod();
    PowerMockito.when(APIUtil.getLcStateFromArtifact(genericArtifact)).thenReturn("CREATED");

    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceUserRegistry(USER_NAME,TENANT_ID)).thenReturn(userRegistry);

    PowerMockito.when(APIUtil.getAPI(genericArtifact)).thenReturn(api);

    PowerMockito.mockStatic(APIManagerFactory.class);
    PowerMockito.when(APIManagerFactory.getInstance()).thenReturn(apiManagerFactory);
    Mockito.when(apiManagerFactory.getAPIProvider(USER_NAME+'@'+TENANT_DOMAIN)).thenReturn(apiProvider);
    CheckListItemBean checkListItemBean1 = new CheckListItemBean();
    checkListItemBean1.setName(APIConstants.DEPRECATE_CHECK_LIST_ITEM);
    checkListItemBean1.setOrder(0);
    CheckListItemBean checkListItemBean2 = new CheckListItemBean();
    checkListItemBean2.setName(APIConstants.RESUBSCRIBE_CHECK_LIST_ITEM);
    checkListItemBean2.setOrder(1);
    CheckListItemBean[] checkListItemBeans = { checkListItemBean1, checkListItemBean2 };
    PowerMockito.mockStatic(GovernanceUtils.class);
    PowerMockito
            .when(GovernanceUtils.getAllCheckListItemBeans(resource, genericArtifact, APIConstants.API_LIFE_CYCLE))
            .thenReturn(checkListItemBeans);

    Tier tier1 = new Tier("GOLD");
    Tier tier2 = new Tier("SILVER");
    Set<Tier> hashSet = new HashSet<Tier>();
    hashSet.add(tier1);
    hashSet.add(tier2);
    Mockito.when(api.getAvailableTiers()).thenReturn(hashSet);
}
 
Example #20
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Update grant types/callback URL
 *
 * @param applicationId Application Id
 * @param keyType       Key Type (Production | Sandbox)
 * @param body          Grant type and callback URL information
 * @return Updated Key Information
 */
@Override
public Response applicationsApplicationIdKeysKeyTypePut(String applicationId, String keyType,
        ApplicationKeyDTO body, MessageContext messageContext) {
    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        if (application != null) {
            if (RestAPIStoreUtils.isUserOwnerOfApplication(application)) {
                String grantTypes = StringUtils.join(body.getSupportedGrantTypes(), ',');
                JsonObject jsonParams = new JsonObject();
                jsonParams.addProperty(APIConstants.JSON_GRANT_TYPES, grantTypes);
                jsonParams.addProperty(APIConstants.JSON_USERNAME, username);
                if (body.getAdditionalProperties() != null) {
                    if (body.getAdditionalProperties() instanceof String &&
                            StringUtils.isNotEmpty((String) body.getAdditionalProperties())) {
                        jsonParams.addProperty(APIConstants.JSON_ADDITIONAL_PROPERTIES,
                                (String) body.getAdditionalProperties());
                    } else if (body.getAdditionalProperties() instanceof Map) {
                        String jsonContent = new Gson().toJson(body.getAdditionalProperties());
                        jsonParams.addProperty(APIConstants.JSON_ADDITIONAL_PROPERTIES, jsonContent);
                    }
                }
                String keyManagerName = APIConstants.KeyManager.DEFAULT_KEY_MANAGER;
                OAuthApplicationInfo updatedData = apiConsumer.updateAuthClient(username, application.getName(),
                        keyType, body.getCallbackUrl(), null, null, null, body.getGroupId(),
                        new Gson().toJson(jsonParams),keyManagerName);
                ApplicationKeyDTO applicationKeyDTO = new ApplicationKeyDTO();
                applicationKeyDTO.setCallbackUrl(updatedData.getCallBackURL());
                JsonObject json = new Gson().fromJson(updatedData.getJsonString(), JsonObject.class);
                if (json.get(APIConstants.JSON_GRANT_TYPES) != null) {
                    String[] updatedGrantTypes = json.get(APIConstants.JSON_GRANT_TYPES).getAsString().split(" ");
                    applicationKeyDTO.setSupportedGrantTypes(Arrays.asList(updatedGrantTypes));
                }
                applicationKeyDTO.setConsumerKey(updatedData.getClientId());
                applicationKeyDTO.setConsumerSecret(updatedData.getClientSecret());
                applicationKeyDTO.setKeyType(ApplicationKeyDTO.KeyTypeEnum.valueOf(keyType));
                Object additionalProperties = updatedData.getParameter(APIConstants.JSON_ADDITIONAL_PROPERTIES);
                if (additionalProperties != null) {
                    applicationKeyDTO.setAdditionalProperties(additionalProperties);
                }
                return Response.ok().entity(applicationKeyDTO).build();
            } else {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while updating application " + applicationId, e, log);
    }
    return null;
}
 
Example #21
Source File: RestApiUtil.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public static APIConsumer getConsumer(String subscriberName) throws APIManagementException {
    return APIManagerFactory.getInstance().getAPIConsumer(subscriberName);
}
 
Example #22
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Generate keys for a application
 *
 * @param applicationId     application identifier
 * @param body              request body
 * @return A response object containing application keys
 */
@Override
public Response applicationsApplicationIdGenerateKeysPost(String applicationId, ApplicationKeyGenerateRequestDTO
        body, MessageContext messageContext) throws APIManagementException {

    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        if (application != null) {
            if (RestAPIStoreUtils.isUserOwnerOfApplication(application)) {
                String[] accessAllowDomainsArray = {"ALL"};
                JSONObject jsonParamObj = new JSONObject();
                jsonParamObj.put(ApplicationConstants.OAUTH_CLIENT_USERNAME, username);
                String grantTypes = StringUtils.join(body.getGrantTypesToBeSupported(), ',');
                if (!StringUtils.isEmpty(grantTypes)) {
                    jsonParamObj.put(APIConstants.JSON_GRANT_TYPES, grantTypes);
                }
                /* Read clientId & clientSecret from ApplicationKeyGenerateRequestDTO object.
                   User can provide clientId only or both clientId and clientSecret
                   User cannot provide clientSecret only */
                if (!StringUtils.isEmpty(body.getClientId())) {
                    jsonParamObj.put(APIConstants.JSON_CLIENT_ID, body.getClientId());
                    if (!StringUtils.isEmpty(body.getClientSecret())) {
                        jsonParamObj.put(APIConstants.JSON_CLIENT_SECRET, body.getClientSecret());
                    }
                }

                if (body.getAdditionalProperties() != null) {
                    if (body.getAdditionalProperties() instanceof String &&
                            StringUtils.isNotEmpty((String) body.getAdditionalProperties())) {
                        jsonParamObj.put(APIConstants.JSON_ADDITIONAL_PROPERTIES, body.getAdditionalProperties());
                    } else if (body.getAdditionalProperties() instanceof Map) {
                        String jsonContent = new Gson().toJson(body.getAdditionalProperties());
                        jsonParamObj.put(APIConstants.JSON_ADDITIONAL_PROPERTIES, jsonContent);
                    }
                }
                String jsonParams = jsonParamObj.toString();
                String tokenScopes = StringUtils.join(body.getScopes(), " ");
                String keyManagerName = APIConstants.KeyManager.DEFAULT_KEY_MANAGER;
                if (StringUtils.isNotEmpty(body.getKeyManager())) {
                    keyManagerName = body.getKeyManager();
                }
                Map<String, Object> keyDetails = apiConsumer.requestApprovalForApplicationRegistration(
                        username, application.getName(), body.getKeyType().toString(), body.getCallbackUrl(),
                        accessAllowDomainsArray, body.getValidityTime(), tokenScopes, application.getGroupId(),
                        jsonParams, keyManagerName);
                ApplicationKeyDTO applicationKeyDTO =
                        ApplicationKeyMappingUtil.fromApplicationKeyToDTO(keyDetails, body.getKeyType().toString());
                applicationKeyDTO.setKeyManager(keyManagerName);
                return Response.ok().entity(applicationKeyDTO).build();
            } else {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
    } catch (EmptyCallbackURLForCodeGrantsException e) {
        RestApiUtil.handleBadRequest(e.getMessage(), log);
    }
    return null;
}
 
Example #23
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Override
public Response applicationsApplicationIdApiKeysKeyTypeRevokePost(String applicationId, String keyType,
                                                                  APIKeyRevokeRequestDTO body, String ifMatch,
                                                                  MessageContext messageContext) {
    String username = RestApiUtil.getLoggedInUsername();
    String apiKey = body.getApikey();
    if (!StringUtils.isEmpty(apiKey) && APIUtil.isValidJWT(apiKey)) {
        try {
            String splitToken[] = apiKey.split("\\.");
            String signatureAlgorithm = APIUtil.getSignatureAlgorithm(splitToken);
            String certAlias = APIUtil.getSigningAlias(splitToken);
            Certificate certificate = APIUtil.getCertificateFromTrustStore(certAlias);
            if(APIUtil.verifyTokenSignature(splitToken, certificate, signatureAlgorithm)) {
                APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
                Application application = apiConsumer.getApplicationByUUID(applicationId);
                org.json.JSONObject decodedBody = new org.json.JSONObject(
                                    new String(Base64.getUrlDecoder().decode(splitToken[1])));
                org.json.JSONObject appInfo = decodedBody.getJSONObject(APIConstants.JwtTokenConstants.APPLICATION);
                if (appInfo != null && application != null) {
                    if (RestAPIStoreUtils.isUserOwnerOfApplication(application)) {
                        String appUuid = appInfo.getString(APIConstants.JwtTokenConstants.APPLICATION_UUID);
                        if (applicationId.equals(appUuid)) {
                            long expiryTime = Long.MAX_VALUE;
                            org.json.JSONObject payload = new org.json.JSONObject(
                                    new String(Base64.getUrlDecoder().decode(splitToken[1])));
                            if (payload.has(APIConstants.JwtTokenConstants.EXPIRY_TIME)) {
                                expiryTime = APIUtil.getExpiryifJWT(apiKey);
                            }
                            String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
                            apiConsumer.revokeAPIKey(apiKey, expiryTime, tenantDomain);
                            return Response.ok().build();
                        } else {
                            if (log.isDebugEnabled()) {
                                log.debug("Application uuid " + applicationId + " isn't matched with the " +
                                        "application in the token " + appUuid + " of API Key " +
                                                                                APIUtil.getMaskedToken(apiKey));
                            }
                            RestApiUtil.handleBadRequest("Validation failed for the given token ", log);
                        }
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Logged in user " + username + " isn't the owner of the application "
                                                                                                    + applicationId);
                        }
                        RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION,
                                                                                                  applicationId, log);
                    }
                } else {
                    if(log.isDebugEnabled()) {
                        if (application == null) {
                            log.debug("Application with given id " + applicationId + " doesn't not exist ");
                        }

                        if (appInfo == null) {
                            log.debug("Application information doesn't exist in the token "
                                                                                + APIUtil.getMaskedToken(apiKey));
                        }
                    }
                    RestApiUtil.handleBadRequest("Validation failed for the given token ", log);
                }
            } else {
                if(log.isDebugEnabled()) {
                    log.debug("Signature verification of given token " + APIUtil.getMaskedToken(apiKey) +
                                                                                                        " is failed");
                }
                RestApiUtil.handleInternalServerError("Validation failed for the given token", log);
            }
        } catch (APIManagementException e) {
            String msg = "Error while revoking API Key of application " + applicationId;
            if(log.isDebugEnabled()) {
                log.debug("Error while revoking API Key of application " +
                        applicationId+ " and token " + APIUtil.getMaskedToken(apiKey));
            }
            log.error(msg, e);
            RestApiUtil.handleInternalServerError(msg, e, log);
        }
    } else {
        log.debug("Provided API Key " + APIUtil.getMaskedToken(apiKey) + " is not valid");
        RestApiUtil.handleBadRequest("Provided API Key isn't valid ", log);
    }
    return null;
}
 
Example #24
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Override
public Response applicationsApplicationIdApiKeysKeyTypeGeneratePost(
        String applicationId, String keyType, APIKeyGenerateRequestDTO body, String ifMatch, MessageContext messageContext) {

    String userName = RestApiUtil.getLoggedInUsername();
    Application application;
    int validityPeriod;
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(userName);
        if ((application = apiConsumer.getApplicationByUUID(applicationId)) == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        } else {
            if (!RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            } else {
                if (APIConstants.API_KEY_TYPE_PRODUCTION.equalsIgnoreCase(keyType)) {
                    application.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
                } else if (APIConstants.API_KEY_TYPE_SANDBOX.equalsIgnoreCase(keyType)) {
                    application.setKeyType(APIConstants.API_KEY_TYPE_SANDBOX);
                } else {
                    RestApiUtil.handleBadRequest("Invalid keyType. KeyType should be either PRODUCTION or SANDBOX", log);
                }
                if (body != null && body.getValidityPeriod() != null && body.getValidityPeriod() > 0) {
                    validityPeriod = body.getValidityPeriod();
                } else {
                    validityPeriod = -1;
                }

                String restrictedIP = null;
                String restrictedReferer = null;

                if (body.getAdditionalProperties() != null) {
                    Map additionalProperties = (HashMap) body.getAdditionalProperties();
                    if (additionalProperties.get(APIConstants.JwtTokenConstants.PERMITTED_IP) != null) {
                        restrictedIP = (String) additionalProperties.get(APIConstants.JwtTokenConstants.PERMITTED_IP);
                    }
                    if (additionalProperties.get(APIConstants.JwtTokenConstants.PERMITTED_REFERER) != null) {
                        restrictedReferer = (String) additionalProperties.get(APIConstants.JwtTokenConstants.PERMITTED_REFERER);
                    }
                }
                String apiKey = apiConsumer.generateApiKey(application, userName, (long) validityPeriod,
                        restrictedIP, restrictedReferer);
                APIKeyDTO apiKeyDto = ApplicationKeyMappingUtil.formApiKeyToDTO(apiKey, validityPeriod);
                return Response.ok().entity(apiKeyDto).build();
            }
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while generatig API Keys for application " + applicationId, e, log);
    }
    return null;
}
 
Example #25
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Update an application by Id
 *
 * @param applicationId     application identifier
 * @param body              request body containing application details
 * @param ifMatch           If-Match header value
 * @return response containing the updated application object
 */
@Override
public Response applicationsApplicationIdPut(String applicationId, ApplicationDTO body, String ifMatch, MessageContext messageContext) {
    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        Application oldApplication = apiConsumer.getApplicationByUUID(applicationId);
        
        if (oldApplication == null) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
        
        if (!RestAPIStoreUtils.isUserOwnerOfApplication(oldApplication)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }

        Object applicationAttributesFromUser = body.getAttributes();
        Map<String, String> applicationAttributes = new ObjectMapper()
                .convertValue(applicationAttributesFromUser, Map.class);

        if (applicationAttributes != null) {
            body.setAttributes(applicationAttributes);
        }
        
        //we do not honor the subscriber coming from the request body as we can't change the subscriber of the application
        Application application = ApplicationMappingUtil.fromDTOtoApplication(body, username);

        //we do not honor the application id which is sent via the request body
        application.setUUID(oldApplication != null ? oldApplication.getUUID() : null);

        apiConsumer.updateApplication(application);

        //retrieves the updated application and send as the response
        Application updatedApplication = apiConsumer.getApplicationByUUID(applicationId);
        ApplicationDTO updatedApplicationDTO = ApplicationMappingUtil
                .fromApplicationtoDTO(updatedApplication);
        return Response.ok().entity(updatedApplicationDTO).build();
            
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToApplicationNameWhiteSpaceValidation(e)) {
            RestApiUtil.handleBadRequest("Application name cannot contains leading or trailing white spaces", log);
        } else if (RestApiUtil.isDueToApplicationNameWithInvalidCharacters(e)) {
            RestApiUtil.handleBadRequest("Application name cannot contain invalid characters", log);
        } else {
            RestApiUtil.handleInternalServerError("Error while updating application " + applicationId, e, log);
        }
    }
    return null;
}
 
Example #26
Source File: ApplicationsApiServiceImpl.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * Get an application by Id
 *
 * @param applicationId   application identifier
 * @param ifNoneMatch     If-None-Match header value
 * @return response containing the required application object
 */
@Override
public Response applicationsApplicationIdGet(String applicationId, String ifNoneMatch, MessageContext messageContext) {
    String username = RestApiUtil.getLoggedInUsername();
    try {
        APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        if (application != null) {
            // Remove hidden attributes and set the rest of the attributes from config
            JSONArray applicationAttributesFromConfig = apiConsumer.getAppAttributesFromConfig(username);
            Map<String, String> existingApplicationAttributes = application.getApplicationAttributes();
            Map<String, String> applicationAttributes = new HashMap<>();
            if (existingApplicationAttributes != null && applicationAttributesFromConfig != null) {
                for (Object object : applicationAttributesFromConfig) {
                    JSONObject attribute = (JSONObject) object;
                    Boolean hidden = (Boolean) attribute.get(APIConstants.ApplicationAttributes.HIDDEN);
                    String attributeName = (String) attribute.get(APIConstants.ApplicationAttributes.ATTRIBUTE);

                    if (!BooleanUtils.isTrue(hidden)) {
                        String attributeVal = existingApplicationAttributes.get(attributeName);
                        if (attributeVal != null) {
                            applicationAttributes.put(attributeName, attributeVal);
                        } else {
                            applicationAttributes.put(attributeName, "");
                        }
                    }
                }
            }
            application.setApplicationAttributes(applicationAttributes);
            if (RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
                ApplicationDTO applicationDTO = ApplicationMappingUtil.fromApplicationtoDTO(application);
                applicationDTO.setHashEnabled(OAuthServerConfiguration.getInstance().isClientSecretHashEnabled());
                Set<Scope> scopes = apiConsumer.getScopesForApplicationSubscription(username, application.getId());
                List<ScopeInfoDTO> scopeInfoList = ApplicationMappingUtil.getScopeInfoDTO(scopes);
                applicationDTO.setSubscriptionScopes(scopeInfoList);
                return Response.ok().entity(applicationDTO).build();
            } else {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while retrieving application " + applicationId, e, log);
    }
    return null;
}
 
Example #27
Source File: RestApiUtil.java    From carbon-apimgt with Apache License 2.0 2 votes vote down vote up
/** Returns an APIConsumer which is corresponding to the current logged in user taken from the carbon context
 *
 * @return an APIConsumer which is corresponding to the current logged in user
 * @throws APIManagementException
 */
public static APIConsumer getLoggedInUserConsumer() throws APIManagementException {
    return APIManagerFactory.getInstance().getAPIConsumer(getLoggedInUsername());
}
 
Example #28
Source File: WSO2APIPublisher.java    From carbon-apimgt with Apache License 2.0 2 votes vote down vote up
/**
 * Get APIProvider instance for the logged in user.
 *
 * @return APIProvider instance
 * @throws APIManagementException If an error occurs while getting APIProvider instance
 */
protected APIProvider getLoggedInUserProvider() throws APIManagementException {
    //Get APIProvider instance for logged in user
    return APIManagerFactory.getInstance().getAPIProvider(getLoggedInUsername());
}
 
Example #29
Source File: ApplicationUtils.java    From carbon-apimgt with Apache License 2.0 2 votes vote down vote up
/**
 * check whether current logged in user is the owner of the application
 *
 * @param applicationId Application id
 * @param username      loged in user
 * @return true if current logged in consumer is the owner of the specified application
 */
public static boolean isUserOwnerOfApplication(int applicationId, String username) throws APIManagementException {
    APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
    Application application = apiConsumer.getApplicationById(applicationId);
    return isUserOwnerOfApplication(application, username);
}