Java Code Examples for javax.ws.rs.core.UriInfo#getAbsolutePathBuilder()

The following examples show how to use javax.ws.rs.core.UriInfo#getAbsolutePathBuilder() . 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: PostMessageDupsOk.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@POST
public Response create(@Context HttpHeaders headers,
                       @QueryParam("durable") Boolean durable,
                       @QueryParam("ttl") Long ttl,
                       @QueryParam("expiration") Long expiration,
                       @QueryParam("priority") Integer priority,
                       @Context UriInfo uriInfo,
                       byte[] body) {
   ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getRequestUri() + "\"");

   try {
      boolean isDurable = defaultDurable;
      if (durable != null) {
         isDurable = durable.booleanValue();
      }
      publish(headers, body, isDurable, ttl, expiration, priority);
   } catch (Exception e) {
      Response error = Response.serverError().entity("Problem posting message: " + e.getMessage()).type("text/plain").build();
      throw new WebApplicationException(e, error);
   }
   Response.ResponseBuilder builder = Response.status(201);
   UriBuilder nextBuilder = uriInfo.getAbsolutePathBuilder();
   URI next = nextBuilder.build();
   serviceManager.getLinkStrategy().setLinkHeader(builder, "create-next", "create-next", next.toString(), "*/*");
   return builder.build();
}
 
Example 2
Source File: PushConsumerResource.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
@POST
@Consumes("application/xml")
public Response create(@Context UriInfo uriInfo, PushRegistration registration) {
   ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\"");

   // todo put some logic here to check for duplicates
   String genId = sessionCounter.getAndIncrement() + "-" + startup;
   registration.setId(genId);
   registration.setDestination(destination);
   PushConsumer consumer = new PushConsumer(sessionFactory, destination, genId, registration, pushStore, jmsOptions);
   try {
      consumer.start();
      if (registration.isDurable() && pushStore != null) {
         pushStore.add(registration);
      }
   } catch (Exception e) {
      consumer.stop();
      throw new WebApplicationException(e, Response.serverError().entity("Failed to start consumer.").type("text/plain").build());
   }

   consumers.put(genId, consumer);
   UriBuilder location = uriInfo.getAbsolutePathBuilder();
   location.path(genId);
   return Response.created(location.build()).build();
}
 
Example 3
Source File: CustomerResource.java    From resteasy-examples with Apache License 2.0 5 votes vote down vote up
@POST
@Consumes("application/xml")
public Response createCustomer(Customer customer, @Context UriInfo uriInfo)
{
   customer.setId(idCounter.incrementAndGet());
   customerDB.put(customer.getId(), customer);
   System.out.println("Created customer " + customer.getId());
   UriBuilder builder = uriInfo.getAbsolutePathBuilder();
   builder.path(Integer.toString(customer.getId()));
   return Response.created(builder.build()).build();

}
 
Example 4
Source File: RuleResource.java    From nifi with Apache License 2.0 5 votes vote down vote up
@POST
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/rules/actions")
public Response createAction(
        @Context final UriInfo uriInfo,
        final ActionEntity requestEntity) {

    // generate a new id
    final String uuid = UUID.randomUUID().toString();

    final Action action;
    try {
        // create the condition object
        final UpdateAttributeModelFactory factory = new UpdateAttributeModelFactory();
        action = factory.createAction(requestEntity.getAction());
        action.setId(uuid);
    } catch (final IllegalArgumentException iae) {
        throw new WebApplicationException(iae, badRequest(iae.getMessage()));
    }

    // build the response
    final ActionEntity responseEntity = new ActionEntity();
    responseEntity.setClientId(requestEntity.getClientId());
    responseEntity.setProcessorId(requestEntity.getProcessorId());
    responseEntity.setRevision(requestEntity.getRevision());
    responseEntity.setAction(DtoFactory.createActionDTO(action));

    // generate the response
    final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
    final ResponseBuilder response = Response.created(uriBuilder.path(uuid).build()).entity(responseEntity);
    return noCache(response).build();
}
 
