Example usage for org.apache.commons.httpclient Cookie getPath

List of usage examples for org.apache.commons.httpclient Cookie getPath

Introduction

In this page you can find the example usage for org.apache.commons.httpclient Cookie getPath.

Prototype

public String getPath() 

Source Link

Usage

From source file:org.archive.modules.fetcher.AbstractCookieStorage.java

public static void saveCookies(String saveCookiesFile, Map<String, Cookie> cookies) {
    // Do nothing if cookiesFile is not specified. 
    if (saveCookiesFile == null || saveCookiesFile.length() <= 0) {
        return;/*  w w  w.j  a va 2  s  .co  m*/
    }

    FileOutputStream out = null;
    try {
        out = new FileOutputStream(new File(saveCookiesFile));
        String tab = "\t";
        out.write("# Heritrix Cookie File\n".getBytes());
        out.write("# This file is the Netscape cookies.txt format\n\n".getBytes());
        for (Cookie cookie : cookies.values()) {
            // Guess an initial size 
            MutableString line = new MutableString(1024 * 2);
            line.append(cookie.getDomain());
            line.append(tab);
            line.append(cookie.isDomainAttributeSpecified() ? "TRUE" : "FALSE");
            line.append(tab);
            line.append(cookie.getPath());
            line.append(tab);
            line.append(cookie.getSecure() ? "TRUE" : "FALSE");
            line.append(tab);
            line.append(cookie.getExpiryDate() != null ? cookie.getExpiryDate().getTime() / 1000 : -1);
            line.append(tab);
            line.append(cookie.getName());
            line.append(tab);
            line.append(cookie.getValue() != null ? cookie.getValue() : "");
            line.append("\n");
            out.write(line.toString().getBytes());
        }
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Unable to write " + saveCookiesFile, e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.codehaus.wadi.web.impl.CommonsHttpProxy.java

protected void doProxy(URI uri, WebInvocation context) throws ProxyingException {
    HttpServletRequest hreq = context.getHreq();
    HttpServletResponse hres = context.getHres();

    long startTime = System.currentTimeMillis();

    String m = hreq.getMethod();//from ww w.  j a v  a 2  s.co  m
    Class clazz = (Class) _methods.get(m);
    if (clazz == null) {
        throw new IrrecoverableException("unsupported http method: " + m);
    }

    HttpMethod hm = null;
    try {
        hm = (HttpMethod) clazz.newInstance();
    } catch (Exception e) {
        throw new IrrecoverableException("could not create HttpMethod instance", e); // should never happen
    }

    String requestURI = getRequestURI(hreq);
    hm.setPath(requestURI);

    String queryString = hreq.getQueryString();
    if (queryString != null) {
        hm.setQueryString(queryString);
        requestURI += queryString;
    }

    hm.setFollowRedirects(false);
    //hm.setURI(new URI(uri));
    hm.setStrictMode(false);

    // check connection header
    String connectionHdr = hreq.getHeader("Connection"); // TODO - what if there are multiple values ?
    if (connectionHdr != null) {
        connectionHdr = connectionHdr.toLowerCase();
        if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close"))
            connectionHdr = null; // TODO  ??
    }

    // copy headers
    boolean xForwardedFor = false;
    boolean hasContent = false;
    int contentLength = 0;
    Enumeration enm = hreq.getHeaderNames();
    while (enm.hasMoreElements()) {
        // TODO could be better than this! - using javax.servlet ?
        String hdr = (String) enm.nextElement();
        String lhdr = hdr.toLowerCase();

        if (_DontProxyHeaders.contains(lhdr))
            continue;
        if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0)
            continue;

        if ("content-length".equals(lhdr)) {
            try {
                contentLength = hreq.getIntHeader(hdr);
                hasContent = contentLength > 0;
            } catch (NumberFormatException e) {
                if (_log.isWarnEnabled())
                    _log.warn("bad Content-Length header value: " + hreq.getHeader(hdr), e);
            }
        }

        if ("content-type".equals(lhdr)) {
            hasContent = true;
        }

        Enumeration vals = hreq.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                hm.addRequestHeader(hdr, val);
                // if (_log.isInfoEnabled()) _log.info("Request " + hdr + ": " + val);
                xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); // why is this not in the outer loop ?
            }
        }
    }

    // cookies...

    // although we copy cookie headers into the request abover - commons-httpclient thinks it knows better and strips them out before sending.
    // we have to explicitly use their interface to add the cookies - painful...

    // DOH! - an org.apache.commons.httpclient.Cookie is NOT a
    // javax.servlet.http.Cookie - and it looks like the two don't
    // map onto each other without data loss...
    HttpState state = new HttpState();
    javax.servlet.http.Cookie[] cookies = hreq.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            javax.servlet.http.Cookie c = cookies[i];
            String domain = c.getDomain();
            if (domain == null) {
                domain = hreq.getServerName(); // TODO - tmp test
                // _log.warn("defaulting cookie domain");
            }
            //     domain=null;
            String cpath = c.getPath();
            if (cpath == null) {
                cpath = hreq.getContextPath(); // fix for Jetty
                // _log.warn("defaulting cookie path");
            }
            //if (_log.isTraceEnabled()) _log.trace("PATH: value="+path+" length="+(path==null?0:path.length()));
            Cookie cookie = new Cookie(domain, c.getName(), c.getValue(), cpath, c.getMaxAge(), c.getSecure()); // TODO - sort out domain
            //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.getDomain()+","+ cookie.getName()+","+ cookie.getValue()+","+ cookie.getPath()+","+ cookie.getExpiryDate()+","+ cookie.getSecure());
            state.addCookie(cookie);
            //if (_log.isTraceEnabled()) _log.trace("Cookie: "+cookie.toString());
        }
    }

    // Proxy headers
    hm.addRequestHeader("Via", "1.1 " + hreq.getLocalName() + ":" + hreq.getLocalPort() + " \"WADI\"");
    if (!xForwardedFor)
        hm.addRequestHeader("X-Forwarded-For", hreq.getRemoteAddr());
    // Max-Forwards...

    // a little bit of cache control
    //      String cache_control = hreq.getHeader("Cache-Control");
    //      if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0))
    //      httpMethod.setUseCaches(false);

    // customize Connection
    //      uc.setDoInput(true);

    int client2ServerTotal = 0;
    if (hasContent) {
        //         uc.setDoOutput(true);

        try {
            if (hm instanceof EntityEnclosingMethod)
                ((EntityEnclosingMethod) hm).setRequestBody(hreq.getInputStream());
            // TODO - do we need to close response stream at end... ?
        } catch (IOException e) {
            throw new IrrecoverableException("could not pss request input across proxy", e);
        }
    }

    try {
        HttpClient client = new HttpClient();
        HostConfiguration hc = new HostConfiguration();
        //String host=location.getAddress().getHostAddress();
        // inefficient - but stops httpclient from rejecting half our cookies...
        String host = uri.getHost();
        hc.setHost(host, uri.getPort());
        client.executeMethod(hc, hm, state);
    } catch (IOException e) // TODO
    {
        _log.warn("problem proxying connection:", e);
    }

    InputStream fromServer = null;

    // handler status codes etc.
    int code = 502;
    //      String message="Bad Gateway: could not read server response code or message";

    code = hm.getStatusCode(); // IOException
    //      message=hm.getStatusText(); // IOException
    hres.setStatus(code);
    //      hres.setStatus(code, message); - deprecated...

    try {
        fromServer = hm.getResponseBodyAsStream(); // IOException
    } catch (IOException e) {
        _log.warn("problem acquiring http client output", e);
    }

    // clear response defaults.
    hres.setHeader("Date", null);
    hres.setHeader("Server", null);

    // set response headers
    // TODO - is it a bug in Jetty that I have to start my loop at 1 ? or that key[0]==null ?
    // Try this inside Tomcat...
    Header[] headers = hm.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        String h = headers[i].toExternalForm();
        int index = h.indexOf(':');
        String key = h.substring(0, index).trim().toLowerCase();
        String val = h.substring(index + 1, h.length()).trim();
        if (val != null && !_DontProxyHeaders.contains(key)) {
            hres.addHeader(key, val);
            // if (_log.isInfoEnabled()) _log.info("Response: "+key+" - "+val);
        }
    }

    hres.addHeader("Via", "1.1 (WADI)");

    // copy server->client
    int server2ClientTotal = 0;
    if (fromServer != null) {
        try {
            OutputStream toClient = hres.getOutputStream();// IOException
            server2ClientTotal += copy(fromServer, toClient, 8192);// IOException
        } catch (IOException e) {
            _log.warn("problem proxying server response back to client", e);
        } finally {
            try {
                fromServer.close();
            } catch (IOException e) {
                // well - we did our best...
                _log.warn("problem closing server response stream", e);
            }
        }
    }

    long endTime = System.currentTimeMillis();
    long elapsed = endTime - startTime;
    if (_log.isDebugEnabled()) {
        _log.debug("in:" + client2ServerTotal + ", out:" + server2ClientTotal + ", status:" + code + ", time:"
                + elapsed + ", uri:" + uri);
    }
}

