Java Code Examples for org.apache.cxf.jaxrs.ext.MessageContext

The following examples show how to use org.apache.cxf.jaxrs.ext.MessageContext. 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
Source Project: carbon-apimgt   Source File: ApplicationsApiServiceImpl.java    License: 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 2
Source Project: jwala   Source File: ResourceServiceRestImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadExternalProperties() throws IOException {
    final MessageContext msgContextMock = mock(MessageContext.class);
    final HttpHeaders httpHeadersMock = mock(HttpHeaders.class);
    final List<MediaType> mediaTypeList = new ArrayList<>();
    final HttpServletRequest httpServletRequestMock = mock(HttpServletRequest.class);
    final HttpServletResponse httpServletResponseMock = mock(HttpServletResponse.class);
    when(httpHeadersMock.getAcceptableMediaTypes()).thenReturn(mediaTypeList);
    when(msgContextMock.getHttpHeaders()).thenReturn(httpHeadersMock);
    when(msgContextMock.getHttpServletRequest()).thenReturn(httpServletRequestMock);
    when(msgContextMock.getHttpServletResponse()).thenReturn(httpServletResponseMock);
    when(httpServletRequestMock.getContentType()).thenReturn("multipart/form-data; boundary=----WebKitFormBoundaryXRxegBGqTe4gApI2");
    when(httpServletRequestMock.getInputStream()).thenReturn(new DelegatingServletInputStream());
    cut.setMessageContext(msgContextMock);

    final SecurityContext securityContextMock = mock(SecurityContext.class);
    final AuthenticatedUser authenticatedUser = new AuthenticatedUser(securityContextMock);

    final Principal mockPrincipal = mock(Principal.class);
    when(mockPrincipal.getName()).thenReturn("user");
    when(securityContextMock.getUserPrincipal()).thenReturn(mockPrincipal);

    cut.uploadExternalProperties(authenticatedUser);
    verify(impl).createResource(any(ResourceIdentifier.class), any(ResourceTemplateMetaData.class), any(InputStream.class));
}
 
Example 3
Source Project: carbon-apimgt   Source File: KeyManagersApiServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public Response keyManagersPost(KeyManagerDTO body, MessageContext messageContext) throws APIManagementException {

        String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
        APIAdmin apiAdmin = new APIAdminImpl();
        try {
            KeyManagerConfigurationDTO keyManagerConfigurationDTO =
                    KeyManagerMappingUtil.toKeyManagerConfigurationDTO(tenantDomain, body);
            KeyManagerConfigurationDTO createdKeyManagerConfiguration =
                    apiAdmin.addKeyManagerConfiguration(keyManagerConfigurationDTO);
            URI location = new URI(RestApiConstants.KEY_MANAGERS + "/" + createdKeyManagerConfiguration.getUuid());
            return Response.created(location)
                    .entity(KeyManagerMappingUtil.toKeyManagerDTO(createdKeyManagerConfiguration)).build();
        } catch (URISyntaxException e) {
            String error = "Error while Creating Key Manager configuration in tenant " + tenantDomain;
            RestApiUtil.handleInternalServerError(error, e, log);
        }
        return null;
    }
 
Example 4
Source Project: tomee   Source File: Contexts.java    License: Apache License 2.0 6 votes vote down vote up
private static Set<Class<?>> contextClasses() {
    final Set<Class<?>> classes = new HashSet<>(); classes.add(UriInfo.class);
    classes.add(SecurityContext.class);
    classes.add(HttpHeaders.class);
    classes.add(ContextResolver.class);
    classes.add(Providers.class);
    classes.add(Request.class);
    /* TODO: when we have jaxrs 2
    classes.add(ResourceInfo.class);
    classes.add(ResourceContext.class);
    */
    classes.add(Application.class);
    classes.add(HttpServletRequest.class);
    classes.add(HttpServletResponse.class);
    classes.add(ServletConfig.class);
    classes.add(ServletContext.class);
    classes.add(MessageContext.class);
    return classes;
}
 
