io.gravitee.common.http.MediaType Java Examples

The following examples show how to use io.gravitee.common.http.MediaType. 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: ResourceAccessPoliciesEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
public void create(RoutingContext context) {
    final JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    final Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);
    final String resource = context.request().getParam(RESOURCE_ID);
    final String basePath = UriBuilderRequest.extractBasePath(context);

    // extract access policy payload
    AccessPolicy accessPolicy = extractRequest(context);

    // store the access policy
    resourceService.createAccessPolicy(accessPolicy, domain.getId(), client.getId(), accessToken.getSub(), resource)
            .subscribe(
                    p ->
                        context.response()
                                .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                                .putHeader(HttpHeaders.PRAGMA, "no-cache")
                                .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                                .putHeader(HttpHeaders.LOCATION, resourceLocation(basePath, p))
                                .setStatusCode(HttpStatusCode.CREATED_201)
                                .end(Json.encodePrettily(p))
                    , error -> context.fail(error)
            );
}
 
Example #2
Source File: ApiAuditResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@GET
@ApiOperation("Retrieve audit logs for a dedicated API")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Permissions({
        @Permission(value = RolePermission.API_AUDIT, acls = RolePermissionAction.READ)
})
public MetadataPage<AuditEntity> list(@PathParam("api") String api,
                                      @BeanParam AuditParam param) {

    AuditQuery query = new AuditQuery();
    query.setFrom(param.getFrom());
    query.setTo(param.getTo());
    query.setPage(param.getPage());
    query.setSize(param.getSize());
    query.setApiIds(Collections.singletonList(api));
    query.setApplicationIds(Collections.emptyList());
    query.setManagementLogsOnly(false);

    if (param.getEvent() != null) {
        query.setEvents(Collections.singletonList(param.getEvent()));
    }

    return auditService.search(query);
}
 
Example #3
Source File: GroupsResource.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create a platform group",
        notes = "User must have the ORGANIZATION_GROUP[CREATE] permission on the specified organization")
@ApiResponses({
        @ApiResponse(code = 201, message = "Group successfully created"),
        @ApiResponse(code = 500, message = "Internal server error")})
public void create(
        @PathParam("organizationId") String organizationId,
        @ApiParam(name = "group", required = true) @Valid @NotNull final NewGroup newGroup,
        @Suspended final AsyncResponse response) {
    final User authenticatedUser = getAuthenticatedUser();

    checkPermission(ReferenceType.ORGANIZATION, organizationId, Permission.ORGANIZATION_GROUP, Acl.CREATE)
            .andThen(groupService.create(ReferenceType.ORGANIZATION, organizationId, newGroup, authenticatedUser)
                    .map(group -> Response.created(URI.create("/organizations/" + organizationId + "/groups/" + group.getId()))
                            .entity(group).build()))
            .subscribe(response::resume, response::resume);
}
 
Example #4
Source File: ApiSubscriptionResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Renew an API key",
        notes = "User must have the MANAGE_API_KEYS permission to use this service")
@ApiResponses({
        @ApiResponse(code = 201, message = "A new API Key", response = ApiKeyEntity.class),
        @ApiResponse(code = 500, message = "Internal server error")})
@Permissions({
        @Permission(value = RolePermission.API_SUBSCRIPTION, acls = RolePermissionAction.UPDATE)
})
public Response renewApiKey(
        @PathParam("api") String api,
        @PathParam("subscription") String subscription) {
    ApiKeyEntity apiKeyEntity = apiKeyService.renew(subscription);
    return Response
            .created(URI.create("/apis/" + api + "/subscriptions/" + subscription +
                    "/keys" + apiKeyEntity.getKey()))
            .entity(apiKeyEntity)
            .build();
}
 
Example #5
Source File: ExtensionGrantPluginResource.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@GET
@Path("schema")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get an extension grant plugin's schema",
        notes = "There is no particular permission needed. User must be authenticated.")
