Java com.codahale.metrics.annotation.Timed 代码实例

・14 分钟阅读

以下是展示如何使用com.codahale.metrics.annotation.Timed的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


/**
 * GET  /rest/authenticate -> check if the user is authenticated, and return its login.
 */
@RequestMapping(value = "/rest/authenticate",
        method = RequestMethod.GET,
        produces = "application/json")
@Timed
public String isAuthenticated(HttpServletRequest request) {
    log.debug("REST request to check if the current user is authenticated");
    return request.getRemoteUser();
}
 

实例 2


@POST
@Timed
@Consumes(MediaType.APPLICATION_JSON)
@Path("/single")
public void single(@Context Request request,
                   @HeaderParam("X-Tenant-Id") String tenantId,
                   @HeaderParam("X-Roles") String roles,
                   @HeaderParam("X-Application-Type") String applicationType,
                   @HeaderParam("X-Dimensions") String dimensionsStr,
                   @QueryParam("tenant_id") String crossTenantId,
                   String payload) {
  LOGGER.debug("/single/{}", tenantId);
  if (!this.isDelegate(roles)) {
    LOGGER.trace(String.format("/single/%s is not delegated request, checking for crossTenantId",
        tenantId));
    if (!Strings.isNullOrEmpty(crossTenantId)) {
      throw Exceptions.forbidden("Project %s cannot POST cross tenant metrics", tenantId);
    }
  }
  final Log log = service.newLog(
      new LogRequestBean()
          .setApplicationType(applicationType)
          .setDimensions(this.getDimensions(dimensionsStr))
          .setContentType(this.getContentType(request))
          .setPayload(payload),
      VALIDATE_LOG
  );
  tenantId = this.getTenantId(tenantId, crossTenantId);
  LOGGER.debug("Shipping log={},tenantId={} pair to kafka", log, tenantId);
  this.service.sendToKafka(log, tenantId);
}
 

实例 3


/***
 * Application Health Checks
 * @return response
 */
@Path(value="/check")
@GET
@Timed
public Response check(){
        final SortedMap<String, HealthCheck.Result> results = this.health.runHealthChecks();
        for(Entry<String, Result> entryResult : results.entrySet()){
                if(!entryResult.getValue().isHealthy()){
                        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(entryResult.getValue().getMessage()).build();
                }
        }
        return Response.status(Status.OK).entity("Healthy!").build();
}
 

实例 4


@POST
@UnitOfWork(readOnly = true, transactional = false,
        cacheMode = CacheMode.GET, flushMode = FlushMode.MANUAL)
@Timed
public Response enforce(@Tenant String tenant,
        String xacmlRequest) {
    LOGGER.debug("Enforcing policies for tenant [{}]", tenant);
    LOGGER.trace("XACML Request: {}", xacmlRequest);
    PDP pdp = pdpFactory.get(tenant, extractSubjectIds(xacmlRequest));
    return Response.ok(pdp.evaluate(xacmlRequest)).build();
}
 

实例 5


@GET
@Timed
@ApiResponses(value = {
        @ApiResponse(code = 200, response = Order[].class, message = ""),
        @ApiResponse(code = 403, response = ErrorR.class, message = "Unauthorized")
})
public Response getAll() {
    return Response.ok(ordersDAO.findAll(), MediaType.APPLICATION_JSON_TYPE).build();
}
 

实例 6


@Override
@Transactional(readOnly = false)
@Timed(name = "GET_TOKEN_TIMER")
@Metered(name = "GET_TOKEN_METER")
@Counted(name="GET_TOKEN_COUNTER", monotonic=true)
public <T extends Token> T getToken(final String tokenId, final Class<T> clazz)
        throws InvalidTokenException {
    Assert.notNull(tokenId, "tokenId cannot be null");
    final T token = this.tokenRegistry.getToken(tokenId, clazz);
    if (token == null) {
        LOGGER.error("Token [{}] by type [{}] cannot be found in the token registry.", tokenId, clazz.getSimpleName());
        throw new InvalidTokenException(tokenId);
    }
    if (token.getTicket().isExpired()) {
        // cleanup the expired ticket and token.
        ticketRegistry.deleteTicket(token.getTicket().getId());
        LOGGER.error("Token [{}] ticket [{}] is expired.", tokenId, token.getTicket().getId());
        throw new InvalidTokenException(tokenId);
    }
    return token;
}
 

实例 7


/**
 * POST  /register -> register the user.
 */
@RequestMapping(value = "/register",
        method = RequestMethod.POST,
        produces = MediaType.TEXT_PLAIN_VALUE)
