/*
(non-Javadoc)
@see okhttp3.WebSocketListener#onOpen(okhttp3.WebSocket, okhttp3.Response)
485734
@Override
  public void onOpen(final WebSocket socket, Response response) {
    callback.onConnected();
    this.socket = socket;
    if (!socket.send(buildStartMessage(options))) {
      callback.onError(new IOException("WebSocket unavailable"));
    } else {
      // Send the InputStream on a different Thread. Elsewise, interim results cannot be
      // received,
      // because the Thread that called SpeechToText.recognizeUsingWebSocket is blocked.
      audioThread = new Thread(AUDIO_TO_WEB_SOCKET) {
        @Override
        public void run() {
          sendInputStream(stream);
          // Do not send the stop message if the socket has been closed already, for example because of the
          // inactivity timeout.
          // If the socket is still open after the sending finishes, for example because the user closed the
          // microphone AudioInputStream, send a stop message.
          if (socketOpen && !socket.send(buildStopMessage())) {
            LOG.log(Level.SEVERE, "Stop message discarded because WebSocket is unavailable");
          }
        }
      };

      audioThread.start();
    }
  }
1340497
static void sendResponse(String output, HttpServletResponse response)
      throws IOException {
    PrintWriter out = null;
    try {
      out = response.getWriter();
      out.write(output);
    } finally {
      if (out != null) {
        out.close();
      }
    }
  }
1323812
public static <S extends HttpServlet> void doOptions(
		HttpServletResponse response,
		Class<S> stopClass,
		Class<? extends S> thisClass,
		String doGet,
		String doPost,
		String doPut,
		String doDelete,
		Class<?>[] paramTypes
	) {
		boolean ALLOW_GET = false;
		boolean ALLOW_HEAD = false;
		boolean ALLOW_POST = false;
		boolean ALLOW_PUT = false;
		boolean ALLOW_DELETE = false;
		boolean ALLOW_TRACE = true;
		boolean ALLOW_OPTIONS = true;
		for (
			Method method
			: getAllDeclaredMethods(stopClass, thisClass)
		) {
			if(Arrays.equals(paramTypes, method.getParameterTypes())) {
				String methodName = method.getName();
				if (doGet.equals(methodName)) {
					ALLOW_GET = true;
					ALLOW_HEAD = true;
				} else if (doPost.equals(methodName)) {
					ALLOW_POST = true;
				} else if (doPut.equals(methodName)) {
					ALLOW_PUT = true;
				} else if (doDelete.equals(methodName)) {
					ALLOW_DELETE = true;
				}
			}
		}
		StringBuilder allow = new StringBuilder();
		if (ALLOW_GET) {
			// if(allow.length() != 0) allow.append(", ");
			allow.append(METHOD_GET);
		}
		if (ALLOW_HEAD) {
			if(allow.length() != 0) allow.append(", ");
			allow.append(METHOD_HEAD);
		}
		if (ALLOW_POST) {
			if(allow.length() != 0) allow.append(", ");
			allow.append(METHOD_POST);
		}
		if (ALLOW_PUT) {
			if(allow.length() != 0) allow.append(", ");
			allow.append(METHOD_PUT);
		}
		if (ALLOW_DELETE) {
			if(allow.length() != 0) allow.append(", ");
			allow.append(METHOD_DELETE);
		}
		if (ALLOW_TRACE) {
			if(allow.length() != 0) allow.append(", ");
			allow.append(METHOD_TRACE);
		}
		if (ALLOW_OPTIONS) {
			if(allow.length() != 0) allow.append(", ");
			allow.append(METHOD_OPTIONS);
		}
		response.setHeader("Allow", allow.toString());
	}
474155
@Internal
    public static Optional<NettyMutableHttpResponse> set(NettyHttpRequest<?> request, HttpResponse<?> response) {
        request.attr(KEY).set((NettyMutableHttpResponse) response);
        return Optional.ofNullable((NettyMutableHttpResponse) response);
    }
478191
private void responseEntity(String html, HttpServletResponse servletResponse)
            throws IOException {
        PrintWriter printWriter = servletResponse.getWriter();
        try {
            printWriter.write(html);
            printWriter.flush();
        } finally {
            closeQuietly(printWriter);
        }
    }
493658
private void processJWKRequest(HttpServletResponse response, JwtConfig jwtConfig) throws IOException {

		/*
		 * if (!jwtConfig.isJwkEnabled()) { String errorMsg =
		 * Tr.formatMessage(tc, "JWK_ENDPOINT_JWK_NOT_ENABLED", new Object[] {
		 * jwtConfig.getId() }); Tr.error(tc, errorMsg);
		 * response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMsg);
		 * return; }
		 */

		String signatureAlg = jwtConfig.getSignatureAlgorithm();
		if (!Constants.SIGNATURE_ALG_RS256.equals(signatureAlg)) {
			String errorMsg = Tr.formatMessage(tc, "JWK_ENDPOINT_WRONG_ALGORITHM",
					new Object[] { jwtConfig.getId(), signatureAlg, Constants.SIGNATURE_ALG_RS256 });
			Tr.error(tc, errorMsg);
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, errorMsg);
			return;
		}

		String jwkString = jwtConfig.getJwkJsonString();

		addNoCacheHeaders(response);
		response.setStatus(200);

		if (jwkString == null) {
			return;
		}
		try {
			PrintWriter pw = response.getWriter();
			response.setHeader(WebConstants.HTTP_HEADER_CONTENT_TYPE, WebConstants.HTTP_CONTENT_TYPE_JSON);
			pw.write(jwkString);
			pw.flush();
			pw.close();
		} catch (IOException e) {
			if (tc.isDebugEnabled()) {
				Tr.debug(tc, "Caught an exception attempting to get the response writer: " + e.getLocalizedMessage());
			}
		}
	}