public void getSchema(@PathParam("extensionGrant") String extensionGrantId,
                      @Suspended final AsyncResponse response) {

    // Check that the extension grant exists
    extensionGrantPluginService.findById(extensionGrantId)
            .switchIfEmpty(Maybe.error(new ExtensionGrantPluginNotFoundException(extensionGrantId)))
            .flatMap(irrelevant -> extensionGrantPluginService.getSchema(extensionGrantId))
            .switchIfEmpty(Maybe.error(new ExtensionGrantPluginSchemaNotFoundException(extensionGrantId)))
            .map(extensionGrantPluginSchema -> Response.ok(extensionGrantPluginSchema).build())
            .subscribe(response::resume, response::resume);
}
 
Example #6
Source File: ApiRatingsResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Permissions({
        @Permission(value = RolePermission.API_RATING, acls = RolePermissionAction.CREATE)
})
public Response createApiRating(@PathParam("apiId") String apiId, @Valid RatingInput ratingInput) {
    if (ratingInput == null) {
        throw new BadRequestException("Input must not be null.");
    }
    Collection<ApiEntity> userApis = apiService.findPublishedByUser(getAuthenticatedUserOrNull());
    if (userApis.stream().anyMatch(a -> a.getId().equals(apiId))) {
        NewRatingEntity rating = new NewRatingEntity();
        rating.setApi(apiId);
        rating.setComment(ratingInput.getComment());
        rating.setTitle(ratingInput.getTitle());
        rating.setRate(ratingInput.getValue().byteValue());
        RatingEntity createdRating = ratingService.create(rating);

        return Response
                .status(Status.CREATED)
                .entity(ratingMapper.convert(createdRating, uriInfo))
                .build();
    }
    throw new ApiNotFoundException(apiId);
}
 
Example #7
Source File: EmailsResource.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Find a email",
        notes = "User must have the DOMAIN_EMAIL_TEMPLATE[READ] permission on the specified domain " +
                "or DOMAIN_EMAIL_TEMPLATE[READ] permission on the specified environment " +
                "or DOMAIN_EMAIL_TEMPLATE[READ] permission on the specified organization")
@ApiResponses({
        @ApiResponse(code = 200, message = "Email successfully fetched"),
        @ApiResponse(code = 500, message = "Internal server error")})
public void get(
        @PathParam("organizationId") String organizationId,
        @PathParam("environmentId") String environmentId,
        @PathParam("domain") String domain,
        @NotNull @QueryParam("template") Template emailTemplate,
        @Suspended final AsyncResponse response) {

    checkAnyPermission(organizationId, environmentId, domain, Permission.DOMAIN_EMAIL_TEMPLATE, Acl.READ)
            .andThen(emailTemplateService.findByDomainAndTemplate(domain, emailTemplate.template()))
            .map(email -> Response.ok(email).build())
            .defaultIfEmpty(Response.ok(new Email(false)).build())
            .subscribe(response::resume, response::resume);
}
 
Example #8
Source File: ApiNotificationSettingsResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@POST
@ApiOperation(value = "Create notification settings")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Object create(@PathParam("api") String api, GenericNotificationConfigEntity config) {
    if (!api.equals(config.getReferenceId())
            || !NotificationReferenceType.API.name().equals(config.getReferenceType())) {
        throw new ForbiddenAccessException();
    }
    if (config.getConfigType().equals(NotificationConfigType.GENERIC)
            && hasPermission(API_NOTIFICATION, api, CREATE)) {
        return genericNotificationConfigService.create(config);
    } else if (config.getConfigType().equals(NotificationConfigType.PORTAL)
            && hasPermission(API_NOTIFICATION, api, READ)) {
        return portalNotificationConfigService.save(convert(config));
    }
    throw new ForbiddenAccessException();
}
 
Example #9
Source File: CertificatePluginResource.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@GET
@Path("schema")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get an certificate's schema",
        notes = "There is no particular permission needed. User must be authenticated.")
