This method handles the dumping of the reponse body, status code and headers if needed

@param response ResponseWrapper that handled the response populated by the webapp
@param id       Generated unique identifier for the request/response couple
768280
private void dumpResponse(final HttpServletResponseLoggingWrapper response, final int id) {
        final StringWriter stringWriter = new StringWriter();
        final PrintWriter printWriter = new PrintWriter(stringWriter);
        printWriter.print("-- ID: ");
        printWriter.println(id);
        printWriter.println(response.getStatusCode());
        if (LOG_HEADERS.isDebugEnabled()) {
            final Map<String, List<String>> headers = response.headers;
            for (Map.Entry<String, List<String>> header : headers.entrySet()) {
                printWriter.print(header.getKey());
                printWriter.print(": ");
                Iterator<String> values = header.getValue().iterator();
                while (values.hasNext()) {
                    printWriter.print(values.next());
                    printWriter.println();
                    if (values.hasNext()) {
                        printWriter.print(' ');
                    }
                }
            }
        }
        printWriter.println("-- Begin response body");

        final String body = response.getContentAsInputString();
        if (body == null || body.length() == 0) {
            printWriter.println("-- NO BODY WRITTEN IN RESPONSE");
        } else {
            printWriter.println(body);
        }
        printWriter.println();
        printWriter.println("-- End response body");
        printWriter.flush();
        LOG_RESPONSE.debug(stringWriter.toString());
    }
1319330
public void setResponse(JsonRpcResponse response) {
    if (response.isError()) {
      setException(response.error());
      return;
    }

    try {
      set((V) Messages.fromJson(method.outputBuilder(), response.result()));
    } catch (Exception e) {
      setException(e);
    }
  }
305408
public static String getResponseCodeOutput(Response response) {
        if (response == null) {
            return "";
        }
        StringBuilder responseOutput = new StringBuilder();
        String uuid = getUUID();
        responseOutput.append(ONCLICK_TOGGLE).append(uuid).append("\")'>Toggle Response Status Code</a> ");
        responseOutput.append(SPAN_ID).append(uuid).append(DISPLAY_NONE);
        responseOutput.append(DIV).append(response.getCode()).append(END_DIV);
        responseOutput.append(END_SPAN);
        return responseOutput.toString();
    }
910369
function responseHandle(error, response, body, reject, resolve) {

    if (error) {
      return reject(error);
    }

    try {
      body = JSON.parse(body);
    } catch (e) {
      return reject(new Error('Wrong JSON Format'));
    }

    resolve(body);
    
  }
826274
private void handleDiscoveryResponse(SsdpResponse response) {
    SsdpService ssdpService = response.toService();
    if (ssdpService.getSerialNumber() == null) {
      callback.onFailed(new NoSerialNumberException());
      return;
    }
    if (!cache.containsKey(ssdpService.getSerialNumber())) {
      callback.onServiceDiscovered(ssdpService);
    }
    cache.put(ssdpService.getSerialNumber(), ssdpService);
  }
117172
private void saveTokenFromResponse(Response response) {
        try {
            JSONObject responseJSON = ((ResponseImpl)response).getResponseJSON();

            String accessToken = responseJSON.getString("access_token");
            String idToken = responseJSON.getString("id_token");

            //save the tokens
            preferences.accessToken.set(accessToken);
            preferences.idToken.set(idToken);

            //save the user identity separately
            String[] idTokenData = idToken.split("\\.");
            byte[] decodedIdTokenData = Base64.decode(idTokenData[1], Base64.DEFAULT);
            String decodedIdTokenString = new String(decodedIdTokenData);
            JSONObject idTokenJSON = new JSONObject(decodedIdTokenString);

            if (idTokenJSON.has("imf.user")) {
                preferences.userIdentity.set(idTokenJSON.getJSONObject("imf.user"));
            }

            logger.debug("token successfully saved");
        } catch (Exception e) {
            throw new RuntimeException("Failed to save token from response", e);
        }
    }
478191
private void responseEntity(String html, HttpServletResponse servletResponse)
            throws IOException {
        PrintWriter printWriter = servletResponse.getWriter();
        try {
            printWriter.write(html);
            printWriter.flush();
        } finally {
            closeQuietly(printWriter);
        }
    }
1193354
protected void doResponseHeaders(final HttpServletResponse response, final String mimeType) {
        if (mimeType != null) {
            response.setContentType(mimeType);
        }
    }
