Search in sources :

Example 26 with Valid

use of javax.validation.Valid in project gravitee-management-rest-api by gravitee-io.

the class ConfigurationResourceTest method shouldGetApplicationTypes.

@Test
public void shouldGetApplicationTypes() throws TechnicalException {
    resetAllMocks();
    ApplicationTypesEntity typesEntity = new ApplicationTypesEntity();
    List<ApplicationTypeEntity> data = new ArrayList<>();
    ApplicationTypeEntity simple = new ApplicationTypeEntity();
    simple.setId("simple");
    simple.setAllowed_grant_types(new ArrayList<>());
    simple.setDefault_grant_types(new ArrayList<>());
    simple.setMandatory_grant_types(new ArrayList<>());
    simple.setName("Simple");
    simple.setDescription("Simple type");
    data.add(simple);
    ApplicationTypeEntity web = new ApplicationTypeEntity();
    web.setId("web");
    List<ApplicationGrantTypeEntity> grantTypes = new ArrayList<>();
    ApplicationGrantTypeEntity grantType = new ApplicationGrantTypeEntity();
    grantType.setName("name");
    List<String> responses_types = new ArrayList<>();
    responses_types.add("token");
    grantType.setResponse_types(responses_types);
    grantTypes.add(grantType);
    web.setAllowed_grant_types(grantTypes);
    web.setDefault_grant_types(new ArrayList<>());
    web.setMandatory_grant_types(new ArrayList<>());
    web.setName("Web");
    web.setDescription("Web type");
    data.add(web);
    typesEntity.setData(data);
    when(applicationTypeService.getEnabledApplicationTypes()).thenReturn(typesEntity);
    final Response response = target().path("applications").path("types").request().get();
    assertEquals(HttpStatusCode.OK_200, response.getStatus());
    final ConfigurationApplicationTypesResponse appTypes = response.readEntity(ConfigurationApplicationTypesResponse.class);
    assertNotNull(appTypes);
    @Valid List<ApplicationType> types = appTypes.getData();
    assertNotNull(types);
    assertEquals(2, types.size());
    assertEquals("web", types.get(1).getId());
    assertEquals(1, types.get(1).getAllowedGrantTypes().size());
}
Also used : ApplicationTypeEntity(io.gravitee.rest.api.model.configuration.application.ApplicationTypeEntity) ApplicationGrantTypeEntity(io.gravitee.rest.api.model.configuration.application.ApplicationGrantTypeEntity) Response(javax.ws.rs.core.Response) Valid(javax.validation.Valid) ApplicationTypesEntity(io.gravitee.rest.api.model.configuration.application.ApplicationTypesEntity) Test(org.junit.Test)

Example 27 with Valid

use of javax.validation.Valid in project keywhiz by square.

the class ClientResource method createClient.

/**
   * Creates a client and assigns to given groups
   *
   * @excludeParams automationClient
   * @param request JSON request to create a client
   *
   * @responseMessage 201 Created client and assigned to given groups
   * @responseMessage 409 Client already exists
   */
