/** * * sendResponse checks for the mode of the server and sends a Response object to the client with * the appropriate string stored and the client's Cookie. * * @param clientCookie - Cookie object received by client * @param responseToClient - Response object that will be sent to client * @param outputObject - Used to write serialized version of object back to client * @throws IOException - Thrown if outputObject is interrupted while processing or fails to * process */ static void sendResponse( Cookie clientCookie, Response responseToClient, ObjectOutputStream outputObject) throws IOException { if (mode.getMode() == ServerMode.JOKE) { // If the mode of the server is set to JOKE, send joke responseToClient.addResponse( joke.say( clientCookie .getJokeKey())); // gets joke from Database and stores string in responseToClient clientCookie.nextJoke(); // clientCookie increments the index of the joke to be accessed later responseToClient.setCookie(clientCookie); // stores clientCookie in responseToClient System.out.println("Sending joke response..."); // notify server joke is being sent outputObject.writeObject( responseToClient); // send a serialized version of Response object to client } else if (mode.getMode() == ServerMode.PROVERB) { // If the mode of the server is set to PROVERB, send proverb responseToClient.addResponse(proverb.say(clientCookie.getProverbKey())); clientCookie.nextProverb(); responseToClient.setCookie(clientCookie); System.out.println("Sending proverb response..."); outputObject.writeObject( responseToClient); // send Response object with proverb and client's Cookie to the client } else if (mode.getMode() == ServerMode .MAINTENANCE) { // If the mode of the server is set to MAINTENANCE, notify clients // server is down for maintenance responseToClient.addResponse("Joke server temporarily down for maintenance.\n"); responseToClient.setCookie(clientCookie); System.out.println("Sending maintenance response..."); outputObject.writeObject( responseToClient); // send Response object with maintenance message and client's Cookie to // the client } }
// BEGIN IA/HERITRIX CHANGES public /*synchronized*/ void addCookie(Cookie cookie) { LOG.trace("enter HttpState.addCookie(Cookie)"); // PRIOR IMPL & COMPARISON HARNESS LEFT COMMENTED OUT FOR TEMPORARY REFERENCE // Cookie removed1 = null; // Cookie removed2 = null; if (cookie != null) { // first remove any old cookie that is equivalent // for (Iterator it = cookiesArrayList.iterator(); it.hasNext();) { // Cookie tmp = (Cookie) it.next(); // if (cookie.equals(tmp)) { // it.remove(); // removed1 = tmp; // break; // } // } if (!cookie.isExpired()) { // cookiesArrayList.add(cookie); cookiesMap.put(cookie.getSortKey(), cookie); } else { cookiesMap.remove(cookie.getSortKey()); } } // if(removed1!=null && !removed1.equals(removed2)) { // System.out.println("addCookie discrepancy"); // } // END IA/HERITRIX CHANGES }
/** Sets cookies to the request. */ public HttpRequest cookies(Cookie... cookies) { if (cookies.length == 0) { return this; } StringBuilder cookieString = new StringBuilder(); boolean first = true; for (Cookie cookie : cookies) { Integer maxAge = cookie.getMaxAge(); if (maxAge != null && maxAge.intValue() == 0) { continue; } if (!first) { cookieString.append("; "); } first = false; cookieString.append(cookie.getName()); cookieString.append('='); cookieString.append(cookie.getValue()); } header("cookie", cookieString.toString(), true); return this; }
private static void saveCookies() { if (cookie_jar != null && (!cookie_jar.exists() || cookie_jar.isFile() && cookie_jar.canWrite())) { Hashtable cookie_list = new Hashtable(); Enumeration en = Util.getList(cookie_cntxt_list, HTTPConnection.getDefaultContext()).elements(); // discard cookies which are not to be kept across sessions while (en.hasMoreElements()) { Cookie cookie = (Cookie) en.nextElement(); if (!cookie.discard()) cookie_list.put(cookie, cookie); } // save any remaining cookies in jar if (cookie_list.size() > 0) { try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(cookie_jar)); oos.writeObject(cookie_list); oos.close(); } catch (IOException t) { if (LOG.isTraceEnabled()) { LOG.trace("An exception occurred: " + t.getMessage()); } } } } }
public static String generateCookie(Cookie cookie) { if (cookie == null) { throw new IllegalArgumentException("the cookie is null"); } else { StringBuilder sb = new StringBuilder(); sb.append(cookie.getName()).append('=').append(cookie.getValue()); return sb.toString(); } }
public static void main(String[] args) { Cookie x = new Cookie(); // acceso de paquete a este método, al estar en el mismo paquete que la clase instanciada, // lo puedo usar x.bite(); // Ejemplo contrario, instancio coche que esta en otro paquete, de hecho lo tengo que importar // y no puedo acceder a su método protected. Coche opel = new Coche("opel"); // opel.printer(); }
/** * Convert a cookie list into a JSONObject. A cookie list is a sequence of name/value pairs. The * names are separated from the values by '='. The pairs are separated by ';'. The names and the * values will be unescaped, possibly converting '+' and '%' sequences. * * <p>To add a cookie to a cooklist, cookielistJSONObject.put(cookieJSONObject.getString("name"), * cookieJSONObject.getString("value")); * * @param string A cookie list string * @return A JSONObject * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); JSONTokener x = new JSONTokener(string); while (x.more()) { String name = Cookie.unescape(x.nextTo('=')); x.next('='); jo.put(name, Cookie.unescape(x.nextTo(';'))); x.next(); } return jo; }
public NewCookie(Cookie cookie, String comment, int maxAge, boolean secure) { super( cookie == null ? null : cookie.getName(), cookie == null ? null : cookie.getValue(), cookie == null ? null : cookie.getPath(), cookie == null ? null : cookie.getDomain(), cookie == null ? DEFAULT_VERSION : cookie.getVersion()); this.comment = comment; this.maxAge = maxAge; this.secure = secure; }
/** * Returns a string representation of the cookies. * * @param cookies The cookies * @return The string representation. */ private static String getCookiesStringRepresentation( final Collection<Cookie> cookies) { // <- IA/HERITRIX CHANGE StringBuffer sbResult = new StringBuffer(); Iterator<Cookie> iter = cookies.iterator(); while (iter.hasNext()) { Cookie ck = iter.next(); if (sbResult.length() > 0) { sbResult.append("#"); } sbResult.append(ck.toExternalForm()); } return sbResult.toString(); }
private String getCookies(HttpConnection req, String path) { String host = req.getHost(); if (path == null) path = "/"; boolean includeSecure = req instanceof HttpsConnection; String res = ""; for (int i = 0; i < savedCookies.size(); ++i) { Cookie c = (Cookie) savedCookies.elementAt(i); if (c.match(host, path) && (includeSecure || !c.isSecure())) { res += c.toString() + "; "; Log.logDebug("Sending Cookie: " + c.getName()); } } return res; }
public void testCookieWithoutExpiry() throws Exception { Cookie cookie = new Cookie("JSESSIONID", "XXX"); cookie.setPath("/path"); System.err.println(cookie); assertFalse(cookie.toString().contains("max-age=10")); assertFalse( cookie .toString() .matches( ".*expires=\\w\\w\\w, \\d\\d \\w\\w\\w \\d\\d\\d\\d \\d\\d:\\d\\d:\\d\\d GMT;.*")); }
public void addCookie(String key, String val, String host, String path) { Cookie c = new Cookie(key, val, host, path); // 设置Cookie String name = c.name(); String value = c.value(); List<String> vals = this.cookies.get(name); if (vals == null) vals = new ArrayList<String>(); vals.add(value); this.cookies.put(key, vals); BasicClientCookie clientCookie = new BasicClientCookie(name, value); clientCookie.setPath(c.path()); clientCookie.setDomain(c.domain()); httpClient.getCookieStore().addCookie(clientCookie); }
@Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { if (cookieHandler != null) { List<String> cookieStrings = new ArrayList<>(); for (Cookie cookie : cookies) { cookieStrings.add(cookie.toString()); } Map<String, List<String>> multimap = Collections.singletonMap("Set-Cookie", cookieStrings); try { cookieHandler.put(url.uri(), multimap); } catch (IOException e) { Internal.logger.log(WARNING, "Saving cookies failed for " + url.resolve("/..."), e); } } }
/** * Stores the cookies currently saved in memory, to the record store. * * @param cookiesStorage the name of the record store to hold the cookies. * @throws IOException */ public void storeCookies(String cookiesStorage) throws IOException { if (savedCookies.size() == 0) { Log.logInfo("No cookies to store in recordstore."); return; // nothing to save. } try { try { connector.rmsDelete(cookiesStorage); } catch (Throwable e) { // try to delete last save cookies. Log.logWarn("Failed to delete old saved cookies file. " + e.getMessage()); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); for (int i = 0; i < savedCookies.size(); ++i) { Cookie c = (Cookie) savedCookies.elementAt(i); Cookie.serialize(c, dout); } byte[] buf = bout.toByteArray(); int free = connector.rmsFree(); if (free < buf.length) throw new IOException("Not enough free storage space to save cookies."); connector.rmsWrite(cookiesStorage, buf); } catch (Throwable e) { if (e instanceof IOException) throw (IOException) e; else throw new IOException("Store cookies failed. " + e.getMessage()); } Log.logInfo("Stored " + savedCookies.size() + " to record store: " + cookiesStorage); }
private void handleCookie(String set_cookie, boolean cookie2, RoRequest req, Response resp) throws ProtocolException { Cookie[] cookies; if (cookie2) cookies = Cookie2.parse(set_cookie, req); else cookies = Cookie.parse(set_cookie, req); if (LOG.isDebugEnabled()) { LOG.debug("Received and parsed " + cookies.length + " cookies:"); for (int idx = 0; idx < cookies.length; idx++) LOG.debug("Cookie " + idx + ": " + cookies[idx]); } Hashtable cookie_list = Util.getList(cookie_cntxt_list, req.getConnection().getContext()); synchronized (cookie_list) { for (int idx = 0; idx < cookies.length; idx++) { Cookie cookie = (Cookie) cookie_list.get(cookies[idx]); if (cookie != null && cookies[idx].hasExpired()) { if (LOG.isDebugEnabled()) LOG.debug("Cookie has expired and is " + "being removed: " + cookie); cookie_list.remove(cookie); // expired, so remove } else if (!cookies[idx].hasExpired()) // new or replaced { if (cookie_handler == null || cookie_handler.acceptCookie(cookies[idx], req, resp)) cookie_list.put(cookies[idx], cookies[idx]); } } } }
/** * Creates a text representation of the given cookies. * * @param parameters the cookies * @return the text representation */ private static final String cookiesText(final Map<String, Cookie> cookies) { final StringWriter writer = new StringWriter(); writer.write("Cookie"); char separator = ' '; synchronized (cookies) { for (final Cookie cookie : cookies.values()) { writer.write(separator); writer.write(cookie.getName()); writer.write('='); writer.write(cookie.getValue()); separator = ';'; } } return writer.toString(); }
/** * Convert a JSONObject into a cookie list. A cookie list is a sequence of name/value pairs. The * names are separated from the values by '='. The pairs are separated by ';'. The characters '%', * '+', '=', and ';' in the names and values are replaced by "%hh". * * @param jo A JSONObject * @return A cookie list string * @throws JSONException If something goes wrong */ public static String toString(final JSONObject jo) throws JSONException { boolean b = false; final Iterator<String> keys = jo.keys(); String string; final StringBuilder sb = new StringBuilder(); while (keys.hasNext()) { string = keys.next(); if (!jo.isNull(string)) { if (b) sb.append(';'); sb.append(Cookie.escape(string)); sb.append("="); sb.append(Cookie.escape(jo.getString(string))); b = true; } } return sb.toString(); }
protected static void addToRequest(HttpRequest nettyRequest, Request request) { for (String key : nettyRequest.getHeaderNames()) { Http.Header hd = new Http.Header(); hd.name = key.toLowerCase(); hd.values = new ArrayList<String>(); for (String next : nettyRequest.getHeaders(key)) { hd.values.add(next); } request.headers.put(hd.name, hd); } String value = nettyRequest.getHeader(COOKIE); if (value != null) { Set<Cookie> cookies = new CookieDecoder().decode(value); if (cookies != null) { for (Cookie cookie : cookies) { Http.Cookie playCookie = new Http.Cookie(); playCookie.name = cookie.getName(); playCookie.path = cookie.getPath(); playCookie.domain = cookie.getDomain(); playCookie.secure = cookie.isSecure(); playCookie.value = cookie.getValue(); playCookie.httpOnly = cookie.isHttpOnly(); request.cookies.put(playCookie.name, playCookie); } } } }
public void processRequestCookie( HttpURLConnection connection, HashMap<String, String> cookieHeaders) { connection.setInstanceFollowRedirects(false); // ----------------------------------------------------------------------------------------------------- // 1、获取所有的Cookie集合 // ----------------------------------------------------------------------------------------------------- CookieStore cookieStore = CookieStoreHandler.getInstance(); List<Cookie> cookies = cookieStore.getCookies(); if (null == cookies || cookies.size() <= 0) { return; } // ----------------------------------------------------------------------------------------------------- // 2、获取CookieOrigin // ----------------------------------------------------------------------------------------------------- CookieOrigin cookieOrigin = getCookieOrigin(connection); // ----------------------------------------------------------------------------------------------------- // 3、过滤符合条件数据,获取符合的Cookie集合 // ----------------------------------------------------------------------------------------------------- CookieSpec cookieSpec = obtainCookieSpec(); final List<Cookie> matchedCookies = new ArrayList<Cookie>(); final Date now = new Date(); boolean expired = false; for (final Cookie cookie : cookies) { if (cookie.isExpired(now)) { // 过期了..,没有设置expire不过期 VolleyLog.v("Cookie " + cookie + " expired"); expired = true; } else { if (cookieSpec.match(cookie, cookieOrigin)) { VolleyLog.v("Cookie " + cookie + " match " + cookieOrigin); matchedCookies.add(cookie); } } } // 有过期的Cookie存在,则去掉所有过期的Cookie if (expired) { cookieStore.clearExpired(now); } // ----------------------------------------------------------------------------------------------------- // 4、将符合条件的Cookie字符串,设置成请求头headers Map中 // ----------------------------------------------------------------------------------------------------- String cookie = cookieSpec.formatCookies(matchedCookies); if (null != cookie && cookie.length() > 0) { cookieHeaders.put("Cookie", cookie); } }
public void forwardCookies(final Request request) { if (request == null) { return; } final String host = Browser.getHost(request.getUrl()); final Cookies cookies = this.getCookies().get(host); if (cookies == null) { return; } for (final Cookie cookie : cookies.getCookies()) { // Pfade sollten verarbeitet werden...TODO if (cookie.isExpired()) { continue; } request.getCookies().add(cookie); } }
/** * Convert a JSONObject into a cookie list. A cookie list is a sequence of name/value pairs. The * names are separated from the values by '='. The pairs are separated by ';'. The characters '%', * '+', '=', and ';' in the names and values are replaced by "%hh". * * @param o A JSONObject * @return A cookie list string * @throws JSONException */ public static String toString(JSONObject o) throws JSONException { boolean b = false; Iterator keys = o.keys(); String s; StringBuffer sb = new StringBuffer(); while (keys.hasNext()) { s = keys.next().toString(); if (!o.isNull(s)) { if (b) { sb.append(';'); } sb.append(Cookie.escape(s)); sb.append("="); sb.append(Cookie.escape(o.getString(s))); b = true; } } return sb.toString(); }
private String normalizePath(final Cookie cookie) { String path = cookie.getPath(); if (path == null) { path = "/"; } if (!path.endsWith("/")) { path = path + '/'; } return path; }
@Override public void addResponseCookie(final Cookie cookie) { javax.servlet.http.Cookie c = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue()); c.setSecure(cookie.isSecure()); c.setPath(cookie.getPath()); c.setMaxAge(cookie.getMaxAge()); c.setHttpOnly(cookie.isHttpOnly()); c.setComment(cookie.getComment()); c.setDomain(cookie.getDomain()); this.response.addCookie(c); }
/** * Builds a RFC 2109 compliant client cookie header for the specified URL. * * @param url The URL for which the cookie header is to be used. * @return A client cookie header (including the "Cookie: " prefix) or null if no cookies are to * be set. */ public String buildCookieHeader(URL url) { String domain = url.getHost(); int dot = domain.indexOf('.'); if (dot >= 0) domain = domain.substring(dot); if (domain.equals(this.domain)) { String path = url.getPath(); int secure = url.getProtocol().equalsIgnoreCase("https") ? 1 : 0; StringBuffer sb = new StringBuffer(); for (String key : this.jar.keySet()) { Cookie c = this.jar.get(key); if (null != c) sb.append(c.getHeader(path, secure)); } if (sb.length() > 0) { sb.append("\r\n"); return "Cookie: " + sb.toString(); } } return null; }
/** * @throws CloneNotSupportedException * @see java.lang.Object#clone() */ @Override public Cookie clone() throws CloneNotSupportedException { Cookie ret = (Cookie) super.clone(); ret.domain = this.domain; ret.name = this.name; ret.value = this.value; ret.path = this.path; ret.max_age = this.max_age; ret.version = this.version; ret.secure = this.secure; return ret; }
private void storeCookieToDomainStore(Map<String, Cookie> domainStore, String cookieString) { // the specification dictates that the first name/value pair // in the string is the cookie name and value, so let's handle // them as a special case: Cookie cookie = null; StringTokenizer st = new StringTokenizer(cookieString, COOKIE_VALUE_DELIMITER); while (st.hasMoreTokens()) { String token = st.nextToken(); int index = token.indexOf(NAME_VALUE_SEPARATOR); if (index < 0 || index >= token.length()) { if (cookie == null) { // e Logger.e(TAG, "Invalid cookie string: " + cookieString); return; } Logger.v(TAG, "Not a value/pair, ignore for now as we don't use it: " + token); continue; } // value pair String name = token.substring(0, index).toLowerCase(Locale.US); String value = token.substring(index + 1); if (cookie == null) { cookie = new Cookie(value); domainStore.put(name, cookie); } if (EXPIRES.equals(name)) { cookie.expires = value; } else if (PATH.equals(name)) { cookie.path = value; } /*else { // don't have any use for this part of the cookie // ... }*/ } }
private void checkHeaders(HTTPMethod method) { if (debugHeaders) { System.out.println("\nOpenConnection Headers for " + method.getPath()); System.out.println("Status Line: " + method.getStatusLine()); } Header[] responseHeaders = method.getResponseHeaders(); for (int i1 = 0; i1 < responseHeaders.length; i1++) { Header responseHeader = responseHeaders[i1]; if (debugHeaders) System.out.print(" " + responseHeader); String key = responseHeader.getName(); String value = responseHeader.getValue(); if (key.equals("Last-Modified")) { lastModified = value; if (debugHeaders) System.out.println(" **found lastModified = " + lastModified); } else if (key.equals("X-Last-Extended")) { lastExtended = value; if (debugHeaders) System.out.println(" **found lastExtended = " + lastExtended); } else if (key.equals("X-Last-Modified-Invalid")) { lastModifiedInvalid = value; if (debugHeaders) System.out.println(" **found lastModifiedInvalid = " + lastModifiedInvalid); } } if (debugHeaders) System.out.println("OpenConnection Headers for " + method.getPath()); Cookie[] cookies = _session.getCookies(); if (cookies.length > 0) { if (debugHeaders) System.out.println("Cookies= "); for (int i = 0; i < cookies.length; i++) { Cookie cooky = cookies[i]; if (debugHeaders) System.out.println(" " + cooky); if (cooky.getName().equalsIgnoreCase("jsessionid")) hasSession = true; } } }
private void saveCookie(String cookieStr, String host) { try { Cookie newCookie = new Cookie(cookieStr, host); int idx = savedCookies.indexOf(newCookie); // check to see if cookie already exists Date expires = newCookie.getExpires(); if (idx > -1) { savedCookies.removeElementAt(idx); } if (expires == null || System.currentTimeMillis() < (expires.getTime())) { savedCookies.addElement(newCookie); Log.logDebug("Saved Cookie " + newCookie.getName()); } else // expiration date is in the past. { Log.logDebug("Removed (expired: " + expires + ") Cookie: " + newCookie.getName()); } } catch (Exception e) { Log.logWarn("Failed to save cookie: " + cookieStr, e); } }
protected static void addToResponse(Response response, HttpResponse nettyResponse) { Map<String, Http.Header> headers = response.headers; for (Map.Entry<String, Http.Header> entry : headers.entrySet()) { Http.Header hd = entry.getValue(); for (String value : hd.values) { nettyResponse.setHeader(entry.getKey(), value); } } Map<String, Http.Cookie> cookies = response.cookies; for (Http.Cookie cookie : cookies.values()) { CookieEncoder encoder = new CookieEncoder(true); Cookie c = new DefaultCookie(cookie.name, cookie.value); c.setSecure(cookie.secure); c.setPath(cookie.path); if (cookie.domain != null) { c.setDomain(cookie.domain); } if (cookie.maxAge != null) { c.setMaxAge(cookie.maxAge); } c.setHttpOnly(cookie.httpOnly); encoder.addCookie(c); nettyResponse.addHeader(SET_COOKIE, encoder.encode()); } if (!response.headers.containsKey(CACHE_CONTROL)) { nettyResponse.setHeader(CACHE_CONTROL, "no-cache"); } }
@Override public Cookie getCookie() { final HashMap<String, String> responseHeader = getResponseHeader(); if (null == responseHeader) return null; String value = responseHeader.get("set-cookie"); if (null == value) return null; String[] values = value.split("<--->"); Pattern pattern = Pattern.compile("^([^\\=]+)=([^;]*)"); final Cookie cookie = new Cookie(); for (int i = 0, len = values.length; i < len; i++) { Matcher matcher = pattern.matcher(values[i]); if (matcher.find()) { cookie.set(matcher.group(1), matcher.group(2)); } } return cookie; }