List of usage examples for org.apache.http.client.fluent Request addHeader
public Request addHeader(final String name, final String value)
From source file:photosharing.api.conx.FileDefinition.java
/** * gets the user library results/* ww w . ja va2 s. com*/ * * @param request * @param response */ public void getUserLibraryResults(String bearer, HttpServletRequest request, HttpServletResponse response) { String userId = request.getParameter("userid"); if (userId == null || userId.isEmpty()) { logger.warning("userId is null"); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } else { // sets the content type - application/json response.setContentType(ContentType.APPLICATION_JSON.getMimeType()); String apiUrl = getUserLibraryApiUrl(userId); logger.info(apiUrl); Request get = Request.Get(apiUrl); get.addHeader("Authorization", "Bearer " + bearer); try { Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Default to SC_OK (200) else if (code == HttpStatus.SC_OK) { response.setStatus(HttpStatus.SC_OK); InputStream in = hr.getEntity().getContent(); String jsonString = org.apache.wink.json4j.utils.XML.toJson(in); // Logging out the JSON Object logger.info(jsonString); JSONObject feed = new JSONObject(jsonString).getJSONObject("feed"); logger.info(feed.toString()); JSONArray files = new JSONArray(); JSONArray entries = null; if (feed.has("entry")) { //Check if the Entry is a JSONObject or JSONArray Object o = feed.get("entry"); if (o.getClass().getName().contains("JSONObject")) { entries = new JSONArray(); entries.put(o); } else { entries = (JSONArray) o; } } else { entries = new JSONArray(); } int len = entries.length(); for (int i = 0; i < len; i++) { JSONObject entry = entries.getJSONObject(i); logger.info(entry.toString()); JSONObject author = entry.getJSONObject("author"); String photographer = author.getString("name"); String uid = author.getString("userid"); String title = entry.getJSONObject("title").getString("content"); String lid = entry.getString("libraryId"); String pid = entry.getString("uuid"); String thumbnail = "./api/file?action=thumbnail&pid=" + pid + "&lid=" + lid; files.add(createPhoto(lid, pid, title, uid, photographer, thumbnail)); } // Flush the Object to the Stream with content type response.setHeader("Content-Type", "application/json"); PrintWriter out = response.getWriter(); out.println(files.toString()); out.flush(); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read userlibrary " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read userlibrary " + e.toString()); e.printStackTrace(); } catch (SAXException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read userlibrary " + e.toString()); } } }
From source file:photosharing.api.conx.FileDefinition.java
/** * gets the user file metadata results//w w w .j a va2 s. c o m * * Payload * {"uid":"20971118","thumbnail": * ".\/api\/file?action=thumbnail&pid=7fdedc74-a9f4-46f1-acde-39bef9975847&lid=2597409c-b292-4059-bb4f-3c92c90f5c2e", * "like":true,"lid":"2597409c-b292-4059-bb4f-3c92c90f5c2e","pid":"7fdedc74-a9f4-46f1-acde-39bef9975847","photographer":"ASIC * ASIC","title":"Test32ab.jpeg","tags":["abcd","photojava"]} * * @param request * @param response */ public void getFileMetadata(String bearer, HttpServletRequest request, HttpServletResponse response) { String library = request.getParameter("lid"); String file = request.getParameter("pid"); if (library == null || library.isEmpty() || file == null || file.isEmpty()) { logger.warning("library or file is null"); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } else { // sets the content type - application/json response.setContentType(ContentType.APPLICATION_JSON.getMimeType()); String apiUrl = getFileMetadata(file, library); logger.info(apiUrl); Request get = Request.Get(apiUrl); get.addHeader("Authorization", "Bearer " + bearer); try { Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Default to SC_OK (200) else if (code == HttpStatus.SC_OK) { response.setStatus(HttpStatus.SC_OK); InputStream in = hr.getEntity().getContent(); String jsonString = org.apache.wink.json4j.utils.XML.toJson(in); // Logging out the JSON Object logger.info(jsonString); JSONObject result = new JSONObject(jsonString); JSONObject entry = result.getJSONObject("entry"); logger.info(entry.toString()); JSONObject author = entry.getJSONObject("author"); String photographer = author.getString("name"); String uid = author.getString("userid"); String date = entry.getString("published"); String title = entry.getJSONObject("title").getString("content"); String lid = entry.getString("libraryId"); String pid = entry.getString("uuid"); String thumbnail = "./api/file?action=thumbnail&pid=" + pid + "&lid=" + lid; JSONObject res = new JSONObject(createPhoto(lid, pid, title, uid, photographer, thumbnail)); JSONArray links = entry.getJSONArray("link"); @SuppressWarnings("rawtypes") Iterator iter = links.iterator(); while (iter.hasNext()) { JSONObject obj = (JSONObject) iter.next(); String rel = obj.getString("rel"); if (rel != null && rel.compareTo("recommendation") == 0) { res.put("like", true); } } JSONArray categories = entry.getJSONArray("category"); iter = categories.iterator(); JSONArray tags = new JSONArray(); while (iter.hasNext()) { JSONObject obj = (JSONObject) iter.next(); if (!obj.has("scheme")) { tags.put(obj.getString("term")); } } res.put("tags", tags); res.put("published", date); // Flush the Object to the Stream with content type response.setHeader("Content-Type", "application/json"); PrintWriter out = response.getWriter(); out.println(res.toString()); out.flush(); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read userlibrary " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read userlibrary " + e.toString()); e.printStackTrace(); } catch (SAXException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read userlibrary " + e.toString()); } } }
From source file:photosharing.api.conx.FileDefinition.java
/** * gets the user's organization's public files results * /* w w w . j av a 2 s. c o m*/ * @param request * @param response */ public void getOrgPublicFeed(String bearer, HttpServletRequest request, HttpServletResponse response) { String apiUrl = getPublicFilesApiUrl(); logger.info(apiUrl); Request get = Request.Get(apiUrl); get.addHeader("Authorization", "Bearer " + bearer); try { // sets the content type - application/json response.setContentType(ContentType.APPLICATION_JSON.getMimeType()); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Default to SC_OK (200) else if (code == HttpStatus.SC_OK) { response.setStatus(HttpStatus.SC_OK); InputStream in = hr.getEntity().getContent(); String jsonString = org.apache.wink.json4j.utils.XML.toJson(in); // Logging out the JSON Object logger.info(jsonString); JSONObject feed = new JSONObject(jsonString).getJSONObject("feed"); logger.info(feed.toString()); JSONArray files = new JSONArray(); JSONArray entries = null; if (feed.has("entry")) { //Check if the Entry is a JSONObject or JSONArray Object o = feed.get("entry"); if (o.getClass().getName().contains("JSONObject")) { entries = new JSONArray(); entries.put(o); } else { entries = (JSONArray) o; } } else { entries = new JSONArray(); } int len = entries.length(); for (int i = 0; i < len; i++) { JSONObject entry = entries.getJSONObject(i); logger.info(entry.toString()); JSONObject author = entry.getJSONObject("author"); String photographer = author.getString("name"); String uid = author.getString("userid"); String title = entry.getJSONObject("title").getString("content"); String lid = entry.getString("libraryId"); String pid = entry.getString("uuid"); String thumbnail = "./api/file?action=file&pid=" + pid + "&lid=" + lid; String share = "0"; String like = "0"; JSONArray rank = entry.getJSONArray("rank"); @SuppressWarnings("rawtypes") Iterator r = rank.iterator(); while (r.hasNext()) { JSONObject temp = (JSONObject) r.next(); String scheme = temp.getString("scheme"); if (scheme.contains("share")) { share = temp.getString("content"); } else if (scheme.contains("recommendations")) { like = temp.getString("content"); } } JSONObject e = createPhoto(lid, pid, title, uid, photographer, thumbnail); e.put("likes", like); e.put("shares", share); files.add(e); } // Flush the Object to the Stream with content type response.setHeader("Content-Type", "application/json"); PrintWriter out = response.getWriter(); out.println(files.toString()); out.flush(); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read user's org feed " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read user's org feed " + e.toString()); e.printStackTrace(); } catch (SAXException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read user's org feed " + e.toString()); } }
From source file:photosharing.api.conx.FileDefinition.java
/** * gets the user's organization's public files results * /*from ww w. j ava2s.c om*/ * @param request * @param response */ public void getPrivateFeed(String bearer, HttpServletRequest request, HttpServletResponse response) { String apiUrl = getPrivateFilesApiUrl(); logger.info(apiUrl); Request get = Request.Get(apiUrl); get.addHeader("Authorization", "Bearer " + bearer); try { // sets the content type - application/json response.setContentType(ContentType.APPLICATION_JSON.getMimeType()); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Default to SC_OK (200) else if (code == HttpStatus.SC_OK) { response.setStatus(HttpStatus.SC_OK); InputStream in = hr.getEntity().getContent(); String jsonString = org.apache.wink.json4j.utils.XML.toJson(in); // Logging out the JSON Object logger.info(jsonString); JSONObject feed = new JSONObject(jsonString).getJSONObject("feed"); logger.info(feed.toString()); JSONArray files = new JSONArray(); JSONArray entries = null; if (feed.has("entry")) { //Check if the Entry is a JSONObject or JSONArray Object o = feed.get("entry"); if (o.getClass().getName().contains("JSONObject")) { entries = new JSONArray(); entries.put(o); } else { entries = (JSONArray) o; } } else { entries = new JSONArray(); } int len = entries.length(); for (int i = 0; i < len; i++) { JSONObject entry = entries.getJSONObject(i); logger.info(entry.toString()); JSONObject author = entry.getJSONObject("author"); String photographer = author.getString("name"); String uid = author.getString("userid"); String title = entry.getJSONObject("title").getString("content"); String lid = entry.getString("libraryId"); String pid = entry.getString("uuid"); String thumbnail = "./api/file?action=file&pid=" + pid + "&lid=" + lid; String share = "0"; String like = "0"; JSONArray rank = entry.getJSONArray("rank"); @SuppressWarnings("rawtypes") Iterator r = rank.iterator(); while (r.hasNext()) { JSONObject temp = (JSONObject) r.next(); String scheme = temp.getString("scheme"); if (scheme.contains("share")) { share = temp.getString("content"); } else if (scheme.contains("recommendations")) { like = temp.getString("content"); } } JSONObject e = createPhoto(lid, pid, title, uid, photographer, thumbnail); e.put("likes", like); e.put("shares", share); files.add(e); } // Flush the Object to the Stream with content type response.setHeader("Content-Type", "application/json"); PrintWriter out = response.getWriter(); out.println(files.toString()); out.flush(); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read user's private feed " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read user's private feed " + e.toString()); e.printStackTrace(); } catch (SAXException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read user's private feed " + e.toString()); } }
From source file:photosharing.api.conx.FileDefinition.java
/** * gets the user's shared files results//from w w w. ja v a 2s . c o m * * @param request * @param response */ public void getSharedFeed(String bearer, HttpServletRequest request, HttpServletResponse response) { String apiUrl = getSharedFiles(); logger.info(apiUrl); Request get = Request.Get(apiUrl); get.addHeader("Authorization", "Bearer " + bearer); try { // sets the content type - application/json response.setContentType(ContentType.APPLICATION_JSON.getMimeType()); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Default to SC_OK (200) else if (code == HttpStatus.SC_OK) { response.setStatus(HttpStatus.SC_OK); InputStream in = hr.getEntity().getContent(); String jsonString = org.apache.wink.json4j.utils.XML.toJson(in); // Logging out the JSON Object logger.info(jsonString); JSONObject feed = new JSONObject(jsonString).getJSONObject("feed"); logger.info(feed.toString()); JSONArray files = new JSONArray(); JSONArray entries = null; if (feed.has("entry")) { //Check if the Entry is a JSONObject or JSONArray Object o = feed.get("entry"); if (o.getClass().getName().contains("JSONObject")) { entries = new JSONArray(); entries.put(o); } else { entries = (JSONArray) o; } } else { entries = new JSONArray(); } int len = entries.length(); for (int i = 0; i < len; i++) { JSONObject entry = entries.getJSONObject(i); logger.info(entry.toString()); JSONObject author = entry.getJSONObject("author"); String photographer = author.getString("name"); String uid = author.getString("userid"); String title = entry.getJSONObject("title").getString("content"); String lid = entry.getString("libraryId"); String pid = entry.getString("uuid"); String thumbnail = "./api/file?action=file&pid=" + pid + "&lid=" + lid; String share = "0"; String like = "0"; JSONArray rank = entry.getJSONArray("rank"); @SuppressWarnings("rawtypes") Iterator r = rank.iterator(); while (r.hasNext()) { JSONObject temp = (JSONObject) r.next(); String scheme = temp.getString("scheme"); if (scheme.contains("share")) { share = temp.getString("content"); } else if (scheme.contains("recommendations")) { like = temp.getString("content"); } } JSONObject e = createPhoto(lid, pid, title, uid, photographer, thumbnail); e.put("likes", like); e.put("shares", share); files.add(e); } // Flush the Object to the Stream with content type response.setHeader("Content-Type", "application/json"); PrintWriter out = response.getWriter(); out.println(files.toString()); out.flush(); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read user's shared feed " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read user's shared feed " + e.toString()); e.printStackTrace(); } catch (SAXException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("Issue with read user's shared feed " + e.toString()); } }
From source file:com.jaspersoft.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java
/** * Extracts info from message context./*from ww w.j a v a 2 s .c om*/ * * @param method * Post method * @param httpClient * The client used for posting * @param msgContext * the message context * @param tmpURL * the url to post to. * * @throws Exception */ private void addContextInfo(Request req, MessageContext msgContext, URL tmpURL) throws Exception { String v = msgContext.getStrProp(MessageContext.HTTP_TRANSPORT_VERSION); if (v != null && v.equals(HTTPConstants.HEADER_PROTOCOL_V10)) req.version(HttpVersion.HTTP_1_0); // optionally set a timeout for the request if (msgContext.getTimeout() != 0) { req.connectTimeout(msgContext.getTimeout()); req.socketTimeout(msgContext.getTimeout()); } // Get SOAPAction, default to "" String action = msgContext.useSOAPAction() ? msgContext.getSOAPActionURI() : ""; if (action == null) action = ""; Message msg = msgContext.getRequestMessage(); if (msg != null) req.addHeader(HTTPConstants.HEADER_CONTENT_TYPE, msg.getContentType(msgContext.getSOAPConstants())); req.addHeader(HTTPConstants.HEADER_SOAP_ACTION, "\"" + action + "\""); req.addHeader(HTTPConstants.HEADER_USER_AGENT, Messages.getMessage("axisUserAgent")); // add compression headers if needed if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) req.addHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP); if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) req.addHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP); // Transfer MIME headers of SOAPMessage to HTTP headers. MimeHeaders mimeHeaders = msg.getMimeHeaders(); if (mimeHeaders != null) { for (Iterator<?> i = mimeHeaders.getAllHeaders(); i.hasNext();) { MimeHeader mimeHeader = (MimeHeader) i.next(); // HEADER_CONTENT_TYPE and HEADER_SOAP_ACTION are already set. // Let's not duplicate them. String headerName = mimeHeader.getName(); if (headerName.equals(HTTPConstants.HEADER_CONTENT_TYPE) || headerName.equals(HTTPConstants.HEADER_SOAP_ACTION)) continue; req.addHeader(mimeHeader.getName(), mimeHeader.getValue()); } } // process user defined headers for information. Hashtable<?, ?> userHeaderTable = (Hashtable<?, ?>) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS); if (userHeaderTable != null) for (Map.Entry<?, ?> me : userHeaderTable.entrySet()) { Object keyObj = me.getKey(); if (null == keyObj) continue; String key = keyObj.toString().trim(); String value = me.getValue().toString().trim(); if (key.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT) && value.equalsIgnoreCase(HTTPConstants.HEADER_EXPECT_100_Continue)) req.useExpectContinue(); else if (key.equalsIgnoreCase(HTTPConstants.HEADER_TRANSFER_ENCODING_CHUNKED)) { req.removeHeader(new BasicHeader("Transfer-Encoding", "chunked")); if (Boolean.parseBoolean(value)) ;// req.setHeader("Transfer-Encoding", "chunked"); } else req.addHeader(key, value); } }
From source file:de.elomagic.carafile.client.CaraFileClient.java
Response executeRequest(final Request request) throws IOException { if (executor == null) { executor = Executor.newInstance(); }/*from w ww .ja va2 s. c o m*/ executor.cookieStore(store); if (authUserName != null) { char[] p = authPassword; p = p == null && passwordListener != null ? passwordListener.getPassword(this) : p; if (authDomain == null) { executor.auth(authUserName, new String(p)); } else { executor.auth(authUserName, new String(p), null, authDomain); } } if (proxyHost != null) { request.viaProxy(proxyHost); } request.addHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString()); return executor.execute(request); }
From source file:eu.trentorise.opendata.jackan.CkanClient.java
/** * Configures the request. Should work both for GETs and POSTs. *//*from w ww.j a v a 2s .c om*/ protected Request configureRequest(Request request) { if (ckanToken != null) { request.addHeader("Authorization", ckanToken); } if (proxy != null) { request.viaProxy(proxy); } request.socketTimeout(this.timeout).connectTimeout(this.timeout); return request; }
From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java
public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { // System.out.println("getAcceptedIssuers ============="); return null; }/*from w w w.j av a2 s . co m*/ public void checkClientTrusted(X509Certificate[] certs, String authType) { // System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { // System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf) .setRedirectStrategy(new DefaultRedirectStrategy() { @Override protected boolean isRedirectable(String arg0) { // TODO Auto-generated method stub return super.isRedirectable(arg0); } @Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { // TODO Auto-generated method stub return super.isRedirected(request, response, context); } }).setDefaultCookieStore(new BasicCookieStore()) .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0") .build(); Executor exec = Executor.newInstance(httpclient); URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html"); String fullURL = ub.build().toASCIIString(); Request req = HttpUtils.get(fullURL, sp); HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL)); if (proxy != null) req.viaProxy(proxy); String tgtID = readData(exec, req, monitor); String action = getFormAction(tgtID); if (action != null) { action = action.replaceFirst("/", ""); int indx = action.indexOf(";jsession"); if (indx >= 0) action = action.substring(0, indx); } else action = "cas/login"; String url = srv.getUrl(); if (!url.endsWith("/")) url += "/"; ub = new URIBuilder(url + action); // fullURL = ub.build().toASCIIString(); req = HttpUtils.get(fullURL, sp); proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL)); if (proxy != null) req.viaProxy(proxy); tgtID = readData(exec, req, monitor); action = getFormAction(tgtID); action = action.replaceFirst("/", ""); ub = new URIBuilder(url + action); Map<String, String> map = getInputs(tgtID); Form form = Form.form(); for (String key : map.keySet()) { if (key.equals("btn-reset")) continue; else if (key.equals("username")) { form.add(key, srv.getUser()); continue; } else if (key.equals("password")) { form.add(key, Pass.getPass(srv.getPassword())); continue; } form.add(key, map.get(key)); } // req = HttpUtils.post(ub.build().toASCIIString(), form, sp); if (proxy != null) req.viaProxy(proxy); // Header header = null; readData(exec, req, monitor); // for (Header h : headers) { // for (HeaderElement he : h.getElements()) { // if (he.getName().equals("CASTGC")) { // header = new BasicHeader("Cookie", h.getValue()); // break; // } // } // } ub = new URIBuilder(url + action); url = sp.getUrl(); if (!url.endsWith("/")) url += "/"; ub.addParameter("service", url + "j_spring_security_check"); req = HttpUtils.get(ub.build().toASCIIString(), sp); if (proxy != null) req.viaProxy(proxy); // req.addHeader("Accept", // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value"); req.addHeader("Referrer", sp.getUrl()); // req.addHeader(header); String html = readData(exec, req, monitor); Matcher matcher = ahrefPattern.matcher(html); while (matcher.find()) { Map<String, String> attributes = parseAttributes(matcher.group(1)); String v = attributes.get("href"); int ind = v.indexOf("ticket="); if (ind > 0) { return v.substring(ind + "ticket=".length()); } } return null; }
From source file:org.apache.sling.distribution.transport.impl.SimpleHttpDistributionTransport.java
public void deliverPackage(@Nonnull ResourceResolver resourceResolver, @Nonnull DistributionPackage distributionPackage, @Nonnull DistributionTransportContext distributionContext) throws DistributionException { String hostAndPort = getHostAndPort(distributionEndpoint.getUri()); DistributionPackageInfo info = distributionPackage.getInfo(); URI packageOrigin = info.get(PACKAGE_INFO_PROPERTY_ORIGIN_URI, URI.class); if (packageOrigin != null && hostAndPort.equals(getHostAndPort(packageOrigin))) { log.debug("skipping distribution of package {}to same origin {}", distributionPackage.getId(), hostAndPort);// w w w. j a va2 s.com } else { try { Executor executor = getExecutor(distributionContext); Request req = Request.Post(distributionEndpoint.getUri()).useExpectContinue(); // add the message body digest, see https://tools.ietf.org/html/rfc3230#section-4.3.2 if (distributionPackage instanceof AbstractDistributionPackage) { AbstractDistributionPackage adb = (AbstractDistributionPackage) distributionPackage; if (adb.getDigestAlgorithm() != null && adb.getDigestMessage() != null) { req.addHeader(DIGEST_HEADER, String.format("%s=%s", adb.getDigestAlgorithm(), adb.getDigestMessage())); } } InputStream inputStream = null; try { inputStream = DistributionPackageUtils.createStreamWithHeader(distributionPackage); req = req.bodyStream(inputStream, ContentType.APPLICATION_OCTET_STREAM); Response response = executor.execute(req); response.returnContent(); // throws an error if HTTP status is >= 300 } finally { IOUtils.closeQuietly(inputStream); } log.debug("delivered packageId={}, endpoint={}", distributionPackage.getId(), distributionEndpoint.getUri()); } catch (HttpHostConnectException e) { throw new RecoverableDistributionException( "endpoint not available " + distributionEndpoint.getUri(), e); } catch (HttpResponseException e) { int statusCode = e.getStatusCode(); if (statusCode == 404 || statusCode == 401) { throw new RecoverableDistributionException( "not enough rights for " + distributionEndpoint.getUri(), e); } throw new DistributionException(e); } catch (Exception e) { throw new DistributionException(e); } } }