List of usage examples for org.apache.http.client.utils URIBuilder build
public URI build() throws URISyntaxException
From source file:io.uploader.drive.drive.largefile.DriveResumableUpload.java
public DriveResumableUpload(HasProxySettings proxySetting, DriveAuth auth, String uploadLocation, DriveUtils.HasId fileId, HasMimeType mimeType, String filename, long fileSize, InputStreamProgressFilter.StreamProgressCallback progressCallback) throws IOException, URISyntaxException { this.auth = auth; this.useOldApi = true; this.fileSize = fileSize; this.proxySetting = proxySetting; if (org.apache.commons.lang3.StringUtils.isEmpty(uploadLocation)) { this.location = createResumableUploadUpdate(fileId, mimeType); } else {//www . j a va 2 s .com this.location = uploadLocation; } Preconditions.checkState(StringUtils.isNotEmpty(this.location)); URIBuilder urib = new URIBuilder(location); uri = urib.build(); //logger.info("URI: " + uri.toASCIIString()); }
From source file:org.talend.dataprep.api.service.command.dataset.DataSetPreview.java
private HttpRequestBase onExecute(String dataSetId, boolean metadata, String sheetName) { try {/*ww w.j ava2s . c om*/ URIBuilder uriBuilder = new URIBuilder(datasetServiceUrl + "/datasets/" + dataSetId + "/preview/"); uriBuilder.addParameter("metadata", Boolean.toString(metadata)); if (StringUtils.isNotEmpty(sheetName)) { // yup this sheet name can contains weird characters space, great french accents or even chinese // characters uriBuilder.addParameter("sheetName", sheetName); } return new HttpGet(uriBuilder.build()); } catch (URISyntaxException e) { throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e); } }
From source file:com.hp.octane.integrations.services.coverage.SonarServiceImpl.java
@Override public String getSonarStatus(String sonarURL) { try {/* w w w . j av a2 s . c om*/ URIBuilder uriBuilder = new URIBuilder(sonarURL + SONAR_STATUS_URI); HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(uriBuilder.build()); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return CIPluginSDKUtils.getObjectMapper().readTree(response.getEntity().getContent()).get("status") .textValue(); } else { return CONNECTION_FAILURE; } } catch (URISyntaxException | IOException e) { return CONNECTION_FAILURE; } }
From source file:com.fredhopper.core.connector.index.upload.impl.RestPublishingStrategy.java
protected URI createUri(final String scheme, final String host, final Integer port, final String servername, final String path, final List<NameValuePair> params) { Preconditions.checkArgument(StringUtils.isNotBlank(scheme)); Preconditions.checkArgument(StringUtils.isNotBlank(host)); Preconditions.checkArgument(port != null); Preconditions.checkArgument(StringUtils.isNotBlank(servername)); Preconditions.checkArgument(StringUtils.isNotBlank(path)); final URIBuilder uriBuilder = new URIBuilder(); uriBuilder.setScheme(scheme);/* w ww . java 2 s .c om*/ uriBuilder.setHost(host); uriBuilder.setPort(port.intValue()); uriBuilder.setPath("/".concat(servername).concat(path)); if (CollectionUtils.isNotEmpty(params)) { uriBuilder.setParameters(params); } try { return uriBuilder.build(); } catch (final URISyntaxException ex) { throw new IllegalArgumentException(ex); } }
From source file:com.revo.deployr.client.core.impl.RRepositoryFileImpl.java
public URL diff() throws RClientException, RSecurityException { URL diffURL;/*from w w w . j av a 2s .com*/ if (this.about.version == null) { throw new RClientException( "Repository file diff can only be requested on a version of a file, not on the latest."); } try { String urlPath = liveContext.serverurl + REndpoints.RREPOSITORYFILEDIFF; urlPath = urlPath + ";jsessionid=" + liveContext.httpcookie; URIBuilder builder = new URIBuilder(urlPath); builder.addParameter("filename", this.about.filename); builder.addParameter("directory", this.about.directory); builder.addParameter("author", this.about.latestby); builder.addParameter("version", this.about.version); diffURL = builder.build().toURL(); } catch (Exception uex) { throw new RClientException("Diff url: ex=" + uex.getMessage()); } return diffURL; }
From source file:uk.co.matbooth.calameo.impl.CalameoClientImpl.java
/** * Internal method that actually does the work of making the request to Calamo and * parsing the response.//from www.ja va 2 s . com * * @param responseType * the class of type T that the response is expected to be * @param params * a map of key/value pairs to be sent to Calamo as query parameters * @return the response object of type T, whose class was specified in the responseType * argument * @throws CalameoException * if there was an error communicating with Calamo */ private <T extends Response<?>> T executeRequest(final Class<T> responseType, final Map<String, String> params) throws CalameoException { HttpClient client = null; HttpGet get = null; InputStreamReader entity = null; try { // Generate signed params Map<String, String> p = new HashMap<String, String>(params); p.put("apikey", getConfig().getKey()); p.put("expires", Long.toString(new Date().getTime() + getConfig().getExpires())); p.put("output", "JSON"); p.put("subscription_id", getConfig().getSubscription()); Set<String> keys = new TreeSet<String>(p.keySet()); StringBuilder input = new StringBuilder(getConfig().getSecret()); for (String key : keys) { input.append(key); input.append(p.get(key)); } p.put("signature", DigestUtils.md5Hex(input.toString())); // Configure HTTP client client = new DefaultHttpClient(); // Configure GET request URIBuilder uri = new URIBuilder(getConfig().getEndpoint()); for (String key : p.keySet()) { uri.addParameter(key, p.get(key)); } get = new HttpGet(uri.build()); log.debug("Request URI: " + get.getURI()); // Execute request and parse response HttpResponse response = client.execute(get); entity = new InputStreamReader(response.getEntity().getContent()); JsonElement parsed = new JsonParser().parse(entity); JsonElement responseJson = parsed.getAsJsonObject().get("response"); T r = new Gson().fromJson(responseJson, responseType); log.debug("Response Object: " + r); // Return response or throw an error if ("error".equals(r.getStatus())) { CalameoException e = new CalameoException(r.getError().getCode(), r.getError().getMessage()); log.error(e.getMessage()); throw e; } else { return r; } } catch (IOException e) { log.error(e.getMessage()); throw new CalameoException(e); } catch (URISyntaxException e) { log.error(e.getMessage()); throw new CalameoException(e); } catch (JsonParseException e) { log.error(e.getMessage()); throw new CalameoException(e); } finally { if (entity != null) { try { entity.close(); } catch (IOException e) { log.warn(e.getMessage()); } } if (get != null) { get.releaseConnection(); } if (client != null) { client.getConnectionManager().shutdown(); } } }
From source file:org.dspace.submit.lookup.CrossRefService.java
public List<Record> search(Context context, Set<String> dois, String apiKey) throws HttpException, IOException, JDOMException, ParserConfigurationException, SAXException { List<Record> results = new ArrayList<Record>(); if (dois != null && dois.size() > 0) { for (String record : dois) { try { HttpGet method = null;//from www .j a v a2 s . c o m try { HttpClient client = new DefaultHttpClient(); client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); try { URIBuilder uriBuilder = new URIBuilder("http://www.crossref.org/openurl/"); uriBuilder.addParameter("pid", apiKey); uriBuilder.addParameter("noredirect", "true"); uriBuilder.addParameter("id", record); method = new HttpGet(uriBuilder.build()); } catch (URISyntaxException ex) { throw new HttpException("Request not sent", ex); } // Execute the method. HttpResponse response = client.execute(method); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("Http call failed: " + statusLine); } Record crossitem; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder db = factory.newDocumentBuilder(); Document inDoc = db.parse(response.getEntity().getContent()); Element xmlRoot = inDoc.getDocumentElement(); Element queryResult = XMLUtils.getSingleElement(xmlRoot, "query_result"); Element body = XMLUtils.getSingleElement(queryResult, "body"); Element dataRoot = XMLUtils.getSingleElement(body, "query"); crossitem = CrossRefUtils.convertCrossRefDomToRecord(dataRoot); results.add(crossitem); } catch (Exception e) { log.warn(LogManager.getHeader(context, "retrieveRecordDOI", record + " DOI is not valid or not exist: " + e.getMessage())); } } finally { if (method != null) { method.releaseConnection(); } } } catch (RuntimeException rt) { log.error(rt.getMessage(), rt); } } } return results; }
From source file:com.github.tmyroadctfig.icloud4j.ICloudService.java
/** * Attempts to log in to iCloud./*from www.j a v a 2 s . co m*/ * * @param params the map of parameters to pass to login. * @return the map of values returned by iCloud. */ public Map<String, Object> authenticate(Map<String, Object> params) { try { URIBuilder uriBuilder = new URIBuilder(setupEndPoint + "/login"); populateUriParameters(uriBuilder); URI uri = uriBuilder.build(); HttpPost post = new HttpPost(uri); post.setEntity(new StringEntity(ICloudUtils.toJson(params), Consts.UTF_8)); populateRequestHeadersParameters(post); try (CloseableHttpResponse response = httpClient.execute(post)) { Map<String, Object> result = new JsonToMapResponseHandler().handleResponse(response); Object error = result.get("error"); if (error != null) throw new RuntimeException("failed to log into iCloud: " + result.get("error")); session.setLoginInfo(result, Boolean.TRUE.equals(params.get("extended_login"))); return result; } } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:com.rackspacecloud.blueflood.http.HttpIntegrationTestBase.java
private HttpPost getHttpPost(String tenantId, String urlPath, String content, ContentType contentType) throws URISyntaxException { // build url to aggregated ingestion endpoint URIBuilder builder = getMetricsURIBuilder().setPath(String.format(urlPath, tenantId)); HttpPost post = new HttpPost(builder.build()); HttpEntity entity = new StringEntity(content, contentType); post.setEntity(entity);/*from w w w . j a v a 2 s. co m*/ return post; }
From source file:com.controller.resource.PaymentResource.java
@POST @Path("/checkout") @Consumes("application/json") @ApiOperation(value = "Test API", notes = "Test API") @ApiResponses(value = { @ApiResponse(code = 404, message = "Session ID not found") }) public Response getPaypalPayment(ProductShoppingCart productShoppingCart, @QueryParam("recaptcha") String recaptcha) { try {/* w w w . jav a 2s . co m*/ HttpClient client = HttpClientBuilder.create().build(); URIBuilder builder = new URIBuilder(System.getenv("GOOGLE_RECAPTCHA_API_ENDPOINT")); builder.setParameter("secret", System.getenv("GOOGLE_RECAPTCHA_API_SECRET")); builder.setParameter("response", recaptcha); LOGGER.error("RECAPTCHA: " + recaptcha); HttpPost httpPost = new HttpPost(builder.build()); HttpResponse httpResponse = client.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { BufferedReader reader = new BufferedReader( new InputStreamReader(httpResponse.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { result.append(line); } ObjectMapper objectMapper = new ObjectMapper(); JsonNode captchaResponse = objectMapper.readTree(result.toString()); LOGGER.error("RECAPTCHA RESPONSE: " + result.toString()); if (captchaResponse.get("success").asBoolean(false)) { PaymentClient paymentClient = new PaymentClient(); return Response.ok() .entity("{\"paypalHref\":\"" + paymentClient.createPayment(productShoppingCart) + "\"}") .build(); } else { LOGGER.error("Error in validating reCaptcha payment: " + captchaResponse.get("error-codes").asText()); } } LOGGER.error("Error in validating reCaptcha payment"); return Response.serverError().entity("{\"message\":\"internal server error\"}").build(); } catch (Exception exception) { LOGGER.error("Error in calculating payment", exception); return Response.serverError().entity("{\"message\":\"internal server error\"}").build(); } }