public void getSchema(
        @PathParam("certificate") String certificateId,
        @Suspended final AsyncResponse response) {

    // Check that the certificate exists
    certificatePluginService.findById(certificateId)
            .switchIfEmpty(Maybe.error(new CertificatePluginNotFoundException(certificateId)))
            .flatMap(irrelevant -> certificatePluginService.getSchema(certificateId))
            .switchIfEmpty(Maybe.error(new CertificatePluginSchemaNotFoundException(certificateId)))
            .map(certificatePluginSchema -> Response.ok(certificatePluginSchema).build())
            .subscribe(response::resume, response::resume);
}
 
Example #10
Source File: DictionaryResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get a dictionary",
        notes = "User must have the DICTIONARY[READ] permission to use this service")
@ApiResponses({
        @ApiResponse(code = 200, message = "A dictionary"),
        @ApiResponse(code = 500, message = "Internal server error")})
@Permissions(@Permission(value = RolePermission.ENVIRONMENT_DICTIONARY, acls = RolePermissionAction.READ))
public DictionaryEntity getDictionary(
        @PathParam("dictionary") String dictionary) {
    DictionaryEntity dictionaryEntity = dictionaryService.findById(dictionary);
    // remove provider informations for readonlyUsers
    boolean notReadOnly = hasPermission(RolePermission.ENVIRONMENT_DICTIONARY, RolePermissionAction.CREATE, RolePermissionAction.UPDATE, RolePermissionAction.DELETE);
    if (!notReadOnly) {
        dictionaryEntity.setProvider(null);
        dictionaryEntity.setTrigger(null);
    }
    return dictionaryEntity;
}
 
Example #11
Source File: ApplicationMembersResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "List application members",
        notes = "User must have the READ permission to use this service")
@ApiResponses({
        @ApiResponse(code = 200, message = "Application successfully deleted", response = MembershipListItem.class, responseContainer = "List"),
        @ApiResponse(code = 500, message = "Internal server error")})
@Permissions({
        @Permission(value = RolePermission.APPLICATION_MEMBER, acls = RolePermissionAction.READ)
})
public List<MembershipListItem> listApplicationMembers(@PathParam("application") String application) {
    applicationService.findById(application);
    return membershipService.getMembersByReference(MembershipReferenceType.APPLICATION, application)
            .stream()
            .map(MembershipListItem::new)
            .sorted(Comparator.comparing(MembershipListItem::getId))
            .collect(Collectors.toList());
}
 
Example #12
Source File: ApiHealthResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation("Health-check statistics for API")
@Permissions({
        @Permission(value = RolePermission.API_HEALTH, acls = RolePermissionAction.READ)
})
public Response health(
        @PathParam("api") String api,
        @QueryParam("type") @DefaultValue("availability") HealthcheckTypeParam healthcheckTypeParam,
        @QueryParam("field") @DefaultValue("endpoint") HealthcheckFieldParam healthcheckFieldParam) {

    switch (healthcheckTypeParam.getValue()) {
        case RESPONSE_TIME:
            return Response.ok(healthCheckService.getResponseTime(api, healthcheckFieldParam.getValue().name())).build();
        default:
            return Response.ok(healthCheckService.getAvailability(api, healthcheckFieldParam.getValue().name())).build();
    }
}
 
Example #13
Source File: DynamicClientAccessEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
/**
 * Read client_metadata.
 * See <a href="https://openid.net/specs/openid-connect-registration-1_0.html#ReadRequest">Read Request</a>
 * See <a href="https://openid.net/specs/openid-connect-registration-1_0.html#ReadResponse">Read Response</a>
 *
 * @param context
 */
public void read(RoutingContext context) {
    LOGGER.debug("Dynamic client registration GET endpoint");

    this.getClient(context)
            .map(DynamicClientRegistrationResponse::fromClient)
            .map(response -> {
                //The Authorization Server need not include the registration access_token or client_uri unless they have been updated.
                response.setRegistrationAccessToken(null);
                response.setRegistrationClientUri(null);
                return response;
            })
            .subscribe(
                    result -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .setStatusCode(HttpStatusCode.OK_200)
                            .end(Json.encodePrettily(result))
                    , error -> context.fail(error)
            );
}
 