Example 5
Source File: RuleResource.java    From nifi with Apache License 2.0 5 votes vote down vote up
@POST
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/rules/conditions")
public Response createCondition(
        @Context final UriInfo uriInfo,
        final ConditionEntity requestEntity) {

    // generate a new id
    final String uuid = UUID.randomUUID().toString();

    final Condition condition;
    try {
        // create the condition object
        final UpdateAttributeModelFactory factory = new UpdateAttributeModelFactory();
        condition = factory.createCondition(requestEntity.getCondition());
        condition.setId(uuid);
    } catch (final IllegalArgumentException iae) {
        throw new WebApplicationException(iae, badRequest(iae.getMessage()));
    }

    // build the response
    final ConditionEntity responseEntity = new ConditionEntity();
    responseEntity.setClientId(requestEntity.getClientId());
    responseEntity.setProcessorId(requestEntity.getProcessorId());
    responseEntity.setRevision(requestEntity.getRevision());
    responseEntity.setCondition(DtoFactory.createConditionDTO(condition));

    // generate the response
    final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
    final ResponseBuilder response = Response.created(uriBuilder.path(uuid).build()).entity(responseEntity);
    return noCache(response).build();
}
 
Example 6
Source File: PushSubscriptionsResource.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@POST
public Response create(@Context UriInfo uriInfo, PushTopicRegistration registration) {
   ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\"");

   //System.out.println("PushRegistration: " + registration);
   // todo put some logic here to check for duplicates
   String genId = sessionCounter.getAndIncrement() + "-topic-" + destination + "-" + startup;
   if (registration.getDestination() == null) {
      registration.setDestination(genId);
   }
   registration.setId(genId);
   registration.setTopic(destination);
   ClientSession createSession = createSubscription(genId, registration.isDurable());
   try {
      PushSubscription consumer = new PushSubscription(sessionFactory, genId, genId, registration, pushStore, jmsOptions);
      try {
         consumer.start();
         if (registration.isDurable() && pushStore != null) {
            pushStore.add(registration);
         }
      } catch (Exception e) {
         consumer.stop();
         throw new WebApplicationException(e, Response.serverError().entity("Failed to start consumer.").type("text/plain").build());
      }

      consumers.put(genId, consumer);
      UriBuilder location = uriInfo.getAbsolutePathBuilder();
      location.path(genId);
      return Response.created(location.build()).build();
   } finally {
      closeSession(createSession);
   }
}
 
Example 7
Source File: ConsumersResource.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@POST
public Response createSubscription(@FormParam("autoAck") @DefaultValue("true") boolean autoAck,
                                   @FormParam("selector") String selector,
                                   @Context UriInfo uriInfo) {
   ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + uriInfo.getPath() + "\"");

   try {
      QueueConsumer consumer = null;
      int attributes = 0;
      if (selector != null) {
         attributes = attributes | SELECTOR_SET;
      }

      if (autoAck) {
         consumer = createConsumer(selector);
      } else {
         attributes |= ACKNOWLEDGED;
         consumer = createAcknowledgedConsumer(selector);
      }

      String attributesSegment = "attributes-" + attributes;
      UriBuilder location = uriInfo.getAbsolutePathBuilder();
      location.path(attributesSegment);
      location.path(consumer.getId());
      Response.ResponseBuilder builder = Response.created(location.build());

      if (autoAck) {
         QueueConsumer.setConsumeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(0) + "/" + attributesSegment + "/" + consumer.getId(), "-1");
      } else {
         AcknowledgedQueueConsumer.setAcknowledgeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(0) + "/" + attributesSegment + "/" + consumer.getId(), "-1");

      }
      return builder.build();

   } catch (ActiveMQException e) {
      throw new RuntimeException(e);
   } finally {
   }
}
 
Example 8
Source File: OrderResource.java    From blog-tutorials with MIT License 5 votes vote down vote up
@POST
public Response createNewOrder(JsonObject order, @Context UriInfo uriInfo) {
    Integer newOrderId = this.orderService.createNewOrder(new Order(order));
    UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
    uriBuilder.path(Integer.toString(newOrderId));

    return Response.created(uriBuilder.build()).build();
}
 
Example 9
Source File: RuleResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@POST
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/rules/actions")
public Response createAction(
        @Context final UriInfo uriInfo,
        @PathParam("id") final String ruleId,
        final ActionEntity requestEntity) {

    // generate a new id
    final String uuid = UUID.randomUUID().toString();

    final Action action;
    try {
        // create the condition object
        final UpdateAttributeModelFactory factory = new UpdateAttributeModelFactory();
        action = factory.createAction(requestEntity.getAction());
        action.setId(uuid);
    } catch (final IllegalArgumentException iae) {
        throw new WebApplicationException(iae, badRequest(iae.getMessage()));
    }

    // build the response
    final ActionEntity responseEntity = new ActionEntity();
    responseEntity.setClientId(requestEntity.getClientId());
    responseEntity.setProcessorId(requestEntity.getProcessorId());
    responseEntity.setRevision(requestEntity.getRevision());
    responseEntity.setAction(DtoFactory.createActionDTO(action));

    // generate the response
    final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
    final ResponseBuilder response = Response.created(uriBuilder.path(uuid).build()).entity(responseEntity);
    return noCache(response).build();
}
 
