Helper method which creates the metrics for the current response and publishes them if enabled.

@param response the response which is needed as context.
169652
private void writeMetrics(final CouchbaseResponse response) {
        if (currentRequest != null && currentOpTime >= 0 && env() != null
            && env().networkLatencyMetricsCollector().isEnabled()) {

            try {
                Class<? extends CouchbaseRequest> requestClass = currentRequest.getClass();
                String simpleName = classNameCache.get(requestClass);
                if (simpleName == null) {
                    simpleName = requestClass.getSimpleName();
                    classNameCache.put(requestClass, simpleName);
                }

                NetworkLatencyMetricsIdentifier identifier = new NetworkLatencyMetricsIdentifier(
                        remoteHostname,
                        serviceType().toString(),
                        simpleName,
                        response.status().toString()
                );
                env().networkLatencyMetricsCollector().record(identifier, currentOpTime);
            } catch (Throwable e) {
                LOGGER.warn("Could not collect latency metric for request {} ({})",
                    user(currentRequest.toString()),
                    currentOpTime,
                    e
                );
            }
        }
    }
1312931
@Override
	public void onAdd(Response response) {
		String message = gson.toJson(response);
		
		try {
			ActiveMqUtils.sendMessage(message, buildQueueNames(response), environment);
		} catch (JMSException e) {
			logger.error("Failed to send response message to output queue.", e);
		}
	}
638697
public void writeTo(HttpServletResponse response) {
		long time = System.currentTimeMillis();
		long processTime = time - contextTsCurrent.get();
		long processTimeTotal = contextMsProcess.get() + processTime;
		long networkTimeTotal = contextMsNetwork.get();
		
		StringBuilder cookiesDump = new StringBuilder();
		for (Entry<String, Cookie> entry : responseCookies.get().entrySet()) {
			javax.servlet.http.Cookie c = buildServletCookie(entry.getKey(), entry.getValue());
			response.addCookie(c);
			cookiesDump.append(c.toString()).append(";");
		}
		
		if (verbose) log.info("<<< Time total " + String.valueOf(time - contextTsStart.get()) + " (+" + processTime + "p " + processTimeTotal + "p " + networkTimeTotal + "n)" + " [" + contextUrl.get() + "]" + ". Set-Cookie to client: " + cookiesDump.toString());
	}
925464
@SuppressWarnings("unchecked")
    public static void after(Object request, Object response) {

        HttpData data = new HttpData();

        /*
         * Use reflection to access the HttpServletRequest/Response as using the
         * true method signature caused ClassLoader issues.
         */
        Class<?> reqClass = request.getClass();
        Class<?> respClass = response.getClass();
        try {
            /*
             * Retrieve the request tracker
             */
            Method getAttribute = reqClass.getMethod(GET_ATTRIBUTE, String.class);
            Method setAttribute = reqClass.getMethod(SET_ATTRIBUTE, String.class, Object.class);
            HttpRequestTracker tracker = (HttpRequestTracker) (getAttribute.invoke(request, TRACKER_ATTRIBUTE));
            if (tracker == null) {
                /*
                 * should never happen
                 */
                throw new JavametricsException("Unable to find request tracker");
            }

            /*
             * Decrement the nesting level and return if still nested
             */
            if (tracker.decrement()) {
                setAttribute.invoke(request, TRACKER_ATTRIBUTE, tracker);
                return;
            }

            /*
             * Clear the tracker
             */
            setAttribute.invoke(request, TRACKER_ATTRIBUTE, null);

            data.setRequestTime(tracker.getRequestTime());

            Method getRequestURL = reqClass.getMethod(GET_REQUEST_URL);
            data.setUrl(((StringBuffer) getRequestURL.invoke(request)).toString());

            Method getMethod = reqClass.getMethod(GET_METHOD);
            data.setMethod((String) getMethod.invoke(request));

            Method getStatus = respClass.getMethod(GET_STATUS);
            data.setStatus((Integer) getStatus.invoke(response));

            if (detailed) {
                Method getContentType = respClass.getMethod(GET_CONTENT_TYPE);
                data.setContentType((String) getContentType.invoke(response));

                Method getHeaders = respClass.getMethod(GET_HEADER_NAMES);
                Method getHeader = respClass.getMethod(GET_HEADER, String.class);
                Collection<String> headers = (Collection<String>) getHeaders.invoke(response);
                if (headers != null) {
                    for (String headerName : headers) {
                        String header = (String) getHeader.invoke(response, headerName);
                        if (header != null) {
                            data.addHeader(headerName, header);
                        }
                    }
                }

                Method getReqHeaders = reqClass.getMethod(GET_HEADER_NAMES);
                Method getReqHeader = reqClass.getMethod(GET_HEADER, String.class);
                Enumeration<String> reqHeaders = (Enumeration<String>) getReqHeaders.invoke(request);
                if (reqHeaders != null) {
                    while (reqHeaders.hasMoreElements()) {
                        String headerName = reqHeaders.nextElement();
                        String header = (String) getReqHeader.invoke(request, headerName);
                        if (header != null) {
                            data.addRequestHeader(headerName, header);
                        }
                    }
                }
            }
            
            data.setDuration(System.currentTimeMillis() - tracker.getRequestTime());

            if (Agent.debug) {
                System.err.println("Javametrics: Sending {\"http\":" + data.toJsonString() + "}");
            }

            /*
             * Send the http request data to the Javametrics agent
             */
            Javametrics.getInstance().sendJSON(HTTP_TOPIC, data.toJsonString());

        } catch (Exception e) {
            // Log any exception caused by our injected code
            System.err.println("Javametrics: Servlet callback exception: " + e.toString());
            e.printStackTrace();
        }

    }
