@GET
 @Path("/event/{eventId}")
 @Produces(APPLICATION_JSON)
 @ApiOperation(value = "Get an existing Event.", response = Event.class)
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Event found."),
       @ApiResponse(code = 404, message = "Event not found.", response = ApiError.class),
       @ApiResponse(code = 500, message = "Internal server error.", response = ApiError.class)
     })
 public Response getEvent(
     @ApiParam(value = "Id of Event to be retrieved.", required = true) @PathParam("eventId")
         final String eventId,
     @ApiParam(
             required = false,
             value = "Return only a thin event, do not include: evalSets, dampening.")
         @QueryParam("thin")
         final Boolean thin) {
   try {
     Event found =
         alertsService.getEvent(tenantId, eventId, ((null == thin) ? false : thin.booleanValue()));
     if (found != null) {
       if (log.isDebugEnabled()) {
         log.debug("Event: " + found);
       }
       return ResponseUtil.ok(found);
     } else {
       return ResponseUtil.notFound("eventId: " + eventId + " not found");
     }
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e);
   }
 }
 @GET
 @Path("/{triggerId}/dampenings/{dampeningId}")
 @Produces(APPLICATION_JSON)
 @ApiOperation(value = "Get an existing dampening")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Dampening Found"),
       @ApiResponse(code = 404, message = "No Dampening Found"),
       @ApiResponse(code = 500, message = "Internal server error")
     })
 public Response getDampening(
     @ApiParam(value = "Trigger definition id to be retrieved", required = true)
         @PathParam("triggerId")
         final String triggerId,
     @ApiParam(value = "Dampening id", required = true) @PathParam("dampeningId")
         final String dampeningId) {
   try {
     Dampening found = definitions.getDampening(tenantId, dampeningId);
     log.debug("Dampening: " + found);
     if (found == null) {
       return ResponseUtil.notFound(
           "No dampening found for triggerId: " + triggerId + " and dampeningId:" + dampeningId);
     }
     return ResponseUtil.ok(found);
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
 @DELETE
 @Path("/{eventId}")
 @ApiOperation(value = "Delete an existing Event.")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Event deleted."),
       @ApiResponse(code = 500, message = "Internal server error.", response = ApiError.class),
       @ApiResponse(code = 404, message = "Event not found.", response = ApiError.class)
     })
 public Response deleteEvent(
     @ApiParam(required = true, value = "Event id to be deleted.") @PathParam("eventId")
         final String eventId) {
   try {
     EventsCriteria criteria = new EventsCriteria();
     criteria.setEventId(eventId);
     int numDeleted = alertsService.deleteEvents(tenantId, criteria);
     if (1 == numDeleted) {
       if (log.isDebugEnabled()) {
         log.debug("EventId: " + eventId);
       }
       return ResponseUtil.ok();
     } else {
       return ResponseUtil.notFound("Event " + eventId + " doesn't exist for delete");
     }
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e);
   }
 }
  @DELETE
  @Path("/{triggerId}")
  @ApiOperation(value = "Delete an existing trigger definition")
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "Success, Trigger deleted"),
        @ApiResponse(code = 500, message = "Internal server error"),
        @ApiResponse(code = 404, message = "Trigger not found")
      })
  public Response deleteTrigger(
      @ApiParam(value = "Trigger definition id to be deleted", required = true)
          @PathParam("triggerId") //
          final String triggerId) {
    try {
      definitions.removeTrigger(tenantId, triggerId);
      if (log.isDebugEnabled()) {
        log.debug("TriggerId: " + triggerId);
      }
      return ResponseUtil.ok();

    } catch (NotFoundException e) {
      return ResponseUtil.notFound("Trigger " + triggerId + " doesn't exist for delete");

    } catch (Exception e) {
      log.debug(e.getMessage(), e);
      return ResponseUtil.internalError(e.getMessage());
    }
  }
  @PUT
  @Path("/groups/{groupId}")
  @Consumes(APPLICATION_JSON)
  @ApiOperation(value = "Update an existing group trigger definition and its member definitions")
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "Success, Group Trigger updated"),
        @ApiResponse(code = 500, message = "Internal server error"),
        @ApiResponse(code = 404, message = "Trigger doesn't exist/Invalid Parameters")
      })
  public Response updateGroupTrigger(
      @ApiParam(value = "Group Trigger id to be updated", required = true) @PathParam("groupId")
          final String groupId,
      @ApiParam(value = "Updated group trigger definition", name = "trigger", required = true)
          final Trigger groupTrigger) {
    try {
      if (groupTrigger != null && !isEmpty(groupId)) {
        groupTrigger.setId(groupId);
      }
      definitions.updateGroupTrigger(tenantId, groupTrigger);
      if (log.isDebugEnabled()) {
        log.debug("Trigger: " + groupTrigger);
      }
      return ResponseUtil.ok();

    } catch (NotFoundException e) {
      return ResponseUtil.notFound("Trigger " + groupId + " doesn't exist for update");

    } catch (Exception e) {
      log.debug(e.getMessage(), e);
      return ResponseUtil.internalError(e.getMessage());
    }
  }
  @POST
  @Path("/groups/members/{memberId}/orphan")
  @Consumes(APPLICATION_JSON)
  @ApiOperation(value = "Make a non-orphan member trigger into an orphan.")
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "Success, Trigger updated"),
        @ApiResponse(code = 500, message = "Internal server error"),
        @ApiResponse(code = 404, message = "Trigger doesn't exist/Invalid Parameters")
      })
  public Response orphanMemberTrigger(
      @ApiParam(value = "Member Trigger id to be made an orphan.", required = true) //
          @PathParam("memberId") //
          final String memberId) {
    try {
      Trigger child = definitions.orphanMemberTrigger(tenantId, memberId);
      if (log.isDebugEnabled()) {
        log.debug("Orphan Member Trigger: " + child);
      }
      return ResponseUtil.ok();

    } catch (NotFoundException e) {
      return ResponseUtil.notFound("Member Trigger " + memberId + " doesn't exist for update");

    } catch (Exception e) {
      log.debug(e.getMessage(), e);
      return ResponseUtil.internalError(e.getMessage());
    }
  }
 @DELETE
 @Path("/groups/{groupId}/dampenings/{dampeningId}")
 @ApiOperation(value = "Delete an existing group dampening definition")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Dampening deleted"),
       @ApiResponse(code = 404, message = "No Dampening found"),
       @ApiResponse(code = 500, message = "Internal server error")
     })
 public Response deleteGroupDampening(
     @ApiParam(value = "Trigger definition id to be retrieved", required = true)
         @PathParam("groupId")
         final String groupId,
     @ApiParam(value = "Dampening id for dampening definition to be deleted", required = true)
         @PathParam("dampeningId")
         final String dampeningId) {
   try {
     boolean exists = (definitions.getDampening(tenantId, dampeningId) != null);
     if (exists) {
       definitions.removeGroupDampening(tenantId, dampeningId);
       if (log.isDebugEnabled()) {
         log.debug("Group DampeningId: " + dampeningId);
       }
       return ResponseUtil.ok();
     } else {
       return ResponseUtil.notFound("Dampening not found for dampeningId: " + dampeningId);
     }
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
 @GET
 @Path("/{triggerId}")
 @Produces(APPLICATION_JSON)
 @ApiOperation(value = "Get an existing trigger definition", response = Trigger.class)
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Trigger found"),
       @ApiResponse(code = 404, message = "Trigger not found"),
       @ApiResponse(code = 500, message = "Internal server error")
     })
 public Response getTrigger(
     @ApiParam(value = "Trigger definition id to be retrieved", required = true)
         @PathParam("triggerId")
         final String triggerId) {
   try {
     Trigger found = definitions.getTrigger(tenantId, triggerId);
     if (found != null) {
       log.debug("Trigger: " + found);
       return ResponseUtil.ok(found);
     } else {
       return ResponseUtil.notFound("triggerId: " + triggerId + " not found");
     }
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
 @POST
 @Path("/groups")
 @Consumes(APPLICATION_JSON)
 @Produces(APPLICATION_JSON)
 @ApiOperation(
     value = "Create a new group trigger",
     response = Trigger.class,
     notes = "Returns created GroupTrigger")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Group Trigger Created"),
       @ApiResponse(code = 500, message = "Internal server error"),
       @ApiResponse(code = 400, message = "Bad Request/Invalid Parameters")
     })
 public Response createGroupTrigger(
     @ApiParam(value = "Trigger definition to be created", name = "groupTrigger", required = true)
         final Trigger groupTrigger) {
   try {
     if (null != groupTrigger) {
       if (isEmpty(groupTrigger.getId())) {
         groupTrigger.setId(Trigger.generateId());
       } else if (definitions.getTrigger(tenantId, groupTrigger.getId()) != null) {
         return ResponseUtil.badRequest("Trigger with ID [" + groupTrigger.getId() + "] exists.");
       }
       definitions.addGroupTrigger(tenantId, groupTrigger);
       log.debug("Group Trigger: " + groupTrigger.toString());
       return ResponseUtil.ok(groupTrigger);
     } else {
       return ResponseUtil.badRequest("Trigger is null");
     }
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
 @GET
 @Path("/groups/{groupId}/members")
 @Produces(APPLICATION_JSON)
 @ApiOperation(
     value = "Find all Group Member Trigger Definitions",
     notes = "Pagination is not yet implemented")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success"),
       @ApiResponse(code = 500, message = "Internal server error")
     })
 public Response findGroupMembers(
     @ApiParam(value = "Group TriggerId", required = true) //
         @PathParam("groupId") //
         final String groupId,
     @ApiParam(value = "include Orphan members? No if omitted.", required = false) //
         @QueryParam("includeOrphans") //
         final boolean includeOrphans) {
   try {
     Collection<Trigger> members =
         definitions.getMemberTriggers(tenantId, groupId, includeOrphans);
     if (log.isDebugEnabled()) {
       log.debug("Member Triggers: " + members);
     }
     return ResponseUtil.ok(members);
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
 @GET
 @Path("/{triggerId}/conditions/{conditionId}")
 @Produces(APPLICATION_JSON)
 @ApiOperation(value = "@Deprecated : Use GET /alerts/triggers/{triggerId}/conditions")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Condition found"),
       @ApiResponse(code = 404, message = "No Condition found"),
       @ApiResponse(code = 500, message = "Internal server error")
     })
 @Deprecated
 public Response getTriggerCondition(
     @ApiParam(value = "Trigger definition id to be retrieved", required = true)
         @PathParam("triggerId")
         final String triggerId,
     @PathParam("conditionId") final String conditionId) {
   try {
     Trigger trigger = definitions.getTrigger(tenantId, triggerId);
     if (trigger == null) {
       return ResponseUtil.notFound("No trigger found for triggerId: " + triggerId);
     }
     Condition found = definitions.getCondition(tenantId, conditionId);
     if (found == null) {
       return ResponseUtil.notFound("No condition found for conditionId: " + conditionId);
     }
     if (!found.getTriggerId().equals(triggerId)) {
       return ResponseUtil.notFound(
           "ConditionId: " + conditionId + " does not belong to triggerId: " + triggerId);
     }
     return ResponseUtil.ok(found);
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
 @GET
 @Path("/{triggerId}/dampenings/mode/{triggerMode}")
 @Produces(APPLICATION_JSON)
 @ApiOperation(value = "Get a dampening using triggerId and triggerMode")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success"),
       @ApiResponse(code = 500, message = "Internal server error")
     })
 public Response getTriggerModeDampenings(
     @ApiParam(value = "Trigger definition id to be retrieved", required = true) //
         @PathParam("triggerId") //
         final String triggerId, //
     @ApiParam(value = "Trigger mode", required = true) //
         @PathParam("triggerMode") //
         final Mode triggerMode) {
   try {
     Collection<Dampening> dampenings =
         definitions.getTriggerDampenings(tenantId, triggerId, triggerMode);
     if (log.isDebugEnabled()) {
       log.debug("Dampenings: " + dampenings);
     }
     return ResponseUtil.ok(dampenings);
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
  @PUT
  @Path("/{triggerId}/conditions/{triggerMode}")
  @Consumes(APPLICATION_JSON)
  @Produces(APPLICATION_JSON)
  @ApiOperation(
      value =
          "Set the conditions for the trigger. This replaces any existing conditions. Returns "
              + "the new conditions.")
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "Success, Condition Set created"),
        @ApiResponse(code = 404, message = "No trigger found"),
        @ApiResponse(code = 500, message = "Internal server error"),
        @ApiResponse(code = 400, message = "Bad Request/Invalid Parameters")
      })
  public Response setConditions(
      @ApiParam(value = "The relevant Trigger.", required = true) @PathParam("triggerId")
          final String triggerId,
      @ApiParam(value = "FIRING or AUTORESOLVE (not case sensitive).", required = true)
          @PathParam("triggerMode")
          final String triggerMode,
      @ApiParam(
              value =
                  "Json representation of a condition list. For examples of Condition types, See "
                      + "https://github.com/hawkular/hawkular-alerts/blob/master/hawkular-alerts-rest-tests/"
                      + "src/test/groovy/org/hawkular/alerts/rest/ConditionsITest.groovy") //
          String jsonConditions) {
    try {
      Mode mode = Mode.valueOf(triggerMode.toUpperCase());
      Collection<Condition> conditions = new ArrayList<>();
      if (!isEmpty(jsonConditions)) {

        ObjectMapper om = new ObjectMapper();
        JsonNode rootNode = om.readTree(jsonConditions);
        for (JsonNode conditionNode : rootNode) {
          Condition condition = JacksonDeserializer.deserializeCondition(conditionNode);
          if (condition == null) {
            return ResponseUtil.badRequest("Bad json conditions: " + jsonConditions);
          }
          condition.setTriggerId(triggerId);
          condition.setTriggerMode(mode);
          conditions.add(condition);
        }
      }

      conditions = definitions.setConditions(tenantId, triggerId, mode, conditions);
      if (log.isDebugEnabled()) {
        log.debug("Conditions: " + conditions);
      }
      return ResponseUtil.ok(conditions);

    } catch (IllegalArgumentException e) {
      return ResponseUtil.badRequest("Bad argument: " + e.getMessage());
    } catch (NotFoundException e) {
      return ResponseUtil.notFound(e.getMessage());
    } catch (Exception e) {
      log.debug(e.getMessage(), e);
      return ResponseUtil.internalError(e.getMessage());
    }
  }
  @POST
  @Path("/{triggerId}/conditions")
  @Consumes(APPLICATION_JSON)
  @Produces(APPLICATION_JSON)
  @ApiOperation(
      value =
          "Deprecated : Use PUT /alerts/triggers/{triggerId}/conditions to set the entire "
              + "condition set in one service.")
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "Success, Condition created"),
        @ApiResponse(code = 404, message = "No trigger found"),
        @ApiResponse(code = 500, message = "Internal server error"),
        @ApiResponse(code = 400, message = "Bad Request/Invalid Parameters")
      })
  @Deprecated
  public Response createCondition(
      @ApiParam(value = "Trigger definition id to be retrieved", required = true)
          @PathParam("triggerId")
          final String triggerId,
      @ApiParam(
              value =
                  "Json representation of a condition. For examples of Condition types, See "
                      + "https://github.com/hawkular/hawkular-alerts/blob/master/hawkular-alerts-rest-tests/"
                      + "src/test/groovy/org/hawkular/alerts/rest/ConditionsITest.groovy") //
          String jsonCondition) {
    try {
      if (isEmpty(jsonCondition) || !jsonCondition.contains("type")) {
        return ResponseUtil.badRequest("json condition empty or without type");
      }

      ObjectMapper om = new ObjectMapper();
      JsonNode rootNode = om.readTree(jsonCondition);
      Condition condition = JacksonDeserializer.deserializeCondition(rootNode);

      if (condition == null) {
        return ResponseUtil.badRequest("Bad json condition");
      }
      condition.setTriggerId(triggerId);

      Collection<Condition> conditions;
      conditions =
          definitions.addCondition(
              tenantId, condition.getTriggerId(), condition.getTriggerMode(), condition);
      if (log.isDebugEnabled()) {
        log.debug("Conditions: " + conditions);
      }
      return ResponseUtil.ok(conditions);

    } catch (NotFoundException e) {
      return ResponseUtil.notFound(e.getMessage());
    } catch (Exception e) {
      log.debug(e.getMessage(), e);
      return ResponseUtil.internalError(e.getMessage());
    }
  }
  private static void printDebugInfo(HttpUriRequest request, HttpResponse response) {
    String br = System.getProperty("line.separator");
    StringBuffer builder = new StringBuffer();
    builder.append("URL: ");
    builder.append(request.getURI().toString());
    builder.append(br);
    builder.append("Request Headers: ");
    builder.append(headersToString(request.getAllHeaders()));
    builder.append(br);
    builder.append("Request Body: ");
    if (request instanceof HttpPost) {
      HttpPost post = (HttpPost) request;
      String body = "This body can't be outputted.";
      try {
        body = ResponseUtil.fromHttpEntityToString(post.getEntity(), "UTF-8");
      } catch (ResponseBodyParseException e) {
        Log.d(TAG, "Parsing request is failed.", e);
      }
      builder.append(body);
    } else {
      builder.append("No body by Get request.");
    }
    builder.append(br);
    builder.append("HTTP Status Code: ");
    builder.append(response.getStatusLine().getStatusCode());
    builder.append(br);
    builder.append("Response Headers: ");
    builder.append(headersToString(response.getAllHeaders()));
    builder.append(br);
    Header contentType = response.getFirstHeader("Content-Type");
    if (contentType != null && "application/json".equals(contentType.getValue())) {
      builder.append("Response Body: ");
      String body = "This body can't be outputted.";
      try {
        body = ResponseUtil.fromHttpEntityToString(response.getEntity(), "UTF-8");
        response.setEntity(new StringEntity(body, "UTF-8"));
      } catch (ResponseBodyParseException e) {
        Log.d(TAG, "Parsing response is failed.", e);
      } catch (UnsupportedEncodingException e) {
        Log.e(TAG, e.getMessage());
      }
      builder.append(body);
      builder.append(br);
    } else {
      builder.append("Response Body is binary data.");
      builder.append(br);
    }

    Log.d(TAG, builder.toString());
  }
 @GET
 @Path("/")
 @Produces(APPLICATION_JSON)
 @ApiOperation(value = "Get triggers with optional filtering")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success"),
       @ApiResponse(code = 500, message = "Internal server error")
     })
 public Response findTriggers(
     @ApiParam(
             required = false,
             value =
                 "filter out triggers for unspecified triggerIds, "
                     + "comma separated list of trigger IDs")
         @QueryParam("triggerIds")
         final String triggerIds,
     @ApiParam(
             required = false,
             value =
                 "filter out triggers for unspecified tags, comma separated list of "
                     + "tags, each tag of format 'name|value'. Specify '*' for value to match all values.")
         @QueryParam("tags")
         final String tags,
     @ApiParam(required = false, value = "return only thin triggers. Currently Ignored")
         @QueryParam("thin")
         final Boolean thin,
     @Context final UriInfo uri) {
   Pager pager = RequestUtil.extractPaging(uri);
   try {
     TriggersCriteria criteria = buildCriteria(triggerIds, tags, thin);
     Page<Trigger> triggerPage = definitions.getTriggers(tenantId, criteria, pager);
     if (log.isDebugEnabled()) {
       log.debug("Triggers: " + triggerPage);
     }
     if (isEmpty(triggerPage)) {
       return ResponseUtil.ok(triggerPage);
     }
     return ResponseUtil.paginatedOk(triggerPage, uri);
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
 @DELETE
 @Path("/{triggerId}/conditions/{conditionId}")
 @Produces(APPLICATION_JSON)
 @ApiOperation(
     value =
         "Deprecated : Use PUT /alerts/triggers/{triggerId}/conditions to set the entire "
             + "condition set in one service.")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Condition deleted"),
       @ApiResponse(code = 404, message = "No Condition found"),
       @ApiResponse(code = 500, message = "Internal server error"),
       @ApiResponse(code = 400, message = "Bad Request/Invalid Parameters")
     })
 @Deprecated
 public Response deleteCondition(
     @ApiParam(value = "Trigger definition id to be retrieved", required = true)
         @PathParam("triggerId")
         final String triggerId,
     @PathParam("conditionId") final String conditionId) {
   try {
     Trigger trigger = definitions.getTrigger(tenantId, triggerId);
     if (trigger == null) {
       return ResponseUtil.notFound("No trigger found for triggerId: " + triggerId);
     }
     Condition condition = definitions.getCondition(tenantId, conditionId);
     if (condition == null) {
       return ResponseUtil.notFound("No condition found for conditionId: " + conditionId);
     }
     if (!condition.getTriggerId().equals(triggerId)) {
       return ResponseUtil.badRequest(
           "ConditionId: " + conditionId + " does not belong to triggerId: " + triggerId);
     }
     Collection<Condition> conditions = definitions.removeCondition(tenantId, conditionId);
     if (log.isDebugEnabled()) {
       log.debug("Conditions: " + conditions);
     }
     return ResponseUtil.ok(conditions);
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
  @POST
  @Path("/groups/members/{memberId}/unorphan")
  @Consumes(APPLICATION_JSON)
  @ApiOperation(value = "Make a non-orphan member trigger into an orphan.")
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "Success, Trigger updated"),
        @ApiResponse(code = 500, message = "Internal server error"),
        @ApiResponse(code = 404, message = "Trigger doesn't exist/Invalid Parameters")
      })
  public Response unorphanMemberTrigger(
      @ApiParam(value = "Member Trigger id to be made an orphan.", required = true) //
          @PathParam("memberId") //
          final String memberId,
      @ApiParam(
              required = true,
              name = "memberTrigger",
              value = "Only context and dataIdMap are used when changing back to a non-orphan.") //
          final UnorphanMemberInfo unorphanMemberInfo) {
    try {
      if (null == unorphanMemberInfo) {
        return ResponseUtil.badRequest("MemberTrigger is null");
      }
      Trigger child =
          definitions.unorphanMemberTrigger(
              tenantId,
              memberId,
              unorphanMemberInfo.getMemberContext(),
              unorphanMemberInfo.getDataIdMap());
      if (log.isDebugEnabled()) {
        log.debug("Member Trigger: " + child);
      }
      return ResponseUtil.ok();

    } catch (NotFoundException e) {
      return ResponseUtil.notFound("Member Trigger " + memberId + " doesn't exist for update");

    } catch (Exception e) {
      log.debug(e.getMessage(), e);
      return ResponseUtil.internalError(e.getMessage());
    }
  }
 @PUT
 @Path("/tags")
 @Consumes(APPLICATION_JSON)
 @ApiOperation(value = "Add tags to existing Events.")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Events tagged successfully."),
       @ApiResponse(code = 500, message = "Internal server error.", response = ApiError.class),
       @ApiResponse(
           code = 400,
           message = "Bad Request/Invalid Parameters.",
           response = ApiError.class)
     })
 public Response addTags(
     @ApiParam(required = true, value = "Comma separated list of eventIds to tag.")
         @QueryParam("eventIds")
         final String eventIds,
     @ApiParam(
             required = true,
             value = "Comma separated list of tags to add, " + "each tag of format 'name|value'.")
         @QueryParam("tags")
         final String tags) {
   try {
     if (!isEmpty(eventIds) || isEmpty(tags)) {
       // criteria just used for convenient type translation
       EventsCriteria c = buildCriteria(null, null, eventIds, null, null, tags, false);
       alertsService.addEventTags(tenantId, c.getEventIds(), c.getTags());
       if (log.isDebugEnabled()) {
         log.debugf("Tagged alertIds:%s, %s", c.getEventIds(), c.getTags());
       }
       return ResponseUtil.ok();
     } else {
       return ResponseUtil.badRequest("EventIds and Tags required for adding tags");
     }
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     if (e.getCause() != null && e.getCause() instanceof IllegalArgumentException) {
       return ResponseUtil.badRequest("Bad arguments: " + e.getMessage());
     }
     return ResponseUtil.internalError(e);
   }
 }
  @DELETE
  @Path("/groups/{groupId}")
  @Consumes(APPLICATION_JSON)
  @Produces(APPLICATION_JSON)
  @ApiOperation(value = "Delete a group trigger.")
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "Success, Group Trigger Removed"),
        @ApiResponse(code = 500, message = "Internal server error"),
        @ApiResponse(code = 404, message = "Group Trigger not found"),
        @ApiResponse(code = 400, message = "Bad Request/Invalid Parameters")
      })
  public Response deleteGroupTrigger(
      @ApiParam(required = true, value = "Group Trigger id") //
          @PathParam("groupId") //
          final String groupId,
      @ApiParam(
              required = true,
              value = "Convert the non-orphan member triggers to standard triggers.") //
          @QueryParam("keepNonOrphans") //
          final boolean keepNonOrphans,
      @ApiParam(
              required = true,
              value = "Convert the orphan member triggers to standard triggers.") //
          @QueryParam("keepOrphans") //
          final boolean keepOrphans) {
    try {
      definitions.removeGroupTrigger(tenantId, groupId, keepNonOrphans, keepOrphans);
      if (log.isDebugEnabled()) {
        log.debug("Remove Group Trigger: " + tenantId + "/" + groupId);
      }
      return ResponseUtil.ok();

    } catch (NotFoundException e) {
      log.debug(e.getMessage(), e);
      return ResponseUtil.notFound(e.getMessage());
    } catch (Exception e) {
      log.debug(e.getMessage(), e);
      return ResponseUtil.internalError(e.getMessage());
    }
  }
 @DELETE
 @Path("/tags")
 @Consumes(APPLICATION_JSON)
 @ApiOperation(value = "Remove tags from existing Events.")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Events untagged successfully."),
       @ApiResponse(code = 500, message = "Internal server error.", response = ApiError.class),
       @ApiResponse(
           code = 400,
           message = "Bad Request/Invalid Parameters.",
           response = ApiError.class)
     })
 public Response deleteTags(
     @ApiParam(required = true, value = "Comma separated list of eventIds to untag.")
         @QueryParam("eventIds")
         final String eventIds,
     @ApiParam(required = true, value = "Comma separated list of tag names to remove.")
         @QueryParam("tagNames")
         final String tagNames) {
   try {
     if (!isEmpty(eventIds) || isEmpty(tagNames)) {
       Collection<String> ids = Arrays.asList(eventIds.split(","));
       Collection<String> tags = Arrays.asList(tagNames.split(","));
       alertsService.removeEventTags(tenantId, ids, tags);
       if (log.isDebugEnabled()) {
         log.debugf("Untagged eventIds:%s, %s", ids, tags);
       }
       return ResponseUtil.ok();
     } else {
       return ResponseUtil.badRequest("EventIds and Tags required for removing tags");
     }
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     if (e.getCause() != null && e.getCause() instanceof IllegalArgumentException) {
       return ResponseUtil.badRequest("Bad arguments: " + e.getMessage());
     }
     return ResponseUtil.internalError(e);
   }
 }
 @POST
 @Path("/")
 @Consumes(APPLICATION_JSON)
 @Produces(APPLICATION_JSON)
 @ApiOperation(
     value = "Create a new Event.",
     notes = "Returns created Event.",
     response = Event.class)
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Event Created."),
       @ApiResponse(code = 500, message = "Internal server error.", response = ApiError.class),
       @ApiResponse(
           code = 400,
           message = "Bad Request/Invalid Parameters.",
           response = ApiError.class)
     })
 public Response createEvent(
     @ApiParam(
             value = "Event to be created. Category and Text fields required,",
             name = "event",
             required = true)
         final Event event) {
   try {
     if (null != event) {
       if (isEmpty(event.getId())) {
         return ResponseUtil.badRequest("Event with id null.");
       }
       if (isEmpty(event.getCategory())) {
         return ResponseUtil.badRequest("Event with category null.");
       }
       event.setTenantId(tenantId);
       if (null != alertsService.getEvent(tenantId, event.getId(), true)) {
         return ResponseUtil.badRequest("Event with ID [" + event.getId() + "] exists.");
       }
       /*
          New events are sent directly to the engine for inference process.
          Input events and new ones generated by the alerts engine are persisted at the end of the process.
       */
       alertsService.addEvents(Collections.singletonList(event));
       if (log.isDebugEnabled()) {
         log.debug("Event: " + event.toString());
       }
       return ResponseUtil.ok(event);
     } else {
       return ResponseUtil.badRequest("Event is null");
     }
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     if (e.getCause() != null && e.getCause() instanceof IllegalArgumentException) {
       return ResponseUtil.badRequest("Bad arguments: " + e.getMessage());
     }
     return ResponseUtil.internalError(e);
   }
 }
 @POST
 @Path("/groups/{groupId}/dampenings")
 @Consumes(APPLICATION_JSON)
 @Produces(APPLICATION_JSON)
 @ApiOperation(
     value = "Create a new group dampening",
     notes = "Returns Dampening created if operation finishes correctly")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Dampening created"),
       @ApiResponse(code = 500, message = "Internal server error"),
       @ApiResponse(code = 400, message = "Bad Request/Invalid Parameters")
     })
 public Response createGroupDampening(
     @ApiParam(value = "Group Trigger definition id attached to dampening", required = true) //
         @PathParam("groupId") //
         final String groupId,
     @ApiParam(value = "Dampening definition to be created", required = true) //
         final Dampening dampening) {
   try {
     dampening.setTriggerId(groupId);
     boolean exists = (definitions.getDampening(tenantId, dampening.getDampeningId()) != null);
     if (!exists) {
       // make sure we have the best chance of clean data..
       Dampening d = getCleanDampening(dampening);
       definitions.addGroupDampening(tenantId, d);
       if (log.isDebugEnabled()) {
         log.debug("Dampening: " + d);
       }
       return ResponseUtil.ok(d);
     } else {
       return ResponseUtil.badRequest(
           "Existing dampening for dampeningId: " + dampening.getDampeningId());
     }
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
 @PUT
 @Path("/groups/{groupId}/dampenings/{dampeningId}")
 @Consumes(APPLICATION_JSON)
 @ApiOperation(
     value =
         "Update an existing group dampening definition. Note that trigger mode can not be changed.")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success, Dampening Updated"),
       @ApiResponse(code = 404, message = "No Dampening Found"),
       @ApiResponse(code = 500, message = "Internal server error")
     })
 public Response updateGroupDampening(
     @ApiParam(value = "Trigger definition id to be retrieved", required = true)
         @PathParam("groupId")
         final String groupId,
     @ApiParam(value = "Dampening id", required = true) @PathParam("dampeningId")
         final String dampeningId,
     @ApiParam(value = "Updated dampening definition", required = true)
         final Dampening dampening) {
   try {
     boolean exists = (definitions.getDampening(tenantId, dampeningId) != null);
     if (exists) {
       // make sure we have the best chance of clean data..
       Dampening d = getCleanDampening(dampening);
       definitions.updateGroupDampening(tenantId, d);
       if (log.isDebugEnabled()) {
         log.debug("Group Dampening: " + d);
       }
       return ResponseUtil.ok(d);
     } else {
       return ResponseUtil.notFound("No dampening found for dampeningId: " + dampeningId);
     }
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
 @GET
 @Path("/{triggerId}/dampenings")
 @Produces(APPLICATION_JSON)
 @ApiOperation(value = "Get all Dampenings for a Trigger (1 Dampening per mode).")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success"),
       @ApiResponse(code = 500, message = "Internal server error")
     })
 public Response getTriggerDampenings(
     @ApiParam(value = "Trigger definition id to be retrieved", required = true)
         @PathParam("triggerId")
         final String triggerId) {
   try {
     Collection<Dampening> dampenings =
         definitions.getTriggerDampenings(tenantId, triggerId, null);
     log.debug("Dampenings: " + dampenings);
     return ResponseUtil.ok(dampenings);
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
 @GET
 @Path("/{triggerId}/conditions")
 @Produces(APPLICATION_JSON)
 @ApiOperation(value = "Get all conditions for a specific trigger.")
 @ApiResponses(
     value = {
       @ApiResponse(code = 200, message = "Success"),
       @ApiResponse(code = 500, message = "Internal server error")
     })
 public Response getTriggerConditions(
     @ApiParam(value = "Trigger definition id to be retrieved", required = true)
         @PathParam("triggerId")
         final String triggerId) {
   try {
     Collection<Condition> conditions =
         definitions.getTriggerConditions(tenantId, triggerId, null);
     log.debug("Conditions: " + conditions);
     return ResponseUtil.ok(conditions);
   } catch (Exception e) {
     log.debug(e.getMessage(), e);
     return ResponseUtil.internalError(e.getMessage());
   }
 }
示例#27
0
 /**
  * Execute the request and return the POJO that represent the response.
  *
  * @param <T> The POJO that represents the response object
  * @param resourcePath the resource path
  * @param params the request parameters
  * @param returnType the POJO class to be parsed from the response
  * @return the POJO object that represent the response
  */
 private <T> T executeRequest(
     String resourcePath, Map<String, Object> params, Class<T> returnType) {
   Request request = Request.Get(resourcePath);
   if (params != null && !params.isEmpty()) {
     for (Map.Entry<String, Object> entry : params.entrySet()) {
       request.withQuery(entry.getKey(), entry.getValue());
     }
   }
   HttpRequestBase requestBase = request.build();
   try {
     HttpResponse response = execute(requestBase);
     return ResponseUtil.getObject(response, returnType);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
  @PUT
  @Path("/{triggerId}/conditions/{conditionId}")
  @Produces(APPLICATION_JSON)
  @ApiOperation(
      value =
          "Deprecated : Use PUT /alerts/triggers/{triggerId}/conditions to set the entire "
              + "condition set in one service.")
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "Success, Condition updated"),
        @ApiResponse(code = 404, message = "No Condition found"),
        @ApiResponse(code = 500, message = "Internal server error"),
        @ApiResponse(code = 400, message = "Bad Request/Invalid Parameters")
      })
  @Deprecated
  public Response updateCondition(
      @ApiParam(value = "Trigger definition id to be retrieved", required = true)
          @PathParam("triggerId")
          final String triggerId,
      @PathParam("conditionId") final String conditionId,
      @ApiParam(value = "Json representation of a condition") String jsonCondition) {
    try {
      Trigger trigger = definitions.getTrigger(tenantId, triggerId);
      if (trigger == null) {
        return ResponseUtil.notFound("No trigger found for triggerId: " + triggerId);
      }
      if (isEmpty(jsonCondition) || !jsonCondition.contains("type")) {
        return ResponseUtil.badRequest("json condition empty or without type");
      }

      ObjectMapper om = new ObjectMapper();
      JsonNode rootNode = om.readTree(jsonCondition);
      Condition condition = JacksonDeserializer.deserializeCondition(rootNode);
      if (condition == null) {
        return ResponseUtil.badRequest("Bad json condition");
      }
      condition.setTriggerId(triggerId);
      boolean exists = false;
      if (conditionId.equals(condition.getConditionId())) {
        exists = (definitions.getCondition(tenantId, condition.getConditionId()) != null);
      }
      if (!exists) {
        return ResponseUtil.notFound("Condition not found for conditionId: " + conditionId);
      } else {
        Collection<Condition> conditions = definitions.updateCondition(tenantId, condition);
        if (log.isDebugEnabled()) {
          log.debug("Conditions: " + conditions);
        }
        return ResponseUtil.ok(conditions);
      }
    } catch (Exception e) {
      log.debug(e.getMessage(), e);
      return ResponseUtil.internalError(e.getMessage());
    }
  }
  @POST
  @Path("/groups/members")
  @Consumes(APPLICATION_JSON)
  @Produces(APPLICATION_JSON)
  @ApiOperation(
      value = "Create a new member trigger for a parent trigger.",
      response = Trigger.class,
      notes = "Returns Member Trigger created if operation finished correctly")
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "Success, Member Trigger Created"),
        @ApiResponse(code = 500, message = "Internal server error"),
        @ApiResponse(code = 404, message = "Group trigger not found."),
        @ApiResponse(code = 400, message = "Bad Request/Invalid Parameters")
      })
  public Response createGroupMember(
      @ApiParam(
              value = "Group member trigger to be created",
              name = "groupMember",
              required = true) //
          final GroupMemberInfo groupMember) {
    try {
      if (null == groupMember) {
        return ResponseUtil.badRequest("MemberTrigger is null");
      }
      String groupId = groupMember.getGroupId();
      String memberName = groupMember.getMemberName();
      if (isEmpty(groupId)) {
        return ResponseUtil.badRequest("MemberTrigger groupId is null");
      }
      if (isEmpty(memberName)) {
        return ResponseUtil.badRequest("MemberTrigger memberName is null");
      }
      Trigger child =
          definitions.addMemberTrigger(
              tenantId,
              groupId,
              groupMember.getMemberId(),
              memberName,
              groupMember.getMemberContext(),
              groupMember.getDataIdMap());
      if (log.isDebugEnabled()) {
        log.debug("Child Trigger: " + child.toString());
      }
      return ResponseUtil.ok(child);

    } catch (NotFoundException e) {
      log.debug(e.getMessage(), e);
      return ResponseUtil.notFound(e.getMessage());
    } catch (Exception e) {
      log.debug(e.getMessage(), e);
      return ResponseUtil.internalError(e.getMessage());
    }
  }
 private static void retryStringOperation(
     String methodId,
     String id,
     Object message,
     ThrowableFutureBiConsumer<AsyncResult<Message<Object>>, String> stringFunction,
     DeliveryOptions deliveryOptions,
     Vertx vertx,
     Throwable t,
     Consumer<Throwable> errorMethodHandler,
     RoutingContext context,
     Map<String, String> headers,
     Encoder encoder,
     Consumer<Throwable> errorHandler,
     ThrowableErrorConsumer<Throwable, String> onFailureRespond,
     int httpStatusCode,
     int retryCount,
     long timeout,
     long circuitBreakerTimeout) {
   ResponseUtil.handleError(errorHandler, t);
   mapToStringResponse(
           methodId,
           id,
           message,
           stringFunction,
           deliveryOptions,
           vertx,
           t,
           errorMethodHandler,
           context,
           headers,
           null,
           encoder,
           errorHandler,
           onFailureRespond,
           httpStatusCode,
           retryCount - 1,
           timeout,
           circuitBreakerTimeout)
       .execute();
 }