Example 10
Source File: RuleResource.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@POST
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/rules/conditions")
public Response createCondition(
        @Context final UriInfo uriInfo,
        @PathParam("id") final String ruleId,
        final ConditionEntity requestEntity) {

    // generate a new id
    final String uuid = UUID.randomUUID().toString();

    final Condition condition;
    try {
        // create the condition object
        final UpdateAttributeModelFactory factory = new UpdateAttributeModelFactory();
        condition = factory.createCondition(requestEntity.getCondition());
        condition.setId(uuid);
    } catch (final IllegalArgumentException iae) {
        throw new WebApplicationException(iae, badRequest(iae.getMessage()));
    }

    // build the response
    final ConditionEntity responseEntity = new ConditionEntity();
    responseEntity.setClientId(requestEntity.getClientId());
    responseEntity.setProcessorId(requestEntity.getProcessorId());
    responseEntity.setRevision(requestEntity.getRevision());
    responseEntity.setCondition(DtoFactory.createConditionDTO(condition));

    // generate the response
    final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
    final ResponseBuilder response = Response.created(uriBuilder.path(uuid).build()).entity(responseEntity);
    return noCache(response).build();
}
 
Example 11
Source File: OrderResource.java    From resteasy-examples with Apache License 2.0 4 votes vote down vote up
protected void addCancelHeader(UriInfo uriInfo, Response.ResponseBuilder builder)
{
   UriBuilder absolute = uriInfo.getAbsolutePathBuilder();
   URI cancelUrl = absolute.clone().path("cancel").build();
   builder.links(Link.fromUri(cancelUrl).rel("cancel").build());
}
 
Example 12
Source File: OrderResource.java    From resteasy-examples with Apache License 2.0 4 votes vote down vote up
@GET
@Produces("application/xml")
@Formatted
public Response getOrders(@QueryParam("start") int start,
                          @QueryParam("size") @DefaultValue("2") int size,
                          @Context UriInfo uriInfo)
{
   UriBuilder builder = uriInfo.getAbsolutePathBuilder();
   builder.queryParam("start", "{start}");
   builder.queryParam("size", "{size}");

   ArrayList<Order> list = new ArrayList<Order>();
   ArrayList<Link> links = new ArrayList<Link>();
   synchronized (orderDB)
   {
      int i = 0;
      for (Order order : orderDB.values())
      {
         if (i >= start && i < start + size) list.add(order);
         i++;
      }
      // next link
      if (start + size < orderDB.size())
      {
         int next = start + size;
         URI nextUri = builder.clone().build(next, size);
         Link nextLink = Link.fromUri(nextUri).rel("next").type("application/xml").build();
         links.add(nextLink);
      }
      // previous link
      if (start > 0)
      {
         int previous = start - size;
         if (previous < 0) previous = 0;
         URI previousUri = builder.clone().build(previous, size);
         Link previousLink = Link.fromUri(previousUri).rel("previous").type("application/xml").build();
         links.add(previousLink);
      }
   }
   Orders orders = new Orders();
   orders.setOrders(list);
   orders.setLinks(links);
   Response.ResponseBuilder responseBuilder = Response.ok(orders);
   addPurgeLinkHeader(uriInfo, responseBuilder);
   return responseBuilder.build();
}
 
Example 13
Source File: OrderResource.java    From resteasy-examples with Apache License 2.0 4 votes vote down vote up
protected void addPurgeLinkHeader(UriInfo uriInfo, Response.ResponseBuilder builder)
{
   UriBuilder absolute = uriInfo.getAbsolutePathBuilder();
   URI purgeUri = absolute.clone().path("purge").build();
   builder.links(Link.fromUri(purgeUri).rel("purge").build());
}
 
