Search in sources :

Example 36 with APIConsumer

use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method preProcessAndAddApplication.

/**
 * Preprocess and add the application
 *
 * @param username       Username
 * @param applicationDto Application DTO
 * @param organization   Identifier of an organization
 * @return Created application
 */
private Application preProcessAndAddApplication(String username, ApplicationDTO applicationDto, String organization) throws APIManagementException {
    APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
    // validate the tier specified for the application
    String tierName = applicationDto.getThrottlingPolicy();
    if (tierName == null) {
        RestApiUtil.handleBadRequest("Throttling tier cannot be null", log);
    }
    Object applicationAttributesFromUser = applicationDto.getAttributes();
    Map<String, String> applicationAttributes = new ObjectMapper().convertValue(applicationAttributesFromUser, Map.class);
    if (applicationAttributes != null) {
        applicationDto.setAttributes(applicationAttributes);
    }
    // we do not honor tokenType sent in the body and
    // all the applications created will of 'JWT' token type
    applicationDto.setTokenType(ApplicationDTO.TokenTypeEnum.JWT);
    // subscriber field of the body is not honored. It is taken from the context
    Application application = ApplicationMappingUtil.fromDTOtoApplication(applicationDto, username);
    int applicationId = apiConsumer.addApplication(application, username, organization);
    // retrieves the created application and send as the response
    return apiConsumer.getApplicationById(applicationId);
}
Also used : JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 37 with APIConsumer

use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method applicationsApplicationIdPut.

/**
 * 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 = RestApiCommonUtil.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);
        }
        Application updatedApplication = preProcessAndUpdateApplication(username, body, oldApplication, 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 if (RestApiUtil.isDueToResourceAlreadyExists(e)) {
            RestApiUtil.handleResourceAlreadyExistsError("An application already exists with name " + body.getName(), e, log);
        } else {
            RestApiUtil.handleInternalServerError("Error while updating application " + applicationId, e, log);
        }
    }
    return null;
}
Also used : ApplicationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 38 with APIConsumer

use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method applicationsApplicationIdOauthKeysKeyMappingIdGenerateTokenPost.

@Override
public Response applicationsApplicationIdOauthKeysKeyMappingIdGenerateTokenPost(String applicationId, String keyMappingId, ApplicationTokenGenerateRequestDTO body, String ifMatch, MessageContext messageContext) throws APIManagementException {
    String username = RestApiCommonUtil.getLoggedInUsername();
    APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
    Application application = apiConsumer.getApplicationByUUID(applicationId);
    if (application != null) {
        if (RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
            ApplicationKeyDTO appKey = getApplicationKeyByAppIDAndKeyMapping(applicationId, keyMappingId);
            if (appKey != null) {
                String jsonInput = null;
                String grantType;
                if (ApplicationTokenGenerateRequestDTO.GrantTypeEnum.TOKEN_EXCHANGE.equals(body.getGrantType())) {
                    grantType = APIConstants.OAuthConstants.TOKEN_EXCHANGE;
                } else {
                    grantType = APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS;
                }
                try {
                    // verify that the provided jsonInput is a valid json
                    if (body.getAdditionalProperties() != null && !body.getAdditionalProperties().toString().isEmpty()) {
                        jsonInput = validateAdditionalParameters(grantType, body);
                    }
                } catch (JsonProcessingException | ParseException | ClassCastException e) {
                    RestApiUtil.handleBadRequest("Error while generating " + appKey.getKeyType() + " token for " + "application " + applicationId + ". Invalid jsonInput '" + body.getAdditionalProperties() + "' provided.", log);
                }
                if (StringUtils.isNotEmpty(body.getConsumerSecret())) {
                    appKey.setConsumerSecret(body.getConsumerSecret());
                }
                String[] scopes = body.getScopes().toArray(new String[0]);
                try {
                    AccessTokenInfo response = apiConsumer.renewAccessToken(body.getRevokeToken(), appKey.getConsumerKey(), appKey.getConsumerSecret(), body.getValidityPeriod().toString(), scopes, jsonInput, appKey.getKeyManager(), grantType);
                    ApplicationTokenDTO appToken = new ApplicationTokenDTO();
                    appToken.setAccessToken(response.getAccessToken());
                    if (response.getScopes() != null) {
                        appToken.setTokenScopes(Arrays.asList(response.getScopes()));
                    }
                    appToken.setValidityTime(response.getValidityPeriod());
                    return Response.ok().entity(appToken).build();
                } catch (APIManagementException e) {
                    Long errorCode = e.getErrorHandler() != null ? e.getErrorHandler().getErrorCode() : ExceptionCodes.INTERNAL_ERROR.getErrorCode();
                    RestApiUtil.handleBadRequest(e.getMessage(), errorCode, log);
                }
            } else {
                RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APP_CONSUMER_KEY, keyMappingId, log);
            }
        } else {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
    } else {
        RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
    }
    return null;
}
Also used : ApplicationTokenDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationTokenDTO) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationKeyDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ParseException(org.json.simple.parser.ParseException) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 39 with APIConsumer

use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method applicationsApplicationIdOauthKeysKeyMappingIdCleanUpPost.

@Override
public Response applicationsApplicationIdOauthKeysKeyMappingIdCleanUpPost(String applicationId, String keyMappingId, String ifMatch, MessageContext messageContext) throws APIManagementException {
    String username = RestApiCommonUtil.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;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 40 with APIConsumer

use of org.wso2.carbon.apimgt.api.APIConsumer in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method preProcessAndUpdateApplication.

/**
 * Preprocess and update the application
 *
 * @param username       Username
 * @param applicationDto Application DTO
 * @param oldApplication Old application
 * @param applicationId  Application UUID
 * @return Updated application
 */
private Application preProcessAndUpdateApplication(String username, ApplicationDTO applicationDto, Application oldApplication, String applicationId) throws APIManagementException {
    APIConsumer apiConsumer = APIManagerFactory.getInstance().getAPIConsumer(username);
    Object applicationAttributesFromUser = applicationDto.getAttributes();
    Map<String, String> applicationAttributes = new ObjectMapper().convertValue(applicationAttributesFromUser, Map.class);
    if (applicationAttributes != null) {
        applicationDto.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(applicationDto, 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
    return apiConsumer.getApplicationByUUID(applicationId);
}
Also used : JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)91 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)79 Application (org.wso2.carbon.apimgt.api.model.Application)50 Test (org.junit.Test)46 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)46 HashMap (java.util.HashMap)32 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)29 ArrayList (java.util.ArrayList)28 API (org.wso2.carbon.apimgt.api.model.API)28 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)28 JSONObject (org.json.simple.JSONObject)23 ExportedApplication (org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication)23 Subscriber (org.wso2.carbon.apimgt.api.model.Subscriber)20 Map (java.util.Map)19 Matchers.anyString (org.mockito.Matchers.anyString)19 ApiTypeWrapper (org.wso2.carbon.apimgt.api.model.ApiTypeWrapper)18 Tier (org.wso2.carbon.apimgt.api.model.Tier)18 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)15 URI (java.net.URI)13 URISyntaxException (java.net.URISyntaxException)13