From source file:org.glite.slcs.shibclient.ShibbolethClient.java

private void dumpHttpClientCookies() {
    if (LOG.isDebugEnabled()) {
        Cookie[] cookies = this.httpClient_.getState().getCookies();
        StringBuffer sb = new StringBuffer();
        sb.append("\n");
        sb.append("---[CookiePolicy=").append(httpClient_.getParams().getCookiePolicy()).append("]---\n");
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            String path = cookie.getPath();
            String domain = cookie.getDomain();
            boolean secure = cookie.getSecure();
            int version = cookie.getVersion();
            // sb.append(name).append('=').append(value).append("\n");
            sb.append(i).append(": ").append(cookie);
            sb.append(" domain:").append(domain);
            sb.append(" path:").append(path);
            sb.append(" secure:").append(secure);
            sb.append(" version:").append(version);
            sb.append("\n");
        }//w  w  w . j  a va2 s  .c  o  m
        sb.append("---[End]---");
        LOG.debug(sb.toString());
    }
}

From source file:org.mozilla.zest.core.v1.ZestRequest.java

@Override
public ZestRequest deepCopy() {
    ZestRequest zr = new ZestRequest(this.getIndex());
    zr.setUrl(this.url);
    zr.setUrlToken(this.urlToken);
    zr.setData(this.data);
    zr.setMethod(this.method);
    zr.setHeaders(this.headers);
    zr.setFollowRedirects(this.followRedirects);

    if (this.getResponse() != null) {
        zr.setResponse(this.getResponse().deepCopy());
    }//  w w w . j  av a  2 s . c o  m
    for (ZestAssertion zt : this.getAssertions()) {
        zr.addAssertion((ZestAssertion) zt.deepCopy());
    }

    for (Cookie cookie : this.cookies) {
        zr.addCookie(new Cookie(cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath(),
                cookie.getExpiryDate(), cookie.getSecure()));
    }
    zr.cookies = this.cookies;
    zr.setEnabled(this.isEnabled());

    return zr;
}