Example 14
Source File: RuleResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@POST
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/rules")
public Response createRule(
        @Context final UriInfo uriInfo,
        final RuleEntity requestEntity) {

    // get the web context
    final NiFiWebConfigurationContext configurationContext = (NiFiWebConfigurationContext) servletContext.getAttribute("nifi-web-configuration-context");

    // ensure the rule has been specified
    if (requestEntity == null || requestEntity.getRule() == null) {
        throw new WebApplicationException(badRequest("The rule must be specified."));
    }

    final RuleDTO ruleDto = requestEntity.getRule();

    // ensure the id hasn't been specified
    if (ruleDto.getId() != null) {
        throw new WebApplicationException(badRequest("The rule id cannot be specified."));
    }

    // ensure there are some conditions
    if (ruleDto.getConditions() == null || ruleDto.getConditions().isEmpty()) {
        throw new WebApplicationException(badRequest("The rule conditions must be set."));
    }

    // ensure there are some actions
    if (ruleDto.getActions() == null || ruleDto.getActions().isEmpty()) {
        throw new WebApplicationException(badRequest("The rule actions must be set."));
    }

    // generate a new id
    final String uuid = UUID.randomUUID().toString();

    // build the request context
    final NiFiWebConfigurationRequestContext requestContext = getConfigurationRequestContext(
            requestEntity.getProcessorId(), requestEntity.getRevision(), requestEntity.getClientId());

    // load the criteria
    final Criteria criteria = getCriteria(configurationContext, requestContext);
    final UpdateAttributeModelFactory factory = new UpdateAttributeModelFactory();

    // create the new rule
    final Rule rule;
    try {
        rule = factory.createRule(ruleDto);
        rule.setId(uuid);
    } catch (final IllegalArgumentException iae) {
        throw new WebApplicationException(iae, badRequest(iae.getMessage()));
    }

    // add the rule
    criteria.addRule(rule);

    // save the criteria
    saveCriteria(requestContext, criteria);

    // create the response entity
    final RuleEntity responseEntity = new RuleEntity();
    responseEntity.setClientId(requestEntity.getClientId());
    responseEntity.setRevision(requestEntity.getRevision());
    responseEntity.setProcessorId(requestEntity.getProcessorId());
    responseEntity.setRule(DtoFactory.createRuleDTO(rule));

    // generate the response
    final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
    final ResponseBuilder response = Response.created(uriBuilder.path(uuid).build()).entity(responseEntity);
    return noCache(response).build();
}
 
Example 15
Source File: CustomerResource.java    From resteasy-examples with Apache License 2.0 4 votes vote down vote up
@GET
@Produces("application/xml")
@Formatted
public Customers getCustomers(@QueryParam("start") int start,
                              @QueryParam("size") @DefaultValue("2") int size,
                              @Context UriInfo uriInfo)
{
   UriBuilder builder = uriInfo.getAbsolutePathBuilder();
   builder.queryParam("start", "{start}");
   builder.queryParam("size", "{size}");

   ArrayList<Customer> list = new ArrayList<Customer>();
   ArrayList<Link> links = new ArrayList<Link>();
   synchronized (customerDB)
   {
      int i = 0;
      for (Customer customer : customerDB.values())
      {
         if (i >= start && i < start + size) list.add(customer);
         i++;
      }
      // next link
      if (start + size < customerDB.size())
      {
         int next = start + size;
         URI nextUri = builder.clone().build(next, size);
         Link nextLink = Link.fromUri(nextUri).rel("next").type("application/xml").build();
         links.add(nextLink);
      }
      // previous link
      if (start > 0)
      {
         int previous = start - size;
         if (previous < 0) previous = 0;
         URI previousUri = builder.clone().build(previous, size);
         Link previousLink = Link.fromUri(previousUri).rel("previous").type("application/xml").build();
         links.add(previousLink);
      }
   }
   Customers customers = new Customers();
   customers.setCustomers(list);
   customers.setLinks(links);
   return customers;
}
 
