List of usage examples for java.net HttpCookie getName
public String getName()
From source file:org.apache.hadoop.yarn.server.webproxy.TestWebAppProxyServlet.java
private boolean isResponseCookiePresent(HttpURLConnection proxyConn, String expectedName, String expectedValue) {// w w w .ja v a2s. 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.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 w w. j a v a 2s . co m return outCookies; }
From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java
private Optional<HttpCookie> findGerritAccountCookie() { List<HttpCookie> cookies = cookieStore.getCookies(); return Iterables.tryFind(cookies, new Predicate<HttpCookie>() { @Override/*from w w w. ja v a2 s . c o m*/ public boolean apply(HttpCookie cookie) { return cookie.getName().equals("GerritAccount"); } }); }
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) *///from w w w . j ava 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: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. *///from www . java 2 s. c om 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.gdevelop.gwt.syncrpc.RemoteServiceSyncProxy.java
public Object doInvoke(RequestCallbackAdapter.ResponseReader responseReader, String requestData) throws Throwable { HttpURLConnection connection = null; InputStream is = null;/*from www. j av a 2s .c o 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:ai.eve.volley.stack.HurlStack.java
@Override public HttpResponse performRequest(Request<?> request) throws IOException, AuthFailureError { HashMap<String, String> map = new HashMap<String, String>(); if (!TextUtils.isEmpty(mUserAgent)) { map.put(HTTP.USER_AGENT, mUserAgent); }/*from w ww .jav a 2s .c o m*/ if (!TextUtils.isEmpty(mSignInfo)) { map.put("SIGN", ESecurity.Encrypt(mSignInfo)); } map.putAll(request.getHeaders()); URL parsedUrl = new URL(request.getUrl()); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } if (EApplication.getCookies() != null) { ELog.I("cookie", EApplication.getCookies().toString()); connection.addRequestProperty("Cookie", EApplication.getReqCookies()); } else { ELog.I("cookie", "null"); } setConnectionParametersForRequest(connection, request); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { if (header.getKey().equalsIgnoreCase("Set-Cookie")) { List<String> cookies = header.getValue(); HashMap<String, HttpCookie> cookieMap = new HashMap<String, HttpCookie>(); for (String string : cookies) { List<HttpCookie> cookie = HttpCookie.parse(string); for (HttpCookie httpCookie : cookie) { if (httpCookie.getDomain() != null && httpCookie.getPath() != null) { cookieMap.put(httpCookie.getName() + httpCookie.getDomain() + httpCookie.getPath(), httpCookie); } else if (httpCookie.getDomain() == null && httpCookie.getPath() != null) { cookieMap.put(httpCookie.getName() + httpCookie.getPath(), httpCookie); } else if (httpCookie.getDomain() != null && httpCookie.getPath() == null) { cookieMap.put(httpCookie.getName() + httpCookie.getDomain(), httpCookie); } else { cookieMap.put(httpCookie.getName(), httpCookie); } } } EApplication.setCookies(cookieMap); if (EApplication.getCookies() != null) { ELog.I("?cookie", EApplication.getCookies().toString()); } } else { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } } return response; }
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);/* w w w. j ava2 s.co m*/ if (cookie.isHttpOnly()) { cookieBuilder.append(";HttpOnly"); } return cookieBuilder.toString(); }
From source file:com.tremolosecurity.proxy.filters.PreAuthFilter.java
@Override public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception { AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)) .getAuthInfo();//from w ww. j a v a 2 s . c o m ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ); List<Cookie> cookies = null; if (userData.getAuthLevel() > 0 && userData.isAuthComplete()) { UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG); HttpSession session = request.getSession(); String uid = (String) session.getAttribute("TREMOLO_PRE_AUTH"); if (uid == null || !uid.equals(userData.getUserDN())) { session.setAttribute("TREMOLO_PRE_AUTH", userData.getUserDN()); HashMap<String, String> uriParams = new HashMap<String, String>(); uriParams.put("fullURI", this.uri); UrlHolder remHolder = cfg.findURL(this.url); org.apache.http.client.methods.HttpRequestBase method = null; if (this.postSAML) { PrivateKey pk = holder.getConfig().getPrivateKey(this.keyAlias); java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.keyAlias); Saml2Assertion assertion = new Saml2Assertion( userData.getAttribs().get(this.nameIDAttribute).getValues().get(0), pk, cert, null, this.issuer, this.assertionConsumerURL, this.audience, this.signAssertion, this.signResponse, false, this.nameIDType, this.authnCtxClassRef); String respXML = ""; try { respXML = assertion.generateSaml2Response(); } catch (Exception e) { throw new ServletException("Could not generate SAMLResponse", e); } List<NameValuePair> formparams = new ArrayList<NameValuePair>(); String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8")); formparams.add(new BasicNameValuePair("SAMLResponse", base64)); if (this.relayState != null && !this.relayState.isEmpty()) { formparams.add(new BasicNameValuePair("RelayState", this.relayState)); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); HttpPost post = new HttpPost(this.assertionConsumerURL); post.setEntity(entity); method = post; } else { HttpGet get = new HttpGet(remHolder.getProxyURL(uriParams)); method = get; } LastMileUtil.addLastMile(cfg, userData.getAttribs().get(loginAttribute).getValues().get(0), this.loginAttribute, method, lastMileKeyAlias, true); BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager( cfg.getHttpClientSocketRegistry()); try { CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(bhcm) .setDefaultRequestConfig(cfg.getGlobalHttpClientConfig()).build(); HttpResponse resp = httpclient.execute(method); if (resp.getStatusLine().getStatusCode() == 500) { BufferedReader in = new BufferedReader( new InputStreamReader(resp.getEntity().getContent())); StringBuffer error = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { error.append(line).append('\n'); } logger.warn("Pre-Auth Failed : " + error); } org.apache.http.Header[] headers = resp.getAllHeaders(); StringBuffer stmp = new StringBuffer(); cookies = new ArrayList<Cookie>(); for (org.apache.http.Header header : headers) { if (header.getName().equalsIgnoreCase("set-cookie") || header.getName().equalsIgnoreCase("set-cookie2")) { //System.out.println(header.getValue()); String cookieVal = header.getValue(); /*if (cookieVal.endsWith("HttpOnly")) { cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly")); } //System.out.println(cookieVal);*/ List<HttpCookie> cookiesx = HttpCookie.parse(cookieVal); for (HttpCookie cookie : cookiesx) { String cookieFinalName = cookie.getName(); if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) { stmp.setLength(0); stmp.append("JSESSIONID").append('-') .append(holder.getApp().getName().replaceAll(" ", "|")); cookieFinalName = stmp.toString(); } //logger.info("Adding cookie name '" + cookieFinalName + "'='" + cookie.getValue() + "'"); Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue()); respcookie.setComment(cookie.getComment()); if (cookie.getDomain() != null) { //respcookie.setDomain(cookie.getDomain()); } respcookie.setMaxAge((int) cookie.getMaxAge()); respcookie.setPath(cookie.getPath()); respcookie.setSecure(cookie.getSecure()); respcookie.setVersion(cookie.getVersion()); cookies.add(respcookie); if (request.getCookieNames().contains(respcookie.getName())) { request.removeCookie(cookieFinalName); } request.addCookie(new Cookie(cookie.getName(), cookie.getValue())); } } } } finally { bhcm.shutdown(); } } } chain.nextFilter(request, response, chain); if (cookies != null) { for (Cookie cookie : cookies) { response.addCookie(cookie); } } }
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. */// www.jav a2s . 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); } }