Example #14
Source File: DynamicClientAccessEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
/**
 * Patch client_metadata.
 * @param context
 */
public void patch(RoutingContext context) {
    LOGGER.debug("Dynamic client registration PATCH endpoint");

    this.getClient(context)
            .flatMapSingle(Single::just)
            .flatMap(client -> this.extractRequest(context)
                    .flatMap(request -> dcrService.patch(client, request, UriBuilderRequest.extractBasePath(context)))
                    .map(clientSyncService::addDynamicClientRegistred)
            )
            .subscribe(
                    client -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .setStatusCode(HttpStatusCode.OK_200)
                            .end(Json.encodePrettily(DynamicClientRegistrationResponse.fromClient(client)))
                    , error -> context.fail(error)
            );
}
 
Example #15
Source File: ReporterPluginResource.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@GET
@Path("schema")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get a reporter plugin's schema")
public void getSchema(
        @PathParam("reporter") String reporterId,
        @Suspended final AsyncResponse response) {

    // Check that the identity provider exists
    reporterPluginService.findById(reporterId)
            .switchIfEmpty(Maybe.error(new ReporterPluginNotFoundException(reporterId)))
            .flatMap(irrelevant -> reporterPluginService.getSchema(reporterId))
            .switchIfEmpty(Maybe.error(new ReporterPluginSchemaNotFoundException(reporterId)))
            .map(reporterPluginSchema -> Response.ok(reporterPluginSchema).build())
            .subscribe(response::resume, response::resume);
}
 
Example #16
Source File: ApplicationMembersResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{memberId}")
@Produces(MediaType.APPLICATION_JSON)
@Permissions({
    @Permission(value = RolePermission.APPLICATION_MEMBER, acls = RolePermissionAction.READ)
})
public Response getApplicationMemberByApplicationIdAndMemberId(@PathParam("applicationId") String applicationId, @PathParam("memberId") String memberId) {
    //Does application exist ?
    applicationService.findById(applicationId);
    
    //Does user exist ?
    userService.findById(memberId);
    
    
    MemberEntity memberEntity = membershipService.getUserMember(MembershipReferenceType.APPLICATION, applicationId, memberId);
    if(memberEntity != null) {
        return Response
                .ok(memberMapper.convert(memberEntity, uriInfo))
                .build();
    }
    throw new NotFoundException();
}
 
Example #17
Source File: OAuth2AuthenticationResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve profile information about the authenticated oauth end-user and authenticate it in Gravitee.
 *
 * @return
 */
private Response authenticateUser(final SocialIdentityProviderEntity socialProvider,
                                  final HttpServletResponse servletResponse,
                                  final String accessToken,
                                  final String state) throws IOException {
    // Step 2. Retrieve profile information about the authenticated end-user.
    Response response = client
            .target(socialProvider.getUserInfoEndpoint())
            .request(javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE)
            .header(HttpHeaders.AUTHORIZATION, String.format(socialProvider.getAuthorizationHeader(), accessToken))
            .get();


    // Step 3. Process the authenticated user.
    final String userInfo = getResponseEntityAsString(response);
    if (response.getStatus() == Response.Status.OK.getStatusCode()) {
        return processUser(socialProvider, servletResponse, userInfo, state);
    } else {
        LOGGER.error("User info failed with status {}: {}\n{}", response.getStatus(), response.getStatusInfo(), userInfo);

    }

    return Response.status(response.getStatusInfo()).build();
}
 
Example #18
Source File: IdentityProvidersResource.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Create an identity provider for the organization",
        notes = "User must have the ORGANIZATION_IDENTITY_PROVIDER[CREATE] permission on the specified organization")
@ApiResponses({
        @ApiResponse(code = 201, message = "Identity provider successfully created"),
        @ApiResponse(code = 500, message = "Internal server error")})