Example 16
Source File: RuleResource.java    From nifi with Apache License 2.0 4 votes vote down vote up
@PUT
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/rules/{id}")
public Response updateRule(
        @Context final UriInfo uriInfo,
        @PathParam("id") final String ruleId,
        final RuleEntity requestEntity) {

    // get the web context
    final NiFiWebConfigurationContext nifiWebContext = (NiFiWebConfigurationContext) servletContext.getAttribute("nifi-web-configuration-context");

    // ensure the rule has been specified
    if (requestEntity == null || requestEntity.getRule() == null) {
        throw new WebApplicationException(badRequest("The rule must be specified."));
    }

    final RuleDTO ruleDto = requestEntity.getRule();

    // ensure the id has been specified
    if (ruleDto.getId() == null) {
        throw new WebApplicationException(badRequest("The rule id must be specified."));
    }
    if (!ruleDto.getId().equals(ruleId)) {
        throw new WebApplicationException(badRequest("The rule id in the path does not equal the rule id in the request body."));
    }

    // ensure the rule name was specified
    if (ruleDto.getName() == null || ruleDto.getName().isEmpty()) {
        throw new WebApplicationException(badRequest("The rule name must be specified and cannot be blank."));
    }

    // ensure there are some conditions
    if (ruleDto.getConditions() == null || ruleDto.getConditions().isEmpty()) {
        throw new WebApplicationException(badRequest("The rule conditions must be set."));
    }

    // ensure there are some actions
    if (ruleDto.getActions() == null || ruleDto.getActions().isEmpty()) {
        throw new WebApplicationException(badRequest("The rule actions must be set."));
    }

    // build the web context config
    final NiFiWebConfigurationRequestContext requestContext = getConfigurationRequestContext(
            requestEntity.getProcessorId(), requestEntity.getRevision(), requestEntity.getClientId(), requestEntity.isDisconnectedNodeAcknowledged());

    // load the criteria
    final UpdateAttributeModelFactory factory = new UpdateAttributeModelFactory();
    final Criteria criteria = getCriteria(nifiWebContext, requestContext);

    // attempt to locate the rule
    Rule rule = criteria.getRule(ruleId);

    // if the rule isn't found add it
    boolean newRule = false;
    if (rule == null) {
        newRule = true;

        rule = new Rule();
        rule.setId(ruleId);
    }

    try {
        // evaluate the conditions and actions before modifying the rule
        final Set<Condition> conditions = factory.createConditions(ruleDto.getConditions());
        final Set<Action> actions = factory.createActions(ruleDto.getActions());

        // update the rule
        rule.setName(ruleDto.getName());
        rule.setConditions(conditions);
        rule.setActions(actions);
    } catch (final IllegalArgumentException iae) {
        throw new WebApplicationException(iae, badRequest(iae.getMessage()));
    }

    // add the new rule if application
    if (newRule) {
        criteria.addRule(rule);
    }

    // save the criteria
    saveCriteria(requestContext, criteria);

    // create the response entity
    final RuleEntity responseEntity = new RuleEntity();
    responseEntity.setClientId(requestEntity.getClientId());
    responseEntity.setRevision(requestEntity.getRevision());
    responseEntity.setProcessorId(requestEntity.getProcessorId());
    responseEntity.setRule(DtoFactory.createRuleDTO(rule));

    // generate the response
    final ResponseBuilder response;
    if (newRule) {
        final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
        response = Response.created(uriBuilder.path(ruleId).build()).entity(responseEntity);
    } else {
        response = Response.ok(responseEntity);
    }
    return noCache(response).build();
}
 
Example 17
Source File: CustomerResource.java    From resteasy-examples with Apache License 2.0 4 votes vote down vote up
@GET
@Produces("application/xml")
@Formatted
public Customers getCustomers(@QueryParam("start") int start,
                              @QueryParam("size") @DefaultValue("2") int size,
                              @Context UriInfo uriInfo)
{
   UriBuilder builder = uriInfo.getAbsolutePathBuilder();
   builder.queryParam("start", "{start}");
   builder.queryParam("size", "{size}");

   ArrayList<Customer> list = new ArrayList<Customer>();
   ArrayList<Link> links = new ArrayList<Link>();
   synchronized (customerDB)
   {
      int i = 0;
      for (Customer customer : customerDB.values())
      {
         if (i >= start && i < start + size) list.add(customer);
         i++;
      }
      // next link
      if (start + size < customerDB.size())
      {
         int next = start + size;
         URI nextUri = builder.clone().build(next, size);
         Link nextLink = Link.fromUri(nextUri).rel("next").type("application/xml").build();
         links.add(nextLink);
       }
      // previous link
      if (start > 0)
      {
         int previous = start - size;
         if (previous < 0) previous = 0;
         URI previousUri = builder.clone().build(previous, size);
         Link previousLink = Link.fromUri(previousUri).rel("previous").type("application/xml").build();
         links.add(previousLink);
      }
   }
   Customers customers = new Customers();
   customers.setCustomers(list);
   customers.setLinks(links);
   return customers;
}
 
