List of usage examples for org.apache.http.client.fluent Request viaProxy
public Request viaProxy(final HttpHost proxy)
From source file:eu.trentorise.opendata.jackan.ckan.CkanClient.java
/** * Returns the latest api version supported by the catalog * * @throws JackanException on error//from w w w .j a va 2 s. c om */ private synchronized int getApiVersion(int number) { String fullUrl = catalogURL + "/api/" + number; logger.log(Level.FINE, "getting {0}", fullUrl); try { Request request = Request.Get(fullUrl); if (proxy != null) { request.viaProxy(proxy); } String json = request.execute().returnContent().asString(); return getObjectMapper().readValue(json, ApiVersionResponse.class).version; } catch (Exception ex) { throw new JackanException("Error while fetching api version!", this, ex); } }
From source file:eu.trentorise.opendata.jackan.ckan.CkanClient.java
/** * Method for http GET/*from w w w. j av a 2 s . c o m*/ * * @param <T> * @param responseType a descendant of CkanResponse * @param path something like /api/3/package_show * @param params list of key, value parameters. They must be not be url * encoded. i.e. "id","laghi-monitorati-trento" * @throws JackanException on error */ <T extends CkanResponse> T getHttp(Class<T> responseType, String path, Object... params) { checkNotNull(responseType); checkNotNull(path); String fullUrl = calcFullUrl(path, params); try { logger.log(Level.FINE, "getting {0}", fullUrl); Request request = Request.Get(fullUrl); if (proxy != null) { request.viaProxy(proxy); } String json = request.execute().returnContent().asString(); T dr = getObjectMapper().readValue(json, responseType); if (!dr.success) { // monkey patching error type throw new JackanException("Reading from catalog " + catalogURL + " was not successful. Reason: " + CkanError.read(getObjectMapper().readTree(json).get("error").asText())); } return dr; } catch (Exception ex) { throw new JackanException("Error while performing GET. Request url was: " + fullUrl, ex); } }
From source file:eu.trentorise.opendata.jackan.ckan.CkanClient.java
/** * * @param <T>/*from w ww . j a v a 2 s . c o m*/ * @param responseType a descendant of CkanResponse * @param path something like 1/api/3/action/package_create * @param body the body of the POST * @param the content type, i.e. * @param params list of key, value parameters. They must be not be url * encoded. i.e. "id","laghi-monitorati-trento" * @throws JackanException on error */ <T extends CkanResponse> T postHttp(Class<T> responseType, String path, String body, ContentType contentType, Object... params) { checkNotNull(responseType); checkNotNull(path); checkNotNull(body); checkNotNull(contentType); String fullUrl = calcFullUrl(path, params); try { logger.log(Level.FINE, "posting to url {0}", fullUrl); Request request = Request.Post(fullUrl); if (proxy != null) { request.viaProxy(proxy); } Response response = request.bodyString(body, contentType).addHeader("Authorization", ckanToken) .execute(); Content out = response.returnContent(); String json = out.asString(); T dr = getObjectMapper().readValue(json, responseType); if (!dr.success) { // monkey patching error type throw new JackanException("posting to catalog " + catalogURL + " was not successful. Reason: " + CkanError.read(getObjectMapper().readTree(json).get("error").asText())); } return dr; } catch (Exception ex) { throw new JackanException("Error while performing a POST! Request url is:" + fullUrl, ex); } }
From source file:de.elomagic.carafile.client.CaraFileClient.java
Response executeRequest(final Request request) throws IOException { if (executor == null) { executor = Executor.newInstance(); }/* w ww . java 2 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 w w .j a va2s .c o m*/ 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.ireport.jasperserver.ws.http.JSSCommonsHTTPSender.java
/** * invoke creates a socket connection, sends the request SOAP message and * then reads the response SOAP message back from the SOAP server * * @param msgContext//w w w. j a va 2 s .co m * the messsage context * * @throws AxisFault */ public void invoke(final MessageContext msgContext) throws AxisFault { if (log.isDebugEnabled()) log.debug(Messages.getMessage("enter00", "CommonsHTTPSender::invoke")); Request req = null; Response response = null; try { if (exec == null) { targetURL = new URL(msgContext.getStrProp(MessageContext.TRANS_URL)); String userID = msgContext.getUsername(); String passwd = msgContext.getPassword(); // if UserID is not part of the context, but is in the URL, use // the one in the URL. if ((userID == null) && (targetURL.getUserInfo() != null)) { String info = targetURL.getUserInfo(); int sep = info.indexOf(':'); if ((sep >= 0) && (sep + 1 < info.length())) { userID = info.substring(0, sep); passwd = info.substring(sep + 1); } else userID = info; } Credentials cred = new UsernamePasswordCredentials(userID, passwd); if (userID != null) { // if the username is in the form "user\domain" // then use NTCredentials instead. int domainIndex = userID.indexOf("\\"); if (domainIndex > 0) { String domain = userID.substring(0, domainIndex); if (userID.length() > domainIndex + 1) { String user = userID.substring(domainIndex + 1); cred = new NTCredentials(user, passwd, NetworkUtils.getLocalHostname(), domain); } } } HttpClient httpClient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy() { public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response, final HttpContext context) throws ProtocolException { URI uri = getLocationURI(request, response, context); String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) return new HttpHead(uri); else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) { HttpPost httpPost = new HttpPost(uri); httpPost.addHeader(request.getFirstHeader("Authorization")); httpPost.addHeader(request.getFirstHeader("SOAPAction")); httpPost.addHeader(request.getFirstHeader("Content-Type")); httpPost.addHeader(request.getFirstHeader("User-Agent")); httpPost.addHeader(request.getFirstHeader("SOAPAction")); if (request instanceof HttpEntityEnclosingRequest) httpPost.setEntity(((HttpEntityEnclosingRequest) request).getEntity()); return httpPost; } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) { return new HttpGet(uri); } else { throw new IllegalStateException( "Redirect called on un-redirectable http method: " + method); } } }).build(); exec = Executor.newInstance(httpClient); HttpHost host = new HttpHost(targetURL.getHost(), targetURL.getPort(), targetURL.getProtocol()); exec.auth(host, cred); exec.authPreemptive(host); HttpUtils.setupProxy(exec, targetURL.toURI()); } boolean posting = true; // If we're SOAP 1.2, allow the web method to be set from the // MessageContext. if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { String webMethod = msgContext.getStrProp(SOAP12Constants.PROP_WEBMETHOD); if (webMethod != null) posting = webMethod.equals(HTTPConstants.HEADER_POST); } HttpHost proxy = HttpUtils.getUnauthProxy(exec, targetURL.toURI()); if (posting) { req = Request.Post(targetURL.toString()); if (proxy != null) req.viaProxy(proxy); Message reqMessage = msgContext.getRequestMessage(); addContextInfo(req, msgContext, targetURL); Iterator<?> it = reqMessage.getAttachments(); if (it.hasNext()) { ByteArrayOutputStream bos = null; try { bos = new ByteArrayOutputStream(); reqMessage.writeTo(bos); req.body(new ByteArrayEntity(bos.toByteArray())); } finally { FileUtils.closeStream(bos); } } else req.body(new StringEntity(reqMessage.getSOAPPartAsString())); } else { req = Request.Get(targetURL.toString()); if (proxy != null) req.viaProxy(proxy); addContextInfo(req, msgContext, targetURL); } response = exec.execute(req); response.handleResponse(new ResponseHandler<String>() { public String handleResponse(final HttpResponse response) throws IOException { HttpEntity en = response.getEntity(); InputStream in = null; try { StatusLine statusLine = response.getStatusLine(); int returnCode = statusLine.getStatusCode(); String contentType = en.getContentType().getValue(); in = new BufferedHttpEntity(en).getContent(); // String str = IOUtils.toString(in); if (returnCode > 199 && returnCode < 300) { // SOAP return is OK - so fall through } else if (msgContext.getSOAPConstants() == SOAPConstants.SOAP12_CONSTANTS) { // For now, if we're SOAP 1.2, fall // through, since the range of // valid result codes is much greater } else if (contentType != null && !contentType.equals("text/html") && ((returnCode > 499) && (returnCode < 600))) { // SOAP Fault should be in here - so // fall through } else { String statusMessage = statusLine.getReasonPhrase(); AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null); fault.setFaultDetailString( Messages.getMessage("return01", "" + returnCode, IOUtils.toString(in))); fault.addFaultDetail(Constants.QNAME_FAULTDETAIL_HTTPERRORCODE, Integer.toString(returnCode)); throw fault; } Header contentEncoding = response.getFirstHeader(HTTPConstants.HEADER_CONTENT_ENCODING); if (contentEncoding != null) { if (contentEncoding.getValue().equalsIgnoreCase(HTTPConstants.COMPRESSION_GZIP)) in = new GZIPInputStream(in); else { AxisFault fault = new AxisFault("HTTP", "unsupported content-encoding of '" + contentEncoding.getValue() + "' found", null, null); throw fault; } } // Transfer HTTP headers of HTTP message // to MIME headers of SOAP // message MimeHeaders mh = new MimeHeaders(); for (Header h : response.getAllHeaders()) mh.addHeader(h.getName(), h.getValue()); Message outMsg = new Message(in, false, mh); outMsg.setMessageType(Message.RESPONSE); msgContext.setResponseMessage(outMsg); if (log.isDebugEnabled()) { log.debug("\n" + Messages.getMessage("xmlRecd00")); log.debug("-----------------------------------------------"); log.debug(outMsg.getSOAPPartAsString()); } } finally { FileUtils.closeStream(in); } return ""; } }); } catch (Exception e) { e.printStackTrace(); log.debug(e); throw AxisFault.makeFault(e); } if (log.isDebugEnabled()) log.debug(Messages.getMessage("exit00", "CommonsHTTPSender::invoke")); }