Example usage for java.net Socket getOutputStream

List of usage examples for java.net Socket getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:com.digitalpebble.storm.crawler.protocol.http.HttpResponse.java

/**
 * Default public constructor./*from  w w  w  . j  a va  2 s. c  om*/
 * 
 * @param http
 * @param url
 * @param knownMetadata
 * @throws IOException
 * @throws HttpException
 */
public HttpResponse(HttpProtocol http, URL url, Metadata knownMetadata) throws IOException, HttpException {

    this.http = http;
    this.url = url;

    Scheme scheme = null;

    if ("http".equals(url.getProtocol())) {
        scheme = Scheme.HTTP;
    } else if ("https".equals(url.getProtocol())) {
        scheme = Scheme.HTTPS;
    } else {
        throw new IOException("Unknown scheme (not http/https) for url:" + url);
    }

    String path = "".equals(url.getFile()) ? "/" : url.getFile();

    // some servers will redirect a request with a host line like
    // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they
    // don't want the :80...

    String host = url.getHost();
    int port;
    String portString;
    if (url.getPort() == -1) {
        if (scheme == Scheme.HTTP) {
            port = 80;
        } else {
            port = 443;
        }
        portString = "";
    } else {
        port = url.getPort();
        portString = ":" + port;
    }
    Socket socket = null;

    try {
        socket = new Socket(); // create the socket
        socket.setSoTimeout(http.getTimeout());

        // connect
        String sockHost = http.useProxy() ? http.getProxyHost() : host;
        int sockPort = http.useProxy() ? http.getProxyPort() : port;
        InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort);
        socket.connect(sockAddr, http.getTimeout());

        if (scheme == Scheme.HTTPS) {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true);
            sslsocket.setUseClientMode(true);

            // Get the protocols and ciphers supported by this JVM
            Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols()));
            Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites()));

            // Intersect with preferred protocols and ciphers
            protocols.retainAll(http.getTlsPreferredProtocols());
            ciphers.retainAll(http.getTlsPreferredCipherSuites());

            sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
            sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()]));

            sslsocket.startHandshake();
            socket = sslsocket;
        }

        this.conf = http.getConf();
        if (ConfUtils.getBoolean(conf, "store.ip.address", false) == true) {
            headers.setValue("_ip_", sockAddr.getAddress().getHostAddress());
        }

        // make request
        OutputStream req = socket.getOutputStream();

        StringBuffer reqStr = new StringBuffer("GET ");
        if (http.useProxy()) {
            reqStr.append(url.getProtocol() + "://" + host + portString + path);
        } else {
            reqStr.append(path);
        }

        reqStr.append(" HTTP/1.0\r\n");

        reqStr.append("Host: ");
        reqStr.append(host);
        reqStr.append(portString);
        reqStr.append("\r\n");

        reqStr.append("Accept-Encoding: x-gzip, gzip, deflate\r\n");

        String userAgent = http.getUserAgent();
        if ((userAgent == null) || (userAgent.length() == 0)) {
            if (HttpProtocol.LOGGER.isErrorEnabled()) {
                HttpProtocol.LOGGER.error("User-agent is not set!");
            }
        } else {
            reqStr.append("User-Agent: ");
            reqStr.append(userAgent);
            reqStr.append("\r\n");
        }

        reqStr.append("Accept-Language: ");
        reqStr.append(this.http.getAcceptLanguage());
        reqStr.append("\r\n");

        reqStr.append("Accept: ");
        reqStr.append(this.http.getAccept());
        reqStr.append("\r\n");

        if (knownMetadata != null) {
            String ifModifiedSince = knownMetadata.getFirstValue("cachedLastModified");
            if (StringUtils.isNotBlank(ifModifiedSince)) {
                reqStr.append("If-Modified-Since: ");
                reqStr.append(ifModifiedSince);
                reqStr.append("\r\n");
            }

            String ifNoneMatch = knownMetadata.getFirstValue("cachedEtag");
            if (StringUtils.isNotBlank(ifNoneMatch)) {
                reqStr.append("If-None-Match: ");
                reqStr.append(ifNoneMatch);
                reqStr.append("\r\n");
            }
        }

        reqStr.append("\r\n");

        // @see http://www.w3.org/Protocols/rfc2068/rfc2068.txt for default
        // charset
        // TODO use UTF-8 and set a charset value explicitely
        byte[] reqBytes = reqStr.toString().getBytes(StandardCharsets.ISO_8859_1);

        req.write(reqBytes);
        req.flush();

        PushbackInputStream in = // process response
                new PushbackInputStream(
                        new BufferedInputStream(socket.getInputStream(), HttpProtocol.BUFFER_SIZE),
                        HttpProtocol.BUFFER_SIZE);

        StringBuffer line = new StringBuffer();

        boolean haveSeenNonContinueStatus = false;
        while (!haveSeenNonContinueStatus) {
            // parse status code line
            this.code = parseStatusLine(in, line);
            // parse headers
            parseHeaders(in, line);
            haveSeenNonContinueStatus = code != 100; // 100 is
                                                     // "Continue"
        }
        String transferEncoding = getHeader(HttpHeaders.TRANSFER_ENCODING);
        if (transferEncoding != null && "chunked".equalsIgnoreCase(transferEncoding.trim())) {
            readChunkedContent(in, line);
        } else {
            readPlainContent(in);
        }

        String contentEncoding = getHeader(HttpHeaders.CONTENT_ENCODING);
        if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
            content = http.processGzipEncoded(content, url);
        } else if ("deflate".equals(contentEncoding)) {
            content = http.processDeflateEncoded(content, url);
        } else {
            HttpProtocol.LOGGER.trace("fetched {}  bytes from {}", content.length, url);
        }

    } finally {
        if (socket != null)
            socket.close();
    }

}