960144
public synchronized void setResponse(HttpServletResponse response) {

        if (perThreadResponse == null) {
            perThreadResponse = new ThreadLocal<HttpServletResponse>();
        }
        perThreadResponse.set(response);
    }
1295251
@Override
    public void emitResponse(T response) {
        if (!isTerminated()) {
            subject.onNext(response);
            valueSet.set(true);
        } else {
            throw new IllegalStateException("Response has already terminated so response can not be set : " + response);
        }
    }
110925
@Override
    public T handleResponse(final HttpResponse response) throws IOException {

        InputStream content = null;
        final T addresses;

        try {
            final StatusLine status = response.getStatusLine();
            if (status.getStatusCode() >= HttpStatus.SC_BAD_REQUEST) {
                throw new IOException(String.format("HTTP error: %s %s", status.getStatusCode(), status.getReasonPhrase()));
            }
            content = response.getEntity().getContent();
            addresses = gsonInstance
                    .fromJson(new InputStreamReader(content, "utf-8"), responseType);
        } finally {
            if (null != content) {
                content.close();
            }
            response.getEntity().consumeContent();
        }

        return addresses;
    }
1158282
protected void sendSofaResponse(SofaResponse response, SofaRpcException sofaException) {
        try {
            if (RpcInvokeContext.isBaggageEnable()) {
                BaggageResolver.carryWithResponse(RpcInvokeContext.peekContext(), response);
            }
            asyncContext.sendResponse(response);
        } finally {
            if (EventBus.isEnable(ServerSendEvent.class)) {
                EventBus.post(new ServerSendEvent(request, response, sofaException));
            }
            if (EventBus.isEnable(ServerEndHandleEvent.class)) {
                EventBus.post(new ServerEndHandleEvent());
            }
        }
    }
697181
public boolean setNonnull(HttpResponse response) {
    Preconditions.checkNotNull(response);
    if (set(response)) {
      callback.completed(response);
      return true;
    } else {
      return false;
    }
  }
1269650
@UnstableApi
    public void setOcspResponse(byte[] response) {
        if (!enableOcsp) {
            throw new IllegalStateException("OCSP stapling is not enabled");
        }

        if (clientMode) {
            throw new IllegalStateException("Not a server SSLEngine");
        }

        synchronized (this) {
            SSL.setOcspResponse(ssl, response);
        }
    }
1103402
public static HttpServletResponse getHttpServletResponse(final Response response)
	{
		final WebResponse webResponse = (WebResponse)response;
		final HttpServletResponse httpServletResponse = (HttpServletResponse)webResponse
			.getContainerResponse();
		return httpServletResponse;
	}
605850
@SuppressWarnings("unchecked")
    @Override
    protected void afterHandle(final Request request, final Response response)
    {
        super.afterHandle(request, response);
        
        final ConcurrentMap<String, Object> responseAttributes = response.getAttributes();
        
        Series<Header> responseHeaders = (Series<Header>)responseAttributes.get(HeaderConstants.ATTRIBUTE_HEADERS);
        
        if(responseHeaders == null)
        {
            responseHeaders = new Series<Header>(Header.class);
            final Series<Header> putIfAbsent =
                    (Series<Header>)responseAttributes.putIfAbsent(HeaderConstants.ATTRIBUTE_HEADERS, responseHeaders);
            
            if(putIfAbsent != null)
            {
                responseHeaders = putIfAbsent;
            }
        }
        
        // Allow all origins
        responseHeaders.add("Access-Control-Allow-Origin", "*");
    }
324830
public void onOpen() {
    LOGGER.d("webSocket established...");
    connectionEstablished = true;
    retryConnectionCount = 0;
    for (AVConnectionListener listener: connectionListeners.values()) {
      listener.onWebSocketOpen();
    }

    resetConnectingStatus(true);

    // auto send login packet.
    LoginPacket lp = new LoginPacket();
    lp.setAppId(AVOSCloud.getApplicationId());
    lp.setInstallationId(AVInstallation.getCurrentInstallation().getInstallationId());
    this.sendPacket(lp);
  }
554487
private void respond(BufferedWriter out, String response) throws IOException {
        out.append(response);
        out.append("\n");
        out.flush();
    }
1250986
protected Token responseToToken(Map<String, String> response) {
		return new Token(response.get(OAUTH_TOKEN), response.get(OAUTH_TOKEN_SECRET));
	}