Example 18
Source File: RuleResource.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@PUT
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/rules/{id}")
public Response updateRule(
        @Context final UriInfo uriInfo,
        @PathParam("id") final String ruleId,
        final RuleEntity requestEntity) {

    // get the web context
    final NiFiWebConfigurationContext nifiWebContext = (NiFiWebConfigurationContext) servletContext.getAttribute("nifi-web-configuration-context");

    // ensure the rule has been specified
    if (requestEntity == null || requestEntity.getRule() == null) {
        throw new WebApplicationException(badRequest("The rule must be specified."));
    }

    final RuleDTO ruleDto = requestEntity.getRule();

    // ensure the id has been specified
    if (ruleDto.getId() == null) {
        throw new WebApplicationException(badRequest("The rule id must be specified."));
    }
    if (!ruleDto.getId().equals(ruleId)) {
        throw new WebApplicationException(badRequest("The rule id in the path does not equal the rule id in the request body."));
    }

    // ensure the rule name was specified
    if (ruleDto.getName() == null || ruleDto.getName().isEmpty()) {
        throw new WebApplicationException(badRequest("The rule name must be specified and cannot be blank."));
    }

    // ensure there are some conditions
    if (ruleDto.getConditions() == null || ruleDto.getConditions().isEmpty()) {
        throw new WebApplicationException(badRequest("The rule conditions must be set."));
    }

    // ensure there are some actions
    if (ruleDto.getActions() == null || ruleDto.getActions().isEmpty()) {
        throw new WebApplicationException(badRequest("The rule actions must be set."));
    }

    // build the web context config
    final NiFiWebConfigurationRequestContext requestContext = getConfigurationRequestContext(
            requestEntity.getProcessorId(), requestEntity.getRevision(), requestEntity.getClientId());

    // load the criteria
    final UpdateAttributeModelFactory factory = new UpdateAttributeModelFactory();
    final Criteria criteria = getCriteria(nifiWebContext, requestContext);

    // attempt to locate the rule
    Rule rule = criteria.getRule(ruleId);

    // if the rule isn't found add it
    boolean newRule = false;
    if (rule == null) {
        newRule = true;

        rule = new Rule();
        rule.setId(ruleId);
    }

    try {
        // evaluate the conditions and actions before modifying the rule
        final Set<Condition> conditions = factory.createConditions(ruleDto.getConditions());
        final Set<Action> actions = factory.createActions(ruleDto.getActions());

        // update the rule
        rule.setName(ruleDto.getName());
        rule.setConditions(conditions);
        rule.setActions(actions);
    } catch (final IllegalArgumentException iae) {
        throw new WebApplicationException(iae, badRequest(iae.getMessage()));
    }

    // add the new rule if application
    if (newRule) {
        criteria.addRule(rule);
    }

    // save the criteria
    saveCriteria(requestContext, criteria);

    // create the response entity
    final RuleEntity responseEntity = new RuleEntity();
    responseEntity.setClientId(requestEntity.getClientId());
    responseEntity.setRevision(requestEntity.getRevision());
    responseEntity.setProcessorId(requestEntity.getProcessorId());
    responseEntity.setRule(DtoFactory.createRuleDTO(rule));

    // generate the response
    final ResponseBuilder response;
    if (newRule) {
        final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
        response = Response.created(uriBuilder.path(ruleId).build()).entity(responseEntity);
    } else {
        response = Response.ok(responseEntity);
    }
    return noCache(response).build();
}
 