Example 5
Source Project: cxf   Source File: HawkAccessTokenValidatorClient.java    License: Apache License 2.0 6 votes vote down vote up
public AccessTokenValidation validateAccessToken(MessageContext mc,
                                                 String authScheme,
                                                 String authSchemeData,
                                                 MultivaluedMap<String, String> extraProps)
    throws OAuthServiceException {
    if (isRemoteSignatureValidation()) {
        MultivaluedMap<String, String> map = new MetadataMap<>();
        if (extraProps != null) {
            map.putAll(extraProps);
        }
        map.putSingle(HTTP_VERB, mc.getRequest().getMethod());
        map.putSingle(HTTP_URI, mc.getUriInfo().getRequestUri().toString());
        return validator.validateAccessToken(mc, authScheme, authSchemeData, map);
    }
    return super.validateAccessToken(mc, authScheme, authSchemeData, extraProps);

}
 
Example 6
Source Project: carbon-apimgt   Source File: KeymanagersApiServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
public Response keymanagersGet(String xWSO2Tenant, MessageContext messageContext) {

        String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
        try {
            if (StringUtils.isNotEmpty(xWSO2Tenant)) {
                tenantDomain = xWSO2Tenant;
            }
            APIAdmin apiAdmin = new APIAdminImpl();
            List<KeyManagerConfigurationDTO> keyManagerConfigurations =
                    apiAdmin.getKeyManagerConfigurationsByTenant(tenantDomain);
            List<KeyManagerDTO> keyManagerDTOList = new ArrayList<>();
            for (KeyManagerConfigurationDTO keyManagerConfiguration : keyManagerConfigurations) {
                keyManagerDTOList.add(toKeyManagerDTO(tenantDomain, keyManagerConfiguration));
            }
            return Response.ok(keyManagerDTOList).build();
        } catch (APIManagementException e) {
            RestApiUtil.handleInternalServerError("Error while retrieving key manager configurations", e, log);
        }
        return null;
    }
 
Example 7
Source Project: carbon-apimgt   Source File: ThrottlingApiServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves all Block Conditions
 *
 * @param accept          Accept header value
 * @param ifNoneMatch     If-None-Match header value
 * @param ifModifiedSince If-Modified-Since header value
 * @return All matched block conditions to the given request
 */
