List of usage examples for java.net HttpCookie getValue
public String getValue()
From source file:org.apache.hadoop.yarn.server.webproxy.TestWebAppProxyServlet.java
private boolean isResponseCookiePresent(HttpURLConnection proxyConn, String expectedName, String expectedValue) {/*from w w w.j a va 2 s .c o m*/ Map<String, List<String>> headerFields = proxyConn.getHeaderFields(); List<String> cookiesHeader = headerFields.get("Set-Cookie"); if (cookiesHeader != null) { for (String cookie : cookiesHeader) { HttpCookie c = HttpCookie.parse(cookie).get(0); if (c.getName().equals(expectedName) && c.getValue().equals(expectedValue)) { return true; } } } return false; }
From source file:com.novartis.opensource.yada.adaptor.RESTAdaptor.java
/** * Gets the input stream from the {@link URLConnection} and stores it in * the {@link YADAQueryResult} in {@code yq} * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery) *//* w w w . j av a 2 s .c o m*/ @Override public void execute(YADAQuery yq) throws YADAAdaptorExecutionException { boolean isPostPutPatch = this.method.equals(YADARequest.METHOD_POST) || this.method.equals(YADARequest.METHOD_PUT) || this.method.equals(YADARequest.METHOD_PATCH); resetCountParameter(yq); int rows = yq.getData().size() > 0 ? yq.getData().size() : 1; /* * Remember: * A row is an set of YADA URL parameter values, e.g., * * x,y,z in this: * ...yada/q/queryname/p/x,y,z * so 1 row * * or each of {col1:x,col2:y,col3:z} and {col1:a,col2:b,col3:c} in this: * ...j=[{qname:queryname,DATA:[{col1:x,col2:y,col3:z},{col1:a,col2:b,col3:c}]}] * so 2 rows */ for (int row = 0; row < rows; row++) { String result = ""; // creates result array and assigns it yq.setResult(); YADAQueryResult yqr = yq.getResult(); String urlStr = yq.getUrl(row); for (int i = 0; i < yq.getParamCount(row); i++) { Matcher m = PARAM_URL_RX.matcher(urlStr); if (m.matches()) { String param = yq.getVals(row).get(i); urlStr = urlStr.replaceFirst(PARAM_SYMBOL_RX, m.group(1) + param); } } l.debug("REST url w/params: [" + urlStr + "]"); try { URL url = new URL(urlStr); URLConnection conn = null; if (this.hasProxy()) { String[] proxyStr = this.proxy.split(":"); Proxy proxySvr = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyStr[0], Integer.parseInt(proxyStr[1]))); conn = url.openConnection(proxySvr); } else { conn = url.openConnection(); } // basic auth if (url.getUserInfo() != null) { //TODO issue with '@' sign in pw, must decode first String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes())); conn.setRequestProperty("Authorization", basicAuth); } // cookies if (yq.getCookies() != null && yq.getCookies().size() > 0) { String cookieStr = ""; for (HttpCookie cookie : yq.getCookies()) { cookieStr += cookie.getName() + "=" + cookie.getValue() + ";"; } conn.setRequestProperty("Cookie", cookieStr); } if (yq.getHttpHeaders() != null && yq.getHttpHeaders().length() > 0) { l.debug("Processing custom headers..."); @SuppressWarnings("unchecked") Iterator<String> keys = yq.getHttpHeaders().keys(); while (keys.hasNext()) { String name = keys.next(); String value = yq.getHttpHeaders().getString(name); l.debug("Custom header: " + name + " : " + value); conn.setRequestProperty(name, value); if (name.equals(X_HTTP_METHOD_OVERRIDE) && value.equals(YADARequest.METHOD_PATCH)) { l.debug("Resetting method to [" + YADARequest.METHOD_POST + "]"); this.method = YADARequest.METHOD_POST; } } } HttpURLConnection hConn = (HttpURLConnection) conn; if (!this.method.equals(YADARequest.METHOD_GET)) { hConn.setRequestMethod(this.method); if (isPostPutPatch) { //TODO make YADA_PAYLOAD case-insensitive and create an alias for it, e.g., ypl // NOTE: YADA_PAYLOAD is a COLUMN NAME found in a JSONParams DATA object. It // is not a YADA param String payload = yq.getDataRow(row).get(YADA_PAYLOAD)[0]; hConn.setDoOutput(true); OutputStreamWriter writer; writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(payload.toString()); writer.flush(); } } // debug Map<String, List<String>> map = conn.getHeaderFields(); for (Map.Entry<String, List<String>> entry : map.entrySet()) { l.debug("Key : " + entry.getKey() + " ,Value : " + entry.getValue()); } try (BufferedReader in = new BufferedReader(new InputStreamReader(hConn.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { result += String.format("%1s%n", inputLine); } } yqr.addResult(row, result); } catch (MalformedURLException e) { String msg = "Unable to access REST source due to a URL issue."; throw new YADAAdaptorExecutionException(msg, e); } catch (IOException e) { String msg = "Unable to read REST response."; throw new YADAAdaptorExecutionException(msg, e); } } }
From source file:com.codename1.corsproxy.CORSProxy.java
@Override protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Header header) {// w w w.j av a 2 s. c o m List<HttpCookie> cookies = HttpCookie.parse(header.getValue()); String path = servletRequest.getContextPath(); // path starts with / or is empty string path += servletRequest.getServletPath(); // servlet path starts with / or is empty string for (HttpCookie cookie : cookies) { //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies String proxyCookieName = getCookieNamePrefix() + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); //set to the path of the proxy servlet // don't set cookie domain //servletCookie.setSecure(cookie.getSecure()); servletCookie.setSecure(false); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }
From source file:com.muk.services.security.DefaultUaaLoginService.java
private List<String> translateInToOutCookies(List<String> inCookies) { final List<String> outCookies = new ArrayList<String>(); for (final String inCookie : inCookies) { final HttpCookie httpCookie = HttpCookie.parse(inCookie).get(0); final StringBuilder cookieBuilder = new StringBuilder(); cookieBuilder.append(httpCookie.getName()).append("=").append(httpCookie.getValue()); outCookies.add(cookieBuilder.toString()); }/*from w ww.j a va 2s. c o m*/ return outCookies; }
From source file:com.gdevelop.gwt.syncrpc.RemoteServiceSyncProxy.java
public Object doInvoke(RequestCallbackAdapter.ResponseReader responseReader, String requestData) throws Throwable { HttpURLConnection connection = null; InputStream is = null;/*from w w w . j a va 2s .co m*/ int statusCode; if (DUMP_PAYLOAD) { log.debug("Send request to {}", remoteServiceURL); log.debug("Request payload: {}", requestData); } // Send request CookieHandler oldCookieHandler = CookieHandler.getDefault(); try { CookieHandler.setDefault(cookieManager); URL url = new URL(remoteServiceURL); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty(RpcRequestBuilder.STRONG_NAME_HEADER, serializationPolicyName); connection.setRequestProperty(RpcRequestBuilder.MODULE_BASE_HEADER, moduleBaseURL); connection.setRequestProperty("Content-Type", "text/x-gwt-rpc; charset=utf-8"); connection.setRequestProperty("Content-Length", "" + requestData.getBytes("UTF-8").length); CookieStore store = cookieManager.getCookieStore(); String cookiesStr = ""; for (HttpCookie cookie : store.getCookies()) { if (!"".equals(cookiesStr)) cookiesStr += "; "; cookiesStr += cookie.getName() + "=" + cookie.getValue(); } connection.setRequestProperty("Cookie", cookiesStr); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(requestData); writer.flush(); writer.close(); } catch (IOException e) { throw new InvocationException("IOException while sending RPC request", e); } finally { CookieHandler.setDefault(oldCookieHandler); } // Receive and process response try { is = connection.getInputStream(); statusCode = connection.getResponseCode(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = is.read(buffer)) > 0) { baos.write(buffer, 0, len); } String encodedResponse = baos.toString("UTF8"); if (DUMP_PAYLOAD) { log.debug("Response code: {}", statusCode); log.debug("Response payload: {}", encodedResponse); } // System.out.println("Response payload (len = " + encodedResponse.length() + "): " + encodedResponse); if (statusCode != HttpURLConnection.HTTP_OK) { throw new StatusCodeException(statusCode, encodedResponse); } else if (encodedResponse == null) { // This can happen if the XHR is interrupted by the server dying throw new InvocationException("No response payload"); } else if (isReturnValue(encodedResponse)) { encodedResponse = encodedResponse.substring(4); return responseReader.read(createStreamReader(encodedResponse)); } else if (isThrownException(encodedResponse)) { encodedResponse = encodedResponse.substring(4); Throwable throwable = (Throwable) createStreamReader(encodedResponse).readObject(); throw throwable; } else { throw new InvocationException("Unknown response " + encodedResponse); } } catch (IOException e) { log.error("error response: {}", IOUtils.toString(connection.getErrorStream())); throw new InvocationException("IOException while receiving RPC response", e); } catch (SerializationException e) { throw new InvocationException("Error while deserialization response", e); } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } if (connection != null) { // connection.disconnect(); } } }
From source file:io.mapzone.controller.vm.http.HttpResponseForwarder.java
/** * Copy cookie from the proxy to the servlet client. Replaces cookie path to * local path and renames cookie to avoid collisions. *///w w w . j a v a 2 s. c o m protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Header header) { List<HttpCookie> cookies = HttpCookie.parse(header.getValue()); String path = servletRequest.getContextPath(); // path starts with / or is empty string path += servletRequest.getServletPath(); // servlet path starts with / or is empty string for (HttpCookie cookie : cookies) { // set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies String proxyCookieName = requestForwarder.cookieNamePrefix.get() + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); // set to the path of the proxy servlet // don't set cookie domain servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }
From source file:com.muk.services.security.DefaultUaaLoginService.java
private String httpCookieToString(HttpCookie cookie) { final OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(cookie.getMaxAge()); final String cookieExpires = DateTimeFormatter.RFC_1123_DATE_TIME.format(now); final StringBuilder cookieBuilder = new StringBuilder(); cookieBuilder.append(cookie.getName()).append("=").append(cookie.getValue()).append(";path=") .append(cookie.getPath()).append(";max-age=").append(cookie.getMaxAge()).append(";expires=") .append(cookieExpires);//from w w w.j av a2s. c om if (cookie.isHttpOnly()) { cookieBuilder.append(";HttpOnly"); } return cookieBuilder.toString(); }
From source file:org.zaproxy.zap.extension.httpsessions.HttpSession.java
/** * Checks if a particular cookie has the same value as one of the token values in the HTTP * session. If the {@literal cookie} parameter is null, the session matches the token if it does * not have a value for the corresponding token. * // w ww . ja v a2s .c o m * @param tokenName the token name * @param cookie the cookie * @return true, if true */ public boolean matchesToken(String tokenName, HttpCookie cookie) { // Check if the cookie is null if (cookie == null) { return tokenValues.containsKey(tokenName) ? false : true; } // Check the value of the token from the cookie String tokenValue = getTokenValue(tokenName); if (tokenValue != null && tokenValue.equals(cookie.getValue())) { return true; } return false; }
From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java
/** * Copy cookie from the proxy to the servlet client. * Replaces cookie path to local path and renames cookie to avoid collisions. *///w ww . j av a 2 s . c o m private void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Header header) { List<HttpCookie> cookies = HttpCookie.parse(header.getValue()); String path = servletRequest.getContextPath(); // path starts with / or is empty string path += servletRequest.getServletPath(); // servlet path starts with / or is empty string for (int i = 0, l = cookies.size(); i < l; i++) { HttpCookie cookie = cookies.get(i); //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies String proxyCookieName = getCookieNamePrefix() + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); //set to the path of the proxy servlet // don't set cookie domain servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }
From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.java
/** Copy cookie from the proxy to the servlet client. * Replaces cookie path to local path and renames cookie to avoid collisions. *//*from w ww .j a v a 2 s .c o m*/ protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Header header) { List<HttpCookie> cookies = HttpCookie.parse(header.getValue()); String path = servletRequest.getContextPath(); // path starts with / or is empty string path += servletRequest.getServletPath(); // servlet path starts with / or is empty string for (HttpCookie cookie : cookies) { //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies String proxyCookieName = getCookieNamePrefix() + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); //set to the path of the proxy servlet // don't set cookie domain servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }