List of usage examples for org.apache.http.impl.client HttpClientBuilder build
public CloseableHttpClient build()
From source file:org.tinymediamanager.scraper.util.TmmHttpClient.java
/** * instantiates a new CloseableHttpClient * /* ww w .j a v a2 s.c om*/ * @return CloseableHttpClient */ public static CloseableHttpClient createHttpClient() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); // Increase default max connection per route to 5 connectionManager.setMaxTotal(5); HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties(); httpClientBuilder.setConnectionManager(connectionManager); // my own retry handler HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 5) { // Do not retry if over max retry count return false; } if (exception instanceof InterruptedIOException) { // Timeout return false; } if (exception instanceof UnknownHostException) { // Unknown host return false; } if (exception instanceof ConnectTimeoutException) { // Connection refused return false; } if (exception instanceof SSLException) { // SSL handshake exception return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent return true; } return false; } }; httpClientBuilder.setRetryHandler(myRetryHandler); // set proxy if needed if ((Globals.settings.useProxy())) { setProxy(httpClientBuilder); } return httpClientBuilder.build(); }
From source file:de.taimos.httputils.HTTPRequest.java
private HttpResponse execute(final HttpUriRequest req) { final HttpClientBuilder builder = HttpClientBuilder.create(); final Builder reqConfig = RequestConfig.custom(); if (this.timeout != null) { reqConfig.setConnectTimeout(this.timeout); }/* www . jav a2s .c o m*/ reqConfig.setRedirectsEnabled(this.followRedirect); builder.setDefaultRequestConfig(reqConfig.build()); if ((this.userAgent != null) && !this.userAgent.isEmpty()) { builder.setUserAgent(this.userAgent); } try { final CloseableHttpClient httpclient = builder.build(); // if request has data populate body if (req instanceof HttpEntityEnclosingRequestBase) { final HttpEntityEnclosingRequestBase entityBase = (HttpEntityEnclosingRequestBase) req; entityBase.setEntity(new StringEntity(this.body, "UTF-8")); } // Set headers final Set<Entry<String, List<String>>> entrySet = this.headers.entrySet(); for (final Entry<String, List<String>> entry : entrySet) { final List<String> list = entry.getValue(); for (final String string : list) { req.addHeader(entry.getKey(), string); } } final HttpResponse response = httpclient.execute(req); return response; } catch (final ClientProtocolException e) { throw new RuntimeException(e); } catch (final IOException e) { throw new RuntimeException(e); } }
From source file:com.basistech.rosette.api.HttpRosetteAPI.java
private void initClient(String key, List<Header> additionalHeaders) { HttpClientBuilder builder = HttpClients.custom(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(connectionConcurrency); builder.setConnectionManager(cm);//from w w w. jav a2 s .co m initHeaders(key, additionalHeaders); builder.setDefaultHeaders(this.additionalHeaders); httpClient = builder.build(); this.additionalHeaders = new ArrayList<>(); }
From source file:com.esri.geoevent.datastore.GeoEventDataStoreProxy.java
private CloseableHttpClient createHttpClient(ServerInfo serverInfo) { HttpClientBuilder builder = (useBuiltinWindowsAuthentication(serverInfo)) ? WinHttpClients.custom() : HttpClients.custom();/*from w ww .ja v a2 s . c o m*/ HttpClientConnectionManager connMgr = createConnectionManagerIfNecessary(); if (connMgr != null) { builder.setConnectionManager(connMgr); } builder.setUserAgent(userAgent); builder.useSystemProperties(); return builder.build(); }
From source file:org.outofbits.sesame.schemagen.SchemaGeneration.java
/** * Requests the RDF file of the vocabulary by using the given HTTP {@link java.net.URL}. The * header-entry ACCEPT contains all supported {@link RDFFormat}s, where the given * {@link RDFFormat} is the preferred one. The responded rdf file will be parsed and a * {@link Model} containing all statements will be returned. An {@link IOException} will be * thrown, if the rdf file cannot be accessed or read. {@link URISyntaxException} will be thrown, * if the given {@link java.net.URL} has a syntax error. * * @param url the url, where the vocabulary is located and accessible by using HTTP. It must * not be null.//from www .j a v a 2 s . co m * @param format the format of the document representing the vocabulary. The format can be null. * @return {@link Model} containing all statements of the vocabulary located at the given * {@link java.net.URL}. * @throws IOException if the rdf file cannot be accessed or read. * @throws URISyntaxException if the given {@link java.net.URL} has a syntax error. */ private Model readVocabularyFromHTTPSource(java.net.URL url, RDFFormat format) throws IOException, URISyntaxException { assert url != null && url.getProtocol().equals("http"); HttpClientBuilder clientBuilder = HttpClientBuilder.create().setUserAgent(HTTP_USER_AGENT); HttpUriRequest vocabularyGETRequest = RequestBuilder.get().setUri(url.toURI()) .setHeader(HttpHeaders.ACCEPT, String.join(", ", RDFFormat.getAcceptParams(supportedRDFFormats.values(), false, format))) .build(); try (CloseableHttpClient client = clientBuilder.build()) { CloseableHttpResponse response = client.execute(vocabularyGETRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new IOException(String.format("The given vocabulary can not requested from '%s'. %d: %s", url, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); } String responseContentType = response.getEntity().getContentType().getValue(); Optional<RDFFormat> optionalResponseRdfFormat = Rio.getParserFormatForMIMEType(responseContentType); try (InputStream vocabResponseStream = response.getEntity().getContent()) { if (optionalResponseRdfFormat.isPresent()) { return Rio.parse(vocabResponseStream, "", optionalResponseRdfFormat.get()); } else { if (format == null) { throw new IOException( String.format("The returned content type (%s) from '%s' is not supported", responseContentType, url)); } try { return Rio.parse(vocabResponseStream, "", format); } catch (RDFParseException | UnsupportedRDFormatException e) { throw new IOException(String.format( "The returned content type (%s) from '%s' is not supported. Fallback to the given format %s, but an error occurred.", responseContentType, url, format), e); } } } } }
From source file:com.googlesource.gerrit.plugins.github.oauth.PooledHttpClientProvider.java
@Override public HttpClient get() { HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnPerRoute(maxConnectionPerRoute) .setMaxConnTotal(maxTotalConnection); if (proxy.getProxyUrl() != null) { URL url = proxy.getProxyUrl(); builder.setProxy(new HttpHost(url.getHost(), url.getPort())); if (!Strings.isNullOrEmpty(proxy.getUsername()) && !Strings.isNullOrEmpty(proxy.getPassword())) { UsernamePasswordCredentials creds = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), creds); builder.setDefaultCredentialsProvider(credsProvider); builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); }//from ww w . j a va 2 s . co m } return builder.build(); }
From source file:com.portfolio.data.attachment.XSLService.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { /**/* www . ja v a2s .co m*/ * Format demand: * <convert> * <portfolioid>{uuid}</portfolioid> * <portfolioid>{uuid}</portfolioid> * <nodeid>{uuid}</nodeid> * <nodeid>{uuid}</nodeid> * <documentid>{uuid}</documentid> * <xsl>{rpertoire}{fichier}</xsl> * <format>[pdf rtf xml ...]</format> * <parameters> * <maVar1>lala</maVar1> * ... * </parameters> * </convert> */ try { //On initialise le dataProvider Connection c = null; //On initialise le dataProvider if (ds == null) // Case where we can't deploy context.xml { c = getConnection(); } else { c = ds.getConnection(); } dataProvider.setConnection(c); credential = new Credential(c); } catch (Exception e) { e.printStackTrace(); } String origin = request.getRequestURL().toString(); /// Variable stuff int userId = 0; int groupId = 0; String user = ""; HttpSession session = request.getSession(true); if (session != null) { Integer val = (Integer) session.getAttribute("uid"); if (val != null) userId = val; val = (Integer) session.getAttribute("gid"); if (val != null) groupId = val; user = (String) session.getAttribute("user"); } /// TODO: A voire si un form get ne ferait pas l'affaire aussi /// On lis le xml /* BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while( (line = rd.readLine()) != null ) sb.append(line); DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = null; Document doc=null; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8"))); } catch( Exception e ) { e.printStackTrace(); } /// On lit les paramtres NodeList portfolioNode = doc.getElementsByTagName("portfolioid"); NodeList nodeNode = doc.getElementsByTagName("nodeid"); NodeList documentNode = doc.getElementsByTagName("documentid"); NodeList xslNode = doc.getElementsByTagName("xsl"); NodeList formatNode = doc.getElementsByTagName("format"); NodeList parametersNode = doc.getElementsByTagName("parameters"); //*/ // String xslfile = xslNode.item(0).getTextContent(); String xslfile = request.getParameter("xsl"); String format = request.getParameter("format"); // String format = formatNode.item(0).getTextContent(); String parameters = request.getParameter("parameters"); String documentid = request.getParameter("documentid"); String portfolios = request.getParameter("portfolioids"); String[] portfolioid = null; if (portfolios != null) portfolioid = portfolios.split(";"); String nodes = request.getParameter("nodeids"); String[] nodeid = null; if (nodes != null) nodeid = nodes.split(";"); System.out.println("PARAMETERS: "); System.out.println("xsl: " + xslfile); System.out.println("format: " + format); System.out.println("user: " + userId); System.out.println("portfolioids: " + portfolios); System.out.println("nodeids: " + nodes); System.out.println("parameters: " + parameters); boolean redirectDoc = false; if (documentid != null) { redirectDoc = true; System.out.println("documentid @ " + documentid); } boolean usefop = false; String ext = ""; if (MimeConstants.MIME_PDF.equals(format)) { usefop = true; ext = ".pdf"; } else if (MimeConstants.MIME_RTF.equals(format)) { usefop = true; ext = ".rtf"; } //// Paramtre portfolio-uuid et file-xsl // String uuid = request.getParameter("uuid"); // String xslfile = request.getParameter("xsl"); StringBuilder aggregate = new StringBuilder(); try { int portcount = 0; int nodecount = 0; // On aggrge les donnes if (portfolioid != null) { portcount = portfolioid.length; for (int i = 0; i < portfolioid.length; ++i) { String p = portfolioid[i]; String portfolioxml = dataProvider .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0) .toString(); aggregate.append(portfolioxml); } } if (nodeid != null) { nodecount = nodeid.length; for (int i = 0; i < nodeid.length; ++i) { String n = nodeid[i]; String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "") .toString(); aggregate.append(nodexml); } } // Est-ce qu'on a eu besoin d'aggrger les donnes? String input = aggregate.toString(); String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration input = input.replaceAll(pattern, ""); input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet [" + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \"" + servletDir + "xhtml-symbol.ent\">" + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters "<root>" + input + "</root>"; // System.out.println("INPUT WITH PROXY:"+ input); /// Rsolution des proxys DocumentBuilder documentBuilder; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(input)); Document doc = documentBuilder.parse(is); /// Proxy stuff XPath xPath = XPathFactory.newInstance().newXPath(); String filterRes = "//asmResource[@xsi_type='Proxy']"; String filterCode = "./code/text()"; NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET); XPathExpression codeFilter = xPath.compile(filterCode); for (int i = 0; i < nodelist.getLength(); ++i) { Node res = nodelist.item(i); Node gp = res.getParentNode(); // resource -> context -> container Node ggp = gp.getParentNode(); Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE); /// Fetch node we want to replace String returnValue = dataProvider .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "") .toString(); Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue))); Element repNode = rep.getDocumentElement(); Node proxyNode = repNode.getFirstChild(); proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned // doc.replaceChild(proxyNode, gp); ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work. ggp.removeChild(gp); } try // Convert XML document to string { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); writer.flush(); input = writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); } // System.out.println("INPUT DATA:"+ input); // Setup a buffer to obtain the content length ByteArrayOutputStream stageout = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); //// Setup Transformer (1st stage) /// Base path String basepath = xslfile.substring(0, xslfile.indexOf(File.separator)); String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator + "xsl" + File.separator + "html2xml.xsl"; System.out.println("FIRST: " + firstStage); Source xsltSrc1 = new StreamSource(new File(firstStage)); Transformer transformer1 = transFactory.newTransformer(xsltSrc1); StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes())); Result stageRes = new StreamResult(stageout); transformer1.transform(stageSource, stageRes); // Setup Transformer (2nd stage) String secondStage = baseDir + File.separator + xslfile; Source xsltSrc2 = new StreamSource(new File(secondStage)); Transformer transformer2 = transFactory.newTransformer(xsltSrc2); // Configure parameter from xml String[] table = parameters.split(";"); for (int i = 0; i < table.length; ++i) { String line = table[i]; int var = line.indexOf(":"); String par = line.substring(0, var); String val = line.substring(var + 1); transformer2.setParameter(par, val); } // Setup input StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes())); // StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") ); Result res = null; if (usefop) { /// FIXME: Might need to include the entity for html stuff? //Setup FOP //Make sure the XSL transformation's result is piped through to FOP Fop fop = fopFactory.newFop(format, out); res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer2.transform(xmlSource, res); } else { res = new StreamResult(out); //Start the transformation and rendering process transformer2.transform(xmlSource, res); } if (redirectDoc) { // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]] String urlTarget = "http://" + server + "/resources/resource/file/" + documentid; System.out.println("Redirect @ " + urlTarget); HttpClientBuilder clientbuilder = HttpClientBuilder.create(); CloseableHttpClient client = clientbuilder.build(); HttpPost post = new HttpPost(urlTarget); post.addHeader("referer", origin); String sessionid = request.getSession().getId(); System.out.println("Session: " + sessionid); post.addHeader("Cookie", "JSESSIONID=" + sessionid); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext); builder.addPart("uploadfile", body); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse ret = client.execute(post); String stringret = new BasicResponseHandler().handleResponse(ret); int code = ret.getStatusLine().getStatusCode(); response.setStatus(code); ServletOutputStream output = response.getOutputStream(); output.write(stringret.getBytes(), 0, stringret.length()); output.close(); client.close(); /* HttpURLConnection connection = CreateConnection( urlTarget, request ); /// Helping construct Json connection.setRequestProperty("referer", origin); /// Send post data ServletInputStream inputData = request.getInputStream(); DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); byte[] buffer = new byte[1024]; int dataSize; while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 ) { writer.write(buffer, 0, dataSize); } inputData.close(); writer.close(); RetrieveAnswer(connection, response, origin); //*/ } else { response.reset(); response.setHeader("Content-Disposition", "attachment; filename=generated" + ext); response.setContentType(format); response.setContentLength(out.size()); response.getOutputStream().write(out.toByteArray()); response.getOutputStream().flush(); } } catch (Exception e) { String message = e.getMessage(); response.setStatus(500); response.getOutputStream().write(message.getBytes()); response.getOutputStream().close(); e.printStackTrace(); } finally { dataProvider.disconnect(); } }
From source file:de.undercouch.gradle.tasks.download.internal.DefaultHttpClientFactory.java
@Override public CloseableHttpClient createHttpClient(HttpHost httpHost, boolean acceptAnyCertificate) { HttpClientBuilder builder = HttpClientBuilder.create(); //configure proxy from system environment builder.setRoutePlanner(new SystemDefaultRoutePlanner(null)); //accept any certificate if necessary if ("https".equals(httpHost.getSchemeName()) && acceptAnyCertificate) { SSLConnectionSocketFactory icsf = getInsecureSSLSocketFactory(); builder.setSSLSocketFactory(icsf); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", icsf).build(); HttpClientConnectionManager cm = new BasicHttpClientConnectionManager(registry); builder.setConnectionManager(cm); }// w ww . j a va 2 s . c om //add an interceptor that replaces the invalid Content-Type //'none' by 'identity' builder.addInterceptorFirst(new ContentEncodingNoneInterceptor()); CloseableHttpClient client = builder.build(); return client; }
From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java
protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey, String deploymentName) {//from w w w . j a va 2s . com String deployApiUrl = modelerAppProperties.getDeploymentApiUrl(); Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set"); String basicAuthUser = properties.getIdmAdmin().getUser(); String basicAuthPassword = properties.getIdmAdmin().getPassword(); String tenantId = tenantProvider.getTenantId(); if (!deployApiUrl.endsWith("/")) { deployApiUrl = deployApiUrl.concat("/"); } deployApiUrl = deployApiUrl .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s", encode(deploymentKey), encode(deploymentName))); if (tenantId != null) { StringBuilder sb = new StringBuilder(deployApiUrl); sb.append("&tenantId=").append(encode(tenantId)); deployApiUrl = sb.toString(); } HttpPost httpPost = new HttpPost(deployApiUrl); httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder() .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8"))))); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName); HttpEntity entity = entityBuilder.build(); httpPost.setEntity(entity); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); clientBuilder .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } })); } catch (Exception e) { LOGGER.error("Could not configure SSL for http client", e); throw new InternalServerErrorException("Could not configure SSL for http client", e); } CloseableHttpClient client = clientBuilder.build(); try { HttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) { return; } else { LOGGER.error("Invalid deploy result code: {} for url", response.getStatusLine() + httpPost.getURI().toString()); throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine()); } } catch (IOException ioe) { LOGGER.error("Error calling deploy endpoint", ioe); throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage()); } finally { if (client != null) { try { client.close(); } catch (IOException e) { LOGGER.warn("Exception while closing http client", e); } } } }