Search in sources :

Example 16 with ApplicationDTO

use of org.wso2.carbon.apimgt.internal.service.dto.ApplicationDTO in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method applicationsPost.

/**
 * Creates a new application
 *
 * @param body        request body containing application details
 * @return 201 response if successful
 */
@Override
public Response applicationsPost(ApplicationDTO body, MessageContext messageContext) throws APIManagementException {
    String username = RestApiCommonUtil.getLoggedInUsername();
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        Application createdApplication = preProcessAndAddApplication(username, body, organization);
        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 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 {
            throw e;
        }
    } catch (URISyntaxException e) {
        RestApiUtil.handleInternalServerError(e.getLocalizedMessage(), log);
    }
    return null;
}
Also used : ApplicationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) URISyntaxException(java.net.URISyntaxException) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) URI(java.net.URI)

Example 17 with ApplicationDTO

use of org.wso2.carbon.apimgt.internal.service.dto.ApplicationDTO 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 18 with ApplicationDTO

use of org.wso2.carbon.apimgt.internal.service.dto.ApplicationDTO 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)

Example 19 with ApplicationDTO

use of org.wso2.carbon.apimgt.internal.service.dto.ApplicationDTO in project carbon-apimgt by wso2.

the class ApplicationMappingUtil method fromApplicationtoDTO.

public static ApplicationDTO fromApplicationtoDTO(Application application) throws APIManagementException {
    ApplicationDTO applicationDTO = new ApplicationDTO();
    applicationDTO.setApplicationId(application.getUUID());
    applicationDTO.setThrottlingPolicy(application.getTier());
    applicationDTO.setDescription(application.getDescription());
    Map<String, String> applicationAttributes = application.getApplicationAttributes();
    applicationDTO.setAttributes(applicationAttributes);
    applicationDTO.setName(application.getName());
    applicationDTO.setStatus(application.getStatus());
    applicationDTO.setOwner(application.getOwner());
    if (StringUtils.isNotEmpty(application.getGroupId())) {
        applicationDTO.setGroups(Arrays.asList(application.getGroupId().split(",")));
    }
    applicationDTO.setTokenType(ApplicationDTO.TokenTypeEnum.OAUTH);
    applicationDTO.setSubscriptionCount(application.getSubscriptionCount());
    if (StringUtils.isNotEmpty(application.getTokenType()) && !APIConstants.DEFAULT_TOKEN_TYPE.equals(application.getTokenType())) {
        applicationDTO.setTokenType(ApplicationDTO.TokenTypeEnum.valueOf(application.getTokenType()));
    }
    /*List<ApplicationKeyDTO> applicationKeyDTOs = new ArrayList<>();
        for(APIKey apiKey : application.getKeys()) {
            ApplicationKeyDTO applicationKeyDTO = ApplicationKeyMappingUtil.fromApplicationKeyToDTO(apiKey);
            applicationKeyDTOs.add(applicationKeyDTO);
        }
        applicationDTO.setKeys(applicationKeyDTOs);*/
    return applicationDTO;
}
Also used : ApplicationDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationDTO)

Example 20 with ApplicationDTO

use of org.wso2.carbon.apimgt.internal.service.dto.ApplicationDTO in project carbon-apimgt by wso2.

the class SessionDataPublisherImpl method getAppsAuthorizedByUser.

/**
 * Method to retrieve applications authorized for user
 * @param authenticatedUser authenticated user info
 * @return array of authorized applications
 * @throws IdentityOAuthAdminException exception
 */
