List of usage examples for org.apache.http.client.utils URIBuilder addParameter
public URIBuilder addParameter(final String param, final String value)
From source file:org.eclipse.rdf4j.http.client.RDF4JProtocolSession.java
protected void upload(HttpEntity reqEntity, String baseURI, boolean overwrite, boolean preserveNodeIds, Action action, Resource... contexts) throws IOException, RDFParseException, RepositoryException, UnauthorizedException { OpenRDFUtil.verifyContextNotNull(contexts); checkRepositoryURL();//w ww .j a va 2 s. c o m boolean useTransaction = transactionURL != null; try { String baseLocation = useTransaction ? transactionURL : Protocol.getStatementsLocation(getQueryURL()); URIBuilder url = new URIBuilder(baseLocation); // Set relevant query parameters for (String encodedContext : Protocol.encodeContexts(contexts)) { url.addParameter(Protocol.CONTEXT_PARAM_NAME, encodedContext); } if (baseURI != null && baseURI.trim().length() != 0) { String encodedBaseURI = Protocol.encodeValue(SimpleValueFactory.getInstance().createIRI(baseURI)); url.setParameter(Protocol.BASEURI_PARAM_NAME, encodedBaseURI); } if (preserveNodeIds) { url.setParameter(Protocol.PRESERVE_BNODE_ID_PARAM_NAME, "true"); } if (useTransaction) { if (action == null) { throw new IllegalArgumentException("action can not be null on transaction operation"); } url.setParameter(Protocol.ACTION_PARAM_NAME, action.toString()); } // Select appropriate HTTP method HttpEntityEnclosingRequestBase method = null; try { if (overwrite || useTransaction) { method = new HttpPut(url.build()); } else { method = new HttpPost(url.build()); } // Set payload method.setEntity(reqEntity); // Send request try { executeNoContent((HttpUriRequest) method); } catch (RepositoryException e) { throw e; } catch (RDFParseException e) { throw e; } catch (RDF4JException e) { throw new RepositoryException(e); } } finally { if (method != null) { method.reset(); } } } catch (URISyntaxException e) { throw new AssertionError(e); } }
From source file:org.nectarframework.base.service.nanohttp.NanoHttpService.java
private Response serveProxy(ProxyResolution proxyResolution, String uri, Method method, Map<String, String> headers, Map<String, List<String>> parms, String queryParameterString, Map<String, String> files) { String remoteTarget = uri.substring(proxyResolution.getPath().length() + 1); if (!remoteTarget.startsWith("/")) { remoteTarget = "/" + remoteTarget; }//from w w w . j av a2s . co m CloseableHttpClient httpclient = HttpClients.createDefault(); URIBuilder remoteUri = new URIBuilder(); remoteUri.setScheme("http"); remoteUri.setHost(proxyResolution.getHost()); remoteUri.setPort(proxyResolution.getPort()); remoteUri.setPath(proxyResolution.getRequestPath() + remoteTarget); remoteUri.setCharset(Charset.defaultCharset()); for (String k : parms.keySet()) { remoteUri.addParameter(k, parms.get(k).get(0)); } HttpGet httpget; try { httpget = new HttpGet(remoteUri.build()); } catch (URISyntaxException e) { Log.warn(e); return newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHttpService.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: URISyntaxException" + e.getMessage()); } CloseableHttpResponse response = null; Response resp = null; try { response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream is = entity.getContent(); long isl = entity.getContentLength(); resp = new Response(Status.lookup(response.getStatusLine().getStatusCode()), null, is, isl); } else { resp = new Response(Status.lookup(response.getStatusLine().getStatusCode()), null, null, 0); } Header[] remoteHeaders = response.getAllHeaders(); for (Header h : remoteHeaders) { resp.addHeader(h.getName(), h.getValue()); } resp.setProxyResponse(response); } catch (IOException e) { Log.warn(e); return newFixedLengthResponse(Status.INTERNAL_ERROR, NanoHttpService.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException" + e.getMessage()); } return resp; }
From source file:com.ittm_solutions.ipacore.IpaApi.java
/** * Exports the given analyses or all analyses of an IPA project. * <p>/* w ww . j ava 2s. c o m*/ * See {@link #exportAnalyses} for details on {@code resultTypes}. * * @param projectId * the id of an IPA project (usually a number) * @param analysisIds * the analyses ids * @param resultTypes * the result types (see {@code exportAnalyses}) * @return the exported results wrapped in a class */ private CloseableHttpResponse exportRawAnalyses(String projectId, List<String> analysisIds, List<String> resultTypes) throws IpaApiException { final String path = "/pa/api/v1/export"; CloseableHttpResponse response; try { URIBuilder uribuilder = new URIBuilder(serverUrl).setPath(path); if (projectId != null) { uribuilder.addParameter("pid", projectId); } // FIXME if we get a large number of analysis ids we may have to split // this list, see section 2.4.1 of IPA Integration Module if (analysisIds.size() > 0) { uribuilder.addParameter("aid", StringUtils.join(analysisIds, ",")); } if (resultTypes.size() > 0) { uribuilder.addParameter("art", StringUtils.join(resultTypes, ",")); } URI uri = uribuilder.build(); CloseableHttpClient hc = this.authenticatedClient(); HttpClientContext context = this.clientContext(); HttpGet httpget = new HttpGet(uri); response = hc.execute(httpget, context); log.info("get " + uri + " status " + response.getStatusLine().getStatusCode()); } catch (URISyntaxException | IOException e) { throw new IpaApiException(e); } return response; }
From source file:eu.esdihumboldt.hale.io.wfs.ui.KVPUtil.java
/** * Add typename and namespace parameters for a WFS request to the given URI * builder./*from w ww. j av a2 s . c o m*/ * * @param builder the builder for the WFS request URI * @param selected the type names to include * @param version the targeted WFS version */ public static void addTypeNameParameter(URIBuilder builder, Iterable<QName> selected, WFSVersion version) { // namespaces mapped to prefixes Map<String, String> namespaces = new HashMap<>(); // type names with updated prefix Set<QName> typeNames = new HashSet<>(); for (QName type : selected) { String prefix; if (type.getNamespaceURI() != null && !type.getNamespaceURI().isEmpty()) { prefix = namespaces.get(type.getNamespaceURI()); if (prefix == null) { // no mapping yet for namespace String candidate = type.getPrefix(); prefix = addPrefix(candidate, type.getNamespaceURI(), namespaces); } } else { // default namespace prefix = XMLConstants.DEFAULT_NS_PREFIX; } // add updated type typeNames.add(new QName(type.getNamespaceURI(), type.getLocalPart(), prefix)); } final String paramNamespaces; final String paramTypenames; final String prefixNamespaceDelim; switch (version) { case V1_1_0: paramNamespaces = "NAMESPACE"; paramTypenames = "TYPENAME"; prefixNamespaceDelim = "="; break; case V2_0_0: case V2_0_2: /* * XXX below are the values as defined in the WFS 2 specification. * There have been problems with some GeoServer instances if used in * that manner. */ paramNamespaces = "NAMESPACES"; paramTypenames = "TYPENAMES"; prefixNamespaceDelim = ","; break; default: // fall-back to WFS 1.1 paramNamespaces = "NAMESPACE"; paramTypenames = "TYPENAME"; prefixNamespaceDelim = "="; } // add namespace prefix definitions if (!namespaces.isEmpty()) { builder.addParameter(paramNamespaces, Joiner.on(',') .join(Maps.transformEntries(namespaces, new EntryTransformer<String, String, String>() { @Override public String transformEntry(String namespace, String prefix) { StringBuilder sb = new StringBuilder(); sb.append("xmlns("); sb.append(prefix); sb.append(prefixNamespaceDelim); sb.append(namespace); sb.append(")"); return sb.toString(); } }).values())); } // add type names if (!typeNames.isEmpty()) { builder.addParameter(paramTypenames, Joiner.on(',').join(Iterables.transform(typeNames, new Function<QName, String>() { @Override public String apply(QName typeName) { String prefix = typeName.getPrefix(); if (prefix == null || prefix.isEmpty()) { return typeName.getLocalPart(); } return prefix + ":" + typeName.getLocalPart(); } }))); } }
From source file:org.apache.ignite.console.agent.handlers.RestHandler.java
/** * @param uri Url.//from w w w . j av a 2 s .co m * @param params Params. * @param demo Use demo node. * @param mtd Method. * @param headers Headers. * @param body Body. */ protected RestResult executeRest(String uri, Map<String, Object> params, boolean demo, String mtd, Map<String, Object> headers, String body) throws IOException, URISyntaxException { if (log.isDebugEnabled()) log.debug("Start execute REST command [method=" + mtd + ", uri=/" + (uri == null ? "" : uri) + ", parameters=" + params + "]"); final URIBuilder builder; if (demo) { // try start demo if needed. AgentClusterDemo.testDrive(cfg); // null if demo node not started yet. if (cfg.demoNodeUri() == null) return RestResult.fail("Demo node is not started yet.", 404); builder = new URIBuilder(cfg.demoNodeUri()); } else builder = new URIBuilder(cfg.nodeUri()); if (builder.getPort() == -1) builder.setPort(DFLT_NODE_PORT); if (uri != null) { if (!uri.startsWith("/") && !cfg.nodeUri().endsWith("/")) uri = '/' + uri; builder.setPath(uri); } if (params != null) { for (Map.Entry<String, Object> entry : params.entrySet()) { if (entry.getValue() != null) builder.addParameter(entry.getKey(), entry.getValue().toString()); } } HttpRequestBase httpReq = null; try { if ("GET".equalsIgnoreCase(mtd)) httpReq = new HttpGet(builder.build()); else if ("POST".equalsIgnoreCase(mtd)) { HttpPost post; if (body == null) { List<NameValuePair> nvps = builder.getQueryParams(); builder.clearParameters(); post = new HttpPost(builder.build()); if (!nvps.isEmpty()) post.setEntity(new UrlEncodedFormEntity(nvps)); } else { post = new HttpPost(builder.build()); post.setEntity(new StringEntity(body)); } httpReq = post; } else throw new IOException("Unknown HTTP-method: " + mtd); if (headers != null) { for (Map.Entry<String, Object> entry : headers.entrySet()) httpReq.addHeader(entry.getKey(), entry.getValue() == null ? null : entry.getValue().toString()); } try (CloseableHttpResponse resp = httpClient.execute(httpReq)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); resp.getEntity().writeTo(out); Charset charset = Charsets.UTF_8; Header encodingHdr = resp.getEntity().getContentEncoding(); if (encodingHdr != null) { String encoding = encodingHdr.getValue(); charset = Charsets.toCharset(encoding); } return RestResult.success(resp.getStatusLine().getStatusCode(), new String(out.toByteArray(), charset)); } catch (ConnectException e) { log.info("Failed connect to node and execute REST command [uri=" + builder.build() + "]"); return RestResult.fail("Failed connect to node and execute REST command.", 404); } } finally { if (httpReq != null) httpReq.reset(); } }
From source file:org.finra.herd.tools.downloader.DownloaderWebClient.java
/** * Gets the storage unit download credentials. * * @param manifest The manifest/* ww w . j a v a 2 s . co m*/ * @param storageName The storage name * * @return StorageUnitDownloadCredential * @throws URISyntaxException When error occurs while URI creation * @throws IOException When error occurs communicating with server * @throws JAXBException When error occurs parsing XML */ public StorageUnitDownloadCredential getStorageUnitDownloadCredential(DownloaderInputManifestDto manifest, String storageName) throws URISyntaxException, IOException, JAXBException { URIBuilder uriBuilder = new URIBuilder().setScheme(getUriScheme()) .setHost(regServerAccessParamsDto.getRegServerHost()) .setPort(regServerAccessParamsDto.getRegServerPort()) .setPath(String.join("/", HERD_APP_REST_URI_PREFIX, "storageUnits", "download", "credential", "namespaces", manifest.getNamespace(), "businessObjectDefinitionNames", manifest.getBusinessObjectDefinitionName(), "businessObjectFormatUsages", manifest.getBusinessObjectFormatUsage(), "businessObjectFormatFileTypes", manifest.getBusinessObjectFormatFileType(), "businessObjectFormatVersions", manifest.getBusinessObjectFormatVersion(), "partitionValues", manifest.getPartitionValue(), "businessObjectDataVersions", manifest.getBusinessObjectDataVersion(), "storageNames", storageName)); if (manifest.getSubPartitionValues() != null) { uriBuilder.addParameter("subPartitionValues", herdStringHelper.join(manifest.getSubPartitionValues(), "|", "\\")); } HttpGet httpGet = new HttpGet(uriBuilder.build()); httpGet.addHeader("Accept", DEFAULT_ACCEPT); if (regServerAccessParamsDto.isUseSsl()) { httpGet.addHeader(getAuthorizationHeader()); } try (CloseableHttpClient httpClient = httpClientOperations.createHttpClient()) { LOGGER.info("Retrieving download credentials from registration server..."); return getStorageUnitDownloadCredential(httpClientOperations.execute(httpClient, httpGet)); } }
From source file:pt.meocloud.sdk.MeoCloudImpl.java
@Override public MeoCloudResponse<File> downloadFile(String path, String revision) { try {//from www. ja va 2 s . co m String builderPath = String.format("/%s/%s/%s%s", MEOCLOUD_API_VERSION, MEOCLOUD_API_METHOD_FILES, apiMode.getCode(), path); URIBuilder builder = new URIBuilder(); builder.setScheme(MEOCLOUD_SCHEME); builder.setHost(MEOCLOUD_API_CONTENT_ENDPOINT); builder.setPath(builderPath); List<NameValuePair> parameters = new LinkedList<>(); if (revision != null) { builder.addParameter(REV_PARAM, revision); parameters.add(new BasicNameValuePair(REV_PARAM, revision)); } String apiCall = builder.build().toString(); HttpClient client = HttpClientBuilder.create().build(); HttpGet getRequest = new HttpGet(apiCall); signHttpRequest(getRequest, "GET", apiCall, parameters); HttpResponse httpResponse = client.execute(getRequest); Integer statusCode = httpResponse.getStatusLine().getStatusCode(); MeoCloudResponse<File> meoCloudResponse = new MeoCloudResponse<>(); meoCloudResponse.setCode(statusCode); if (statusCode == HttpStatus.SC_OK) { InputStream is = httpResponse.getEntity().getContent(); File tempFile = new File(UUID.randomUUID().toString()); FileOutputStream fos = new FileOutputStream(tempFile); byte[] buffer = new byte[1024 * 100]; int nBytes = -1; while ((nBytes = is.read(buffer)) != -1) { fos.write(buffer, 0, nBytes); fos.flush(); } is.close(); fos.close(); meoCloudResponse.setResponse(tempFile); } else process(meoCloudResponse, statusCode); return meoCloudResponse; } catch (Exception e) { log.error("Exception caught downloading file.", e); } return null; }
From source file:pt.meocloud.sdk.MeoCloudImpl.java
/** * Max file size: 2048MB//from w ww . j a v a 2 s . co m * Disallowed characters: +*<>:"/\|?* * */ @Override public MeoCloudResponse<Metadata> uploadFile(String filePath, String path, Boolean overwrite, String parentRevision) { try { String builderPath = String.format("/%s/%s/%s%s", MEOCLOUD_API_VERSION, MEOCLOUD_API_METHOD_FILES, apiMode.getCode(), path); URIBuilder builder = new URIBuilder(); builder.setScheme(MEOCLOUD_SCHEME); builder.setHost(MEOCLOUD_API_CONTENT_ENDPOINT); builder.setPath(builderPath); List<NameValuePair> parameters = new LinkedList<>(); if (overwrite != null) { builder.addParameter(OVERWRITE_PARAM, overwrite.toString()); parameters.add(new BasicNameValuePair(OVERWRITE_PARAM, overwrite.toString())); } if (parentRevision != null) { builder.addParameter(PARENT_REV_PARAM, parentRevision); parameters.add(new BasicNameValuePair(PARENT_REV_PARAM, parentRevision)); } String apiCall = builder.build().toString(); HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(apiCall); signHttpRequest(post, "POST", apiCall, parameters); FileEntity fileEntity = new FileEntity(new File(filePath)); // fileEntity.setChunked(true); post.setEntity(fileEntity); HttpResponse response = client.execute(post); Integer statusCode = response.getStatusLine().getStatusCode(); MeoCloudResponse<Metadata> meoCloudResponse = new MeoCloudResponse<>(); meoCloudResponse.setCode(statusCode); if (statusCode == HttpStatus.SC_OK) { String responseBody = convertStreamToString(response.getEntity().getContent()); Metadata metatada = Metadata.fromJson(responseBody, Metadata.class); meoCloudResponse.setResponse(metatada); } else process(meoCloudResponse, statusCode); } catch (Exception e) { log.error("Exception caught uploading file.", e); } return null; }
From source file:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java
protected HttpUriRequest getQueryMethod(QueryLanguage ql, String query, String baseURI, Dataset dataset, boolean includeInferred, int maxQueryTime, Binding... bindings) { List<NameValuePair> queryParams = getQueryMethodParameters(ql, query, baseURI, dataset, includeInferred, maxQueryTime, bindings);//from w w w.j av a2s .c o m HttpUriRequest method; String queryUrlWithParams; try { URIBuilder urib = new URIBuilder(getQueryURL()); for (NameValuePair nvp : queryParams) urib.addParameter(nvp.getName(), nvp.getValue()); queryUrlWithParams = urib.toString(); } catch (URISyntaxException e) { throw new AssertionError(e); } if (shouldUsePost(queryUrlWithParams)) { // we just built up a URL for nothing. oh well. // It's probably not much overhead against // the poor triplestore having to process such as massive query HttpPost postMethod = new HttpPost(getQueryURL()); postMethod.setHeader("Content-Type", Protocol.FORM_MIME_TYPE + "; charset=utf-8"); postMethod.setEntity(new UrlEncodedFormEntity(queryParams, UTF8)); method = postMethod; } else { method = new HttpGet(queryUrlWithParams); } // functionality to provide custom http headers as required by the // applications for (Map.Entry<String, String> additionalHeader : additionalHttpHeaders.entrySet()) { method.addHeader(additionalHeader.getKey(), additionalHeader.getValue()); } return method; }
From source file:org.apache.hadoop.crypto.key.kms.KMSClientProvider.java
private URL createURL(String collection, String resource, String subResource, Map<String, ?> parameters) throws IOException { try {/*w w w . j a v a2 s . c om*/ StringBuilder sb = new StringBuilder(); sb.append(kmsUrl); if (collection != null) { sb.append(collection); if (resource != null) { sb.append("/").append(URLEncoder.encode(resource, UTF8)); if (subResource != null) { sb.append("/").append(subResource); } } } URIBuilder uriBuilder = new URIBuilder(sb.toString()); if (parameters != null) { for (Map.Entry<String, ?> param : parameters.entrySet()) { Object value = param.getValue(); if (value instanceof String) { uriBuilder.addParameter(param.getKey(), (String) value); } else { for (String s : (String[]) value) { uriBuilder.addParameter(param.getKey(), s); } } } } return uriBuilder.build().toURL(); } catch (URISyntaxException ex) { throw new IOException(ex); } }