From source file:fi.iki.elonen.NanoHTTPD.java

/**
 * Start the server./*  www  . j a v a  2 s .  com*/
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket
            .bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    if (inputStream == null) {
                        safeClose(finalAccept);
                        unRegisterConnection(finalAccept);
                    } else {
                        asyncRunner.exec(new Runnable() {
                            @Override
                            public void run() {
                                BufferedInputStream bufferedInputStream = null;
                                OutputStream outputStream = null;
                                try {
                                    bufferedInputStream = new BufferedInputStream(inputStream);
                                    outputStream = finalAccept.getOutputStream();
                                    TempFileManager tempFileManager = tempFileManagerFactory.create();
                                    HTTPSession session = new HTTPSession(tempFileManager, bufferedInputStream,
                                            outputStream, finalAccept.getInetAddress());
                                    while (!finalAccept.isClosed()) {
                                        session.execute();
                                    }
                                } catch (Exception e) {
                                    // When the socket is closed by the client, we throw our own SocketException
                                    // to break the  "keep alive" loop above.
                                    if (!(e instanceof SocketException
                                            && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                        e.printStackTrace();
                                    }
                                } finally {
                                    safeClose(bufferedInputStream);
                                    safeClose(outputStream);
                                    safeClose(finalAccept);
                                    unRegisterConnection(finalAccept);
                                }
                            }
                        });
                    }
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}