private OAuthConsumerAppDTO[] getAppsAuthorizedByUser(AuthenticatedUser authenticatedUser) throws IdentityOAuthAdminException {
    OAuthAppDAO appDAO = new OAuthAppDAO();
    String tenantAwareusername = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    String username = UserCoreUtil.addTenantDomainToEntry(tenantAwareusername, tenantDomain);
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    Set<String> clientIds;
    SystemApplicationDTO[] systemApplicationDTOS;
    SystemApplicationDAO systemApplicationDAO = new SystemApplicationDAO();
    Set<String> systemAppClientIds = new HashSet<>();
    try {
        systemApplicationDTOS = systemApplicationDAO.getApplications(tenantDomain);
        if (systemApplicationDTOS.length < 0) {
            if (log.isDebugEnabled()) {
                log.debug("The tenant: " + tenantDomain + " doesn't have any system apps");
            }
        } else {
            for (SystemApplicationDTO applicationDTO : systemApplicationDTOS) {
                try {
                    if (ApplicationMgtUtil.isUserAuthorized(applicationDTO.getName(), tenantAwareusername)) {
                        systemAppClientIds.add(applicationDTO.getConsumerKey());
                    }
                } catch (IdentityApplicationManagementException e) {
                    log.error("Error occurred while checking the authorization of the application " + applicationDTO.getName(), e);
                }
            }
        }
    } catch (APIMgtDAOException e) {
        log.error("Error thrown while retrieving system applications for the tenant domain " + tenantDomain, e);
    }
    clientIds = systemAppClientIds;
    Set<OAuthConsumerAppDTO> appDTOs = new HashSet<>();
    for (String clientId : clientIds) {
        Set<AccessTokenDO> accessTokenDOs;
        try {
            accessTokenDOs = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessTokens(clientId, authenticatedUser, userStoreDomain, true);
        } catch (IdentityOAuth2Exception e) {
            throw handleError("Error occurred while retrieving access tokens issued for " + "Client ID : " + clientId + ", User ID : " + username, e);
        }
        if (!accessTokenDOs.isEmpty()) {
            Set<String> distinctClientUserScopeCombo = new HashSet<>();
            for (AccessTokenDO accessTokenDO : accessTokenDOs) {
                AccessTokenDO scopedToken;
                String scopeString = OAuth2Util.buildScopeString(accessTokenDO.getScope());
                try {
                    scopedToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(clientId, authenticatedUser, userStoreDomain, scopeString, true);
                    if (scopedToken != null && !distinctClientUserScopeCombo.contains(clientId + ":" + username)) {
                        OAuthAppDO appDO;
                        try {
                            appDO = appDAO.getAppInformation(scopedToken.getConsumerKey());
                            appDTOs.add(buildConsumerAppDTO(appDO));
                            if (log.isDebugEnabled()) {
                                log.debug("Found App: " + appDO.getApplicationName() + " for user: " + username);
                            }
                        } catch (InvalidOAuthClientException e) {
                            String errorMsg = "Invalid Client ID : " + scopedToken.getConsumerKey();
                            log.error(errorMsg, e);
                            throw new IdentityOAuthAdminException(errorMsg);
                        } catch (IdentityOAuth2Exception e) {
                            String errorMsg = "Error occurred while retrieving app information " + "for Client ID : " + scopedToken.getConsumerKey();
                            log.error(errorMsg, e);
                            throw new IdentityOAuthAdminException(errorMsg);
                        }
                        distinctClientUserScopeCombo.add(clientId + ":" + username);
                    }
                } catch (IdentityOAuth2Exception e) {
                    String errorMsg = "Error occurred while retrieving latest access token issued for Client ID :" + " " + clientId + ", User ID : " + username + " and Scope : " + scopeString;
                    throw handleError(errorMsg, e);
                }
            }
        }
    }
    return appDTOs.toArray(new OAuthConsumerAppDTO[0]);
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) APIMgtDAOException(org.wso2.carbon.apimgt.api.APIMgtDAOException) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthAppDAO(org.wso2.carbon.identity.oauth.dao.OAuthAppDAO) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SystemApplicationDTO(org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO) SystemApplicationDAO(org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Aggregations

Application (org.wso2.carbon.apimgt.core.models.Application)11 ApplicationDTO (org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationDTO)11 ArrayList (java.util.ArrayList)10 Application (org.wso2.carbon.apimgt.api.model.Application)8 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)7 ExportedApplication (org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication)7 Test (org.junit.Test)6 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)6 ApplicationKeysDTO (org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationKeysDTO)6 ApplicationDTO (org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationDTO)6 HashMap (java.util.HashMap)5 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)5 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)5 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)5 ApplicationCreationResponse (org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse)5 ApplicationTokenDTO (org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenDTO)5 URI (java.net.URI)4 URISyntaxException (java.net.URISyntaxException)4 Response (javax.ws.rs.core.Response)4 JSONObject (org.json.simple.JSONObject)4