861049
private final void handleHttpWorkerResponse(
            ResponseOnSingeRequest respOnSingleReq) throws Exception {
        // Successful response from GenericAsyncHttpWorker

        // Jeff 20310411: use generic response

        String responseContent = respOnSingleReq.getResponseBody();
        response.setResponseContent(respOnSingleReq.getResponseBody());

        /**
         * Poller logic if pollable: check if need to poll/ or already complete
         * 1. init poller data and HttpPollerProcessor 2. check if task
         * complete, if not, send the request again.
         */
        if (request.isPollable()) {
            boolean scheduleNextPoll = false;
            boolean errorFindingUuid = false;

            // set JobId of the poller
            if (!pollerData.isUuidHasBeenSet()) {
                String jobId = httpPollerProcessor
                        .getUuidFromResponse(respOnSingleReq);

                if (jobId.equalsIgnoreCase(PcConstants.NA)) {
                    errorFindingUuid = true;
                    pollingErrorCount++;
                    logger.error("!!POLLING_JOB_FAIL_FIND_JOBID_IN_RESPONSE!! FAIL FAST NOW. PLEASE CHECK getJobIdRegex or retry. "

                            + "DEBUG: REGEX_JOBID: "
                            + httpPollerProcessor.getJobIdRegex()

                            + "RESPONSE: "
                            + respOnSingleReq.getResponseBody()
                            + " polling Error count"
                            + pollingErrorCount
                            + " at " + PcDateUtils.getNowDateTimeStrStandard());
                    // fail fast
                    pollerData.setError(true);
                    pollerData.setComplete(true);

                } else {
                    pollerData.setJobIdAndMarkHasBeenSet(jobId);
                    // if myResponse has other errors, mark poll data as error.
                    pollerData.setError(httpPollerProcessor
                            .ifThereIsErrorInResponse(respOnSingleReq));
                }

            }
            if (!pollerData.isError()) {

                pollerData
                        .setComplete(httpPollerProcessor
                                .ifTaskCompletedSuccessOrFailureFromResponse(respOnSingleReq));
                pollerData.setCurrentProgress(httpPollerProcessor
                        .getProgressFromResponse(respOnSingleReq));
            }

            // poll again only if not complete AND no error; 2015: change to
            // over limit
            scheduleNextPoll = !pollerData.isComplete()
                    && (pollingErrorCount <= httpPollerProcessor
                            .getMaxPollError());

            // Schedule next poll and return. (not to answer back to manager yet
            // )
            if (scheduleNextPoll
                    && (pollingErrorCount <= httpPollerProcessor
                            .getMaxPollError())) {

                pollMessageCancellable = getContext()
                        .system()
                        .scheduler()
                        .scheduleOnce(
                                Duration.create(httpPollerProcessor
                                        .getPollIntervalMillis(),
                                        TimeUnit.MILLISECONDS), getSelf(),
                                OperationWorkerMsgType.POLL_PROGRESS,
                                getContext().system().dispatcher(), getSelf());

                logger.info("\nPOLLER_NOW_ANOTHER_POLL: POLL_RECV_SEND"
                        + String.format("PROGRESS:%.3f, BODY:%s ",
                                pollerData.getCurrentProgress(),
                                responseContent,
                                PcDateUtils.getNowDateTimeStrStandard()));

                String responseContentNew = errorFindingUuid ? responseContent
                        + "_PollingErrorCount:" + pollingErrorCount
                        : responseContent;
                logger.info(responseContentNew);
                // log
                pollerData.getPollingHistoryMap().put(
                        "RECV_" + PcDateUtils.getNowDateTimeStrConciseNoZone(),
                        String.format("PROGRESS:%.3f, BODY:%s",
                                pollerData.getCurrentProgress(),
                                responseContent));
                return;
            } else {
                pollerData
                        .getPollingHistoryMap()
                        .put("RECV_"
                                + PcDateUtils.getNowDateTimeStrConciseNoZone(),
                                String.format(
                                        "POLL_COMPLETED_OR_ERROR: PROGRESS:%.3f, BODY:%s ",
                                        pollerData.getCurrentProgress(),
                                        responseContent));
            }

        }// end if (request.isPollable())

        reply(respOnSingleReq.isFailObtainResponse(),
                respOnSingleReq.getErrorMessage(),
                respOnSingleReq.getStackTrace(),
                respOnSingleReq.getStatusCode(),
                respOnSingleReq.getStatusCodeInt(),
                respOnSingleReq.getReceiveTime(), respOnSingleReq.getResponseHeaders());

    }