From source file:fm.last.android.player.StreamProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;/*w  w  w.j  a  va2 s.  c  o  m*/
    }
    Log.d(LOG_TAG, "processing");
    String url = request.getRequestLine().getUri();

    DefaultHttpClient seed = new DefaultHttpClient();
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    SingleClientConnManager mgr = new MyClientConnManager(seed.getParams(), registry);
    DefaultHttpClient http = new DefaultHttpClient(mgr, seed.getParams());
    HttpGet method = new HttpGet(url);
    for (Header h : request.getAllHeaders()) {
        method.addHeader(h);
    }
    HttpResponse realResponse = null;
    try {
        Log.d(LOG_TAG, "starting download");
        realResponse = http.execute(method);
        Log.d(LOG_TAG, "downloaded");
    } catch (ClientProtocolException e) {
        Log.e(LOG_TAG, "Error downloading", e);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error downloading", e);
    }

    if (realResponse == null) {
        return;
    }

    if (!isRunning)
        return;

    Log.d(LOG_TAG, "downloading...");

    InputStream data = realResponse.getEntity().getContent();
    StatusLine line = realResponse.getStatusLine();
    HttpResponse response = new BasicHttpResponse(line);
    response.setHeaders(realResponse.getAllHeaders());

    Log.d(LOG_TAG, "reading headers");
    StringBuilder httpString = new StringBuilder();
    httpString.append(response.getStatusLine().toString());

    httpString.append("\n");
    for (Header h : response.getAllHeaders()) {
        httpString.append(h.getName()).append(": ").append(h.getValue()).append("\n");
    }
    httpString.append("\n");
    Log.d(LOG_TAG, "headers done");

    try {
        byte[] buffer = httpString.toString().getBytes();
        int readBytes;
        Log.d(LOG_TAG, "writing to client");
        client.getOutputStream().write(buffer, 0, buffer.length);

        // Start streaming content.
        byte[] buff = new byte[8192];
        while (isRunning && (readBytes = data.read(buff, 0, buff.length)) != -1) {
            client.getOutputStream().write(buff, 0, readBytes);
        }
    } catch (Exception e) {
        Log.e("", e.getMessage(), e);
    } finally {
        mgr.shutdown();
        client.close();
        Log.d(LOG_TAG, "streaming complete");
    }
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContextCollection.java

