Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

In this page you can find the example usage for java.net Socket getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:org.apache.hadoop.hdfs.web.TestWebHdfsTimeouts.java

/**
 * Starts a background thread that accepts one and only one client connection
 * on the server socket, sends an HTTP 307 Temporary Redirect response, and
 * then exits.  This is useful for testing timeouts on the second step of
 * methods that issue 2 HTTP requests (request 1, redirect, request 2).
 * /*from  w ww  .  ja  v a 2 s.  co m*/
 * For handling the first request, this method sets socket timeout to use the
 * initial values defined in URLUtils.  Afterwards, it guarantees that the
 * second request will use a very short timeout.
 * 
 * Optionally, the thread may consume the connection backlog immediately after
 * receiving its one and only client connection.  This is useful for forcing a
 * connection timeout on the second request.
 * 
 * On tearDown, open client connections are closed, and the thread is joined.
 * 
 * @param consumeConnectionBacklog boolean whether or not to consume connection
 *   backlog and thus force a connection timeout on the second request
 */
private void startSingleTemporaryRedirectResponseThread(final boolean consumeConnectionBacklog) {
    fs.connectionFactory = URLConnectionFactory.DEFAULT_SYSTEM_CONNECTION_FACTORY;
    serverThread = new Thread() {
        @Override
        public void run() {
            Socket clientSocket = null;
            OutputStream out = null;
            InputStream in = null;
            InputStreamReader isr = null;
            BufferedReader br = null;
            try {
                // Accept one and only one client connection.
                clientSocket = serverSocket.accept();

                // Immediately setup conditions for subsequent connections.
                fs.connectionFactory = connectionFactory;
                if (consumeConnectionBacklog) {
                    consumeConnectionBacklog();
                }

                // Consume client's HTTP request by reading until EOF or empty line.
                in = clientSocket.getInputStream();
                isr = new InputStreamReader(in);
                br = new BufferedReader(isr);
                for (;;) {
                    String line = br.readLine();
                    if (line == null || line.isEmpty()) {
                        break;
                    }
                }

                // Write response.
                out = clientSocket.getOutputStream();
                out.write(temporaryRedirect().getBytes("UTF-8"));
            } catch (IOException e) {
                // Fail the test on any I/O error in the server thread.
                LOG.error("unexpected IOException in server thread", e);
                fail("unexpected IOException in server thread: " + e);
            } finally {
                // Clean it all up.
                IOUtils.cleanup(LOG, br, isr, in, out);
                IOUtils.closeSocket(clientSocket);
            }
        }
    };
    serverThread.start();
}

From source file:org.signserver.client.cli.performance.PerformanceTestPDFServlet.java

License:asdf

