Example usage for java.net HttpCookie setValue

List of usage examples for java.net HttpCookie setValue

Introduction

In this page you can find the example usage for java.net HttpCookie setValue.

Prototype

public void setValue(String newValue) 

Source Link

Document

Assigns a new value to a cookie after the cookie is created.

Usage

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

/**
 * This methos is the implementation of the HTPP request and sends the response.
 *//* w  w  w .j ava  2 s.co  m*/
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();
    }

}

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

/**
 * This method parses the http headers from the Http content
 * @param httpheader//from ww w  . j  a v a  2  s.c o m
 * @return
 */
public HttpHeaderClient parseHttpHeaders(String httpheader) {
    char c = (char) 13;
    String[] header = httpheader.split("" + c);
    HttpHeaderClient httpClient = new HttpHeaderClient();
    String httpHeader = header[0];
    String[] httpHeaderArray = httpHeader.split(" ");
    httpClient.setHttpMethod(httpHeaderArray[0]);
    ConcurrentHashMap urlParams = new ConcurrentHashMap();
    httpClient.setResourceToObtain(ObtainUrlAndParams(httpHeaderArray[1], urlParams));
    httpClient.setParameters(urlParams);
    httpClient.setHttpVersion(httpHeaderArray[2]);
    String tmpHeader;
    String[] headerParam;
    String boundary;
    String boundaryValue;
    for (int i = 1; i < header.length; i++) {
        tmpHeader = header[i];
        //logger.info(tmpHeader);
        headerParam = splitHeaderParams(tmpHeader);
        if (headerParam[0].equals(HttpHeaderParamNames.HOST)) {
            httpClient.setHost(headerParam[1]);
        } else if (headerParam[0].equals(HttpHeaderParamNames.ACCEPT)) {
            httpClient.setAcceptResource(headerParam[1]);
        } else if (headerParam[0].equals(HttpHeaderParamNames.ACCEPT_ENCODING)) {
            httpClient.setAcceptEncoding(headerParam[1]);
        } else if (headerParam[0].equals(HttpHeaderParamNames.ACCEPT_LANGUAGE)) {
            httpClient.setAcceptLanguage(headerParam[1]);
        } else if (headerParam[0].equals(HttpHeaderParamNames.CONNECTION)) {
            httpClient.setConnection(headerParam[1]);
        } else if (headerParam[0].equals(HttpHeaderParamNames.USERAGENT)) {
            httpClient.setUserAgent(headerParam[1]);
        } else if (headerParam[0].equals(HttpHeaderParamNames.CONTENTLENGTH)) {
            httpClient.setContentLength(headerParam[1]);
        } else if (headerParam[0].equals(HttpHeaderParamNames.COOKIE)) {
            String[] cookies = headerParam[1].split(";");
            String[] cookieKeyValue;
            HttpCookie httpCookie;
            for (String cookie : cookies) {
                cookieKeyValue = cookie.split("=");
                httpCookie = new HttpCookie();
                httpCookie.setKey(cookieKeyValue[0].trim());
                httpCookie.setValue(cookieKeyValue[1].trim());
                httpClient.addCookie(httpCookie);
            }
        } else if (headerParam[0].equals(HttpHeaderParamNames.CONTENTTYPE)) {
            String[] headerParamValue = headerParam[1].split(";");
            httpClient.setContentType(headerParamValue[0].trim());
            if (headerParamValue != null && headerParamValue.length > 1) {
                if (httpClient.getContentType().equalsIgnoreCase(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)) {
                    if (headerParamValue[1].contains(HttpHeaderParamNames.BOUNDARY)) {
                        int equalToIndexInBoundary = headerParamValue[1].indexOf('=');
                        boundary = headerParamValue[1].substring(0, equalToIndexInBoundary).trim();
                        boundaryValue = headerParamValue[1].substring(equalToIndexInBoundary + 1).trim();
                        httpClient.setBoundary(boundaryValue);
                    }
                }

            }
        }
    }

    return httpClient;
}