public void create(
        @PathParam("organizationId") String organizationId,
        @ApiParam(name = "identity", required = true) @Valid @NotNull final NewIdentityProvider newIdentityProvider,
        @Suspended final AsyncResponse response) {

    final User authenticatedUser = getAuthenticatedUser();

    checkPermission(ReferenceType.ORGANIZATION, organizationId, Permission.ORGANIZATION_IDENTITY_PROVIDER, Acl.CREATE)
            .andThen(identityProviderService.create(ReferenceType.ORGANIZATION, organizationId, newIdentityProvider, authenticatedUser)
                    .flatMap(identityProviderManager::reloadUserProvider)
                    .map(identityProvider -> Response
                            .created(URI.create("/organizations/" + organizationId + "/identities/" + identityProvider.getId()))
                            .entity(identityProvider)
                            .build()))
            .subscribe(response::resume, response::resume);
}
 
Example #19
Source File: ResourceRegistrationEndpoint.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext context) {
    JWT accessToken = context.get(OAuth2AuthHandler.TOKEN_CONTEXT_KEY);
    Client client = context.get(OAuth2AuthHandler.CLIENT_CONTEXT_KEY);

    this.resourceService.listByDomainAndClientAndUser(domain.getId(), client.getId(), accessToken.getSub())
            .flatMapPublisher(Flowable::fromIterable)
            .map(Resource::getId)
            .collect(JsonArray::new, JsonArray::add)
            .subscribe(
                    buffer -> context.response()
                            .putHeader(HttpHeaders.CACHE_CONTROL, "no-store")
                            .putHeader(HttpHeaders.PRAGMA, "no-cache")
                            .putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                            .setStatusCode(buffer.isEmpty()?HttpStatusCode.NO_CONTENT_204:HttpStatusCode.OK_200)
                            .end(Json.encodePrettily(buffer))
                    , error -> context.fail(error)
            );
}
 
Example #20
Source File: ApplicationEmailsResource.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Find a email for an application",
        notes = "User must have APPLICATION_EMAIL_TEMPLATE[READ] permission on the specified application " +
                "or APPLICATION_EMAIL_TEMPLATE[READ] permission on the specified domain " +
                "or APPLICATION_EMAIL_TEMPLATE[READ] permission on the specified environment " +
                "or APPLICATION_EMAIL_TEMPLATE[READ] permission on the specified organization")
@ApiResponses({
        @ApiResponse(code = 200, message = "Email successfully fetched"),
        @ApiResponse(code = 500, message = "Internal server error")})
public void get(
        @PathParam("organizationId") String organizationId,
        @PathParam("environmentId") String environmentId,
        @PathParam("domain") String domain,
        @PathParam("application") String application,
        @NotNull @QueryParam("template") Template emailTemplate,
        @Suspended final AsyncResponse response) {

    checkAnyPermission(organizationId, environmentId, domain, application, Permission.APPLICATION_EMAIL_TEMPLATE, Acl.READ)
            .andThen(emailTemplateService.findByDomainAndClientAndTemplate(domain, application, emailTemplate.template())
                    .map(email -> Response.ok(email).build())
                    .defaultIfEmpty(Response.ok(new Email(false)).build()))
            .subscribe(response::resume, response::resume);
}
 
Example #21
Source File: PostContentGatewayTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void get_no_content_with_chunked_encoding_transfer() throws Exception {
    stubFor(get(urlEqualTo("/team/my_team")).willReturn(ok()));

    Request request = Request.Get("http://localhost:8082/test/my_team")
            .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
            .removeHeaders(HttpHeaders.TRANSFER_ENCODING);

    Response response = request.execute();

    HttpResponse returnResponse = response.returnResponse();
    assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());

    // Set chunk mode in request but returns raw because of the size of the content
    assertEquals(null, returnResponse.getFirstHeader("X-Forwarded-Transfer-Encoding"));

    String responseContent = StringUtils.copy(returnResponse.getEntity().getContent());
    assertEquals(0, responseContent.length());

    verify(getRequestedFor(urlEqualTo("/team/my_team"))
            .withoutHeader(HttpHeaders.TRANSFER_ENCODING)
            .withHeader(io.gravitee.common.http.HttpHeaders.CONTENT_TYPE, new EqualToPattern(MediaType.APPLICATION_JSON)));
}
 