@Timed
public ResponseEntity<?> registerAccount(@Valid @RequestBody UserDTO userDTO, HttpServletRequest request) {
    User user = userRepository.findOneByLogin(userDTO.getLogin());
    if (user != null) {
        return ResponseEntity.badRequest().contentType(MediaType.TEXT_PLAIN).body("login already in use");
    } else {
        if (userRepository.findOneByEmail(userDTO.getEmail()) != null) {
            return ResponseEntity.badRequest().contentType(MediaType.TEXT_PLAIN).body("e-mail address already in use");
        }
        user = userService.createUserInformation(userDTO.getLogin(), userDTO.getPassword(),
        userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail().toLowerCase(),
        userDTO.getLangKey());
        String baseUrl = request.getScheme() + // "http"
        "://" +                            // "://"
        request.getServerName() +          // "myhost"
        ":" +                              // ":"
        request.getServerPort();           // "80"
        mailService.sendActivationEmail(user, baseUrl);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
}
 

实例 8


@RequestMapping(value = "/api/user", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@Timed
public void createUser(@RequestBody UserCreate userCreate) throws UserExistsException {
    LOGGER.debug("Received create user request {}", userCreate);
    if (!auctionUserDao.createUser(userCreate)) throw new UserExistsException();
}
 

实例 9


@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
  String timerTag = buildTimerTag(invocation.getMethod().getAnnotation(Timed.class), invocation.getMethod());
  final Timer.Context timer = metricRegistry.timer(timerTag).time();
  try {
    return invocation.proceed();
  } finally {
    timer.stop();
  }
}
 

实例 10


@GET
@Path("/named")
@Timed
@Produces("text/plain")
public String saySpecialHello(@Auth HelloAccount account) {
  return "Hello " + account.getUsername();
}
 

实例 11


/**
 * POST  /bankAccounts -> Create a new bankAccount.
 */
@RequestMapping(value = "/bankAccounts",
    method = RequestMethod.POST,
    produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<BankAccount> createBankAccount(@Valid @RequestBody BankAccount bankAccount) throws URISyntaxException {
    log.debug("REST request to save BankAccount : {}", bankAccount);
    if (bankAccount.getId() != null) {
        return ResponseEntity.badRequest().header("Failure", "A new bankAccount cannot already have an ID").body(null);
    }
    BankAccount result = bankAccountRepository.save(bankAccount);
    return ResponseEntity.created(new URI("/api/bankAccounts/" + result.getId()))
        .headers(HeaderUtil.createEntityCreationAlert("bankAccount", result.getId().toString()))
        .body(result);
}
 

实例 12


@POST
@Timed
@Path(value = "/login")
public Response login(@FormParam("username") String username,
                      @FormParam("password") String password, @Context final HttpServletRequest request) {
    WebTarget target = client.target(tokenUrl);
    Invocation.Builder builder = target.request();
    Form form = new Form();
    form.param("grant_type", "password");
    form.param("username", username);
    form.param("password", password);
    form.param("scope", cfg.getScope());
    form.param("client_id", cfg.getClient_id());
    form.param("client_secret", cfg.getClient_secret());
    Response response = builder.accept(MediaType.APPLICATION_JSON)
            .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED));
    if (response.getStatus() != HttpStatus.SC_OK) {
        response.close();
        return Response.
                status(Response.Status.UNAUTHORIZED).entity("{ "error": "auth failed"}").build();
    }
    try {
        AccessToken token = response.readEntity(AccessToken.class);
        NewCookie nc = engine.buildCookie(username, token, request.getServerName());
        return Response.ok().cookie(nc).build();
    } catch (Exception ex) {
        log.error("Error while building login response", ex);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } finally {
        response.close();
    }
}
 

实例 13


@POST
@UnitOfWork(flushMode = FlushMode.ALWAYS)
@Path("login")
@Timed
public Response login(@Context HttpServletRequest request, Map<String, String> credentials) throws Exception {
    Optional<User> user = userDao.findByUsername(credentials.get("username"));
    if (!user.isPresent()) {
        throw new WebApplicationException(Response.Status.UNAUTHORIZED);
    } else if (user.get().getPassword().equals(credentials.get("password"))) {
        if (!user.get().isActive())
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("User blocked.").build();
        Map<String, String> attributes = new HashMap<>();
        attributes.put("userAgent", request.getHeader("User-Agent"));
        attributes.put("remoteAddr", request.getRemoteAddr());
        Token token = TokenFactory.getInstance().createToken(user.get().getUserId(), user.get().getEmail(), DateTime.now(), attributes);
        token.setExpiration(token.getMaxAge());
        credentials.remove("password");
        credentials.put("domain", TokenBasedAuthResponseFilter.getTokenSentence("dummy"));
        user.get().setLastLoginTime(DateTime.now().toDate());
        user.get().setFailCount(0);
        logAction(new ActionLog("LOGIN", null, user.get().toString(), true));
        return Response.ok().header("Set-Cookie", TokenBasedAuthResponseFilter.getTokenSentence(token.getTokenString())).entity(credentials).build();
    } else {
        if (!user.get().isActive()) {
            logAction(new ActionLog("LOGIN", "Blocked", user.get().toString(), false));
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("User blocked.").build();
        }
        int failCount = user.get().getFailCount() + 1;
        user.get().setFailCount(failCount);
        boolean block = failCount >= Integer.valueOf((String) SystemParameterCache.get("USER_BLOCK_FAIL_LIMIT", "3"));
        if (block)
            user.get().setActive(false);
        userDao.update(user.get());
        logAction(new ActionLog("LOGIN", "Wrong Password", user.get().toString(), false));
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
}
 

实例 14


@GET
@Timed
public Saying get(@QueryParam("name") Optional<String> name,
        @QueryParam("sleep") Optional<Integer> sleepParameter) throws InterruptedException, SuspendExecution {
    Fiber.sleep(sleepParameter.or(10));
    return new Saying(ai.incrementAndGet(), name.or("name"));
}
 

实例 15


@PUT
@Path("/newpassword")
@Timed
public Response newPassword(ForgotpassDTO forgotpassDTO) {
    PlayerAction playerAction = new PlayerAction(db);
    boolean yes = playerAction.newPassword(forgotpassDTO);
    if (yes) {
        return Response.ok().build();
    } else {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
}
 
讨论
淘淘あ西西 profile image