28835
protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response) {
        parseRequest(request,
                     response);
        if (profile == null) {
            profile = _profileService.findProfile(request,
                                                  "jbpm");
        }
        Repository repository = profile.getRepository();
        if (!initialized) {
            try {
                initializeDefaultRepo(profile,
                                      repository,
                                      request);
                initialized = true;
            } catch (Exception e) {
                logger.error("Unable to initialize repository: " + e.getMessage());
            }
        }
        JSONObject returnJson = new JSONObject();
        try {
            Iterator<String> keys = requestParams.keySet().iterator();
            while (keys.hasNext()) {
                String key = keys.next();
            }

            String cmd = (String) requestParams.get("cmd");
            if (cmd != null && cmd.equals("open")) {
                OpenCommand command = new OpenCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("mkdir")) {
                MakeDirCommand command = new MakeDirCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("mkfile")) {
                MakeFileCommand command = new MakeFileCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("rm")) {
                RemoveAssetCommand command = new RemoveAssetCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("rename")) {
                RenameCommand command = new RenameCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("paste")) {
                PasteCommand command = new PasteCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("upload")) {
                UploadCommand command = new UploadCommand();
                command.init(request,
                             response,
                             profile,
                             repository,
                             requestParams,
                             listFiles,
                             listFileStreams);
                output(response,
                       false,
                       command.execute());
            } else if (cmd != null && cmd.equals("getsvg")) {
                try {
                    Asset asset = profile.getRepository().loadAssetFromPath((String) requestParams.get("current"));
                    if (asset != null && asset.getAssetContent() != null) {
                        outputPlain(response,
                                    false,
                                    (String) asset.getAssetContent(),
                                    "image/svg+xml");
                    } else {
                        outputPlain(response,
                                    true,
                                    "<p><b>Process image not available.</p><p>You can generate the process image in the process editor.</b></p>",
                                    null);
                    }
                } catch (NoSuchFileException e) {
                    logger.warn("Error loading process image: " + e.getMessage());
                    outputPlain(response,
                                true,
                                "<p><b>Could not find process image.</p><p>You can generate the process image in the process editor.</b></p>",
                                null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            putResponse(returnJson,
                        "error",
                        e.getMessage());

            // output the error
            try {
                output(response,
                       false,
                       returnJson);
            } catch (Exception ee) {
                logger.error("",
                             ee);
            }
        }
    }
1270146
private static ResponseSwitch getResponseSwitch(Object response)
  {
      // unwrap the response until we find a ResponseSwitch
      while (response != null)
      {
          if (response instanceof ResponseSwitch)
          {
              // found
              return (ResponseSwitch) response;
          }
          if (response instanceof ServletResponseWrapper)
          {
              // unwrap
              response = ((ServletResponseWrapper) response).getResponse();
          }
          // no more possibilities to find a ResponseSwitch
          break; 
      }
      return null; // not found
  }
1301256
function storeResponse(message, id, dest)
  {
    var response =
    {
      message: message,
      /** Timeout to auto-clean old responses */
      timeout: setTimeout(function()
      {
        responses.remove(id, dest);
      },
      response_timeout)
    };

    responses.set(response, id, dest);
  }
1161579
@Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    JsonGenerator jg = null;
    String jsonpcb = null;
    PrintWriter writer = null;
    try {

      writer = response.getWriter();

      // "callback" parameter implies JSONP output
      jsonpcb = request.getParameter(CALLBACK_PARAM);
      if (jsonpcb != null) {
        response.setContentType("application/javascript; charset=utf8");
        writer.write(jsonpcb + "(");
      } else {
        response.setContentType("application/json; charset=utf8");
      }

      jg = jsonFactory.createJsonGenerator(writer);
      jg.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
      jg.useDefaultPrettyPrinter();

      int statusCode = renderMBeans(jg, request.getParameterValues("qry"));
      response.setStatus(statusCode);

    } catch (IOException e) {
      writeException(jg, e);
      response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (MalformedObjectNameException e) {
      writeException(jg, e);
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } finally {
      if (jg != null) {
        jg.close();
      }
      if (jsonpcb != null) {
        writer.write(");");
      }
      if (writer != null) {
        writer.close();
      }
    }

  }
1026972
public void onResponse(final MobicentsSipServletResponse response, final int status) throws DispatcherException
	{
		// If we are canceled but still receiving provisional responses try to cancel them
		if(canceled && status < 200) {
			if(logger.isDebugEnabled()) {
				logger.debug("ProxyBranch " + this + " with outgoing request " + outgoingRequest + " cancelled and still receiving provisional response, trying to cancel them");
			}
			try {
				final SipServletRequest cancelRequest = outgoingRequest.createCancel();
				cancelRequest.send();
			} catch (Exception e) {
				if(logger.isDebugEnabled()) {
					logger.debug("Failed to cancel again a provisional response " + response.toString()
							, e);
				}
			}
		}

		// We have already sent TRYING, don't send another one
		if(status == 100) {
			if(logger.isDebugEnabled() && proxyBranch1xxTimerStarted) {
				logger.debug("1xx received, cancelling 1xx timer ");
			}
			cancel1xxTimer();
			return;
		}
		
		// Send informational responses back immediately
		if((status > 100 && status < 200) || (status == 200 &&
				(Request.PRACK.equals(response.getMethod()) || Request.UPDATE.equals(response.getMethod()))))
		{
			// Deterimine if the response is reliable. We just look at RSeq, because
			// every such response is required to have it.
			if(response.getHeader("RSeq") != null) {
				this.setWaitingForPrack(true); // this branch is expecting a PRACK now
			}
			
			final SipServletResponseImpl proxiedResponse = 
				ProxyUtils.createProxiedResponse(response, this);
			
			if(proxiedResponse == null) {
				if(logger.isDebugEnabled())
					logger.debug("Response dropped because it was addressed to this machine.");
				return; // this response was addressed to this proxy
			}
			
			try {
				String branch = ((Via)proxiedResponse.getMessage().getHeader(Via.NAME)).getBranch();
				synchronized(this.ongoingTransactions) {
					for(TransactionRequest tr : this.ongoingTransactions) {
						if(tr.branchId.equals(branch)) {
							((SipServletResponseImpl)proxiedResponse).setTransaction(tr.request.getTransaction());
							((SipServletResponseImpl)proxiedResponse).setOriginalRequest(tr.request);
							break;
						}
					}
				}

				proxiedResponse.send();
				if(logger.isDebugEnabled())
					logger.debug("Proxy response sent out sucessfully");
			} catch (Exception e) {
				logger.error("A problem occured while proxying a response", e);
			}
			if(logger.isDebugEnabled())
				logger.debug("SipSession state " + response.getSipSession().getState());
			if(status == 200 &&
				(Request.PRACK.equals(response.getMethod()) || Request.UPDATE.equals(response.getMethod()))
				// Added for http://code.google.com/p/sipservlets/issues/detail?id=41
				&& State.EARLY.equals(response.getSipSession().getState())) {
				
				updateTimer(true, response.getSipApplicationSession(false));
			}
			
			if(logger.isDebugEnabled())
					logger.debug("About to return from onResponse");
			
			return;
		}
		
		// Non-provisional responses must also cancel the timer, otherwise it will timeout
		// and return multiple responses for a single transaction.
		cancelTimer();
		
		if(status >= 600) // Cancel all 10.2.4
			this.proxy.cancelAllExcept(this, null, null, null, false);
		
		// FYI: ACK is sent automatically by jsip when needed
		
		boolean recursed = false;
		if(status >= 300 && status < 400 && recurse) {
			String contact = response.getHeader("Contact");
			if(contact != null) {
				//javax.sip.address.SipURI uri = SipFactoryImpl.addressFactory.createAddress(contact);
				try {
					if(logger.isDebugEnabled())
						logger.debug("Processing recursed response");
					int start = contact.indexOf('<');
					int end = contact.indexOf('>');
					contact = contact.substring(start + 1, end);
					URI uri = proxy.getSipFactoryImpl().createURI(contact);
					ArrayList<SipURI> list = new ArrayList<SipURI>();
					list.add((SipURI)uri);
					List<ProxyBranch> pblist = proxy.createProxyBranches(list);
					ProxyBranchImpl pbi = (ProxyBranchImpl)pblist.get(0);
					this.addRecursedBranch(pbi);
					pbi.start();
					recursed = true;
				} catch (ServletParseException e) {
					throw new IllegalArgumentException("Can not parse contact header", e);
				}
			}
		}		
		if(status >= 200 && !recursed)
		{
			
			if(proxy.getFinalBranchForSubsequentRequests() == null ||
					(outgoingRequest != null && outgoingRequest.isInitial())) {
				if(logger.isDebugEnabled())
					logger.debug("Handling final response for initial request");
				this.proxy.onFinalResponse(this);
			} else {
				if(logger.isDebugEnabled())
					logger.debug("Handling final response for non-initial request");				
				this.proxy.sendFinalResponse(response, this);
			}
		}
		
	}
25813
protected void handleTrace(HttpServletRequest request,
                            HttpServletResponse response)
        throws IOException
    {
        response.setHeader(HttpFields.__ContentType,
                           HttpFields.__MessageHttp);
        OutputStream out = response.getOutputStream();
        ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer();
        writer.write(request.toString());
        writer.flush();
        response.setIntHeader(HttpFields.__ContentLength,writer.size());
        writer.writeTo(out);
        out.flush();
    }
961989
protected void handleAppendResponse(MemberState member, AppendRequest request, AppendResponse response) {
    if (response.status() == Response.Status.OK) {
      handleAppendResponseOk(member, request, response);
    } else {
      handleAppendResponseError(member, request, response);
    }
  }
148311
@Override
  public void processResponse(CloseableHttpResponse response) throws IOException, UnexpectedResponseException {
    if (response.getStatusLine().getStatusCode() >= 400) {
      if (response.getEntity() != null) {
        throw new RuntimeException("Failed. " + EntityUtils.toString(response.getEntity())
                                 + " , response: " + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE));
      }
      throw new RuntimeException("Failed. Response: " + ToStringBuilder.reflectionToString(response, ToStringStyle.SHORT_PREFIX_STYLE));
    }
  }