@Timed
@ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response createClient(@Auth AutomationClient automationClient, @Valid CreateClientRequestV2 request) {
    String creator = automationClient.getName();
    String client = request.name();
    clientDAOReadWrite.getClient(client).ifPresent((c) -> {
        logger.info("Automation ({}) - Client {} already exists", creator, client);
        throw new ConflictException("Client name already exists.");
    });
    // Creates new client record
    long clientId = clientDAOReadWrite.createClient(client, creator, request.description());
    auditLog.recordEvent(new Event(Instant.now(), EventTag.CLIENT_CREATE, creator, client));
    // Enrolls client in any requested groups
    groupsToGroupIds(request.groups()).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAOReadWrite.findAndEnrollClient(clientId, groupId, auditLog, creator, new HashMap<>())));
    URI uri = UriBuilder.fromResource(ClientResource.class).path(client).build();
    return Response.created(uri).build();
}
Also used : NotImplementedException(org.apache.commons.lang3.NotImplementedException) PathParam(javax.ws.rs.PathParam) AclDAO(keywhiz.service.daos.AclDAO) Produces(javax.ws.rs.Produces) ClientDAO(keywhiz.service.daos.ClientDAO) GET(javax.ws.rs.GET) ClientDetailResponseV2(keywhiz.api.automation.v2.ClientDetailResponseV2) Event(keywhiz.log.Event) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) Auth(io.dropwizard.auth.Auth) GroupDAOFactory(keywhiz.service.daos.GroupDAO.GroupDAOFactory) HashMap(java.util.HashMap) Inject(javax.inject.Inject) Valid(javax.validation.Valid) AutomationClient(keywhiz.api.model.AutomationClient) ClientDAOFactory(keywhiz.service.daos.ClientDAO.ClientDAOFactory) Consumes(javax.ws.rs.Consumes) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) ModifyGroupsRequestV2(keywhiz.api.automation.v2.ModifyGroupsRequestV2) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) Client(keywhiz.api.model.Client) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) GroupDAO(keywhiz.service.daos.GroupDAO) Collectors.toSet(java.util.stream.Collectors.toSet) DELETE(javax.ws.rs.DELETE) CreateClientRequestV2(keywhiz.api.automation.v2.CreateClientRequestV2) AuditLog(keywhiz.log.AuditLog) ModifyClientRequestV2(keywhiz.api.automation.v2.ModifyClientRequestV2) Group(keywhiz.api.model.Group) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) Set(java.util.Set) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) Sets(com.google.common.collect.Sets) NotFoundException(javax.ws.rs.NotFoundException) String.format(java.lang.String.format) Timed(com.codahale.metrics.annotation.Timed) EventTag(keywhiz.log.EventTag) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) PUT(javax.ws.rs.PUT) ConflictException(keywhiz.service.exceptions.ConflictException) Event(keywhiz.log.Event) URI(java.net.URI) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 28 with Valid

use of javax.validation.Valid in project ocvn by devgateway.

the class TenderPriceByTypeYearController method tenderPriceByAllBidSelectionMethods.

@ApiOperation(value = "Same as /api/tenderPriceByBidSelectionMethod, but it always returns " + "all bidSelectionMethods (it adds the missing bid selection methods with zero totals")
@RequestMapping(value = "/api/tenderPriceByAllBidSelectionMethods", method = { RequestMethod.POST, RequestMethod.GET }, produces = "application/json")
public List<DBObject> tenderPriceByAllBidSelectionMethods(@ModelAttribute @Valid final YearFilterPagingRequest filter) {
    List<DBObject> tenderPriceByBidSelectionMethod = tenderPriceByBidSelectionMethod(filter);
    // create a treeset ordered by procurment method details key
    Collection<DBObject> ret = new TreeSet<>((DBObject o1, DBObject o2) -> o1.get(Keys.PROCUREMENT_METHOD_DETAILS).toString().compareTo(o2.get(Keys.PROCUREMENT_METHOD_DETAILS).toString()));
    // add them all to sorted set
    for (DBObject o : tenderPriceByBidSelectionMethod) {
        if (o.containsField(Keys.PROCUREMENT_METHOD_DETAILS) && o.get(Keys.PROCUREMENT_METHOD_DETAILS) != null) {
            ret.add(o);
        } else {
            o.put(Keys.PROCUREMENT_METHOD_DETAILS, UNSPECIFIED);
            ret.add(o);
        }
    }
    // get all the non null bid selection methods
    Set<Object> bidSelectionMethods = bidSelectionMethodSearchController.bidSelectionMethods().stream().filter(e -> e.get(Fields.UNDERSCORE_ID) != null).map(e -> e.get(Fields.UNDERSCORE_ID)).collect(Collectors.toCollection(LinkedHashSet::new));
    bidSelectionMethods.add(UNSPECIFIED);
    // remove elements that already are in the result
    bidSelectionMethods.removeAll(ret.stream().map(e -> e.get(Keys.PROCUREMENT_METHOD_DETAILS)).collect(Collectors.toSet()));
    // add the missing procurementmethoddetails with zero amounts
    bidSelectionMethods.forEach(e -> {
        DBObject obj = new BasicDBObject(Keys.PROCUREMENT_METHOD_DETAILS, e.toString());
        obj.put(Keys.TOTAL_TENDER_AMOUNT, BigDecimal.ZERO);
        ret.add(obj);
    });
    return new ArrayList<>(ret);
}
Also used : YearFilterPagingRequest(org.devgateway.ocds.web.rest.controller.request.YearFilterPagingRequest) Aggregation.group(org.springframework.data.mongodb.core.aggregation.Aggregation.group) Aggregation.newAggregation(org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation) Cacheable(org.springframework.cache.annotation.Cacheable) Aggregation.sort(org.springframework.data.mongodb.core.aggregation.Aggregation.sort) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Aggregation.match(org.springframework.data.mongodb.core.aggregation.Aggregation.match) Fields(org.springframework.data.mongodb.core.aggregation.Fields) MongoConstants(org.devgateway.ocds.persistence.mongo.constants.MongoConstants) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) BigDecimal(java.math.BigDecimal) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) DBObject(com.mongodb.DBObject) Direction(org.springframework.data.domain.Sort.Direction) LinkedHashSet(java.util.LinkedHashSet) Criteria.where(org.springframework.data.mongodb.core.query.Criteria.where) Collection(java.util.Collection) BasicDBObject(com.mongodb.BasicDBObject) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Set(java.util.Set) BidSelectionMethodSearchController(org.devgateway.ocds.web.rest.controller.selector.BidSelectionMethodSearchController) AggregationResults(org.springframework.data.mongodb.core.aggregation.AggregationResults) Aggregation(org.springframework.data.mongodb.core.aggregation.Aggregation) RestController(org.springframework.web.bind.annotation.RestController) Collectors(java.util.stream.Collectors) List(java.util.List) Aggregation.project(org.springframework.data.mongodb.core.aggregation.Aggregation.project) CacheConfig(org.springframework.cache.annotation.CacheConfig) CustomProjectionOperation(org.devgateway.toolkit.persistence.mongo.aggregate.CustomProjectionOperation) BasicDBObject(com.mongodb.BasicDBObject) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 29 with Valid

