/*
Template method.

(non-Javadoc)
@see de.fhhannover.inform.trust.ifmapj.channel.CommunicationHandler#doRequest(java.io.InputStream)
556744
@Override
	public final InputStream doRequest(InputStream httpBody) throws CommunicationException {
		InputStream reply = null;

		try {

			getSocket();

			prepareCommunication();

			createPostRequest(getPath());

			writeHostLine();

			writeContentTypeHeaders();

			httpBody = logAndCloneInputStream(httpBody, "request");

			if (usesGzip()) {
				httpBody = compressInputStream(httpBody);
				writeGzipHeaders();
			}

			if (usesBasicAuth()) {
				writeAuthHeader();
			}

			writeContentLengthHeader(httpBody.available());

			finishHeaders();

			reply = doActualRequest(httpBody);

			reply = logAndCloneInputStream(reply, "response");

			if (replyIsGzipped()) {
				reply = new GZIPInputStream(reply);
			}

			return reply;

		} catch (IOException e) {
			throw new CommunicationException(e.getMessage());
		}
	}
1070444
public RequestPaymentConfigurationHandler parseRequestPaymentConfigurationResponse(InputStream inputStream)
            throws IOException {
        RequestPaymentConfigurationHandler handler = new RequestPaymentConfigurationHandler();
        parseXmlInputStream(handler, inputStream);
        return handler;
    }
130249
@Deprecated
    public static InputStream inputStreamForRequest(InputStream is,
            AmazonWebServiceRequest req) {
        return req == null
             ? is
             : inputStreamForRequest(is, req.getGeneralProgressListener());
    }
731433
public void setRequest(HttpServletRequest request) {
		WaybackRequest wbRequest = new WaybackRequest();
		wbRequest.extractHttpRequestInfo(request);
		this.wbRequest = wbRequest;
	}
334436
private static void __serveStream(HttpServletRequest request, HttpServletResponse response, InputStream is, String path, String mime, int bufferSize, long lastModified) throws IOException {
        Map<String, String> reqHeaders = __getRequestHeaderMap(request);

        String queryString = request.getQueryString();
        if (queryString == null) {
            queryString = "";
        }

        // Calculate etag
        String etag = Integer.toHexString((path + lastModified + queryString + is.available()).hashCode());

        // Support (simple) skipping:
        long startFrom = 0;
        long endAt = -1;

        String range = reqHeaders.get("range");
        if (range != null) {
            if (range.startsWith("bytes=")) {
                range = range.substring("bytes=".length());
                int minus = range.indexOf('-');

                if (minus > 0) {
                    startFrom = __parseLong(range.substring(0, minus), 0);
                    endAt = __parseLong(range.substring(minus + 1), -1);
                }
            }
        }

        response.addHeader("Accept-Ranges", "bytes");

        // Change return code and add Content-Range header when skipping is requested
        long fileLen = is.available();
        if (range != null && startFrom >= 0) {
            if (startFrom >= fileLen) {
                response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                response.setContentType("text/plain");
                response.addHeader("Content-Range", "bytes 0-0/" + fileLen);
                response.addHeader("ETag", etag);
            } else {
                if (endAt < 0) {
                    endAt = fileLen - 1;
                }

                long newLen = endAt - startFrom + 1;

                if (newLen < 0) {
                    newLen = 0;
                }

                final long dataLen = newLen;

                is.skip(startFrom);

                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                response.setContentType(mime);
                __flush(is, response.getOutputStream(), bufferSize);
                response.addHeader("Content-Length", "" + dataLen);
                response.addHeader("Content-Range", "bytes " + startFrom + "-" + endAt + "/" + fileLen);
                response.addHeader("ETag", etag);
            }
        } else {
            if (etag.equals(reqHeaders.get("if-none-match"))) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                response.setContentType(mime);
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType(mime);
                __flush(is, response.getOutputStream(), bufferSize);
                response.addHeader("Content-Length", "" + fileLen);
                response.addHeader("ETag", etag);
            }
        }

    }
856269
public OkRequest<T> send(final File input) throws IOException {
        final InputStream stream;

        stream = new BufferedInputStream(new FileInputStream(input));
        return send(stream);
    }
1081374
protected void doRequest(javax.servlet.sip.SipServletRequest req) throws javax.servlet.ServletException, java.io.IOException{
    	String m = req.getMethod();
		if ("INVITE".equals(m))
			doInvite(req);
		else if ("ACK".equals(m))
			doAck(req);
		else if ("OPTIONS".equals(m))
			doOptions(req);
		else if ("BYE".equals(m))
			doBye(req);
		else if ("CANCEL".equals(m))
			doCancel(req);
		else if ("REGISTER".equals(m))
			doRegister(req);
		else if ("SUBSCRIBE".equals(m))
			doSubscribe(req);
		else if ("NOTIFY".equals(m))
			doNotify(req);
		else if ("MESSAGE".equals(m))
			doMessage(req);
		else if ("INFO".equals(m))
			doInfo(req);
		else if ("REFER".equals(m))
			doRefer(req);
		else if ("PUBLISH".equals(m))
			doPublish(req);
		else if ("UPDATE".equals(m))
			doUpdate(req);
		else if ("PRACK".equals(m))
			doPrack(req);
		else if (req.isInitial())
			notHandled(req);
    }
515404
public RequestResponse doPost(String url, Map<String, Object> headers,
            Map<String, Object> urlParams, Object requestData) {
        RequestResponse rr = initRequestResponse("POST", url, headers, urlParams, requestData);
        Request.Builder requestBuilder = buildRequest(url, headers, urlParams)
                .post(buildRequestBody(rr));
        return doCall(client, requestBuilder.build(), rr);
    }
720356
private void handleRequest(ByteBuf request, ChannelHandlerContext context) {
    NettyConnection connection = getConnection(context.channel());
    if (connection != null) {
      connection.handleRequest(request);
    }
  }
651398
private void handleRequest(long requestId, Object request, HandlerHolder handler) {
    @SuppressWarnings("unchecked")
    CompletableFuture<Object> responseFuture = handler.handler.apply(request);
    if (responseFuture != null) {
      responseFuture.whenComplete((response, error) -> {
        ThreadContext context = ThreadContext.currentContext();
        if (context == null) {
          this.context.executor().execute(() -> {
            if (error == null) {
              handleRequestSuccess(requestId, response, this.context);
            } else {
              handleRequestFailure(requestId, error, this.context);
            }
          });
        } else {
          if (error == null) {
            handleRequestSuccess(requestId, response, context);
          } else {
            handleRequestFailure(requestId, error, context);
          }
        }
      });
    }
  }
238182
@Override
    protected boolean performRequest() {

        SocketChannel sc = null;
        boolean closeOnError = false;

        // If we were woken up because we have work to do, do it.
        Set<SelectionKey> keySet = this.selector.selectedKeys();
        Iterator<SelectionKey> keyIterator = keySet.iterator();
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(this, tc, "performRequest - processing " + keySet.size() + " items");
        }

        while (keyIterator.hasNext()) {
            closeOnError = false;

            // If we get exceptions repeatedly, we may need to take a break for a number of reasons
            if (numExceptions >= 3100) {
                // if we don't recover after 290 more seconds, wait for 10 minutes
                if (pauseAccept()) {
                    resetExceptions(); // clear exceptions if we weren't interrupted
                }
                continue;
            } else if (numExceptions >= 200) {
                // if we get exceptions repeatedly, wait a tenth to give
                // other threads some time. It should take about 10 seconds for
                // us to get up to 200 exceptions (via trace analysis).
                if (numExceptions == 1500) {
                    FFDCFilter.processException(new Exception("TCP channel has received 1500 exceptions in a row on the accept selector"),
                                                getClass().getName(), "101", this);
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ie) {
                    // ignore it
                }
            }

            // PK40415 - change audit handling of errors
            SelectionKey key = keyIterator.next();
            TCPPort endPoint = (TCPPort) key.attachment();
            TCPChannel tcpChannel = endPoint.getTCPChannel();

            try {
                // safe remove from set while iterating
                keyIterator.remove();

                // perform accept
                ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();

                try {
                    sc = serverSocketChannel.accept();

                    // Configure all inbound channels to be non-blocking
                    if (sc != null) {
                        sc.configureBlocking(false);
                    }

                } catch (IOException ioe) {
                    incrementExceptions();
                    this.numAcceptIOExceptions++;
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                        Tr.event(this, tc, "TCP Channel: " + tcpChannel.getExternalName() + " caught IOException doing accept: " + ioe + " total=" + numExceptions + " count="
                                           + numAcceptIOExceptions);
                    }
                    // Since we could be monitoring several serverSocketChannels, we need
                    // to continue processing even though we got an IOException on this
                    // serverSocketChannel.
                    continue;
                }

                // sometimes the accept can return null. This seems to happen when
                // there is a network problem, and we got notified it was ready to
                // accept, but when we went to do the accept we couldn't complete the accept. If
                // this happens, just skip this and go on
                if (sc == null) {
                    incrementExceptions();
                    this.numAcceptNulls++;
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                        Tr.event(this, tc, "TCP Channel: " + tcpChannel.getExternalName() + " accept() returned null, total=" + numExceptions + " count=" + numAcceptNulls);
                    }
                    continue;
                }

                Socket socket = sc.socket();
                if (!testSocket(sc)) {
                    continue;
                }
                closeOnError = true;

                if (!tcpChannel.verifyConnection(socket)) {
                    closeSocketChannel(sc);

                    // if we made it this far, then the accept worked without exceptions
                    if (0 < this.numExceptions) {
                        resetExceptions();
                    }
                    continue;
                }

                SocketIOChannel ioSocket = null;
                try {
                    ioSocket = tcpChannel.createInboundSocketIOChannel(sc);
                } catch (IOException ioe) {
                    // no FFDC required
                    incrementExceptions();
                    this.numConfigureIOExceptions++;
                    if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                        Tr.event(this, tc, "IOException caught while configuring socket: " + ioe + ", total=" + numExceptions + " count=" + numConfigureIOExceptions);
                    }
                    closeSocketChannel(sc);
                    continue;
                }
                endPoint.processNewConnection(ioSocket);

            } catch (CancelledKeyException cke) {
                // no FFDC required
                // Should only get this if the socket was closed. Therefore
                // log error and continue processing
                incrementExceptions();
                this.numCancelledKeys++;
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(this, tc, "Cancelled key exception found, cke=" + cke + " total=" + numExceptions + " count=" + numCancelledKeys);
                }
                continue;
            } catch (Throwable t) {
                // don't leak sockets if we can't proceed after the accept
                if (closeOnError) {
                    closeSocketChannel(sc);
                }
                // the catcher of the RTE will do the FFDC
                throw new RuntimeException(t);
            }

            // if we made it this far, then the accept worked without exceptions
            if (0 < this.numExceptions) {
                resetExceptions();
            }
        } // end-while
        return false;
    }
912192
protected void doRequest (HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
    {
        InvocationContext context = null;
        try {
            context =  new InvocationContext(request, response);
            setContentType(request, response);

            Template template = handleRequest(request, response, context);
            if (template != null) {
                mergeTemplate(template, context);
            }

        } catch (Exception e) {
            log.warning("doRequest failed", "uri", request.getRequestURI(), e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
1226977
public static HttpRequest parseMessage(InputStream in) throws IOException {
        HttpRequest m = new HttpRequest();
        m.parse(in);
        return m;
    }
284878
protected Response executeRequest(Request request)
    {
        try
        {
            com.squareup.okhttp.Request httpRequest = buildHttpRequest(request);

            if(logger.isInfoEnabled())
                logger.info("Sending request: {} {}",httpRequest.method(),httpRequest.urlString());

            if(logger.isDebugEnabled() && request.getRequestMethod().isBodyRequest())
            {
                Buffer buffer = new Buffer();
                httpRequest.body().writeTo(buffer);
                if(maxLoggedBodySize == -1 || buffer.size() <= maxLoggedBodySize )
                    logger.debug("Request body: {}", buffer.readUtf8());
                else
                    logger.debug("Request body not captured: too large. ");
            }

            if(logger.isTraceEnabled())
                logger.trace("Request headers: {}",httpRequest.headers().toString());

            Response response = client.newCall(httpRequest).execute();

            if(response.code() == HttpURLConnection.HTTP_UNAUTHORIZED && authorizationFactory != null
                    && authorizationFactory.retryOnAuthenticationError())
            {
                if(authorizationFactory instanceof ResettableAuthorizationFactory)
                    ((ResettableAuthorizationFactory) authorizationFactory).reset();

                response = client.newCall(httpRequest).execute();
            }

            logger.info("Response code: {}",response.code());

            if(logger.isTraceEnabled())
                logger.trace("Response headers: {}",response.headers().toString());

            if(logger.isDebugEnabled())
            {
                ByteArrayOutputStream copy = new ByteArrayOutputStream();
                copy(response.body().byteStream(),copy);
                response = response.newBuilder().body(ResponseBody.create(response.body().contentType(),copy.toByteArray())).build();

                if(maxLoggedBodySize == -1 || copy.size() <= maxLoggedBodySize)
                    logger.debug("Response body: {}",copy.toString());
                else
                    logger.debug("Response body not captured: too large.");
            }
            if (response.code() >= HttpURLConnection.HTTP_BAD_REQUEST)
            {
                throw readException(response);
            }

            return response;
        }
        catch (IOException e)
        {
            throw new ClientConnectionException("Error calling service.",e);
        }

    }
64843
private static Request consume(final Request req) throws IOException {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        new RqPrint(req).printBody(baos);
        return new Request() {
            @Override
            public Iterable<String> head() throws IOException {
                return req.head();
            }

            @Override
            public InputStream body() {
                return new ByteArrayInputStream(baos.toByteArray());
            }
        };
    }
1259529
@Override
    public void handleRequest(HttpServletRequest request, HttpServletResponse response) {
        handleRequest(request, response, null, null, false);
    }
239132
public void doProcess(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException
    {
        Utility.getLogger().info("doProcess called in xmlws servlet");
        XMLMessageTransport xmlMessageTransport = null;
        ServletTask servletTask = null;
        BaseMessage msgReplyInternal = null;
        try {
            Map<String,Object> properties = m_initProperties;
        	String strDomain = BaseHttpTask.getParam(req, DBParams.DOMAIN);
        	if (strDomain != null)
        	{
		        properties = new HashMap<String,Object>();
		        if (m_initProperties != null)
		        	properties.putAll(m_initProperties);
				properties.put(DBParams.DOMAIN, strDomain);
        	}
            servletTask = new ServletTask(this, BasicServlet.SERVLET_TYPE.XML);
            servletTask.setProperties(properties);
            Environment env = null;
            if (servletTask.getApplication() != null)
                env = ((BaseApplication)servletTask.getApplication()).getEnvironment();
            if (env == null)
                env = Environment.getEnvironment(null);
            App app = env.getMessageApplication(true, properties);
            servletTask.setApplication(app);

            xmlMessageTransport = new XMLMessageTransport(servletTask);
            InputStream inStream = req.getInputStream();	// .getReader();
            Reader in = new InputStreamReader(inStream);
            String message = Utility.transferURLStream(null, null, in, null);
            try   {
                message = URLDecoder.decode(message, DBConstants.URL_ENCODING);
            } catch (java.io.UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
            //xMap<String,Object> properties = PropertiesField.stringToProperties(message);
            if (message.startsWith("xml="))	// Always
                message = message.substring(4);
            Map<String, Object> propMessage = null;
            if (message.length() == 0)
            {
            	Enumeration<?> names = req.getParameterNames();
            	while (names.hasMoreElements())
            	{
            		String key = names.nextElement().toString();
            		if ("xml".equalsIgnoreCase(key))
            			message = (String)req.getParameter(key);
            		else
            		{
            			if (propMessage == null)
            				propMessage = new HashMap<String, Object>();
            			propMessage.put(key, req.getParameter(key));	// RESTful params
            		}
            	}
            }

            BaseMessage messageIn = new TreeMessage(null, null);
            new XmlTrxMessageIn(messageIn, message);
            if (propMessage != null)
            {
            	for (String key : propMessage.keySet())
            	{
            		messageIn.put(key, propMessage.get(key));
            	}
            }

            msgReplyInternal = xmlMessageTransport.processIncomingMessage(messageIn, null);
            Utility.getLogger().info("msgReplyInternal: " + msgReplyInternal);

            int iErrorCode = xmlMessageTransport.convertToExternal(msgReplyInternal, null);
            Utility.getLogger().info("externalMessageReply: " + msgReplyInternal);

            if (iErrorCode == DBConstants.NORMAL_RETURN)
            {
            	if (msgReplyInternal.getExternalMessage() != null)
            	{	// Always
	                String strReply = msgReplyInternal.getExternalMessage().toString();
    	            res.getWriter().print(strReply);
        	        String strTrxID = (String)msgReplyInternal.getMessageHeader().get(TrxMessageHeader.LOG_TRX_ID);
            	    xmlMessageTransport.logMessage(strTrxID, msgReplyInternal, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_OUT, MessageStatusModel.SENTOK, null, null);    // Sent (no reply required)
            	}
            }
        } catch (Throwable ex)  {
            ex.printStackTrace();
            String strError = "Error in processing or replying to a message";
            Utility.getLogger().warning(strError);
            if ((msgReplyInternal != null) && (xmlMessageTransport != null))
            {
                String strTrxID = (String)msgReplyInternal.getMessageHeader().get(TrxMessageHeader.LOG_TRX_ID);
                xmlMessageTransport.logMessage(strTrxID, msgReplyInternal, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_OUT, MessageStatusModel.ERROR, strError, null);
            }
            return; // Error
        } finally   {
            if (xmlMessageTransport != null)
            {
                xmlMessageTransport.free();
                xmlMessageTransport = null;
            }
            if (servletTask != null)
                servletTask.free();
        }
    }