List of usage examples for org.apache.http.client.utils URIBuilder build
public URI build() throws URISyntaxException
From source file:org.flowable.admin.service.engine.FlowableClientService.java
public String getServerUrl(ServerConfig serverConfig, URIBuilder builder) { try {/*from w ww . j a va2 s. c o m*/ return getServerUrl(serverConfig, builder.build().toString()); } catch (URISyntaxException e) { throw new FlowableServiceException("Error while creating Flowable endpoint URL: " + e.getMessage()); } }
From source file:org.apache.olingo.client.core.communication.request.invoke.ODataInvokeRequestImpl.java
/** * {@inheritDoc }/* www . j av a2 s. c o m*/ */ @Override public ODataInvokeResponse<T> execute() { final InputStream input = getPayload(); if (!this.parameters.isEmpty()) { if (this.method == HttpMethod.GET) { final URIBuilder uriBuilder = new URIBuilder(this.uri); for (Map.Entry<String, ODataValue> param : parameters.entrySet()) { if (!param.getValue().isPrimitive()) { throw new IllegalArgumentException("Only primitive values can be passed via GET"); } uriBuilder.addParameter(param.getKey(), param.getValue().toString()); } try { ((HttpRequestBase) this.request).setURI(uriBuilder.build()); } catch (URISyntaxException e) { throw new IllegalArgumentException("While adding GET parameters", e); } } else if (this.method == HttpMethod.POST) { ((HttpPost) request).setEntity(URIUtils.buildInputStreamEntity(odataClient, input)); setContentType(ODataPubFormat.JSON.toString(odataClient.getServiceVersion())); } } try { return new ODataInvokeResponseImpl(httpClient, doExecute()); } finally { IOUtils.closeQuietly(input); } }
From source file:gov.medicaid.screening.dao.impl.MedicalPracticeLicenseDAOBean.java
/** * Performs a search for all possible results. * * @param criteria The search criteria./* www .ja v a 2s . c om*/ * @param byName flag indicating it is a search by name. * @return the search result for licenses * @throws URISyntaxException if an error occurs while building the URL. * @throws ClientProtocolException if client does not support protocol used. * @throws IOException if an error occurs while parsing response. * @throws ParseException if an error occurs while parsing response. * @throws ServiceException for any other problems encountered */ private SearchResult<License> getAllResults(MedicalPracticeLicenseSearchCriteria criteria, boolean byName) throws URISyntaxException, ClientProtocolException, IOException, ParseException, ServiceException { DefaultHttpClient client = new DefaultHttpClient(); URIBuilder builder = new URIBuilder(getSearchURL()).setPath("/BMP/DesktopModules/ServiceForm.aspx"); String hostId = builder.toString(); builder.setParameter("svid", "30").setParameter("mid", "176"); HttpGet httpget = new HttpGet(builder.build()); HttpResponse landing = client.execute(httpget); Document document = Jsoup.parse(EntityUtils.toString(landing.getEntity())); HttpPost httppost = new HttpPost(builder.build()); HttpEntity entity = postForm(hostId, client, httppost, new String[][] { { "__EVENTTARGET", byName ? "_ctl7_rblSearchOption_0" : "_ctl7_rblSearchOption_1" }, { "__EVENTARGUMENT", "" }, { "_ctl7:rblSearchOption", byName ? "Name" : "Specialty" }, { "__VIEWSTATE", document.select("#Form1 input[name=__VIEWSTATE]").first().val() } }, true); document = Jsoup.parse(EntityUtils.toString(entity)); httppost.releaseConnection(); if (byName) { entity = postForm(hostId, client, httppost, new String[][] { { "__EVENTTARGET", "" }, { "__EVENTARGUMENT", "" }, { "_ctl7:cmdSearch", "Search" }, { "_ctl7:rblSearchOption", "Name" }, { "_ctl7:txtCity", Util.defaultString(criteria.getCity()) }, { "_ctl7:txtFirstName", Util.defaultString(criteria.getFirstName()) }, { "_ctl7:txtLastName", Util.defaultString(criteria.getLastName()) }, { "_ctl7:txtLicNbr", Util.defaultString(criteria.getIdentifier()) }, { "__VIEWSTATE", document.select("#Form1 input[name=__VIEWSTATE]").first().val() } }, true); } else { String code = matchSpecialtyCode(criteria, document); entity = postForm(hostId, client, httppost, new String[][] { { "__EVENTTARGET", "" }, { "__EVENTARGUMENT", "" }, { "_ctl7:cmdSearchSpecialty", "Search" }, { "_ctl7:ddlbSpecialty", code }, { "_ctl7:rblSearchOption", "Specialty" }, { "_ctl7:txtSpecialtyCity", Util.defaultString(criteria.getCity()) }, { "_ctl7:txtSpecialtyZip", Util.defaultString(criteria.getZipcode()) }, { "__VIEWSTATE", document.select("#Form1 input[name=__VIEWSTATE]").first().val() } }, true); } // licenses list List<License> licenseList = new ArrayList<License>(); if (entity != null) { String result = EntityUtils.toString(entity); document = Jsoup.parse(result); Elements rows = document.select( "#_ctl7_grdSearchResults tr.TableItem, #_ctl7_grdSearchResults tr.TableAlternatingItem"); for (Element row : rows) { String href = row.select("a[name=Hyperlink1]").first().attr("href"); String city = row.select("td:eq(4)").text(); String detailsLink = getSearchURL() + "/BMP/DesktopModules/" + href.replaceAll(" ", "%20"); HttpGet detailsGet = new HttpGet(detailsLink); HttpResponse detailsResponse = client.execute(detailsGet); HttpEntity detailsEntity = detailsResponse.getEntity(); if (detailsEntity != null) { Document details = Jsoup.parse(EntityUtils.toString(detailsEntity)); licenseList.add(parseLicense(city, details)); } } } SearchResult<License> result = new SearchResult<License>(); result.setItems(licenseList); return result; }
From source file:at.gv.egiz.pdfas.lib.pki.impl.OCSPClient.java
/** * Retrieves an OCSP response for a certain certificate ({@code eeCertificate}) of a certain CA * ({@code issuerCertificate})./*from ww w . ja v a 2s . c o m*/ * * @param issuerCertificate The issuer certificate (required; must not be {@code null}). * @param eeCertificate The end entity certificate (required; must not be {@code null}). * @return The OCSP response (never {@code null}) with guaranteed response status "successful" and with <strong>any * revocation state</strong>. * @throws IOException Thrown in case of error communicating with OCSP responder. * @throws OCSPClientException In case the client could not process the response (e.g. non-successful response * state like malformedRequest, internalError... or an unknown/unsupported response * type). * @throws IllegalArgumentException In case the provided {@code eeCertificate} does not provide an OCSP responder * url (use {@link Util#hasOcspResponder(X509Certificate)} in order to determine if * it is safe to call this method) or the provided certificates could not be used * for OCSP request creation. * @implNote This implementation just returns OCSP responses (<strong>of any revocation status</strong>) as they * were retrieved from the OCSP responder (provided the response status indicates a successful response) * without performing further checks like OCSP signature verification or OCSP responder certificate * validation. */ public OCSPResponse getOcspResponse(X509Certificate issuerCertificate, X509Certificate eeCertificate) throws IOException, OCSPClientException { Objects.requireNonNull(issuerCertificate, "Issuer certificate required... must not be null."); Objects.requireNonNull(eeCertificate, "End-entity certificate required... must not be null."); StopWatch sw = new StopWatch(); sw.start(); if (log.isDebugEnabled()) { log.debug("Retrieving OCSP revocation info for: {}", eeCertificate.getSubjectDN()); } else if (log.isInfoEnabled()) { log.info("Retrieving OCSP revocation info for certificate (SHA-1 fingerprint): {}", Hex.encodeHexString(eeCertificate.getFingerprintSHA())); } String ocspUrl = Util.getOcspUrl(eeCertificate); if (ocspUrl == null) { throw new IllegalArgumentException("The provided certificate does not feature an ocsp responder url."); } // create request byte[] ocspRequestEncoded; ReqCert reqCert; try { CertID certID = new CertID(AlgorithmID.sha1, issuerCertificate, eeCertificate); reqCert = new ReqCert(ReqCert.certID, certID); Request request = new Request(reqCert); OCSPRequest ocspRequest = new OCSPRequest(); ocspRequest.setRequestList(new Request[] { request }); ocspRequestEncoded = ocspRequest.getEncoded(); if (log.isTraceEnabled()) { log.trace("Creating OCSP request: {}", request); } } catch (NoSuchAlgorithmException e) { // should not occur actually throw new IllegalStateException("Required algorithm (SHA-1) not available.", e); } catch (CodingException e) { throw new IllegalArgumentException( "Unable to encode ocsp request with the provided issuer and end-entity certificates.", e); } // https://tools.ietf.org/html/rfc6960 // GET {url}/{url-encoding of base-64 encoding of the DER encoding of the OCSPRequest} String b64OcspRequest = org.apache.commons.codec.binary.Base64.encodeBase64String(ocspRequestEncoded); String urlEncodedB64OcspRequest = URLEncoder.encode(b64OcspRequest, "UTF-8"); HttpRequestBase request; if (httpCachingEnabled && urlEncodedB64OcspRequest.length() <= 255) { // spec proposes GET request URI ocspResponderUri; try { URIBuilder uriBuilder = new URIBuilder(ocspUrl); uriBuilder .setPath(StringUtils.appendIfMissing(uriBuilder.getPath(), "/") + urlEncodedB64OcspRequest); ocspResponderUri = uriBuilder.build(); } catch (URISyntaxException e) { // can only occur with eeCertificate containing invalid ocsp responder url throw new IllegalArgumentException( "Unable process OCSP responder uri of provided certificate: " + ocspUrl, e); } request = new HttpGet(ocspResponderUri); log.debug("Sending OCSP request using HTTP GET to: {}", ocspUrl); } else { // spec proposes POST request HttpPost httpPost = new HttpPost(ocspUrl); httpPost.setEntity( new ByteArrayEntity(ocspRequestEncoded, ContentType.create("application/ocsp-request"))); request = httpPost; log.debug("Sending OCSP request using HTTP POST to: {}", ocspUrl); } request.setConfig(requestConfig); try (CloseableHttpResponse httpResponse = httpClient.execute(request)) { StatusLine statusLine = httpResponse.getStatusLine(); log.debug("OCSP response HTTP status: {}", statusLine); if (statusLine.getStatusCode() != HttpStatus.SC_OK) { throw new IOException("OCSP responder did not report HTTP 200: " + statusLine); } HttpEntity responseEntity = httpResponse.getEntity(); OCSPResponse ocspResponse; try (InputStream in = responseEntity.getContent()) { ocspResponse = new OCSPResponse(in); } catch (UnknownResponseException e) { throw new OCSPClientException("Unknown (unsupported) OCSP response type: " + e.getResponseType(), e); } if (log.isTraceEnabled()) { log.trace("OCSP response: {}", ocspResponse); } log.debug("OCSP response status: {}", ocspResponse.getResponseStatusName()); if (ocspResponse.getResponseStatus() != OCSPResponse.successful) { throw new OCSPClientException("OCSP response status was not successful, got response status: " + ocspResponse.getResponseStatusName()); } // get the basic ocsp response (which is the only type currently supported, otherwise an // UnknownResponseException would have been thrown during parsing the response) BasicOCSPResponse basicOCSPResponse = (BasicOCSPResponse) ocspResponse.getResponse(); // for future improvement: verify ocsp response, responder certificate... SingleResponse singleResponse; try { log.trace("Looking for OCSP response specific for: {}", reqCert); singleResponse = basicOCSPResponse.getSingleResponse(reqCert); } catch (OCSPException e) { try { singleResponse = basicOCSPResponse.getSingleResponse(issuerCertificate, eeCertificate, null); } catch (OCSPException e1) { throw new OCSPClientException( "Unable to process received OCSP response for the provided certificate (SHA-1 fingerprint): " + Hex.encodeHexString(eeCertificate.getFingerprintSHA()), e1); } } if (log.isTraceEnabled()) { log.trace("OCSP respose for specific certificate: {}", singleResponse); } CertStatus certStatus = singleResponse.getCertStatus(); String formattedThisUpdate = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT .format(singleResponse.getThisUpdate()); log.info("Certificate revocation state (@{}}: {}", formattedThisUpdate, certStatus); sw.stop(); log.debug("OCSP query took: {}ms", sw.getTime()); return ocspResponse; } // close httpResponse }
From source file:hudson.plugins.jira.JiraRestService.java
public void releaseVersion(String projectKey, Version version) { final URIBuilder builder = new URIBuilder(uri) .setPath(String.format("%s/version/%s", baseApiPath, version.getId())); final VersionInput versionInput = new VersionInput(projectKey, version.getName(), version.getDescription(), version.getReleaseDate(), version.isArchived(), version.isReleased()); try {/*from w w w . java 2 s .co m*/ jiraRestClient.getVersionRestClient().updateVersion(builder.build(), versionInput).get(timeout, TimeUnit.SECONDS); } catch (Exception e) { LOGGER.log(WARNING, "jira rest client release version error. cause: " + e.getMessage(), e); } }
From source file:eu.eubrazilcc.lvl.storage.gravatar.Gravatar.java
public URL imageUrl() { try {//from w w w . j av a 2s.co m final URIBuilder uriBuilder = new URIBuilder( (secure ? SECURE_URL_BASE : DEFAULT_URL_BASE) + emailHash(email)).addParameter("s", Integer.toString(imageSize)); if (imageRating != Rating.GENERAL_AUDIENCES) { uriBuilder.addParameter("r", imageRating.getCode()); } if (defaultImage != DefaultImage.DEFAULT) { uriBuilder.addParameter("d", defaultImage.getCode()); } return uriBuilder.build().toURL(); } catch (Exception e) { throw new IllegalStateException("Failed to get Gravatar image URL", e); } }
From source file:org.modeshape.web.jcr.rest.AbstractRestTest.java
private <T extends HttpRequestBase> T newRequest(Class<T> clazz, InputStream inputStream, String contentType, String accepts, String... pathSegments) { String url = RestHelper.urlFrom(getServerContext(), pathSegments); try {/* ww w. jav a 2s . c o m*/ URIBuilder uriBuilder; try { uriBuilder = new URIBuilder(url); } catch (URISyntaxException e) { uriBuilder = new URIBuilder(URL_ENCODER.encode(url)); } T result = clazz.getConstructor(URI.class).newInstance(uriBuilder.build()); result.setHeader("Accept", accepts); result.setHeader("Content-Type", contentType); if (inputStream != null) { assertTrue("Invalid request clazz (requires an entity)", result instanceof HttpEntityEnclosingRequestBase); InputStreamEntity inputStreamEntity = new InputStreamEntity(inputStream, inputStream.available()); ((HttpEntityEnclosingRequestBase) result).setEntity(new BufferedHttpEntity(inputStreamEntity)); } return result; } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); return null; } }
From source file:org.apache.james.jmap.methods.integration.cucumber.DownloadStepdefs.java
private Request authenticatedDownloadRequest(URIBuilder uriBuilder, String blobId, String username) throws URISyntaxException { AccessToken accessToken = userStepdefs.tokenByUser.get(username); AttachmentAccessTokenKey key = new AttachmentAccessTokenKey(username, blobId); if (attachmentAccessTokens.containsKey(key)) { uriBuilder.addParameter("access_token", attachmentAccessTokens.get(key).serialize()); }//from ww w. ja v a 2 s. c o m Request request = Request.Get(uriBuilder.build()); if (accessToken != null) { request.addHeader("Authorization", accessToken.serialize()); } return request; }
From source file:com.teradata.tempto.internal.hadoop.hdfs.WebHDFSClient.java
private URI buildUri(String path, String username, String operation, Pair<String, String>... parameters) { try {//from w ww. j a v a 2s .c o m if (!path.startsWith("/")) { path = "/" + path; } URIBuilder uriBuilder = new URIBuilder().setScheme("http").setHost(nameNode.getHostText()) .setPort(nameNode.getPort()).setPath("/webhdfs/v1" + checkNotNull(path)) .setParameter("op", checkNotNull(operation)).setParameter("user.name", checkNotNull(username)); for (Pair<String, String> parameter : parameters) { uriBuilder.setParameter(parameter.getKey(), parameter.getValue()); } return uriBuilder.build(); } catch (URISyntaxException e) { throw new RuntimeException("Could not create save file URI" + ", nameNode: " + nameNode + ", path: " + path + ", username: " + username); } }
From source file:client.Traveller.java
public void searchFlights(FlightSearch flightSearch) { // Keeps current search in order to store session variables currentFlightSearch = flightSearch;/*from w ww .j a va2 s . c om*/ try { // Builds URL for HTTP request that queries for departing flights URIBuilder uriBuilder = new URIBuilder(hostURL + "/search/flight"); uriBuilder.addParameter("origin", flightSearch.getOrigin()); uriBuilder.addParameter("destination", flightSearch.getDestination()); uriBuilder.addParameter("departureDate", flightSearch.getDepartureDate()); uriBuilder.addParameter("numberOfPassengers", String.valueOf(flightSearch.getNumberOfPassengers())); // Converts URL to string String urlString = uriBuilder.build().toString(); // Send GET request and waits for response String response = httpConnector.sendGet(urlString); // Handles response (REST API returns a JSON array) ArrayList<Flight> departingFlights = new ArrayList<>(); JSONArray flights = new JSONArray(response); int n = flights.length(); Flight f; for (int i = 0; i < n; ++i) { final JSONObject flight = flights.getJSONObject(i); String flightNumber = (flight.getString("flightNumber")); String airline = (flight.getString("airline")); String origin = (flight.getString("origin")); String destination = (flight.getString("destination")); String departureDate = (flight.getString("departureDate")); String arrivalDate = (flight.getString("arrivalDate")); departureDate = (flight.getString("departureDate")); String departureTime = (flight.getString("departureTime")); String arrivalTime = (flight.getString("arrivalTime")); String airfare = (flight.getString("airfare")); int availableSeats = (flight.getInt("availableSeats")); f = new Flight(flightNumber, airline, origin, destination, departureDate, departureTime, arrivalTime, Double.parseDouble(airfare), availableSeats); departingFlights.add(f); } // Creates array for returning flights ArrayList<Flight> returningFlights = new ArrayList<>(); // Prepares second GET request if user searched for a round trip flights if (flightSearch.getRoundTrip()) { // Builds URL for HTTP request that queries for returning flights uriBuilder = new URIBuilder(hostURL + "/search/flight"); uriBuilder.addParameter("destination", flightSearch.getOrigin()); uriBuilder.addParameter("origin", flightSearch.getDestination()); uriBuilder.addParameter("departureDate", flightSearch.getReturnDate()); uriBuilder.addParameter("numberOfPassengers", String.valueOf(flightSearch.getNumberOfPassengers())); // Converts URL to string urlString = uriBuilder.build().toString(); // Sends second GET request and waits for response response = httpConnector.sendGet(urlString); // Handles response from second GET request flights = new JSONArray(response); n = flights.length(); for (int i = 0; i < n; ++i) { final JSONObject flight = flights.getJSONObject(i); String flightNumber = (flight.getString("flightNumber")); String airline = (flight.getString("airline")); String origin = (flight.getString("origin")); String destination = (flight.getString("destination")); String departureDate = (flight.getString("departureDate")); departureDate = (flight.getString("departureDate")); String departureTime = (flight.getString("departureTime")); String arrivalTime = (flight.getString("arrivalTime")); String airfare = (flight.getString("airfare")); int availableSeats = (flight.getInt("availableSeats")); f = new Flight(flightNumber, airline, origin, destination, departureDate, departureTime, arrivalTime, Double.parseDouble(airfare), availableSeats); returningFlights.add(f); } } // Display search results in a new window flightSearchResultsFrame = new FlightSearchResultsFrame(this, departingFlights, returningFlights); flightSearchResultsFrame.setLocationRelativeTo(null); flightSearchResultsFrame.setVisible(true); } catch (URISyntaxException ex) { this.displayBookingConfirmation("ERROR | Invalid search"); } }