@Override
public Socket wrapAcceptedSocket(Socket socket) throws IOException {
    InputStream ins = socket.getInputStream();

    byte[] buffer = new byte[0xFF];
    int position = 0;
    SSLCapabilities capabilities = null;

    // Read the header of TLS record
    while (position < SSLExplorer.RECORD_HEADER_SIZE) {
        int count = SSLExplorer.RECORD_HEADER_SIZE - position;
        int n = ins.read(buffer, position, count);
        if (n < 0) {
            throw new IOException("unexpected end of stream!");
        }/*from   www .j a v  a  2s .  com*/
        position += n;
    }

    // Get the required size to explore the SSL capabilities
    int recordLength = SSLExplorer.getRequiredSize(buffer, 0, position);
    if (buffer.length < recordLength) {
        buffer = Arrays.copyOf(buffer, recordLength);
    }

    while (position < recordLength) {
        int count = recordLength - position;
        int n = ins.read(buffer, position, count);
        if (n < 0) {
            throw new IOException("unexpected end of stream!");
        }
        position += n;
    }

    capabilities = SSLExplorer.explore(buffer, 0, recordLength);

    SSLContext sslContext = null;

    if (capabilities != null) {
        List<SNIServerName> serverNames = capabilities.getServerNames();
        if (serverNames != null && serverNames.size() > 0) {
            OUTER: for (SNIServerName snisn : serverNames) {
                String hostname = new String(snisn.getEncoded(), "UTF-8");
                for (int i = 0; i < dnsNames.size(); i++)
                    if (dnsNames.get(i).matcher(hostname).matches()) {
                        sslContext = sslContexts.get(i);
                        break OUTER;
                    }
            }
            if (sslContext == null) {
                // no hostname matched: send 'unrecognized_name' alert and close socket

                byte[] alert_unrecognized_name = { 21 /* alert */, 3, 1 /* TLS 1.0 */, 0,
                        2 /* length: 2 bytes */, 2 /* fatal */, 112 /* unrecognized_name */ };

                try {
                    socket.getOutputStream().write(alert_unrecognized_name);
                } finally {
                    socket.close();
                }

                StringBuilder hostname = null;
                for (SNIServerName snisn : serverNames) {
                    if (hostname == null)
                        hostname = new StringBuilder();
                    else
                        hostname.append(", ");
                    hostname.append(new String(snisn.getEncoded(), "UTF-8"));
                }

                throw new RuntimeException(
                        "no certificate configured (sending unrecognized_name alert) for hostname \"" + hostname
                                + "\"");
            }
        }
    }

    // no Server Name Indication used by the client: fall back to first sslContext
    if (sslContext == null)
        sslContext = sslContexts.get(0);

    SSLSocketFactory serviceSocketFac = sslContext.getSocketFactory();

    ByteArrayInputStream bais = new ByteArrayInputStream(buffer, 0, position);

    SSLSocket serviceSocket;
    // "serviceSocket = (SSLSocket)serviceSocketFac.createSocket(socket, bais, true);" only compileable with Java 1.8
    try {
        serviceSocket = (SSLSocket) createSocketMethod.invoke(serviceSocketFac,
                new Object[] { socket, bais, true });
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }

    sslContext.applyCiphers(serviceSocket);
    if (sslContext.getProtocols() != null) {
        serviceSocket.setEnabledProtocols(sslContext.getProtocols());
    } else {
        String[] protocols = serviceSocket.getEnabledProtocols();
        Set<String> set = new HashSet<String>();
        for (String protocol : protocols) {
            if (protocol.equals("SSLv3") || protocol.equals("SSLv2Hello")) {
                continue;
            }
            set.add(protocol);
        }
        serviceSocket.setEnabledProtocols(set.toArray(new String[0]));
    }
    serviceSocket.setWantClientAuth(sslContext.isWantClientAuth());
    serviceSocket.setNeedClientAuth(sslContext.isNeedClientAuth());

    return serviceSocket;
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

/**
 * Helper function for getRemoteCheckpoint above that actually fetches the
 * reads from the socket and writes to a local file.
 * /*from  w w  w  .  j  av  a  2  s. c  o  m*/
 * @param rcGroupName
 * @param sockAddr
 * @param remoteFilename
 * @param fileSize
 * @return
 */
private String getRemoteCheckpoint(String rcGroupName, InetSocketAddress sockAddr, String remoteFilename,
        long fileSize) {
    synchronized (this.fileSystemLock) {
        String request = remoteFilename + "\n";
        Socket sock = null;
        FileOutputStream fos = null;
        String localCPFilename = null;
        try {
            sock = new Socket(sockAddr.getAddress(), sockAddr.getPort());
            sock.getOutputStream().write(request.getBytes(CHARSET));
            InputStream inStream = (sock.getInputStream());
            if (!this.createCheckpointFile(localCPFilename = this.getCheckpointFile(rcGroupName)))
                return null;
            fos = new FileOutputStream(new File(localCPFilename));
            byte[] buf = new byte[1024];
            int nread = 0;
            int nTotalRead = 0;
            // read from sock, write to file
            while ((nread = inStream.read(buf)) >= 0) {
                /* Need to ensure that the read won't block forever if the
                 * remote endpoint crashes ungracefully and there is no
                 * exception triggered here. But this method itself is
                 * currently unused. */
                nTotalRead += nread;
                fos.write(buf, 0, nread);
            }
            // check exact expected file size
            if (nTotalRead != fileSize)
                localCPFilename = null;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
                if (sock != null)
                    sock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return localCPFilename;
    }
}

From source file:de.prozesskraft.pradar.parts.PradarPartUi3.java

/**
 * asks for entities from the first pradar-server that responds
 * @return void//from w w w .j  a  va  2 s . co m
 */
void loadData() {
    for (String portAtMachineAsString : this.pradar_server_port_at_hostname) {
        String[] port_and_machine = portAtMachineAsString.split("@");

        int portNumber = Integer.parseInt(port_and_machine[0]);
        String machineName = port_and_machine[1];
        log("info", "want to load data from pradar-server");
        log("info", "trying pradar-server " + portNumber + "@" + machineName);
        try {

            // socket einrichten und Out/Input-Streams setzen
            //            log("debug", "machineName="+machineName+" | portNumber="+portNumber);

            //            log("debug", "server objekt erstellen");
            Socket connectToServerSocket = new Socket(machineName, portNumber);
            connectToServerSocket.setSoTimeout(20000);

            //            log("debug", "outputStream erstellen");
            OutputStream streamToServer = connectToServerSocket.getOutputStream();

            //            log("debug", "outputStream  flushen");
            streamToServer.flush();

            //            log("debug", "objectOutputStream  erstellen");
            ObjectOutputStream objectToServer = new ObjectOutputStream(streamToServer);

            //            log("debug", "objectOutputStream  flushen");
            objectToServer.flush();

            // Objekte zum server uebertragen
            //            log("debug", "write: getallfromuser");
            objectToServer.writeObject("getallfromuser");
            objectToServer.writeObject(System.getProperty("user.name"));

            //            log("debug", "outputStream  flushen");
            streamToServer.flush();

            //            log("debug", "objectOutputStream  flushen");
            objectToServer.flush();

            // sende-object zerstoeren - wird nicht mehr gebraucht
            //            log("debug", "objectOutputStream schliessen");
            //            objectToServer.close();

            //            log("debug", "inputStream erstellen");
            InputStream streamFromServer = connectToServerSocket.getInputStream();

            //            log("debug", "objectInputStream  erstellen");
            ObjectInputStream objectFromServer = new ObjectInputStream(streamFromServer);

            // Antwort vom Server lesen - ein array aller Entities
            try {
                //               log("debug", "reading");
                Object serverAnswer = objectFromServer.readObject();
                //               log("debug", "reading done");

                // lese-object zerstoeren - wird nicht mehr gebraucht
                objectFromServer.close();
                //               log("debug", "objectFromServer closed");

                ArrayList<Object> serverAnswer2 = null;
                if (serverAnswer instanceof ArrayList) {
                    //                  log("debug", "serverAnswer is an ArrayList");
                    serverAnswer2 = (ArrayList<Object>) serverAnswer;
                }

                // alle existierenden entities loeschen
                this.entities_all.clear();

                // die neuen entities casten und in einem map unterbringen id->Entities erstellen um die children bei ihren parents einsortieren zu koennen
                Map<String, Entity> entities_all = new HashMap<String, Entity>();
                for (Object actObject : serverAnswer2) {
                    // 
                    if (actObject instanceof Entity) {
                        //                     log("debug", "item of ArrayList<Object> is an Entity  --->  adding to ArrayList<Entity>");
                        Entity newEntity = (Entity) actObject;
                        this.entities_all.add(newEntity);
                    }
                }

                //               log("debug", "reading done! closing ");
                objectFromServer.close();

                //               log("debug", "read finished");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // daten holen aus db
            log("info", "refreshing data...");
            connectToServerSocket.close();

        } catch (UnknownHostException e) {
            log("warn", "unknown host " + machineName);
            this.pradar_server_port_at_hostname = null;
        } catch (IOException e) {
            log("warn", "input / output problems at " + portNumber + "@" + machineName);
            e.printStackTrace();
        }

        this.refresh_last = Calendar.getInstance();
        this.refresh_next = Calendar.getInstance();
        this.refresh_next.add(13, this.refresh_interval);
    }
}

From source file:LCModels.MessageListener.java

public void run() {
    /* Keep Thread running */
    while (true) {
        try {//  w w w  .  j a va2 s  .  com
            /* Accept connection on server */
            Socket serverSocket = server.accept();
            /* DataInputStream to get message sent by client program */
            DataInputStream in = new DataInputStream(serverSocket.getInputStream());
            /* We are receiving message in JSON format from client. Parse String to JSONObject */
            JSONObject clientMessage = new JSONObject(in.readUTF());

            /* Flag to check chat window is opened for user that sent message */
            boolean flagChatWindowOpened = false;
            /* Reading Message and Username from JSONObject */
            String userName = clientMessage.get("Username").toString();
            String message = clientMessage.getString("Message").toString();

            /* Get list of Frame/Windows opened by mainFrame.java */
            for (Frame frame : Frame.getFrames()) {
                /* Check Frame/Window is opened for user */
                if (frame.getTitle().equals(userName)) {
                    /* Frame/ Window is already opened */
                    flagChatWindowOpened = true;
                    /* Get instance of ChatWindow */
                    ChatWindowUI chatWindow = (ChatWindowUI) frame;
                    /* Get previous messages from TextArea */
                    String previousMessage = chatWindow.getMessageArea().getText();
                    /* Set message to TextArea with new message */
                    chatWindow.getMessageArea().setText(previousMessage + "\n" + userName + ": " + message);
                }
            }

            /* ChatWindow is not open for user sent message to server */
            if (!flagChatWindowOpened) {
                /* Create an Object of ChatWindow */
                ChatWindowUI chatWindow = new ChatWindowUI();
                /**
                 * We are setting title of window to identify user for next
                 * message we gonna receive You can set hidden value in
                 * ChatWindow.java file.
                 */
                chatWindow.setTitle(userName);
                /* Set message to TextArea */
                chatWindow.getMessageArea().setText(message);
                /* Make ChatWindow visible */
                chatWindow.setVisible(true);
            }

            /* Get DataOutputStream of client to repond */
            DataOutputStream out = new DataOutputStream(serverSocket.getOutputStream());
            /* Send response message to client */
            out.writeUTF("Received from " + clientMessage.get("Username").toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.web.server.WebServer.java

/**
 * This methos is the implementation of the HTPP request and sends the response.
 *///  w  w  w.  ja  va 2 s . c  om
public void run() {
    byte[] response;
    byte[] content;
    byte[] uploadData = null;
    HttpHeaderClient httpHeaderClient = null;
    InputStream istream = null;
    OutputStream ostream = null;
    HttpHeaderServer serverParam = new HttpHeaderServer();
    StringBuffer buffer = new StringBuffer();
    String value;
    char c;
    String endvalue = "\r\n\r\n";
    String urlFormEncoded;
    int responseCode;
    try {
        ////System.out.println("value=");
        istream = socket.getInputStream();
        BufferedInputStream bistr = new BufferedInputStream(istream);
        //socket.setReceiveBufferSize(10000);
        //System.out.println("value1=");
        int availbleStream;
        int totalBytRead = 0;
        int ch;
        ByteArrayOutputStream bytout = new ByteArrayOutputStream();
        ByteArrayOutputStream contentout = new ByteArrayOutputStream();
        //System.out.println(istream.available());
        int bytesRead;
        int endbytIndex = 0;
        int contentbytIndex = 0;
        boolean httpHeaderEndFound = false;
        byte[] byt;
        while ((ch = bistr.read()) != -1) {
            bytout.write(ch);
            if (!httpHeaderEndFound && (char) ch == endvalue.charAt(endbytIndex)) {
                endbytIndex++;
                if (endbytIndex == endvalue.length()) {
                    byt = bytout.toByteArray();
                    value = new String(ObtainBytes(byt, 0, byt.length - 4));
                    //System.out.println(value);
                    httpHeaderClient = parseHttpHeaders(value);
                    httpHeaderEndFound = true;
                    bytout.close();
                    endbytIndex = 0;
                    if (httpHeaderClient.getContentLength() == null)
                        break;
                }
            } else {
                endbytIndex = 0;
            }
            if (httpHeaderClient != null && httpHeaderEndFound) {
                contentout.write(ch);
                contentbytIndex++;
                if (httpHeaderClient.getContentLength() != null
                        && contentbytIndex >= Integer.parseInt(httpHeaderClient.getContentLength())) {
                    break;
                }
            }
            totalBytRead++;
        }
        /*while(totalBytRead==0){
           while((ch = bistr.read())!=-1){
              System.out.println((char)ch);
              ////System.out.println("availableStream="+availbleStream);
              bytarrayOutput.write(ch);
              totalBytRead++;
           }
        }*/
        if (totalBytRead == 0) {
            System.out.println("Since byte is 0 sock and istream os closed");
            //istream.close();
            socket.close();
            return;
        }
        //istream.read(bt,0,9999999);
        System.out.println("bytes read");
        byte[] contentByte = contentout.toByteArray();
        contentout.close();
        //System.out.println("String="+new String(bt));
        /*int index=containbytes(bt,endvalue.getBytes());
        if(index==-1)index=totalBytRead;
        value=new String(ObtainBytes(bt,0,index));*/
        System.out.println("value2=");

        ConcurrentHashMap<String, HttpCookie> httpCookies = httpHeaderClient.getCookies();
        HttpSessionServer session = null;
        if (httpCookies != null) {
            Iterator<String> cookieNames = httpCookies.keySet().iterator();
            for (; cookieNames.hasNext();) {
                String cookieName = cookieNames.next();
                //System.out.println(cookieName+" "+httpCookies.get(cookieName).getValue());
                if (cookieName.equals("SERVERSESSIONID")) {
                    session = (HttpSessionServer) sessionObjects.get(httpCookies.get(cookieName).getValue());
                    httpHeaderClient.setSession(session);
                    //break;
                }
            }
        }
        //System.out.println("Session="+session);
        if (session == null) {
            HttpCookie cookie = new HttpCookie();
            cookie.setKey("SERVERSESSIONID");
            cookie.setValue(UUID.randomUUID().toString());
            httpCookies.put("SERVERSESSIONID", cookie);
            session = new HttpSessionServer();
            sessionObjects.put(cookie.getValue(), session);
            httpHeaderClient.setSession(session);
        }
        if (httpHeaderClient.getContentType() != null
                && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)) {
            ////System.out.println(new String(uploadData));
            ConcurrentHashMap paramMap = new MultipartFormData().parseContent(contentByte, httpHeaderClient);
            httpHeaderClient.setParameters(paramMap);
            ////logger.info(uploadData);
        } else if (httpHeaderClient.getContentType() != null
                && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.URLENCODED)) {
            urlFormEncoded = new String(contentByte);
            ConcurrentHashMap paramMap = parseUrlEncoded(urlFormEncoded);
            httpHeaderClient.setParameters(paramMap);
        }
        ////logger.info(serverconfig.getDeploydirectory()+httpHeaderClient.getResourceToObtain());
        ////System.out.println("value3=");

        ////logger.info(new String(bt));
        serverParam.setContentType("text/html");
        URLDecoder decoder = new URLDecoder();
        System.out.println("content Length= " + socket);
        responseCode = 200;
        File file = new File(deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain()));
        FileContent fileContent = (FileContent) cache.get(httpHeaderClient.getResourceToObtain());
        if (fileContent != null && file.lastModified() == fileContent.getLastModified()) {
            System.out.println("In cache");
            content = (byte[]) fileContent.getContent();
        } else {
            content = ObtainContentExecutor(deployDirectory, httpHeaderClient.getResourceToObtain(),
                    httpHeaderClient, serverdigester, urlClassLoaderMap, servletMapping, session);
            System.out.println("content Length2= " + content);
            if (content == null) {
                //System.out.println("In caching content");
                content = obtainContent(
                        deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain()));
                if (content != null) {
                    fileContent = new FileContent();
                    fileContent.setContent(content);
                    fileContent.setFileName(httpHeaderClient.getResourceToObtain());
                    fileContent.setLastModified(file.lastModified());
                    cache.put(httpHeaderClient.getResourceToObtain(), fileContent);
                }
            }
            ////System.out.println("value4=");

        }

        if (content == null) {
            responseCode = 404;
            content = ("<html><body><H1>The Request resource " + httpHeaderClient.resourceToObtain
                    + " Not Found</H1><body></html>").getBytes();
        }
        ////System.out.println("content Length3= ");
        serverParam.setContentLength("" + (content.length + 4));
        if (httpHeaderClient.getResourceToObtain().endsWith(".ico")) {
            serverParam.setContentType("image/png");
        }
        ////System.out.println("value5=");

        ////System.out.println("content Length4= ");
        response = formHttpResponseHeader(responseCode, serverParam, content, httpHeaderClient.getCookies());
        ////System.out.println("value6=");
        ostream = socket.getOutputStream();
        //logger.info("Response="+new String(response));
        //System.out.println("value6=");
        //logger.info("Response="+new String(response));
        ////System.out.println("content "+"Response="+new String(response));
        ostream.write(response);
        ostream.flush();
        ostream.close();
        socket.close();
    } catch (IOException e) {
        Socket socket;
        e.printStackTrace();

        //logger.error(e);
        try {
            socket = new Socket("localhost", shutdownPort);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
            outputStream.close();
        } catch (Exception ex) {

            ex.printStackTrace();
        }
        e.printStackTrace();
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}