use of javax.validation.Valid in project bisq-api by mrosseel.

the class OfferResource method takeOffer.

@ApiOperation(value = "Take offer", response = TradeDetails.class)
@POST
@Path("/{id}/take")
public void takeOffer(@Suspended final AsyncResponse asyncResponse, @PathParam("id") String id, @Valid TakeOffer data) {
    // TODO how do we go about not blocking this REST thread?
    final CompletableFuture<Trade> completableFuture = bisqProxy.offerTake(id, data.paymentAccountId, data.amount, true);
    completableFuture.thenApply(trade -> asyncResponse.resume(new TradeDetails(trade))).exceptionally(e -> {
        final Throwable cause = e.getCause();
        final Response.ResponseBuilder responseBuilder;
        if (cause instanceof ValidationException) {
            final int status = 422;
            responseBuilder = toValidationErrorResponse(cause, status);
        } else if (cause instanceof IncompatiblePaymentAccountException) {
            responseBuilder = toValidationErrorResponse(cause, 423);
        } else if (cause instanceof NoAcceptedArbitratorException) {
            responseBuilder = toValidationErrorResponse(cause, 424);
        } else if (cause instanceof PaymentAccountNotFoundException) {
            responseBuilder = toValidationErrorResponse(cause, 425);
        } else if (cause instanceof InsufficientMoneyException) {
            responseBuilder = toValidationErrorResponse(cause, 427);
        } else if (cause instanceof NotFoundException) {
            responseBuilder = toValidationErrorResponse(cause, 404);
        } else {
            final String message = cause.getMessage();
            responseBuilder = Response.status(500);
            if (null != message)
                responseBuilder.entity(new ValidationErrorMessage(ImmutableList.of(message)));
            log.error("Unable to take offer: " + id + " " + Json.pretty(data), cause);
        }
        return asyncResponse.resume(responseBuilder.build());
    });
}
Also used : io.bisq.api(io.bisq.api) AsyncResponse(javax.ws.rs.container.AsyncResponse) Json(io.swagger.util.Json) CompletableFuture(java.util.concurrent.CompletableFuture) Suspended(javax.ws.rs.container.Suspended) Offer(io.bisq.core.offer.Offer) Valid(javax.validation.Valid) ApiOperation(io.swagger.annotations.ApiOperation) ResourceHelper(io.bisq.api.service.ResourceHelper) Slf4j(lombok.extern.slf4j.Slf4j) MediaType(javax.ws.rs.core.MediaType) Collectors.toList(java.util.stream.Collectors.toList) Trade(io.bisq.core.trade.Trade) ImmutableList(com.google.common.collect.ImmutableList) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) ValidationException(javax.validation.ValidationException) NotFoundException(io.bisq.api.NotFoundException) io.bisq.api.model(io.bisq.api.model) NotEmpty(org.hibernate.validator.constraints.NotEmpty) ResourceHelper.toValidationErrorResponse(io.bisq.api.service.ResourceHelper.toValidationErrorResponse) ValidationErrorMessage(io.dropwizard.jersey.validation.ValidationErrorMessage) Api(io.swagger.annotations.Api) ValidationException(javax.validation.ValidationException) NotFoundException(io.bisq.api.NotFoundException) ValidationErrorMessage(io.dropwizard.jersey.validation.ValidationErrorMessage) AsyncResponse(javax.ws.rs.container.AsyncResponse) Response(javax.ws.rs.core.Response) ResourceHelper.toValidationErrorResponse(io.bisq.api.service.ResourceHelper.toValidationErrorResponse) Trade(io.bisq.core.trade.Trade) ApiOperation(io.swagger.annotations.ApiOperation)

