default <T> CompletableFuture<T> runPublishingTimerMetric(String name, CompletableFuture<T> future) { TimeMetric timer = timer(name); return future.whenComplete((result, throwable) -> timer.stopAndPublish()); } }
default <T> T runPublishingTimerMetric(String name, Supplier<T> operation) { TimeMetric timer = timer(name); try { return operation.get(); } finally { timer.stopAndPublish(); } }
default <T> T runPublishingTimerMetric(String name, Supplier<T> operation) { TimeMetric timer = timer(name); try { return operation.get(); } finally { timer.stopAndPublish(); } }
@Override public void deliver(MailboxListener mailboxListener, Event event) { TimeMetric timer = metricFactory.timer("mailbox-listener-" + mailboxListener.getClass().getSimpleName()); try { mailboxListener.event(event); } catch (Throwable throwable) { LOGGER.error("Error while processing listener {} for {}", mailboxListener.getClass().getCanonicalName(), event.getClass().getCanonicalName(), throwable); } finally { timer.stopAndPublish(); } } }
private HttpServletRequest authenticate(HttpServletRequest httpRequest) { TimeMetric timeMetric = metricFactory.timer("JMAP-authentication-filter"); try { return authMethods.stream() .flatMap(auth -> createSession(auth, httpRequest)) .findFirst() .map(mailboxSession -> addSessionToRequest(httpRequest, mailboxSession)) .orElseThrow(UnauthorizedException::new); } finally { timeMetric.stopAndPublish(); } }
@Override public void handle(Request request, Response response) throws Exception { if (request.attribute(MetricPreFilter.METRICS) instanceof TimeMetric) { TimeMetric timeMetric = request.attribute(MetricPreFilter.METRICS); timeMetric.stopAndPublish(); } } }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { TimeMetric timeMetric = metricFactory.timer("JMAP-request"); try { List<Object[]> responses = requestAsJsonStream(req) .map(ProtocolRequest::deserialize) .map(x -> AuthenticatedProtocolRequest.decorate(x, req)) .flatMap(this::handle) .map(ProtocolResponse::asProtocolSpecification) .collect(Collectors.toList()); resp.setContentType(JSON_CONTENT_TYPE); objectMapper.writeValue(resp.getOutputStream(), responses); } catch (IOException e) { LOGGER.warn("error handling request", e); resp.setStatus(SC_BAD_REQUEST); } catch (Exception e) { LOGGER.error("Error handling request", e); throw new ServletException(e); } finally { timeMetric.stopAndPublish(); } }
@VisibleForTesting void createMailboxesIfNeeded(MailboxSession session) { TimeMetric timeMetric = metricFactory.timer("JMAP-mailboxes-provisioning"); try { User user = session.getUser(); createDefaultMailboxes(user); } catch (MailboxException e) { throw new RuntimeException(e); } finally { timeMetric.stopAndPublish(); } }
@Override public Collection<String> findMXRecords(String hostname) throws TemporaryResolutionException { TimeMetric timeMetric = metricFactory.timer("findMXRecords"); List<String> servers = new ArrayList<>(); try { servers = findMXRecordsRaw(hostname); return Collections.unmodifiableCollection(servers); } finally { // If we found no results, we'll add the original domain name if // it's a valid DNS entry if (servers.size() == 0) { LOGGER.info("Couldn't resolve MX records for domain {}.", hostname); try { getByName(hostname); servers.add(hostname); } catch (UnknownHostException uhe) { // The original domain name is not a valid host, // so we can't add it to the server list. In this // case we return an empty list of servers LOGGER.error("Couldn't resolve IP address for host {}.", hostname, uhe); } } timeMetric.stopAndPublish(); } }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { TimeMetric timeMetric = metricFactory.timer("JMAP-download-post"); String pathInfo = req.getPathInfo(); try { respondAttachmentAccessToken(getMailboxSession(req), DownloadPath.from(pathInfo), resp); } catch (IllegalArgumentException e) { LOGGER.error("Error while generating attachment access token '{}'", pathInfo, e); resp.setStatus(SC_BAD_REQUEST); } finally { timeMetric.stopAndPublish(); } }
@Override public Collection<String> findMXRecords(String hostname) throws TemporaryResolutionException { TimeMetric timeMetric = metricFactory.timer("findMXRecords"); List<String> servers = new ArrayList<>(); try { servers = findMXRecordsRaw(hostname); return Collections.unmodifiableCollection(servers); } finally { // If we found no results, we'll add the original domain name if // it's a valid DNS entry if (servers.size() == 0) { LOGGER.info("Couldn't resolve MX records for domain {}.", hostname); try { getByName(hostname); servers.add(hostname); } catch (UnknownHostException uhe) { // The original domain name is not a valid host, // so we can't add it to the server list. In this // case we return an empty list of servers LOGGER.error("Couldn't resolve IP address for host {}.", hostname, uhe); } } timeMetric.stopAndPublish(); } }
@Override public Collection<String> findTXTRecords(String hostname) { TimeMetric timeMetric = metricFactory.timer("findTXTRecords"); List<String> txtR = new ArrayList<>(); Record[] records = lookupNoException(hostname, Type.TXT, "TXT"); try { if (records != null) { for (Record record : records) { TXTRecord txt = (TXTRecord) record; txtR.add(txt.rdataToString()); } } return txtR; } finally { timeMetric.stopAndPublish(); } }
@Override public Collection<String> findTXTRecords(String hostname) { TimeMetric timeMetric = metricFactory.timer("findTXTRecords"); List<String> txtR = new ArrayList<>(); Record[] records = lookupNoException(hostname, Type.TXT, "TXT"); try { if (records != null) { for (Record record : records) { TXTRecord txt = (TXTRecord) record; txtR.add(txt.rdataToString()); } } return txtR; } finally { timeMetric.stopAndPublish(); } }
@Override public Collection<InetAddress> getAllByName(String host) throws UnknownHostException { TimeMetric timeMetric = metricFactory.timer("getAllByName"); String name = allowIPLiteral(host); try { // Check if its local if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName) || name.equals(localAddress)) { return ImmutableList.of(getLocalHost()); } InetAddress addr = org.xbill.DNS.Address.getByAddress(name); return ImmutableList.of(addr); } catch (UnknownHostException e) { Record[] records = lookupNoException(name, Type.A, "A"); if (records != null && records.length >= 1) { InetAddress[] addrs = new InetAddress[records.length]; for (int i = 0; i < records.length; i++) { ARecord a = (ARecord) records[i]; addrs[i] = InetAddress.getByAddress(name, a.getAddress().getAddress()); } return ImmutableList.copyOf(addrs); } else { throw e; } } finally { timeMetric.stopAndPublish(); } }
private void respondAttachmentAccessToken(MailboxSession mailboxSession, DownloadPath downloadPath, HttpServletResponse resp) { TimeMetric timeMetric = metricFactory.timer("JMAP-download-get"); String blobId = downloadPath.getBlobId(); try { if (! attachmentExists(mailboxSession, blobId)) { resp.setStatus(SC_NOT_FOUND); return; } resp.setContentType(TEXT_PLAIN_CONTENT_TYPE); resp.getOutputStream().print(simpleTokenFactory.generateAttachmentAccessToken(mailboxSession.getUser().getUserName(), blobId).serialize()); resp.setStatus(SC_OK); } catch (MailboxException | IOException e) { LOGGER.error("Error while asking attachment access token", e); resp.setStatus(SC_INTERNAL_SERVER_ERROR); } finally { timeMetric.stopAndPublish(); } }
processingActive.decrementAndGet(); numActive.decrementAndGet(); timeMetric.stopAndPublish();
@Override public SetMailboxesResponse process(SetMailboxesRequest request, MailboxSession mailboxSession) { TimeMetric timeMetric = metricFactory.timer(JMAP_PREFIX + "SetMailboxesCreationProcessor"); SetMailboxesResponse.Builder builder = SetMailboxesResponse.builder(); try { Map<MailboxCreationId, MailboxId> creationIdsToCreatedMailboxId = new HashMap<>(); sortingHierarchicalCollections.sortFromRootToLeaf(request.getCreate().entrySet()) .forEach(entry -> createMailbox(entry.getKey(), entry.getValue(), mailboxSession, creationIdsToCreatedMailboxId, builder)); } catch (CycleDetectedException e) { markRequestsAsNotCreatedDueToCycle(request, builder); } timeMetric.stopAndPublish(); return builder.build(); }
@VisibleForTesting void createAccountIfNeeded(MailboxSession session) { TimeMetric timeMetric = metricFactory.timer("JMAP-user-provisioning"); try { User user = session.getUser(); if (needsAccountCreation(user)) { createAccount(user); } } catch (AlreadyExistInUsersRepositoryException e) { // Ignore } catch (UsersRepositoryException e) { throw new RuntimeException(e); } finally { timeMetric.stopAndPublish(); } }
@Override public Collection<InetAddress> getAllByName(String host) throws UnknownHostException { TimeMetric timeMetric = metricFactory.timer("getAllByName"); String name = allowIPLiteral(host); try { // Check if its local if (name.equalsIgnoreCase(localHostName) || name.equalsIgnoreCase(localCanonicalHostName) || name.equals(localAddress)) { return ImmutableList.of(getLocalHost()); } InetAddress addr = org.xbill.DNS.Address.getByAddress(name); return ImmutableList.of(addr); } catch (UnknownHostException e) { Record[] records = lookupNoException(name, Type.A, "A"); if (records != null && records.length >= 1) { InetAddress[] addrs = new InetAddress[records.length]; for (int i = 0; i < records.length; i++) { ARecord a = (ARecord) records[i]; addrs[i] = InetAddress.getByAddress(name, a.getAddress().getAddress()); } return ImmutableList.copyOf(addrs); } else { throw e; } } finally { timeMetric.stopAndPublish(); } }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String contentType = req.getContentType(); if (Strings.isNullOrEmpty(contentType)) { resp.setStatus(SC_BAD_REQUEST); } else { TimeMetric timeMetric = metricFactory.timer("JMAP-upload-post"); try { uploadHandler.handle(contentType, req.getInputStream(), getMailboxSession(req), resp); } catch (IOException e) { if (e instanceof EOFException) { LOGGER.info("An upload has been canceled before the end", e); } else { internalServerError(resp, e); } } catch (MailboxException e) { internalServerError(resp, e); } finally { timeMetric.stopAndPublish(); } } }