From source file:org.mule.transport.http.CookieHelper.java

/**
 * This method formats the cookie so it can be send from server to client in a
 * {@linkplain HttpConstants#HEADER_COOKIE_SET "Set-Cookie"} header.
 *///from   w  w  w  .j ava 2  s  .com
public static String formatCookieForASetCookieHeader(Cookie cookie) {
    StringBuffer sb = new StringBuffer();
    ServerCookie.appendCookieValue(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
            cookie.getPath(), cookie.getDomain(), cookie.getComment(), -1, cookie.getSecure());

    Date expiryDate = cookie.getExpiryDate();
    if (expiryDate != null) {
        sb.append("; Expires=");
        sb.append(EXPIRE_FORMATTER.format(expiryDate));
    }

    return sb.toString();
}

From source file:org.mule.transport.http.CookieWrapperTestCase.java

@Test
public void testCookieWrapper() throws ParseException {
    cookieWrapper.setName("test");
    cookieWrapper.setValue("test");
    cookieWrapper.setDomain("localhost");
    cookieWrapper.setPath("/");
    cookieWrapper.setMaxAge("3600");
    cookieWrapper.setSecure("true");
    cookieWrapper.setVersion("1");

    mockParse();//from  www  . j a  v  a  2s .c om

    cookieWrapper.parse(mockMuleMessage, mockExpressionManager);
    Cookie cookie = cookieWrapper.createCookie();

    assertEquals("test", cookie.getName());
    assertEquals("test", cookie.getValue());
    assertEquals("localhost", cookie.getDomain());
    assertEquals("/", cookie.getPath());
    assertTrue(cookie.getSecure());
    assertEquals(1, cookie.getVersion());
}