Example #22
Source File: PermissionEndpointTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void success_extendedRequest() {
    PermissionTicket success = new PermissionTicket().setId("success");
    final String extendedRequest = "[{\"resource_id\":\"{{set_one}}\", \"resource_scopes\":[\"profile:read\"]}, {\"resource_id\":\"{{set_two}}\",\"resource_scopes\":[\"avatar:write\"]}]";

    when(context.getBody()).thenReturn(Buffer.buffer(extendedRequest));
    when(context.response()).thenReturn(response);
    when(response.putHeader(anyString(),anyString())).thenReturn(response);
    when(response.setStatusCode(anyInt())).thenReturn(response);
    when(permissionTicketService.create(anyList(), eq(DOMAIN_ID), eq(CLIENT_ID))).thenReturn(Single.just(success));
    endpoint.handle(context);
    verify(response, times(1)).putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    verify(context.response(), times(1)).setStatusCode(intCaptor.capture());
    verify(context.response(), times(1)).end(strCaptor.capture());
    Assert.assertEquals("Expecting 201 creation status",intCaptor.getValue().intValue(),201);
    Assert.assertTrue("Expect success id", strCaptor.getValue().contains("success"));
}
 
Example #23
Source File: PostContentGatewayTest.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void get_no_content_with_chunked_encoding_transfer_and_content_type() throws Exception {
    stubFor(get(urlEqualTo("/team/my_team")).willReturn(ok()));

    Request request = Request.Get("http://localhost:8082/test/my_team")
            .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);

    Response response = request.execute();

    HttpResponse returnResponse = response.returnResponse();
    assertEquals(HttpStatus.SC_OK, returnResponse.getStatusLine().getStatusCode());

    // Set chunk mode in request but returns raw because of the size of the content
    assertEquals(null, returnResponse.getFirstHeader("X-Forwarded-Transfer-Encoding"));

    String responseContent = StringUtils.copy(returnResponse.getEntity().getContent());
    assertEquals(0, responseContent.length());

    verify(getRequestedFor(urlEqualTo("/team/my_team"))
            .withHeader(io.gravitee.common.http.HttpHeaders.CONTENT_TYPE, new EqualToPattern(MediaType.APPLICATION_JSON)));
}
 
Example #24
Source File: CategoriesResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getCategories(@BeanParam PaginationParam paginationParam) {
    Set<ApiEntity> apis = apiService.findPublishedByUser(getAuthenticatedUserOrNull());
    
    List<Category> categoriesList = categoryService.findAll()
            .stream()
            .filter(c -> !c.isHidden())
            .sorted(Comparator.comparingInt(CategoryEntity::getOrder))
            .map(c -> {
                c.setTotalApis(categoryService.getTotalApisByCategory(apis, c));
                return c;
            })
            .map(c-> categoryMapper.convert(c, uriInfo.getBaseUriBuilder()))
            .collect(Collectors.toList());
    
    return createListResponse(categoriesList, paginationParam);
}
 
Example #25
Source File: ApisResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@POST
@Path("import")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Create an API by importing an API definition",
        notes = "Create an API by importing an existing API definition in JSON format")
@ApiResponses({
        @ApiResponse(code = 200, message = "API successfully created"),
        @ApiResponse(code = 500, message = "Internal server error")})
@Permissions({
        @Permission(value = RolePermission.ENVIRONMENT_API, acls = RolePermissionAction.CREATE),
        @Permission(value = RolePermission.ENVIRONMENT_API, acls = RolePermissionAction.UPDATE)
})
public Response importDefinition(
        @ApiParam(name = "definition", required = true) @Valid @NotNull String apiDefinition) {
    return Response.ok(apiService.createOrUpdateWithDefinition(
            null, apiDefinition, getAuthenticatedUser())).build();
}
 
Example #26
Source File: ApiResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@POST
@Path("import/swagger")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
        value = "Update the API with an existing Swagger descriptor",
        notes = "User must have the MANAGE_API permission to use this service")