Example 19
Source File: ScannerResource.java    From hbase with Apache License 2.0 4 votes vote down vote up
Response update(final ScannerModel model, final boolean replace,
    final UriInfo uriInfo) {
  servlet.getMetrics().incrementRequests(1);
  if (servlet.isReadOnly()) {
    return Response.status(Response.Status.FORBIDDEN)
      .type(MIMETYPE_TEXT).entity("Forbidden" + CRLF)
      .build();
  }
  byte[] endRow = model.hasEndRow() ? model.getEndRow() : null;
  RowSpec spec = null;
  if (model.getLabels() != null) {
    spec = new RowSpec(model.getStartRow(), endRow, model.getColumns(), model.getStartTime(),
        model.getEndTime(), model.getMaxVersions(), model.getLabels());
  } else {
    spec = new RowSpec(model.getStartRow(), endRow, model.getColumns(), model.getStartTime(),
        model.getEndTime(), model.getMaxVersions());
  }

  try {
    Filter filter = ScannerResultGenerator.buildFilterFromModel(model);
    String tableName = tableResource.getName();
    ScannerResultGenerator gen =
      new ScannerResultGenerator(tableName, spec, filter, model.getCaching(),
        model.getCacheBlocks(), model.getLimit());
    String id = gen.getID();
    ScannerInstanceResource instance =
      new ScannerInstanceResource(tableName, id, gen, model.getBatch());
    scanners.put(id, instance);
    if (LOG.isTraceEnabled()) {
      LOG.trace("new scanner: " + id);
    }
    UriBuilder builder = uriInfo.getAbsolutePathBuilder();
    URI uri = builder.path(id).build();
    servlet.getMetrics().incrementSucessfulPutRequests(1);
    return Response.created(uri).build();
  } catch (Exception e) {
    LOG.error("Exception occurred while processing " + uriInfo.getAbsolutePath() + " : ", e);
    servlet.getMetrics().incrementFailedPutRequests(1);
    if (e instanceof TableNotFoundException) {
      return Response.status(Response.Status.NOT_FOUND)
        .type(MIMETYPE_TEXT).entity("Not found" + CRLF)
        .build();
    } else if (e instanceof RuntimeException
        || e instanceof JsonMappingException | e instanceof JsonParseException) {
      return Response.status(Response.Status.BAD_REQUEST)
        .type(MIMETYPE_TEXT).entity("Bad request" + CRLF)
        .build();
    }
    return Response.status(Response.Status.SERVICE_UNAVAILABLE)
      .type(MIMETYPE_TEXT).entity("Unavailable" + CRLF)
      .build();
  }
}
 
Example 20
Source File: RuleResource.java    From nifi with Apache License 2.0 4 votes vote down vote up
@POST
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/rules")
public Response createRule(
        @Context final UriInfo uriInfo,
        final RuleEntity requestEntity) {

    // get the web context
    final NiFiWebConfigurationContext configurationContext = (NiFiWebConfigurationContext) servletContext.getAttribute("nifi-web-configuration-context");

    // ensure the rule has been specified
    if (requestEntity == null || requestEntity.getRule() == null) {
        throw new WebApplicationException(badRequest("The rule must be specified."));
    }

    final RuleDTO ruleDto = requestEntity.getRule();

    // ensure the id hasn't been specified
    if (ruleDto.getId() != null) {
        throw new WebApplicationException(badRequest("The rule id cannot be specified."));
    }

    // ensure there are some conditions
    if (ruleDto.getConditions() == null || ruleDto.getConditions().isEmpty()) {
        throw new WebApplicationException(badRequest("The rule conditions must be set."));
    }

    // ensure there are some actions
    if (ruleDto.getActions() == null || ruleDto.getActions().isEmpty()) {
        throw new WebApplicationException(badRequest("The rule actions must be set."));
    }

    // generate a new id
    final String uuid = UUID.randomUUID().toString();

    // build the request context
    final NiFiWebConfigurationRequestContext requestContext = getConfigurationRequestContext(
            requestEntity.getProcessorId(), requestEntity.getRevision(), requestEntity.getClientId(), requestEntity.isDisconnectedNodeAcknowledged());

    // load the criteria
    final Criteria criteria = getCriteria(configurationContext, requestContext);
    final UpdateAttributeModelFactory factory = new UpdateAttributeModelFactory();

    // create the new rule
    final Rule rule;
    try {
        rule = factory.createRule(ruleDto);
        rule.setId(uuid);
    } catch (final IllegalArgumentException iae) {
        throw new WebApplicationException(iae, badRequest(iae.getMessage()));
    }

    // add the rule
    criteria.addRule(rule);

    // save the criteria
    saveCriteria(requestContext, criteria);

    // create the response entity
    final RuleEntity responseEntity = new RuleEntity();
    responseEntity.setClientId(requestEntity.getClientId());
    responseEntity.setRevision(requestEntity.getRevision());
    responseEntity.setProcessorId(requestEntity.getProcessorId());
    responseEntity.setRule(DtoFactory.createRuleDTO(rule));

    // generate the response
    final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
    final ResponseBuilder response = Response.created(uriBuilder.path(uuid).build()).entity(responseEntity);
    return noCache(response).build();
}