From source file:org.mule.transport.http.CookieWrapperTestCase.java

@Test
public void testCookieWrapperWithExpressions() throws ParseException {
    cookieWrapper.setName("#[name]");
    cookieWrapper.setValue("#[value]");
    cookieWrapper.setDomain("#[domain]");
    cookieWrapper.setPath("#[path]");
    cookieWrapper.setMaxAge("#[maxAge]");
    cookieWrapper.setSecure("#[secure]");
    cookieWrapper.setVersion("#[version]");

    when(mockExpressionManager.parse("#[name]", mockMuleMessage)).thenReturn("test");
    when(mockExpressionManager.parse("#[value]", mockMuleMessage)).thenReturn("test");
    when(mockExpressionManager.parse("#[domain]", mockMuleMessage)).thenReturn("localhost");
    when(mockExpressionManager.parse("#[path]", mockMuleMessage)).thenReturn("/");
    when(mockExpressionManager.parse("#[maxAge]", mockMuleMessage)).thenReturn("3600");
    when(mockExpressionManager.parse("#[secure]", mockMuleMessage)).thenReturn("true");
    when(mockExpressionManager.parse("#[version]", mockMuleMessage)).thenReturn("1");

    cookieWrapper.parse(mockMuleMessage, mockExpressionManager);
    Cookie cookie = cookieWrapper.createCookie();

    assertEquals("test", cookie.getName());
    assertEquals("test", cookie.getValue());
    assertEquals("localhost", cookie.getDomain());
    assertEquals("/", cookie.getPath());
    assertTrue(cookie.getSecure());/*from   w ww . j av a 2s  . co  m*/
    assertEquals(1, cookie.getVersion());
}

From source file:org.mule.transport.http.HttpResponseTestCase.java

private void validateCookie(Cookie cookie) {
    if ("cookie1".equals(cookie.getName())) {
        assertEquals("value1", cookie.getValue());
        assertEquals("/", cookie.getPath());
        assertEquals("localhost", cookie.getDomain());
        validateDate(cookie.getExpiryDate());
        assertTrue(cookie.getSecure());//from   w  w  w. ja  v a 2  s.  co m
    } else {
        assertEquals("cookie2", cookie.getName());
        assertEquals("value2", cookie.getValue());
        assertFalse(cookie.getSecure());
    }
}

From source file:org.zaproxy.zap.extension.zest.dialogs.ZestRequestDialog.java