Example 30 with Valid

use of javax.validation.Valid in project rpki-validator-3 by RIPE-NCC.

the class ValidatedRpkiObjects method initialize.

@PostConstruct
private synchronized void initialize() {
    new TransactionTemplate(transactionManager).execute((status) -> {
        Map<@NotNull @Valid TrustAnchor, List<RpkiObject>> grouped = Stream.concat(rpkiObjects.findCurrentlyValidated(RpkiObject.Type.ROA), rpkiObjects.findCurrentlyValidated(RpkiObject.Type.ROUTER_CER)).collect(Collectors.groupingBy(pair -> pair.getLeft().getTrustAnchor(), Collectors.mapping(pair -> pair.getRight(), Collectors.toList())));
        grouped.forEach(this::update);
        return null;
    });
}
Also used : X509RouterCertificate(net.ripe.rpki.commons.crypto.x509cert.X509RouterCertificate) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) Value(lombok.Value) ArrayList(java.util.ArrayList) Sorting(net.ripe.rpki.validator3.api.Sorting) Valid(javax.validation.Valid) Asn(net.ripe.ipresource.Asn) Paging(net.ripe.rpki.validator3.api.Paging) ImmutableList(com.google.common.collect.ImmutableList) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) Transactions(net.ripe.rpki.validator3.util.Transactions) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) ImmutableSet(com.google.common.collect.ImmutableSet) Transactional(javax.transaction.Transactional) IpRange(net.ripe.ipresource.IpRange) Collection(java.util.Collection) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) Consumer(java.util.function.Consumer) Slf4j(lombok.extern.slf4j.Slf4j) Component(org.springframework.stereotype.Component) Base64(java.util.Base64) List(java.util.List) Stream(java.util.stream.Stream) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) PostConstruct(javax.annotation.PostConstruct) ValidationResult(net.ripe.rpki.commons.validation.ValidationResult) SearchTerm(net.ripe.rpki.validator3.api.SearchTerm) Optional(java.util.Optional) X509CertificateUtil(net.ripe.rpki.commons.crypto.x509cert.X509CertificateUtil) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) PostConstruct(javax.annotation.PostConstruct)

Aggregations

Valid (javax.validation.Valid)59 Response (javax.ws.rs.core.Response)14 Logger (org.slf4j.Logger)14 LoggerFactory (org.slf4j.LoggerFactory)14 UnexpectedRollbackException (org.springframework.transaction.UnexpectedRollbackException)14 List (java.util.List)12 java.util (java.util)11 Autowired (org.springframework.beans.factory.annotation.Autowired)11 Timed (com.codahale.metrics.annotation.Timed)10 User (com.vsct.vboard.models.User)10 HttpServletRequest (javax.servlet.http.HttpServletRequest)10 Path (javax.ws.rs.Path)10 Produces (javax.ws.rs.Produces)10 DateTime (org.joda.time.DateTime)10 VBoardException (com.vsct.vboard.models.VBoardException)9 IOException (java.io.IOException)9 ArrayList (java.util.ArrayList)9 Optional (java.util.Optional)9 Collectors (java.util.stream.Collectors)9 Collectors.toList (java.util.stream.Collectors.toList)9