196324
void setResponse(HttpResponse response) {
        if (isResponseAborted) {
            // This means that we already tried to close the request, so abort the response immediately.
            if (!response.isComplete()) {
                response.abort();
            }
        } else {
            this.response = response;
        }
    }
911999
@Transactional
	public void save(Response response) {
		Response merged = em.merge(response);
		em.flush();
		response.setId(merged.getId());
	}
641872
public void onSuccess (final WriteResponse response) {
    for (final Thunk thunk: this.thunks) {
      thunk.callback.onSuccess(new WriteResponse() {
        @Override
        public Object getRawResponse() {
          return response.getRawResponse();
        }

        @Override
        public String getStringResponse() {
          return response.getStringResponse();
        }

        @Override
        public long bytesWritten() {
          return thunk.sizeInBytes;
        }
      });
    }
  }
1132048
private void processSnapshotResponse(ClientResponse response) {
        setState(State.WAITING);
        final long now = System.currentTimeMillis();
        m_nextSnapshotTime += m_frequencyInMillis;
        if (m_nextSnapshotTime < now) {
            m_nextSnapshotTime = now - 1;
        }

        if (response.getStatus() != ClientResponse.SUCCESS){
            logFailureResponse("Snapshot failed", response);
            return;
        }

        final VoltTable results[] = response.getResults();
        final VoltTable result = results[0];

        final String err = SnapshotUtil.didSnapshotRequestFailWithErr(results);
        if (err != null) {
            SNAP_LOG.warn("Snapshot failed with failure response: " +  err);
            m_snapshots.removeLast();
            return;
        }

        //assert(result.getColumnName(1).equals("TABLE"));
        boolean success = true;
        while (result.advanceRow()) {
            if (!result.getString("RESULT").equals("SUCCESS")) {
                success = false;
                SNAP_LOG.warn("Snapshot save feasibility test failed for host "
                        + result.getLong("HOST_ID") + " table " + result.getString("TABLE") +
                        " with error message " + result.getString("ERR_MSG"));
            }
        }
        if (!success) {
            m_snapshots.removeLast();
        }
    }
1267171
@Override
	public void analyze(Response response) {
		if (response != null) {
			logger.info("NO-OP Response for user <" + response.getUser().getUsername() + "> - should be executing response action " + response.getAction());
		}
	}
337127
@SuppressWarnings("unchecked")
  private void handleResponseOk(long requestId, Object response) {
    ContextualFuture future = futures.remove(requestId);
    if (future != null) {
      future.context.executor().execute(() -> future.complete(response));
    }
  }
1180006
public static void makeStringResponse(HttpResponse response, String s) {
        StringEntity entity = new StringEntity(s, ContentType.TEXT_PLAIN);
        entity.setContentEncoding("utf-8");
        response.setEntity(entity);
    }
13304
@Override
	public void onAdd(Response response) {
		String message = gson.toJson(response);
		
		try {
			RabbitMqUtils.sendMessage(message, buildQueueNames(response), environment);
		} catch (IOException e) {
			logger.error("Failed to send response message to output queue.", e);
		}
	}
1085056
public void setResponse(HttpCarbonResponse response) {
        this.response = response;
        allPromisesReceived = true;
        responseFuture.notifyPromiseAvailability();      // Response received so no more promises allowed
        responseFuture.notifyHttpListener(response);
    }
108418
void handleResponse(ByteBuf response) {
    long requestId = response.readLong();
    byte status = response.readByte();
    switch (status) {
      case SUCCESS:
        try {
          handleResponseSuccess(requestId, readResponse(response));
        } catch (SerializationException e) {
          handleResponseFailure(requestId, e);
        }
        break;
      case FAILURE:
        try {
          handleResponseFailure(requestId, readError(response));
        } catch (SerializationException e) {
          handleResponseFailure(requestId, e);
        }
        break;
    }
    response.release();
  }
984038
protected void writeHeaders(HttpServletResponse response, Resource resource, long count) throws IOException
    {
        ResourceCache.ResourceMetaData metaData = _httpContext.getResourceMetaData(resource);

        response.setContentType(metaData.getMimeType());
        if (count != -1)
        {
            if (count == resource.length() && response instanceof ServletHttpResponse )
                response.setHeader(HttpFields.__ContentLength, metaData.getLength());
            else
                response.setContentLength((int) count);
        }

        response.setHeader(HttpFields.__LastModified, metaData.getLastModified());

        if (_acceptRanges)
            response.setHeader(HttpFields.__AcceptRanges, "bytes");
    }
1209813
@Override
    public void submitMetric(PrincipalUser submitter, Metric metric) {
        submitMetrics(submitter, Arrays.asList(new Metric[] { metric }));
    }
608112
protected boolean shouldResponseBeRecordedAsFailure(final HttpServletResponse response) {
        val status = response.getStatus();
        return status != HttpStatus.SC_CREATED && status != HttpStatus.SC_OK && status != HttpStatus.SC_MOVED_TEMPORARILY;
    }