/** @see org.signserver.client.PerformanceTestTask */
public boolean invoke(int threadId) {
    if (startTime == 0) {
        startTime = System.currentTimeMillis();
    }/*from www  .  j a  v  a  2 s .  com*/
    byte[] testPDF = pdfs
            .get((int) ((System.currentTimeMillis() - startTime) * ((long) pdfs.size()) / runTime));
    URL target;
    try {
        target = new URL(baseURLString);
        InetAddress addr = InetAddress.getByName(target.getHost());
        Socket socket = new Socket(addr, target.getPort());
        OutputStream raw = socket.getOutputStream();
        final int contentLength = REQUEST_CONTENT_WORKERNAME.length() + REQUEST_CONTENT_FILE.length()
                + testPDF.length + REQUEST_CONTENT_END.length();
        final String command = "POST " + target.getPath() + "pdf HTTP/1.0\r\n"
                + "Content-Type: multipart/form-data; boundary=signserver\r\n" + "Content-Length: "
                + contentLength + "\r\n" + "\r\n";
        raw.write(command.getBytes());
        raw.write(REQUEST_CONTENT_WORKERNAME.getBytes());
        raw.write(REQUEST_CONTENT_FILE.getBytes());
        raw.write(testPDF);
        raw.write(REQUEST_CONTENT_END.getBytes());
        raw.flush();

        InputStream in = socket.getInputStream();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        in.close();
        os.close();
        byte[] inbytes = os.toByteArray();

        PdfReader pdfReader = new PdfReader(inbytes);
        if (!new String(pdfReader.getPageContent(1)).contains(PDF_CONTENT)) {
            System.err.println("Did not get the same document back..");
            return false;
        }
        pdfReader.close();
        raw.close();
        socket.close();
    } catch (IOException e) {
        System.err.println("testPDF.length=" + testPDF.length + "," + e.getMessage());
        //e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.jayway.maven.plugins.android.AbstractEmulatorMojo.java

/**
 * Sends a user command to the running emulator via its telnet interface.
 *
 * @param port    The emulator's telnet port.
 * @param command The command to execute on the emulator's telnet interface.
 * @return Whether sending the command succeeded.
 *///from   ww  w.ja v a2 s . c  o m
private boolean sendEmulatorCommand(
        //final Launcher launcher,
        //final PrintStream logger,
        final int port, final String command) {
    Callable<Boolean> task = new Callable<Boolean>() {
        public Boolean call() throws IOException {
            Socket socket = null;
            BufferedReader in = null;
            PrintWriter out = null;
            try {
                socket = new Socket("127.0.0.1", port);
                out = new PrintWriter(socket.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                if (in.readLine() == null) {
                    return false;
                }

                out.write(command);
                out.write("\r\n");
            } finally {
                try {
                    out.close();
                    in.close();
                    socket.close();
                } catch (Exception e) {
                    // Do nothing
                }
            }

            return true;
        }

        private static final long serialVersionUID = 1L;
    };

    boolean result = false;
    try {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<Boolean> future = executor.submit(task);
        result = future.get();
    } catch (Exception e) {
        getLog().error(String.format("Failed to execute emulator command '%s': %s", command, e));
    }

    return result;
}

From source file:hornet.framework.clamav.service.ClamAVCheckService.java

/**
 * Cette mthode permet l'envoie d'une commande  ClamAV et retourne le rsultat sous la forme d'une
 * chaine de caractre.//ww w  .j a v a 2  s  . c om
 *
 * @param command
 *            - la commade  transmettre
 * @param strEndDetection
 *            - la chaine de caractre permettant de dtecter la dernire ligne du retour.
 * @return La rponse de clamAV sans traitement
 * @throws ClamAVException
 *             the clam av exception
 */
private ClamAvResponse callClamAV(final TypeResponse command, final String strEndDetection)
        throws ClamAVException {

    ClamAvResponse result;

    final StringBuilder resultat = new StringBuilder();
    final Date dateDebut = new Date();
    Socket socket = null;
    BufferedReader buffer = null;

    try {
        socket = this.connect(command);
        if (socket == null) {
            result = ClamAvResponse.createNoServiceResponse();
        } else {
            // timeout pour l'ensemble des oprations sur la
            // socket
            socket.setSoTimeout(this.timeout);
            final InputStream input = socket.getInputStream();
            final OutputStream ouput = socket.getOutputStream();

            // envoi de la commande  clamAV
            ouput.write(("n" + command.toString() + "\n").getBytes(UTF_8));

            // Attente et traitement de la rponse
            buffer = new BufferedReader(new InputStreamReader(input, UTF_8));

            String retour = "";
            int indexResultat = -1;
            while (retour != null && indexResultat == -1) {
                retour = buffer.readLine();
                if (retour != null) {
                    indexResultat = retour.indexOf(strEndDetection);
                    resultat.append(retour);
                    resultat.append('\n');
                }
            }
            ClamAVCheckService.LOGGER.debug("Retour ClamAV (en {} ms) :\n{}",
                    new Date().getTime() - dateDebut.getTime(), resultat);
            result = this.traitementReponseClamAV(resultat.toString(), command);
        }
    } catch (final UnknownHostException e) {
        ClamAVCheckService.LOGGER.error(String.format(ERROR_ON_COMMAND, command), e);
        throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e);
    } catch (final IOException e) {
        ClamAVCheckService.LOGGER.error(String.format(ERROR_ON_COMMAND, command), e);
        throw new ClamAVException(ERR_TEC_CLAMAV_01, new String[] { e.getMessage() }, e);
    } finally {
        this.safeClose(command, socket, buffer);
    }

    return result;
}

From source file:net.demilich.metastone.bahaviour.ModifiedMCTS.MCTSCritique.java

public void sendCaffeData(double[][] data2, double[][] labels2, double[][] weights, String name,
        boolean ordered, boolean file) {
    double[][] data = new double[data2.length][];
    double[][] labels = new double[data2.length][];
    if (!ordered) {
        for (int i = 0; i < data2.length; i++) {
            data[i] = data2[i].clone();//w  w w.  j  ava2s. c  om
            labels[i] = labels2[i].clone();
        }
    } else {
        data = data2;
        labels = labels2;
    }
    try {
        String sentence;
        String modifiedSentence;
        Random generator = new Random();
        //set up our socket server

        BufferedReader inFromServer = null;
        DataOutputStream outToServer = null;
        Socket clientSocket = null;

        //add in data in a random order
        if (!file) {
            System.err.println("starting to send on socket");
            clientSocket = new Socket("localhost", 5004);
            clientSocket.setTcpNoDelay(false);
            outToServer = new DataOutputStream(clientSocket.getOutputStream());
            inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            outToServer.writeBytes(name + "\n");

            outToServer.writeBytes((data.length + " " + data[0].length + " " + labels[0].length) + "\n");
            try {
                Thread.sleep(10000);
            } catch (Exception e) {
            }
        } else {
            outToServer = new DataOutputStream((OutputStream) new FileOutputStream(name));
        }
        StringBuffer wholeMessage = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            if (i % 1000 == 0) {
                System.err.println("(constructed) i is " + i);
            }
            String features = "";
            int randomIndex = generator.nextInt(data.length - i);

            if (!ordered) {
                swap(data, i, i + randomIndex);
                swap(labels, i, i + randomIndex);
            }
            for (int a = 0; a < data[i].length; a++) {
                wholeMessage.append(data[i][a] + " ");
            }
            wholeMessage.append("\n");
            String myLabels = "";
            for (int a = 0; a < labels[i].length; a++) {
                wholeMessage.append(labels[i][a] + " ");
            }
            wholeMessage.append("\n");
            wholeMessage.append(weights[i][0] + "");
            wholeMessage.append("\n");
            outToServer.writeBytes(wholeMessage.toString());
            wholeMessage = new StringBuffer();

        }
        System.err.println("total message size is " + wholeMessage.toString().length());

        //outToServer.writeBytes(wholeMessage.toString());
        if (!file) {
            System.err.println("sending done");
            outToServer.writeBytes("done\n");
            System.err.println("waiting for ack...");
            inFromServer.readLine();
            System.err.println("got the ack!");
            clientSocket.close();
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("server wasn't waiting");
    }
    System.err.println("hey i sent somethin!");

}

From source file:com.nohkumado.ipx800control.Ipx800Control.java

/**
 sendCmd// ww  w  .ja  va2  s .  co m
 @param cmd the command to send
 opens a TCP port and sends a m2m command to the ipx, stores the eventual result in 
  return in @see returnMsg
 */
protected boolean sendCmd(String cmd) {
    Socket socket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    //System.out.println("sendcmd for "+cmd);
    try {
        //System.out.println("opening "+server+":"+port);
        socket = new Socket(server, port);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //System.out.println("about to send out cmd");
        out.println(cmd);
        //System.out.println("waiting for return");
        returnMsg = in.readLine();
        //System.out.println("return from ipx:"+returnMsg);
        if (returnMsg.matches("=")) {
            String[] parts = returnMsg.split("=");
            //String part1 = parts[0]; // Getin
            returnMsg = parts[1]; // value
        }
        out.close();
        in.close();
        socket.close();
    } catch (UnknownHostException e) {
        System.err.println("Don't know about host " + server);
        return false;
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for the connection");
        return false;
    }

    return true;
}

From source file:com.envirover.spl.SPLGroungControlTest.java

@Test
public void testMOMessagePipeline()
        throws URISyntaxException, ClientProtocolException, IOException, InterruptedException {
    System.out.println("MO TEST: Testing MO message pipeline...");

    Thread.sleep(1000);/*from   w  w  w  .j a v a  2  s  .com*/

    Thread mavlinkThread = new Thread(new Runnable() {
        public void run() {
            Socket client = null;

            try {
                System.out.printf("MO TEST: Connecting to tcp://%s:%d",
                        InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());
                System.out.println();

                client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort());

                System.out.printf("MO TEST: Connected tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(),
                        config.getMAVLinkPort());
                System.out.println();

                Parser parser = new Parser();
                DataInputStream in = new DataInputStream(client.getInputStream());
                while (true) {
                    MAVLinkPacket packet;
                    do {
                        int c = in.readUnsignedByte();
                        packet = parser.mavlink_parse_char(c);
                    } while (packet == null);

                    System.out.printf("MO TEST: MAVLink message received: msgid = %d", packet.msgid);
                    System.out.println();

                    Thread.sleep(100);
                }
            } catch (InterruptedException ex) {
                return;
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    mavlinkThread.start();

    HttpClient httpclient = HttpClients.createDefault();

    URIBuilder builder = new URIBuilder();
    builder.setScheme("http");
    builder.setHost(InetAddress.getLocalHost().getHostAddress());
    builder.setPort(config.getRockblockPort());
    builder.setPath(config.getHttpContext());

    URI uri = builder.build();
    HttpPost httppost = new HttpPost(uri);

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair("imei", config.getRockBlockIMEI()));
    params.add(new BasicNameValuePair("momsn", "12345"));
    params.add(new BasicNameValuePair("transmit_time", "12-10-10 10:41:50"));
    params.add(new BasicNameValuePair("iridium_latitude", "52.3867"));
    params.add(new BasicNameValuePair("iridium_longitude", "0.2938"));
    params.add(new BasicNameValuePair("iridium_cep", "9"));
    params.add(new BasicNameValuePair("data", Hex.encodeHexString(getSamplePacket().encodePacket())));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // Execute and get the response.
    System.out.printf("MO TEST: Sending test message to %s", uri.toString());
    System.out.println();

    HttpResponse response = httpclient.execute(httppost);

    if (response.getStatusLine().getStatusCode() != 200) {
        fail(String.format("RockBLOCK HTTP message handler status code = %d.",
                response.getStatusLine().getStatusCode()));
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream responseStream = entity.getContent();
        try {
            String responseString = IOUtils.toString(responseStream);
            System.out.println(responseString);
        } finally {
            responseStream.close();
        }
    }

    Thread.sleep(1000);

    mavlinkThread.interrupt();
    System.out.println("MO TEST: Complete.");
}

From source file:gobblin.tunnel.TalkPastServer.java

@Override
void handleClientSocket(Socket clientSocket) throws IOException {
    LOG.info("Writing to client");
    try {/*  w  ww.j  a va2s .c o m*/
        final BufferedOutputStream serverOut = new BufferedOutputStream(clientSocket.getOutputStream());
        EasyThread clientWriterThread = new EasyThread() {
            @Override
            void runQuietly() throws Exception {
                long t = System.currentTimeMillis();
                try {
                    for (int i = 0; i < nMsgs; i++) {
                        serverOut.write(generateMsgFromServer(i).getBytes());
                        sleepQuietly(2);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                LOG.info("Server done writing in " + (System.currentTimeMillis() - t) + " ms");
            }
        }.startThread();
        _threads.add(clientWriterThread);

        BufferedReader serverIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String line = serverIn.readLine();
        while (line != null && !line.equals("Goodbye")) {
            String[] tokens = line.split(":", 2);
            String client = tokens[0];
            digestMsgsRecvdAtServer.get(client).update(line.getBytes());
            digestMsgsRecvdAtServer.get(client).update("\n".getBytes());
            line = serverIn.readLine();
        }
        LOG.info("Server done reading");
        try {
            clientWriterThread.join();
        } catch (InterruptedException e) {
        }
        serverOut.write("Goodbye\n".getBytes());
        serverOut.flush();
        clientSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:mamo.vanillaVotifier.VotifierServer.java

public synchronized void start() throws IOException {
    if (isRunning()) {
        throw new IllegalStateException("Server is already running!");
    }/* ww  w  . j a va  2s  .  c  o  m*/
    notifyListeners(new ServerStartingEvent());
    serverSocket = new ServerSocket();
    serverSocket.bind(votifier.getConfig().getInetSocketAddress());
    running = true;
    notifyListeners(new ServerStartedEvent());
    new Thread(new Runnable() {
        @Override
        public void run() {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            while (isRunning()) {
                try {
                    final Socket socket = serverSocket.accept();
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                notifyListeners(new ConnectionEstablishedEvent(socket));
                                socket.setSoTimeout(SocketOptions.SO_TIMEOUT); // SocketException: handled by try/catch.
                                BufferedWriter writer = new BufferedWriter(
                                        new OutputStreamWriter(socket.getOutputStream()));
                                writer.write("VOTIFIER 2.9\n");
                                writer.flush();
                                BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // IOException: handled by try/catch.
                                byte[] request = new byte[((RSAPublicKey) votifier.getConfig().getKeyPair()
                                        .getPublic()).getModulus().bitLength() / Byte.SIZE];
                                in.read(request); // IOException: handled by try/catch.
                                notifyListeners(new EncryptedInputReceivedEvent(socket, new String(request)));
                                request = RsaUtils
                                        .getDecryptCipher(votifier.getConfig().getKeyPair().getPrivate())
                                        .doFinal(request); // IllegalBlockSizeException: can't happen.
                                String requestString = new String(request);
                                notifyListeners(new DecryptedInputReceivedEvent(socket, requestString));
                                String[] requestArray = requestString.split("\n");
                                if ((requestArray.length == 5 || requestArray.length == 6)
                                        && requestArray[0].equals("VOTE")) {
                                    notifyListeners(new VoteEventVotifier(socket, new Vote(requestArray[1],
                                            requestArray[2], requestArray[3], requestArray[4])));
                                    for (VoteAction voteAction : votifier.getConfig().getVoteActions()) {
                                        String[] params = new String[4];
                                        try {
                                            for (int i = 0; i < params.length; i++) {
                                                params[i] = SubstitutionUtils.applyRegexReplacements(
                                                        requestArray[i + 1], voteAction.getRegexReplacements());
                                            }
                                        } catch (PatternSyntaxException e) {
                                            notifyListeners(new RegularExpressionPatternErrorException(e));
                                            params = new String[] { requestArray[1], requestArray[2],
                                                    requestArray[3], requestArray[4] };
                                        }
                                        if (voteAction.getCommandSender() instanceof RconCommandSender) {
                                            RconCommandSender commandSender = (RconCommandSender) voteAction
                                                    .getCommandSender();
                                            StrSubstitutor substitutor = SubstitutionUtils.buildStrSubstitutor(
                                                    new SimpleEntry<String, Object>("service-name", params[0]),
                                                    new SimpleEntry<String, Object>("user-name", params[1]),
                                                    new SimpleEntry<String, Object>("address", params[2]),
                                                    new SimpleEntry<String, Object>("timestamp", params[3]));
                                            for (String command : voteAction.getCommands()) {
                                                String theCommand = substitutor.replace(command);
                                                notifyListeners(new SendingRconCommandEvent(
                                                        commandSender.getRconConnection(), theCommand));
                                                try {
                                                    notifyListeners(new RconCommandResponseEvent(
                                                            commandSender.getRconConnection(), commandSender
                                                                    .sendCommand(theCommand).getPayload()));
                                                } catch (Exception e) {
                                                    notifyListeners(new RconExceptionEvent(
                                                            commandSender.getRconConnection(), e));
                                                }
                                            }
                                        }
                                        if (voteAction.getCommandSender() instanceof ShellCommandSender) {
                                            ShellCommandSender commandSender = (ShellCommandSender) voteAction
                                                    .getCommandSender();
                                            HashMap<String, String> environment = new HashMap<String, String>();
                                            environment.put("voteServiceName", params[0]);
                                            environment.put("voteUserName", params[1]);
                                            environment.put("voteAddress", params[2]);
                                            environment.put("voteTimestamp", params[3]);
                                            for (String command : voteAction.getCommands()) {
                                                notifyListeners(new SendingShellCommandEvent(command));
                                                try {
                                                    commandSender.sendCommand(command, environment);
                                                    notifyListeners(new ShellCommandSentEvent());
                                                } catch (Exception e) {
                                                    notifyListeners(new ShellCommandExceptionEvent(e));
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    notifyListeners(new InvalidRequestEvent(socket, requestString));
                                }
                            } catch (SocketTimeoutException e) {
                                notifyListeners(new ReadTimedOutExceptionEvent(socket, e));
                            } catch (BadPaddingException e) {
                                notifyListeners(new DecryptInputExceptionEvent(socket, e));
                            } catch (Exception e) {
                                notifyListeners(new CommunicationExceptionEvent(socket, e));
                            }
                            try {
                                socket.close();
                                notifyListeners(new ConnectionClosedEvent(socket));
                            } catch (Exception e) { // IOException: catching just in case. Continue even if socket doesn't close.
                                notifyListeners(new ConnectionCloseExceptionEvent(socket, e));
                            }
                        }
                    });
                } catch (Exception e) {
                    if (running) { // Show errors only while running, to hide error while stopping.
                        notifyListeners(new ConnectionEstablishExceptionEvent(e));
                    }
                }
            }
            executorService.shutdown();
            if (!executorService.isTerminated()) {
                notifyListeners(new ServerAwaitingTaskCompletionEvent());
                try {
                    executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
                } catch (Exception e) {
                    // InterruptedException: can't happen.
                }
            }
            notifyListeners(new ServerStoppedEvent());
        }
    }).start();
}

From source file:com.tasktop.c2c.server.web.proxy.ajp.AjpProtocol.java

public void forward(HttpServletRequest request, HttpServletResponse response) throws IOException {
    debug(request, "forward");

    Packet packet = new Packet();
    packet.reset();//from ww  w. j  av  a2  s  .  c o  m
    // AJP13_FORWARD_REQUEST
    packet.write(Type.REQUEST_FORWARD.code);
    packet.write(computeMethod(request.getMethod()).code);
    packet.write(request.getProtocol());
    packet.write(request.getRequestURI());
    packet.write(request.getRemoteAddr());
    packet.write(request.getRemoteAddr());
    packet.write(request.getServerName());
    packet.write(request.getServerPort());
    packet.write(request.isSecure());

    // request headers
    Map<String, String> headers = new HashMap<String, String>();
    @SuppressWarnings("rawtypes")
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement().toString();
        String headerValue = request.getHeader(headerName);
        headerValue = headerFilter.processRequestHeader(headerName, headerValue);
        if (headerValue != null) {
            headers.put(headerName, headerValue);
        }
    }
    packet.write(headers.size());
    for (Map.Entry<String, String> header : headers.entrySet()) {
        HttpRequestHeader headerType = HttpRequestHeader.fromHeaderName(header.getKey());
        if (headerType != null) {
            packet.write(headerType.code);
        } else {
            packet.write(header.getKey());
        }
        String headerValue = header.getValue();
        packet.write(headerValue == null ? "" : headerValue);
    }

    // request attributes
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        packet.write(Attribute.REMOTE_USER.code);
        packet.write(authentication.getName());
    }

    String queryString = request.getQueryString();
    if (queryString != null) {
        packet.write(Attribute.QUERY_STRING.code);
        packet.write(queryString);
    }

    // packet terminator
    packet.write((byte) 0xff);

    final Object socketKey = new AjpPoolableConnectionFactory.Key(proxyHost, proxyPort);
    Socket connection;

    try {
        connection = allocateSocket(socketKey);
        debug("allocated", connection);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        throw new RuntimeException(e);
    }

    boolean invalidate = true;
    try {
        OutputStream outputStream = connection.getOutputStream();
        InputStream inputStream = connection.getInputStream();
        packet.write(outputStream);
        packet.reset();

        int bytesWritten = 0;

        int contentLength = request.getContentLength();
        if (contentLength == -1) { // Unknown content length
            contentLength = Integer.MAX_VALUE;
        }
        ServletInputStream requestInput = request.getInputStream();

        OutputStream responseOutput = null;
        boolean reuse = false;

        if (request.getHeader("Content-Length") != null) {
            bytesWritten += processRequestBody(packet, outputStream, bytesWritten, contentLength, requestInput,
                    contentLength);
            debug("sent [" + bytesWritten + "] initial body bytes", connection);
        }

        for (;; packet.reset()) {
            debug("reading packet", connection);
            packet.read(inputStream);

            Type packetType = Type.fromCode(packet.readByte());
            debug("received " + packetType, connection);
            if (packetType == Type.END_RESPONSE) {
                reuse = packet.readBoolean();
                break;
            }
            switch (packetType) {
            case GET_BODY_CHUNK:
                int requestedSize = packet.readInt();
                packet.reset();
                int chunkSize = processRequestBody(packet, outputStream, bytesWritten, contentLength,
                        requestInput, requestedSize);
                bytesWritten += chunkSize;
                debug("sent [" + chunkSize + "] bytes of body chunk", connection);
                break;
            case SEND_HEADERS: {
                response.reset();
                int httpStatusCode = packet.readInt();
                packet.readString(); // status message, not used
                response.setStatus(httpStatusCode);
                int headerCount = packet.readInt();
                for (int x = 0; x < headerCount; ++x) {
                    byte b = packet.readByte();
                    packet.unreadByte();
                    String headerName;
                    if (b == ((byte) 0xA0)) {
                        int headerCode = packet.readInt();
                        headerName = HttpResponseHeader.fromCode(headerCode).headerName;
                    } else {
                        headerName = packet.readString();
                    }
                    String headerValue = packet.readString();
                    headerValue = headerFilter.processResponseHeader(headerName, headerValue);
                    if (headerValue != null) {
                        response.setHeader(headerName, headerValue);
                    }
                }
            }
                break;
            case SEND_BODY_CHUNK:
                if (responseOutput == null) {
                    responseOutput = response.getOutputStream();
                }
                packet.copy(responseOutput);
                break;
            }
        }

        // ORDER DEPENDENCY: this should come last
        invalidate = !reuse;

        if (responseOutput != null) {
            responseOutput.close();
        }
    } finally {
        if (!shareConnections) {
            invalidate = true;
        }
        deallocateSocket(socketKey, connection, invalidate);
        debug("released " + (invalidate ? "invalidate" : "reuse"), connection);
    }
}