List of usage examples for org.apache.http.client.utils URIBuilder build
public URI build() throws URISyntaxException
From source file:com.geoxp.oss.client.OSSClient.java
public static void putSecret(String ossURL, String secretname, byte[] secret, String sshKeyFingerprint) throws OSSException { SSHAgentClient agent = null;/* w w w .j a v a 2s. co m*/ HttpClient httpclient = null; try { agent = new SSHAgentClient(); List<SSHKey> sshkeys = agent.requestIdentities(); // // If no SSH Key fingerprint was provided, try all SSH keys available in the agent // List<String> fingerprints = new ArrayList<String>(); if (null == sshKeyFingerprint) { for (SSHKey key : sshkeys) { fingerprints.add(key.fingerprint); } } else { fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", "")); } int idx = 0; for (String fingerprint : fingerprints) { idx++; // // Ask the SSH agent for the SSH key blob // byte[] keyblob = null; for (SSHKey key : sshkeys) { if (key.fingerprint.equals(fingerprint)) { keyblob = key.blob; break; } } // // Throw an exception if this condition is encountered as it can only happen if // there was a provided fingerprint which is not in the agent. // if (null == keyblob) { throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent."); } // // Retrieve OSS RSA key // RSAPublicKey pubkey = getOSSRSA(ossURL); // // Build the token // // <TS> <<WRAPPED_SECRET><ENCRYPTED_WRAPPING_KEY>> <SSH Signing Key Blob> <SSH Signature Blob> // ByteArrayOutputStream token = new ByteArrayOutputStream(); byte[] tsdata = nowBytes(); token.write(CryptoHelper.encodeNetworkString(tsdata)); ByteArrayOutputStream subtoken = new ByteArrayOutputStream(); subtoken.write(CryptoHelper.encodeNetworkString(secretname.getBytes("UTF-8"))); subtoken.write(CryptoHelper.encodeNetworkString(secret)); token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray())); token.write(CryptoHelper.encodeNetworkString(keyblob)); byte[] sigblob = agent.sign(keyblob, token.toByteArray()); token.write(CryptoHelper.encodeNetworkString(sigblob)); // // Encrypt the token with a random AES256 key // byte[] aeskey = new byte[32]; CryptoHelper.getSecureRandom().nextBytes(aeskey); byte[] wrappedtoken = CryptoHelper.wrapAES(aeskey, token.toByteArray()); // // Encrypt the random key with OSS' RSA key // byte[] sealedaeskey = CryptoHelper.encryptRSA(pubkey, aeskey); // // Create the token // token.reset(); token.write(CryptoHelper.encodeNetworkString(wrappedtoken)); token.write(CryptoHelper.encodeNetworkString(sealedaeskey)); // // Base64 encode the encryptedtoken // String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8"); // // Send request to OSS // URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_PUT_SECRET); builder.addParameter("token", b64token); URI uri = builder.build(); String qs = uri.getRawQuery(); HttpPost post = new HttpPost( uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath()); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new StringEntity(qs)); httpclient = newHttpClient(); HttpResponse response = httpclient.execute(post); HttpEntity resEntity = response.getEntity(); String content = EntityUtils.toString(resEntity, "UTF-8"); post.reset(); if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) { // Only throw an exception if this is the last SSH key we could try if (idx == fingerprints.size()) { throw new OSSException("None of the provided keys (" + idx + ") could be used to store the secret. Latest error message was: " + response.getStatusLine().getReasonPhrase()); } else { continue; } } return; } } catch (OSSException osse) { throw osse; } catch (Exception e) { throw new OSSException(e); } finally { if (null != httpclient) { httpclient.getConnectionManager().shutdown(); } if (null != agent) { agent.close(); } } }
From source file:com.esri.geoportal.commons.agp.client.AgpClient.java
/** * Updates item item.//from w w w.j ava 2s .c o m * @param owner user name * @param folderId folder id (optional) * @param itemId item id * @param title title * @param description description * @param text text * @param thumbnailUrl thumbnail URL * @param itemType item type (must be a URL type) * @param extent extent * @param typeKeywords type keywords * @param tags tags tags * @param token token * @return add item response * @throws URISyntaxException if invalid URL * @throws IOException if operation fails */ public ItemResponse updateItem(String owner, String folderId, String itemId, String title, String description, String text, URL thumbnailUrl, ItemType itemType, Double[] extent, String[] typeKeywords, String[] tags, String token) throws IOException, URISyntaxException { URIBuilder builder = new URIBuilder(updateItemUri(owner, StringUtils.trimToNull(folderId), itemId)); HttpPost req = new HttpPost(builder.build()); HashMap<String, String> params = new HashMap<>(); params.put("f", "json"); params.put("title", title); params.put("description", description); params.put("type", itemType.getTypeName()); params.put("text", text); if (thumbnailUrl != null) { params.put("thumbnailurl", thumbnailUrl.toExternalForm()); } if (extent != null && extent.length == 4) { params.put("extent", Arrays.asList(extent).stream().map(Object::toString).collect(Collectors.joining(","))); } if (typeKeywords != null) { params.put("typeKeywords", Arrays.asList(typeKeywords).stream().collect(Collectors.joining(","))); } if (tags != null) { params.put("tags", Arrays.asList(tags).stream().collect(Collectors.joining(","))); } params.put("token", token); req.setEntity(createEntity(params)); return execute(req, ItemResponse.class); }
From source file:com.esri.geoportal.commons.agp.client.AgpClient.java
/** * Adds item./*from w ww . ja v a2 s .c om*/ * @param owner user name * @param folderId folder id (optional) * @param itemId item id * @param title title * @param description description * @param url URL * @param thumbnailUrl thumbnail URL * @param itemType item type (must be a URL type) * @param extent extent * @param typeKeywords type keywords * @param tags tags tags * @param token token * @return add item response * @throws URISyntaxException if invalid URL * @throws IOException if operation fails */ public ItemResponse updateItem(String owner, String folderId, String itemId, String title, String description, URL url, URL thumbnailUrl, ItemType itemType, Double[] extent, String[] typeKeywords, String[] tags, String token) throws IOException, URISyntaxException { URIBuilder builder = new URIBuilder(updateItemUri(owner, StringUtils.trimToNull(folderId), itemId)); HttpPost req = new HttpPost(builder.build()); HashMap<String, String> params = new HashMap<>(); params.put("f", "json"); params.put("title", title); params.put("description", description); params.put("type", itemType.getTypeName()); params.put("url", url.toExternalForm()); if (thumbnailUrl != null) { params.put("thumbnailurl", thumbnailUrl.toExternalForm()); } if (extent != null && extent.length == 4) { params.put("extent", Arrays.asList(extent).stream().map(Object::toString).collect(Collectors.joining(","))); } if (typeKeywords != null) { params.put("typeKeywords", Arrays.asList(typeKeywords).stream().collect(Collectors.joining(","))); } if (tags != null) { params.put("tags", Arrays.asList(tags).stream().collect(Collectors.joining(","))); } params.put("token", token); req.setEntity(createEntity(params)); return execute(req, ItemResponse.class); }
From source file:com.alibaba.shared.django.DjangoClient.java
protected URI buildURI(String baseUrl, Map<String, String> params, boolean hasAccessToken) { try {//from w w w. j ava 2 s . c o m URIBuilder builder = new URIBuilder(baseUrl); if (hasAccessToken) { builder.addParameter(ACCESS_TOKEN_KEY, accessToken()); } for (String paramName : params.keySet()) { builder.addParameter(paramName, params.get(paramName)); } return builder.build(); } catch (URISyntaxException e) { throw new DjangoRequestException(e.getMessage(), e); } }
From source file:org.n52.oxf.util.web.SimpleHttpClient.java
public HttpResponse executeGet(String baseUri, RequestParameters parameters) throws HttpClientException { try {/*from ww w . jav a 2 s. c o m*/ URIBuilder uriBuilder = new URIBuilder(baseUri); for (String key : parameters.getParameterNames()) { if (parameters.isSingleValue(key)) { uriBuilder.addParameter(key, parameters.getSingleValue(key)); } else { Iterable<String> multipleValues = parameters.getAllValues(key); uriBuilder.addParameter(key, createCsvValue(multipleValues)); } } URI uri = uriBuilder.build(); LOGGER.debug("executing GET method '{}'", uri); return executeMethod(new HttpGet(uri)); } catch (URISyntaxException e) { throw new HttpClientException("Invalid base URI: " + baseUri, e); } }
From source file:com.michaeljones.httpclient.apache.ApacheMethodClient.java
@Override public int PutFile(String url, String filePath, List<Pair<String, String>> queryParams, StringBuilder redirect) throws FileNotFoundException { try {//from w w w .j a v a2s.co m URIBuilder fileUri = new URIBuilder(url); if (queryParams != null) { // Query params are optional. In the case of a redirect the url will contain // all the params. for (Pair<String, String> queryParam : queryParams) { fileUri.addParameter(queryParam.getFirst(), queryParam.getSecond()); } } HttpPut httpPut = new HttpPut(fileUri.build()); InputStream fileInStream = new FileInputStream(filePath); InputStreamEntity chunkedStream = new InputStreamEntity(fileInStream, -1, ContentType.APPLICATION_OCTET_STREAM); chunkedStream.setChunked(true); httpPut.setEntity(chunkedStream); CloseableHttpResponse response = clientImpl.execute(httpPut); try { Header[] hdrs = response.getHeaders("Location"); if (redirect != null && hdrs.length > 0) { String redirectLocation = hdrs[0].getValue(); redirect.append(redirectLocation); LOGGER.debug("Redirect to: " + redirectLocation); } return response.getStatusLine().getStatusCode(); } finally { // I believe this releases the connection to the client pool, but does not // close the connection. response.close(); } } catch (IOException | URISyntaxException ex) { throw new RuntimeException("Apache method putQuery: " + ex.getMessage()); } }
From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpAnnotationsIntegrationTest.java
private URI getAnnotationsQueryURI() throws URISyntaxException { URIBuilder builder = new URIBuilder().setScheme("http").setHost("127.0.0.1").setPort(queryPort) .setPath("/v2.0/" + tenantId + "/events/getEvents"); Set<String> parameters = parameterMap.keySet(); Iterator<String> setIterator = parameters.iterator(); while (setIterator.hasNext()) { String paramName = setIterator.next(); builder.setParameter(paramName, parameterMap.get(paramName)); }//from w w w . j a v a 2s . c o m return builder.build(); }
From source file:org.talend.dataprep.api.service.command.dataset.MoveDataSet.java
/** * Constructor./*from w ww . ja v a 2 s . c o m*/ * * @param dataSetId the requested dataset id. * @param folderPath the origin folder othe the dataset * @param newFolderPath the new folder path * @param newName the new name (optional) */ public MoveDataSet(String dataSetId, String folderPath, String newFolderPath, String newName) { super(GenericCommand.DATASET_GROUP); execute(() -> { try { URIBuilder uriBuilder = new URIBuilder(datasetServiceUrl + "/datasets/move/" + dataSetId); if (StringUtils.isNotEmpty(folderPath)) { uriBuilder.addParameter("folderPath", folderPath); } if (StringUtils.isNotEmpty(newFolderPath)) { uriBuilder.addParameter("newFolderPath", newFolderPath); } if (StringUtils.isNotEmpty(newName)) { uriBuilder.addParameter("newName", newName); } return new HttpPut(uriBuilder.build()); } catch (URISyntaxException e) { throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e); } }); onError(e -> new TDPException(APIErrorCodes.UNABLE_TO_COPY_DATASET_CONTENT, e, build().put("id", dataSetId))); on(HttpStatus.OK, HttpStatus.BAD_REQUEST).then((httpRequestBase, httpResponse) -> { try { // we transfer status code and content type return new HttpResponse(httpResponse.getStatusLine().getStatusCode(), // IOUtils.toString(httpResponse.getEntity().getContent()), // httpResponse.getStatusLine().getStatusCode() == HttpStatus.BAD_REQUEST.value() ? // APPLICATION_JSON_VALUE : TEXT_PLAIN_VALUE); } catch (IOException e) { throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e); } finally { httpRequestBase.releaseConnection(); } }); }
From source file:de.ii.xtraplatform.ogc.csw.client.CSWAdapter.java
private HttpResponse requestPOST(CSWOperation operation) throws ParserConfigurationException { URI url = findUrl(operation.getOperation(), CSW.METHOD.POST); HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient; URIBuilder uri = new URIBuilder(url); String xml = operation.toXml(nsStore, version); LOGGER.debug("{}\n{}", uri, xml); HttpPost httpPost;/*w w w .j a va 2 s .co m*/ HttpResponse response = null; try { httpPost = new HttpPost(uri.build()); for (String key : operation.getRequestHeaders().keySet()) { httpPost.setHeader(key, operation.getRequestHeaders().get(key)); } // TODO: temporary basic auth hack if (useBasicAuth) { String basic_auth = new String(Base64.encodeBase64((user + ":" + password).getBytes())); httpPost.addHeader("Authorization", "Basic " + basic_auth); } StringEntity xmlEntity = new StringEntity(xml, ContentType.create("text/plain", "UTF-8")); httpPost.setEntity(xmlEntity); response = httpClient.execute(httpPost, new BasicHttpContext()); // check http status checkResponseStatus(response.getStatusLine().getStatusCode(), uri); } catch (SocketTimeoutException ex) { if (ignoreTimeouts) { //LOGGER.warn(FrameworkMessages.POST_REQUEST_TIMED_OUT_AFTER_MS_URL_REQUEST, HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri.toString(), xml); } response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, ""); response.setEntity(new StringEntity("", ContentType.TEXT_XML)); } catch (IOException ex) { //LOGGER.error(ERROR_IN_POST_REQUEST_TO_URL_REQUEST, uri.toString(), xml, ex); //LOGGER.debug("Error requesting URL: {}", uri.toString()); try { if (!isDefaultUrl(uri.build(), CSW.METHOD.POST)) { //LOGGER.info(FrameworkMessages.REMOVING_URL, uri.toString()); this.urls.remove(operation.getOperation().toString()); //LOGGER.info(FrameworkMessages.RETRY_WITH_DEFAULT_URL, this.urls.get("default")); return requestPOST(operation); } } catch (URISyntaxException ex0) { } //LOGGER.error(FrameworkMessages.FAILED_REQUESTING_URL, uri.toString()); throw new ReadError("Failed requesting URL: '{}'", uri); } catch (URISyntaxException ex) { //LOGGER.error(FrameworkMessages.FAILED_REQUESTING_URL, uri.toString()); throw new ReadError("Failed requesting URL: '{}'", uri); } catch (ReadError ex) { //LOGGER.error(FrameworkMessages.FAILED_REQUESTING_URL, uri.toString()); throw ex; } //LOGGER.debug(FrameworkMessages.WFS_REQUEST_SUBMITTED); return response; }
From source file:org.dspace.submit.lookup.PubmedService.java
public List<Record> search(String query) throws IOException, HttpException { List<Record> results = new ArrayList<>(); if (!ConfigurationManager.getBooleanProperty(SubmissionLookupService.CFG_MODULE, "remoteservice.demo")) { HttpGet method = null;//w w w .j a va 2 s .co m try { HttpClient client = new DefaultHttpClient(); client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); URIBuilder uriBuilder = new URIBuilder("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi"); uriBuilder.addParameter("db", "pubmed"); uriBuilder.addParameter("datetype", "edat"); uriBuilder.addParameter("retmax", "10"); uriBuilder.addParameter("term", query); method = new HttpGet(uriBuilder.build()); // Execute the method. HttpResponse response = client.execute(method); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("WS call failed: " + statusLine); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); Document inDoc = builder.parse(response.getEntity().getContent()); Element xmlRoot = inDoc.getDocumentElement(); Element idList = XMLUtils.getSingleElement(xmlRoot, "IdList"); List<String> pubmedIDs = XMLUtils.getElementValueList(idList, "Id"); results = getByPubmedIDs(pubmedIDs); } catch (ParserConfigurationException e1) { log.error(e1.getMessage(), e1); } catch (SAXException e1) { log.error(e1.getMessage(), e1); } } catch (Exception e1) { log.error(e1.getMessage(), e1); } finally { if (method != null) { method.releaseConnection(); } } } else { InputStream stream = null; try { File file = new File(ConfigurationManager.getProperty("dspace.dir") + "/config/crosswalks/demo/pubmed-search.xml"); stream = new FileInputStream(file); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document inDoc = builder.parse(stream); Element xmlRoot = inDoc.getDocumentElement(); Element idList = XMLUtils.getSingleElement(xmlRoot, "IdList"); List<String> pubmedIDs = XMLUtils.getElementValueList(idList, "Id"); results = getByPubmedIDs(pubmedIDs); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } } return results; }