public void init(ScriptNode parent, ScriptNode node) {
    this.parent = parent;
    if (node == null) {
        this.node = new ScriptNode();
        request = new ZestRequest();
        this.node.setUserObject(request);
        add = true;//from   www  .j  a  va2 s . c  o m
    } else {
        this.node = node;
        this.request = (ZestRequest) ZestZapUtils.getElement(node);
        add = false;
    }

    this.removeAllFields();
    this.getCookieModel().clear();
    for (Cookie cookie : this.request.getCookies()) {
        this.getCookieModel().add(cookie.getDomain(), cookie.getName(), cookie.getValue(), cookie.getPath());
    }

    // Request tab
    this.addNodeSelectField(0, FIELD_URL, null, true, false);
    String url;
    if (request.getUrlToken() != null) {
        url = request.getUrlToken();
    } else if (request.getUrl() != null) {
        url = request.getUrl().toString();
    } else {
        url = "";
    }
    this.setFieldValue(FIELD_URL, url);
    this.addComboField(0, FIELD_METHOD, METHODS, request.getMethod());
    this.addCheckBoxField(0, FIELD_FOLLOW_REDIR, request.isFollowRedirects());
    this.addMultilineField(0, FIELD_HEADERS, request.getHeaders());
    this.addMultilineField(0, FIELD_BODY, request.getData());

    ZestZapUtils.setMainPopupMenu(this.getField(FIELD_URL));
    ZestZapUtils.setMainPopupMenu(this.getField(FIELD_HEADERS));
    ZestZapUtils.setMainPopupMenu(this.getField(FIELD_BODY));

    // Cookies tab
    List<JButton> buttons = new ArrayList<JButton>();
    buttons.add(getAddButton());
    buttons.add(getModifyButton());
    buttons.add(getRemoveButton());

    this.addTableField(1, this.getCookiesTable(), buttons);

    // Response tab
    if (request.getResponse() != null) {
        this.addComboField(2, FIELD_RESP_STATUS_CODE, statusCodeStrings(),
                Integer.toString(request.getResponse().getStatusCode()), false);
        this.addNumberField(2, FIELD_RESP_TIME_MS, 0, Integer.MAX_VALUE,
                (int) request.getResponse().getResponseTimeInMs());
        this.addMultilineField(2, FIELD_RESP_HEADERS, request.getResponse().getHeaders());
        this.addMultilineField(2, FIELD_RESP_BODY, request.getResponse().getBody());
    } else {
        this.addComboField(2, FIELD_RESP_STATUS_CODE, statusCodeStrings(), Integer.toString(HttpStatusCode.OK),
                false);
        this.addNumberField(2, FIELD_RESP_TIME_MS, 0, Integer.MAX_VALUE, 0);
        this.addMultilineField(2, FIELD_RESP_HEADERS, "");
        this.addMultilineField(2, FIELD_RESP_BODY, "");
    }
}

From source file:uk.gov.devonline.www.xforms.XFormsFilter.java

/**
 * stores cookies that may exist in request and passes them on to processor for usage in
 * HTTPConnectors. Instance loading and submission then uses these cookies. Important for
 * applications using auth.//from w ww. j av  a2  s  .c o m
 *
 * @param request the servlet request
 * @param adapter the WebAdapter instance
 */
protected void storeCookies(HttpServletRequest request, WebAdapter adapter) {
    javax.servlet.http.Cookie[] cookiesIn = request.getCookies();
    if (cookiesIn != null) {
        Cookie[] commonsCookies = new Cookie[cookiesIn.length];
        for (int i = 0; i < cookiesIn.length; i += 1) {
            javax.servlet.http.Cookie c = cookiesIn[i];

            String domain = c.getDomain();
            if (domain == null) {
                domain = "";
            }
            String path = c.getPath();
            if (path == null) {
                path = "/";
            }

            commonsCookies[i] = new Cookie(domain, c.getName(), c.getValue(), path, c.getMaxAge(),
                    c.getSecure());
        }
        adapter.setContextParam(AbstractHTTPConnector.REQUEST_COOKIE, commonsCookies);
    }
}