@ApiResponses({
        @ApiResponse(code = 200, message = "API successfully updated from Swagger descriptor", response = ApiEntity.class),
        @ApiResponse(code = 500, message = "Internal server error")})
@Permissions({
        @Permission(value = RolePermission.API_DEFINITION, acls = RolePermissionAction.UPDATE)
})
public Response updateWithSwagger(
        @PathParam("api") String api,
        @ApiParam(name = "swagger", required = true) @Valid @NotNull ImportSwaggerDescriptorEntity swaggerDescriptor) {
    SwaggerApiEntity swaggerApiEntity = swaggerService.createAPI(swaggerDescriptor);
    final ApiEntity updatedApi = apiService.update(api, swaggerApiEntity, swaggerDescriptor);
    return Response
            .ok(updatedApi)
            .tag(Long.toString(updatedApi.getUpdatedAt().getTime()))
            .lastModified(updatedApi.getUpdatedAt())
            .build();
}
 
Example #27
Source File: ApiMembersResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "List API members",
        notes = "User must have the MANAGE_MEMBERS permission to use this service")
@ApiResponses({
        @ApiResponse(code = 200, message = "List of API's members", response = MembershipListItem.class, responseContainer = "List"),
        @ApiResponse(code = 500, message = "Internal server error")})
@Permissions({
        @Permission(value = RolePermission.API_MEMBER, acls = RolePermissionAction.READ)
})
public List<MembershipListItem> listApiMembers(@PathParam("api") String api) {
    apiService.findById(api);
    return membershipService.getMembersByReference(MembershipReferenceType.API, api)
            .stream()
            .map(MembershipListItem::new)
            .sorted(Comparator.comparing(MembershipListItem::getId))
            .collect(Collectors.toList());
}
 
Example #28
Source File: ApiRatingResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@DELETE
@Produces(MediaType.APPLICATION_JSON)
@Permissions({
        @Permission(value = RolePermission.API_RATING, acls = RolePermissionAction.DELETE)
})
public Response deleteApiRating(@PathParam("apiId") String apiId, @PathParam("ratingId") String ratingId) {
    Collection<ApiEntity> userApis = apiService.findPublishedByUser(getAuthenticatedUserOrNull());
    if (userApis.stream().anyMatch(a -> a.getId().equals(apiId))) {

        RatingEntity ratingEntity = ratingService.findById(ratingId);

        if (ratingEntity!= null && ratingEntity.getApi().equals(apiId)) {

            ratingService.delete(ratingId);
            return Response
                    .status(Status.NO_CONTENT)
                    .build();
        }
        throw new RatingNotFoundException(ratingId, apiId);
    }
    throw new ApiNotFoundException(apiId);
}
 
Example #29
Source File: ApplicationSubscriptionsResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@GET
@Path("{subscription}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Get subscription information",
        notes = "User must have the READ permission to use this service")
@ApiResponses({
        @ApiResponse(code = 200, message = "Subscription information", response = Subscription.class),
        @ApiResponse(code = 500, message = "Internal server error")})
@Permissions({
        @Permission(value = RolePermission.APPLICATION_SUBSCRIPTION, acls = RolePermissionAction.READ)
})
public Subscription getSubscription(
        @PathParam("application") String application,
        @PathParam("subscription") String subscription) {
    return convert(subscriptionService.findById(subscription));
}
 
Example #30
Source File: ApiPagesResource.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@PUT
@Path("/_import")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Import pages",
        notes = "User must be ADMIN to use this service")
@ApiResponses({
        @ApiResponse(code = 201, message = "Page successfully updated", response = PageEntity.class),
        @ApiResponse(code = 500, message = "Internal server error")})
@Permissions({
        @Permission(value = RolePermission.API_DOCUMENTATION, acls = RolePermissionAction.CREATE)
})
public List<PageEntity> updateImportFiles(
        @PathParam("api") String api,
        @ApiParam(name = "page", required = true) @Valid @NotNull ImportPageEntity pageEntity) {
    pageEntity.setLastContributor(getAuthenticatedUser());
    return pageService.importFiles(api, pageEntity);
}