List of usage examples for org.apache.http.client.utils URIBuilder addParameter
public URIBuilder addParameter(final String param, final String value)
From source file:com.spotify.helios.client.HeliosClient.java
private URI uri(final String path, final Map<String, String> query) { checkArgument(path.startsWith("/")); final URIBuilder builder = new URIBuilder().setScheme("http").setHost("helios").setPath(path); for (final Map.Entry<String, String> q : query.entrySet()) { builder.addParameter(q.getKey(), q.getValue()); }/*from w w w.j av a2 s .c o m*/ builder.addParameter("user", user); try { return builder.build(); } catch (URISyntaxException e) { throw Throwables.propagate(e); } }
From source file:org.artifactory.version.VersionInfoServiceImpl.java
/** * Retrieves the remote version info asynchronously. * * @param headersMap A map of the needed headers * @return ArtifactoryVersioning - Versioning info from the server *//*from w w w . ja va 2 s . c om*/ @Override public synchronized Future<ArtifactoryVersioning> getRemoteVersioningAsync(Map<String, String> headersMap) { ArtifactoryVersioning result; CloseableHttpClient client = null; CloseableHttpResponse response = null; try { URIBuilder urlBuilder = new URIBuilder(URL) .addParameter(artifactoryVersion.getPropertyName(), artifactoryVersion.getString()) .addParameter(PARAM_JAVA_VERSION, System.getProperty(PARAM_JAVA_VERSION)) .addParameter(PARAM_OS_ARCH, System.getProperty(PARAM_OS_ARCH)) .addParameter(PARAM_OS_NAME, System.getProperty(PARAM_OS_NAME)) .addParameter(PARAM_HASH, addonsManager.getLicenseKeyHash()); if (addonsManager.isPartnerLicense()) { urlBuilder.addParameter(PARAM_OEM, "VMware"); } HttpGet getMethod = new HttpGet(urlBuilder.build()); //Append headers setHeader(getMethod, headersMap, HttpHeaders.USER_AGENT); setHeader(getMethod, headersMap, HttpHeaders.REFERER); client = createHttpClient(); log.debug("Retrieving Artifactory versioning from remote server"); response = client.execute(getMethod); String returnedInfo = null; if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { returnedInfo = EntityUtils.toString(response.getEntity()); } if (StringUtils.isBlank(returnedInfo)) { log.debug("Versioning response contains no data"); result = createServiceUnavailableVersioning(); } else { result = VersionParser.parse(returnedInfo); } } catch (Exception e) { log.debug("Failed to retrieve Artifactory versioning from remote server {}", e.getMessage()); result = createServiceUnavailableVersioning(); } finally { IOUtils.closeQuietly(client); IOUtils.closeQuietly(response); } cache.put(VersionInfoServiceImpl.CACHE_KEY, result); return new AsyncResult<>(result); }
From source file:guru.nidi.atlassian.remote.rest.RestAccess.java
private URIBuilder addQuery(URIBuilder builder, Map<String, Object> parameters) { if (parameters != null) { for (Map.Entry<String, Object> entry : parameters.entrySet()) { String value;/*from w w w . j a v a2s . c o m*/ if (entry.getValue() instanceof List) { value = StringUtils.join((List<?>) entry.getValue(), ","); } else if (entry.getValue().getClass().isArray()) { value = StringUtils.join((Object[]) entry.getValue(), ","); } else { value = entry.getValue().toString(); } builder.addParameter(entry.getKey(), value); } } return builder; }
From source file:de.taimos.httputils.HTTPRequest.java
private URI buildURI() { try {/*from ww w.j a v a 2 s . com*/ String u = this.url; for (final Entry<String, String> pathEntry : this.pathParams.entrySet()) { u = u.replace("{" + pathEntry.getKey() + "}", pathEntry.getValue()); } final URIBuilder builder = new URIBuilder(u); final Set<Entry<String, List<String>>> entrySet = this.queryParams.entrySet(); for (final Entry<String, List<String>> entry : entrySet) { final List<String> list = entry.getValue(); for (final String string : list) { builder.addParameter(entry.getKey(), string); } } final URI uri = builder.build(); return uri; } catch (final URISyntaxException e) { throw new RuntimeException("Invalid URI", e); } }
From source file:com.jive.myco.seyren.core.util.graphite.GraphiteHttpClient.java
public byte[] getChart(String target, int width, int height, String from, String to, LegendState legendState, AxesState axesState, BigDecimal warnThreshold, BigDecimal errorThreshold) throws Exception { URI baseUri = new URI(graphiteScheme, graphiteHost, graphitePath + "/render/", null, null); URIBuilder uriBuilder = new URIBuilder(baseUri).addParameter("target", target).addParameter("from", from) .addParameter("width", String.valueOf(width)).addParameter("height", String.valueOf(height)) .addParameter("uniq", String.valueOf(new DateTime().getMillis())) .addParameter("hideLegend", legendState == LegendState.HIDE ? "true" : "false") .addParameter("hideAxes", axesState == AxesState.HIDE ? "true" : "false"); if (warnThreshold != null) { uriBuilder.addParameter("target", String.format(THRESHOLD_TARGET, warnThreshold.toString(), "yellow", "warn level")); }// www. jav a 2 s. c o m if (errorThreshold != null) { uriBuilder.addParameter("target", String.format(THRESHOLD_TARGET, errorThreshold.toString(), "red", "error level")); } HttpGet get = new HttpGet(uriBuilder.build()); try { return client.execute(get, chartBytesHandler, context); } catch (Exception e) { throw new GraphiteReadException("Failed to read from Graphite", e); } finally { get.releaseConnection(); } }
From source file:com.activiti.service.activiti.ActivitiClientService.java
public void addParameterToBuilder(String name, JsonNode bodyNode, URIBuilder builder) { JsonNode nameNode = bodyNode.get(name); if (nameNode != null && nameNode.isNull() == false) { builder.addParameter(name, nameNode.asText()); ((ObjectNode) bodyNode).remove(name); }/* w ww. j av a2 s.c o m*/ }
From source file:org.dasein.cloud.terremark.TerremarkMethod.java
public Document invoke(boolean debug) throws TerremarkException, CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + TerremarkMethod.class.getName() + ".invoke(" + debug + ")"); }/*from w w w .j a va 2 s . co m*/ try { if (logger.isDebugEnabled()) { logger.debug("Talking to server at " + url); } if (parameters != null) { URIBuilder uri = null; try { uri = new URIBuilder(url); } catch (URISyntaxException e) { e.printStackTrace(); } for (NameValuePair parameter : parameters) { uri.addParameter(parameter.getName(), parameter.getValue()); } url = uri.toString(); } HttpUriRequest method = null; if (methodType.equals(HttpMethodName.GET)) { method = new HttpGet(url); } else if (methodType.equals(HttpMethodName.POST)) { method = new HttpPost(url); } else if (methodType.equals(HttpMethodName.DELETE)) { method = new HttpDelete(url); } else if (methodType.equals(HttpMethodName.PUT)) { method = new HttpPut(url); } else if (methodType.equals(HttpMethodName.HEAD)) { method = new HttpHead(url); } else { method = new HttpGet(url); } HttpResponse status = null; try { HttpClient client = new DefaultHttpClient(); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); attempts++; String proxyHost = provider.getProxyHost(); if (proxyHost != null) { int proxyPort = provider.getProxyPort(); boolean ssl = url.startsWith("https"); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort, ssl ? "https" : "http")); } for (Map.Entry<String, String> entry : headers.entrySet()) { method.addHeader(entry.getKey(), entry.getValue()); } if (body != null && body != "" && (methodType.equals(HttpMethodName.PUT) || methodType.equals(HttpMethodName.POST))) { try { HttpEntity entity = new StringEntity(body, "UTF-8"); ((HttpEntityEnclosingRequestBase) method).setEntity(entity); } catch (UnsupportedEncodingException e) { logger.warn(e); } } if (wire.isDebugEnabled()) { wire.debug(methodType.name() + " " + method.getURI()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } if (body != null) { wire.debug(body); } } try { status = client.execute(method); if (wire.isDebugEnabled()) { wire.debug("HTTP STATUS: " + status); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int statusCode = status.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_ACCEPTED) { try { InputStream input = status.getEntity().getContent(); try { return parseResponse(input); } finally { input.close(); } } catch (IOException e) { logger.error("Error parsing response from Teremark: " + e.getMessage()); e.printStackTrace(); throw new CloudException(CloudErrorType.COMMUNICATION, statusCode, null, e.getMessage()); } } else if (statusCode == HttpStatus.SC_NO_CONTENT) { logger.debug("Recieved no content in response. Creating an empty doc."); DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = null; try { docBuilder = dbfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } return docBuilder.newDocument(); } else if (statusCode == HttpStatus.SC_FORBIDDEN) { String msg = "OperationNotAllowed "; try { msg += parseResponseToString(status.getEntity().getContent()); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } wire.error(msg); throw new TerremarkException(statusCode, "OperationNotAllowed", msg); } else { String response = "Failed to parse response."; ParsedError parsedError = null; try { response = parseResponseToString(status.getEntity().getContent()); parsedError = parseErrorResponse(response); } catch (IllegalStateException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } if (logger.isDebugEnabled()) { logger.debug("Received " + status + " from " + url); } if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { if (attempts >= 5) { String msg; wire.warn(response); if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE) { msg = "Cloud service is currently unavailable."; } else { msg = "The cloud service encountered a server error while processing your request."; try { msg = msg + "Response from server was:\n" + response; } catch (RuntimeException runException) { logger.warn(runException); } catch (Error error) { logger.warn(error); } } wire.error(response); logger.error(msg); if (parsedError != null) { throw new TerremarkException(parsedError); } else { throw new CloudException("HTTP Status " + statusCode + msg); } } else { try { Thread.sleep(5000L); } catch (InterruptedException e) { /* ignore */ } return invoke(); } } wire.error(response); if (parsedError != null) { throw new TerremarkException(parsedError); } else { String msg = "\nResponse from server was:\n" + response; logger.error(msg); throw new CloudException("HTTP Status " + statusCode + msg); } } } finally { try { if (status != null) { EntityUtils.consume(status.getEntity()); } } catch (IOException e) { e.printStackTrace(); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT - " + TerremarkMethod.class.getName() + ".invoke()"); } } }
From source file:org.openrdf.http.client.SesameSession.java
public synchronized void commitTransaction() throws OpenRDFException, IOException, UnauthorizedException { checkRepositoryURL();//from w w w . j a v a2s.c o m if (transactionURL == null) { throw new IllegalStateException("Transaction URL has not been set"); } HttpPost method = null; try { URIBuilder url = new URIBuilder(transactionURL); url.addParameter(Protocol.ACTION_PARAM_NAME, Action.COMMIT.toString()); method = new HttpPost(url.build()); } catch (URISyntaxException e) { logger.error("could not create URL for transaction commit", e); throw new RuntimeException(e); } final HttpResponse response = execute(method); try { int code = response.getStatusLine().getStatusCode(); if (code == HttpURLConnection.HTTP_OK) { // we're done. transactionURL = null; } else { throw new RepositoryException("unable to commit transaction. HTTP error code " + code); } } finally { EntityUtils.consumeQuietly(response.getEntity()); } }