@Override
public Response throttlingBlacklistGet(String accept, String ifNoneMatch, String ifModifiedSince,
                                       MessageContext messageContext) {
    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        List<BlockConditionsDTO> blockConditions = apiProvider.getBlockConditions();
        BlockingConditionListDTO listDTO =
                BlockingConditionMappingUtil.fromBlockConditionListToListDTO(blockConditions);
        return Response.ok().entity(listDTO).build();
    } catch (APIManagementException | ParseException e) {
        String errorMessage = "Error while retrieving Block Conditions";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example 8
Source Project: carbon-apimgt   Source File: SettingsApiServiceImpl.java    License: 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 Project: cxf   Source File: OAuthUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Response handleException(MessageContext mc,
                                       Exception e,
                                       int status) {
    ResponseBuilder builder = Response.status(status);
    if (PropertyUtils.isTrue(mc.getContextualProperty(REPORT_FAILURE_DETAILS))) {
        boolean asHeader = PropertyUtils.isTrue(
            mc.getContextualProperty(REPORT_FAILURE_DETAILS_AS_HEADER));
        String text = null;
        if (e instanceof OAuthProblemException) {
            OAuthProblemException problem = (OAuthProblemException)e;
            if (asHeader && problem.getProblem() != null) {
                text = problem.getProblem();
            }
        }
        if (text == null) {
            text = e.getMessage();
        }
        if (asHeader) {
            builder.header("oauth_problem", text);
        } else {
            builder.entity(e.getMessage());
        }
    }
    return builder.build();
}
 
Example 10
Source Project: cxf   Source File: AccessTokenValidatorClient.java    License: Apache License 2.0 6 votes vote down vote up
public AccessTokenValidation validateAccessToken(MessageContext mc,
                                                 String authScheme,
                                                 String authSchemeData,
                                                 MultivaluedMap<String, String> extraProps)
    throws OAuthServiceException {
    WebClient client = WebClient.fromClient(tokenValidatorClient, true);
    MultivaluedMap<String, String> props = new MetadataMap<>();
    props.putSingle(OAuthConstants.AUTHORIZATION_SCHEME_TYPE, authScheme);
    props.putSingle(OAuthConstants.AUTHORIZATION_SCHEME_DATA, authSchemeData);
    if (extraProps != null) {
        props.putAll(extraProps);
    }
    try {
        return client.post(props, AccessTokenValidation.class);
    } catch (WebApplicationException ex) {
        throw new OAuthServiceException(ex);
    }
}
 
Example 11
Source Project: cxf   Source File: AttachmentUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static MultipartBody getMultipartBody(MessageContext mc,
    String attachmentDir, String attachmentThreshold, String attachmentMaxSize) {
    if (attachmentDir != null) {
        mc.put(AttachmentDeserializer.ATTACHMENT_DIRECTORY, attachmentDir);
    }
    if (attachmentThreshold != null) {
        mc.put(AttachmentDeserializer.ATTACHMENT_MEMORY_THRESHOLD, attachmentThreshold);
    }
    if (attachmentMaxSize != null) {
        mc.put(AttachmentDeserializer.ATTACHMENT_MAX_SIZE, attachmentMaxSize);
    }

    boolean embeddedAttachment = mc.get("org.apache.cxf.multipart.embedded") != null;
    String propertyName = embeddedAttachment ? MultipartBody.INBOUND_MESSAGE_ATTACHMENTS + ".embedded"
        : MultipartBody.INBOUND_MESSAGE_ATTACHMENTS;

    MultipartBody body = (MultipartBody)mc.get(propertyName);
    if (!embeddedAttachment && mc.get(IN_FILTERS) != null) {
        List<MultipartInputFilter> filters = CastUtils.cast((List<?>)mc.get(IN_FILTERS));
        for (MultipartInputFilter filter : filters) {
            filter.filter(body.getAllAttachments());
        }
    }
    return body;
}
 
Example 12
@Override
public Response applicationKeyMappingsGet(String xWSO2Tenant, String consumerKey, MessageContext messageContext) {

    SubscriptionValidationDAO subscriptionValidationDAO = new SubscriptionValidationDAO();
    xWSO2Tenant = SubscriptionValidationDataUtil.validateTenantDomain(xWSO2Tenant, messageContext);

    if (StringUtils.isNotEmpty(consumerKey)) {
        ApplicationKeyMapping keyMapping = subscriptionValidationDAO.getApplicationKeyMapping(consumerKey);
        List<ApplicationKeyMapping> applicationKeyMappings = new ArrayList<>();
        if (keyMapping != null) {
            applicationKeyMappings.add(keyMapping);
        }
        return Response.ok().entity(SubscriptionValidationDataUtil.
                fromApplicationKeyMappingToApplicationKeyMappingListDTO(applicationKeyMappings)).build();
    }
    if (StringUtils.isNotEmpty(xWSO2Tenant)) {
        return Response.ok().entity(SubscriptionValidationDataUtil.
                fromApplicationKeyMappingToApplicationKeyMappingListDTO(subscriptionValidationDAO.
                        getAllApplicationKeyMappings(xWSO2Tenant))).build();

    }
    return Response.ok().entity(SubscriptionValidationDataUtil.
            fromApplicationKeyMappingToApplicationKeyMappingListDTO(
                    subscriptionValidationDAO.getAllApplicationKeyMappings())).build();
}
 
Example 13
Source Project: cxf   Source File: BookStore.java    License: Apache License 2.0 5 votes vote down vote up
@GET
@Path("books/check/malformedmt/{id}")
@Produces("text/plain")
public Response checkBookMalformedMT(@PathParam("id") Long id,
                                     @Context MessageContext mc) {
    mc.put("org.apache.cxf.jaxrs.mediaTypeCheck.strict", false);
    return Response.ok(books.containsKey(id)).type("text").build();
}
 
Example 14
protected List<String> getArrayKeys() {
    MessageContext mc = getContext();
    if (mc != null) {
        Object prop = mc.get(ARRAY_KEYS_PROPERTY);
        if (prop instanceof List) {
            return CastUtils.cast((List<?>)prop);
        }
    }
    return arrayKeys;
}
 
Example 15
Source Project: carbon-apimgt   Source File: SettingsApiServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves admin portal related server settings
 *
 * @param messageContext
 * @return settings list
 * @throws APIManagementException
 */
@Override
public Response settingsGet(MessageContext messageContext) throws APIManagementException {

        String username = RestApiUtil.getLoggedInUsername();
        boolean isUserAvailable = false;
        if (!APIConstants.WSO2_ANONYMOUS_USER.equalsIgnoreCase(username)) {
            isUserAvailable = true;
        }
        SettingsMappingUtil settingsMappingUtil = new SettingsMappingUtil();
        SettingsDTO settingsDTO = settingsMappingUtil.fromSettingsToDTO(isUserAvailable);
        return Response.ok().entity(settingsDTO).build();
}
 
Example 16
Source Project: carbon-apimgt   Source File: ApiCategoriesApiServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Response apiCategoriesGet(MessageContext messageContext) {
    try {
        APIAdmin apiAdmin = new APIAdminImpl();
        String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
        int tenantID = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
        List<APICategory> categoryList = apiAdmin.getAPICategoriesOfTenant(tenantID);
        APICategoryListDTO categoryListDTO = APICategoryMappingUtil.fromCategoryListToCategoryListDTO(categoryList);
        return Response.ok().entity(categoryListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving API categories";
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example 17
Source Project: carbon-apimgt   Source File: ApiCategoriesApiServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Response apiCategoriesApiCategoryIdDelete(String apiCategoryId, String ifMatch, String ifUnmodifiedSince,
                                                 MessageContext messageContext) {
    try {
        APIAdmin apiAdmin = new APIAdminImpl();
        String userName = RestApiUtil.getLoggedInUsername();
        apiAdmin.deleteCategory(apiCategoryId, userName);
        return Response.ok().build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while deleting API Category '" + apiCategoryId + "' - " + e.getMessage();
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example 18
Source Project: carbon-apimgt   Source File: WorkflowsApiServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This is used to get the workflow pending requests
 *
 * @param limit        maximum number of workflow returns
 * @param offset       starting index
 * @param accept       accept header value
 * @param ifNoneMatch  If-None-Match header value
 * @param workflowType is the the type of the workflow request. (e.g: Application Creation, Application Subscription etc.)
 * @return
 */
@Override
public Response workflowsGet(Integer limit, Integer offset, String accept, String ifNoneMatch, String workflowType, MessageContext messageContext) throws APIManagementException {
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    WorkflowListDTO workflowListDTO;
    try {
        Workflow[] workflows;
        String status = "CREATED";
        APIAdmin apiAdmin = new APIAdminImpl();
        if(workflowType != null) {
            if (workflowType.equals("APPLICATION_CREATION")) {
                workflowType = "AM_APPLICATION_CREATION";
            } else if (workflowType.equals("SUBSCRIPTION_CREATION")) {
                workflowType = "AM_SUBSCRIPTION_CREATION";
            } else if (workflowType.equals("USER_SIGNUP")) {
                workflowType = "AM_USER_SIGNUP";
            } else if (workflowType.equals("APPLICATION_REGISTRATION_PRODUCTION")) {
                workflowType = "AM_APPLICATION_REGISTRATION_PRODUCTION";
            } else if (workflowType.equals("APPLICATION_REGISTRATION_SANDBOX")) {
                workflowType = "AM_APPLICATION_REGISTRATION_SANDBOX";
            } else if (workflowType.equals("API_STATE")) {
                workflowType = "AM_API_STATE";
            }
        }
        workflows = apiAdmin.getworkflows(workflowType, status, tenantDomain);
        workflowListDTO = WorkflowMappingUtil.fromWorkflowsToDTO(workflows, limit, offset);
        WorkflowMappingUtil.setPaginationParams(workflowListDTO, limit, offset,
                workflows.length);
        return Response.ok().entity(workflowListDTO).build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while retrieving workflow requests. ", e, log);
    }
    return null;
}
 
Example 19
Source Project: carbon-apimgt   Source File: ApisApiServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Response apisApiIdGraphqlPoliciesComplexityTypesGet(String apiId, MessageContext messageContext) throws APIManagementException {
    GraphQLSchemaDefinition graphql = new GraphQLSchemaDefinition();
    try {
        APIConsumer apiConsumer = RestApiUtil.getLoggedInUserConsumer();
        String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
        APIIdentifier apiIdentifier = APIMappingUtil.getAPIIdentifierFromUUID(apiId, tenantDomain);
        API api = apiConsumer.getAPIbyUUID(apiId, tenantDomain);
        if (APIConstants.GRAPHQL_API.equals(api.getType())) {
            String schemaContent = apiConsumer.getGraphqlSchema(apiIdentifier);
            List<GraphqlSchemaType> typeList = graphql.extractGraphQLTypeList(schemaContent);
            GraphQLSchemaTypeListDTO graphQLSchemaTypeListDTO =
                    GraphqlQueryAnalysisMappingUtil.fromGraphqlSchemaTypeListtoDTO(typeList);
            return Response.ok().entity(graphQLSchemaTypeListDTO).build();
        } else {
            throw new APIManagementException(ExceptionCodes.API_NOT_GRAPHQL);
        }
    } catch (APIManagementException e) {
        //Auth failure occurs when cross tenant accessing APIs. Sends 404, since we don't need
        // to expose the existence of the resource
        if (RestApiUtil.isDueToResourceNotFound(e) || RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (isAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure(
                    "Authorization failure while retrieving types and fields of API : " + apiId, e, log);
        } else {
            String msg = "Error while retrieving types and fields of the schema of API " + apiId;
            RestApiUtil.handleInternalServerError(msg, e, log);
        }
    }
    return null;
}
 
Example 20
Source Project: carbon-apimgt   Source File: TenantsApiServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This is used to get the tenants using its state
 *
 * @param state          Tenant state either active or inactive
 * @param limit          Maximum number returned at once
 * @param offset         Starting index
 * @param messageContext
 * @return List of tenant domains
 */
@Override
public Response getTenantsByState(String state, Integer limit, Integer offset, MessageContext messageContext) {
    List<TenantDTO> tenantDTOList = new ArrayList<>();
    Integer paginationLimit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    Integer paginationOffset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;
    PaginationDTO paginationDTO = new PaginationDTO();
    paginationDTO.setOffset(paginationOffset);
    paginationDTO.setLimit(paginationLimit);

    if (!state.equalsIgnoreCase(TENANT_STATE_ACTIVE) && !state.equalsIgnoreCase(TENANT_STATE_INACTIVE)) {
        RestApiUtil.handleBadRequest("Invalid tenant state", log);
    }

    String status = TENANT_STATE_ACTIVE.equalsIgnoreCase(state) ? TENANT_STATE_ACTIVE : TENANT_STATE_INACTIVE;
    Set<String> tenantDomains = null;
    try {
        tenantDomains = APIUtil.getTenantDomainsByState(state);
        for (String domain : tenantDomains) {
            TenantDTO tenantDTO = new TenantDTO();
            tenantDTO.setDomain(domain);
            tenantDTO.setStatus(status);
            tenantDTOList.add(tenantDTO);
        }

        TenantListDTO tenantList = new TenantListDTO();
        tenantList.count(tenantDTOList.size());
        tenantList.setList(tenantDTOList);
        paginationDTO.setTotal(tenantDTOList.size());
        tenantList.setPagination(paginationDTO);
        return Response.ok().entity(tenantList).build();
    } catch (UserStoreException e) {
        RestApiUtil.handleInternalServerError("Error while getting active tenant domains", e, log);
    }
    return null;
}
 
Example 21
Source Project: cxf   Source File: HawkAccessTokenValidatorClient.java    License: Apache License 2.0 5 votes vote down vote up
protected AccessTokenValidation getAccessTokenValidation(MessageContext mc,
                                                         String authScheme,
                                                         String authSchemeData,
                                                         MultivaluedMap<String, String> extraProps,
                                                         Map<String, String> schemeParams) {
    return validator.validateAccessToken(mc, authScheme, authSchemeData, extraProps);
}
 
Example 22
/**
 * Get external store list configured for the current of logged in user.
 *
 * @param messageContext CXF Message Context
 * @return External Store list
 */
@Override
public Response getAllExternalStores(MessageContext messageContext) {
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    try {
        Set<APIStore> apiStores = APIUtil.getExternalAPIStores(APIUtil.getTenantIdFromTenantDomain(tenantDomain));
        ExternalStoreListDTO externalStoreListDTO =
                ExternalStoreMappingUtil.fromExternalStoreCollectionToDTO(apiStores);
        return Response.ok().entity(externalStoreListDTO).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while retrieving external API Stores for tenant domain:" + tenantDomain;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example 23
Source Project: cxf   Source File: XSLTJaxbProvider.java    License: Apache License 2.0 5 votes vote down vote up
protected Templates createTemplatesFromContext() {
    MessageContext mc = getContext();
    if (mc != null) {
        String template = (String)mc.getContextualProperty(XSLT_TEMPLATE_PROPERTY);
        if (template != null) {
            return createTemplates(template);
        }
    }
    return null;
}
 
Example 24
Source Project: carbon-apimgt   Source File: KeyManagersApiServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public Response keyManagersGet(String xWSO2Tenant, MessageContext messageContext) {

        String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
        APIAdmin apiAdmin = new APIAdminImpl();
        try {
            List<KeyManagerConfigurationDTO> keyManagerConfigurations =
                    apiAdmin.getKeyManagerConfigurationsByTenant(tenantDomain);
            return Response.ok(KeyManagerMappingUtil.toKeyManagerListDto(keyManagerConfigurations)).build();
        } catch (APIManagementException e) {
            RestApiUtil
                    .handleInternalServerError("Error while retrieving keyManager Details for Tenant " + tenantDomain,
                            log);
        }
        return null;
    }
 
Example 25
public static String validateTenantDomain(String xWSO2Tenant, MessageContext messageContext) {


        String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
        if (!tenantDomain.equalsIgnoreCase(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
            xWSO2Tenant = tenantDomain;
        }
        return xWSO2Tenant;
    }
 
Example 26
Source Project: carbon-apimgt   Source File: LabelsApiServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Delete label
 *
 * @param labelId           Label identifier
 * @param ifMatch           If-Match header value
 * @param ifUnmodifiedSince If-Unmodified-Since header value
 * @return Status of label Deletion
 */
@Override
public Response labelsLabelIdDelete(String labelId, String ifMatch, String ifUnmodifiedSince,
                                    MessageContext messageContext) {
    try {
        APIAdmin apiAdmin = new APIAdminImpl();
        String user = RestApiUtil.getLoggedInUsername();
        apiAdmin.deleteLabel(user, labelId);
        return Response.ok().build();
    } catch (APIManagementException e) {
        String errorMessage = "Error while deleting label : " + labelId;
        RestApiUtil.handleInternalServerError(errorMessage, e, log);
    }
    return null;
}
 
Example 27
/**
 * Retrieve a list of bot detection alert subscriptions
 *
 * @param messageContext
 * @return list of bot detection alert subscriptions
 * @throws APIManagementException if an error occurs when retrieving bot detection alert subscriptions
 */
@Override
public Response getBotDetectionAlertSubscriptions(MessageContext messageContext) throws APIManagementException {

    APIAdmin apiAdmin = new APIAdminImpl();
    List<BotDetectionData> botDetectionDataList = apiAdmin.getBotDetectionAlertSubscriptions();
    BotDetectionAlertSubscriptionListDTO listDTO =
            BotDetectionMappingUtil.fromAlertSubscriptionListToListDTO(botDetectionDataList);
    return Response.ok().entity(listDTO).build();
}
 
Example 28
public Response endpointCertificatesGet(Integer limit, Integer offset, String alias, String endpoint,
        MessageContext messageContext) {
    limit = limit != null ? limit : RestApiConstants.PAGINATION_LIMIT_DEFAULT;
    offset = offset != null ? offset : RestApiConstants.PAGINATION_OFFSET_DEFAULT;

    List<CertificateMetadataDTO> certificates;
    String userName = RestApiUtil.getLoggedInUsername();
    int tenantId = APIUtil.getTenantId(userName);
    String query = CertificateRestApiUtils.buildQueryString("alias", alias, "endpoint", endpoint);

    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();

        if (StringUtils.isNotEmpty(alias) || StringUtils.isNotEmpty(endpoint)) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Call the search certificate api to get the filtered certificates for " +
                        "tenant id : %d, alias : %s, and endpoint : %s", tenantId, alias, endpoint));
            }
            certificates = apiProvider.searchCertificates(tenantId, alias, endpoint);
        } else {
            if (log.isDebugEnabled()) {
                log.debug(String.format("There is no query parameters provided. So, retrieve all the certificates" +
                        " belongs to the tenantId : %d", tenantId));
            }
            certificates = apiProvider.getCertificates(userName);
        }

        CertificatesDTO certificatesDTO = CertificateRestApiUtils.getPaginatedCertificates(certificates, limit,
                offset, query);
        return Response.status(Response.Status.OK).entity(certificatesDTO).build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while retrieving the certificates.", e, log);
    }
    return null;
}
 
Example 29
Source Project: cxf   Source File: OAuthContextUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param mc the {@link MessageContext}
 * @param client the desired client registration id
 * @throws WebApplicationException with Status 403 if the current client id is not valid
 */
public static void assertClient(MessageContext mc, String client) {
    String cl = resolveClient(mc);
    if ((cl == null) || !cl.equals(client)) {
        throw ExceptionUtils.toForbiddenException(null, null);
    }
}
 
Example 30
public Response endpointCertificatesAliasGet(String alias, MessageContext messageContext) {
    String tenantDomain = RestApiUtil.getLoggedInUserTenantDomain();
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);

    if (!StringUtils.isNotEmpty(alias)) {
        RestApiUtil.handleBadRequest("The alias cannot be empty", log);
    }

    if (log.isDebugEnabled()) {
        log.debug(String.format("Retrieving the common information of the certificate which is represented by the" +
                " alias : %s", alias));
    }

    try {
        APIProvider apiProvider = RestApiUtil.getLoggedInUserProvider();
        if (!apiProvider.isCertificatePresent(tenantId, alias)) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Could not find a certificate in truststore which belongs to tenant %d " +
                        "and with alias %s. Hence the operation is terminated.", tenantId, alias));
            }
            String message = "Certificate for Alias '" + alias + "' is not found.";
            RestApiUtil.handleResourceNotFoundError(message, log);
        }

        CertificateInformationDTO certificateInformationDTO = apiProvider.getCertificateStatus(alias);

        CertificateValidityDTO certificateValidityDTO = new CertificateValidityDTO();
        certificateValidityDTO.setFrom(certificateInformationDTO.getFrom());
        certificateValidityDTO.setTo(certificateInformationDTO.getTo());

        CertificateInfoDTO certificateInfoDTO = new CertificateInfoDTO();
        certificateInfoDTO.setValidity(certificateValidityDTO);
        certificateInfoDTO.setStatus(certificateInformationDTO.getStatus());
        certificateInfoDTO.setSubject(certificateInformationDTO.getSubject());
        certificateInfoDTO.setVersion(certificateInformationDTO.getVersion());

        return Response.ok().entity(certificateInfoDTO).build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while retrieving the certificate status.", e, log);
    }
    return null;
}