List of usage examples for org.apache.commons.httpclient Cookie getSecure
public boolean getSecure()
From source file:com.gargoylesoftware.htmlunit.javascript.host.DocumentTest.java
private void checkCookie(final Cookie cookie, final String name, final String value, final String path, final String domain, final boolean secure, final Date date) { assertEquals(name, cookie.getName()); assertEquals(value, cookie.getValue()); assertNull(cookie.getComment());/*from w w w .jav a2 s . co m*/ assertEquals(path, cookie.getPath()); assertEquals(domain, cookie.getDomain()); assertEquals(secure, cookie.getSecure()); assertEquals(date, cookie.getExpiryDate()); }
From source file:org.archive.crawler.fetcher.OptimizeFetchHTTP.java
/** * Saves cookies to a file.//from ww w . ja v a 2 s. c o m * * Output file is in the Netscape 'cookies.txt' format. * * @param saveCookiesFile output file. */ public void saveCookies(String saveCookiesFile) { // Do nothing if cookiesFile is not specified. if (saveCookiesFile == null || saveCookiesFile.length() <= 0) { return; } FileOutputStream out = null; try { out = new FileOutputStream(new File(saveCookiesFile)); @SuppressWarnings("unchecked") HttpClient http = this.getClient(); Map<String, Cookie> cookies = http.getState().getCookiesMap(); 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()) { MutableString line = new MutableString(1024 * 2 /*Guess an initial size*/); line.append(cookie.getDomain()); line.append(tab); line.append(cookie.isDomainAttributeSpecified() == true ? "TRUE" : "FALSE"); line.append(tab); line.append(cookie.getPath()); line.append(tab); line.append(cookie.getSecure() == true ? "TRUE" : "FALSE"); line.append(tab); line.append(cookie.getName()); line.append(tab); line.append((null == cookie.getValue()) ? "" : cookie.getValue()); line.append("\n"); out.write(line.toString().getBytes()); } } catch (FileNotFoundException e) { // We should probably throw FatalConfigurationException. System.out.println("Could not find file: " + saveCookiesFile + " (Element: " + ATTR_SAVE_COOKIES + ")"); } catch (IOException e) { e.printStackTrace(); } finally { try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } }
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;//from ww w.j a v a2s .c om } 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();/*w ww . j av a 2 s .c o 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"); }/*from w ww. j a v a 2 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()); }/*from w w w .j a v a 2 s . com*/ 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 a v a 2 s .c o m*/ 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();// w w w. jav a2 s . c o m 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()); 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()); } else {/*from w w w . j a v a 2s. c o m*/ assertEquals("cookie2", cookie.getName()); assertEquals("value2", cookie.getValue()); assertFalse(cookie.getSecure()); } }