List of usage examples for org.apache.http.client.utils URIBuilder setParameter
public URIBuilder setParameter(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();/*from ww w . 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:eu.esdihumboldt.hale.io.wfs.ui.capabilities.WFSCapabilitiesFieldEditor.java
private boolean getValidState() { String value = getValue();/*from w w w .j a va2 s . c o m*/ DialogPage page = getPage(); // try to create a URL try { new URI(value); } catch (Exception e) { if (page != null) { page.setErrorMessage(e.getLocalizedMessage()); } return false; } // try to get capabilities try { URIBuilder builder = new URIBuilder(value); // add fixed parameters boolean requestPresent = false; boolean servicePresent = false; String versionParam = null; for (NameValuePair param : builder.getQueryParams()) { String name = param.getName().toLowerCase(); if (name.equals("request")) requestPresent = true; if (name.equals("service")) servicePresent = true; if (name.equals("version")) versionParam = param.getName(); } if (!requestPresent) { builder.addParameter("REQUEST", "GetCapabilities"); } if (!servicePresent) { builder.addParameter("SERVICE", "WFS"); } WFSVersion version = getWFSVersion(); if (version != null) { if (versionParam == null) { versionParam = "VERSION"; } builder.setParameter(versionParam, version.toString()); } usedUrl = builder.build().toURL(); try (InputStream in = usedUrl.openStream()) { capabilities = CapabilitiesHelper.loadCapabilities(in); } } catch (Exception e) { if (page != null) { page.setErrorMessage(e.getLocalizedMessage()); } return false; } // passed all tests if (page != null) { page.setErrorMessage(null); } return true; }
From source file:com.pennassurancesoftware.tutum.client.TutumClient.java
private URI createUri(ApiRequest request) { URIBuilder ub = new URIBuilder(); ub.setScheme(Constants.HTTPS_SCHEME); ub.setHost(apiHost);// ww w . j a v a 2 s . co m ub.setPath(createPath(request)); for (String paramName : request.getQueryParams().keySet()) { final List<String> values = request.getQueryParams().get(paramName); for (String value : values) { ub.setParameter(paramName, value); } } URI uri = null; try { uri = ub.build(); } catch (URISyntaxException use) { LOG.error(use.getMessage(), use); } return uri; }
From source file:ching.icecreaming.action.ResourceDescriptors.java
@Action(value = "resource-descriptors", results = { @Result(name = "success", location = "json.jsp") }) public String execute() throws Exception { int int1 = 401, int0 = 0; String string1 = null;// ww w . j ava2 s . co m URL url1 = null; URI uri1 = null; HttpGet httpGet1 = null; HttpResponse httpResponse1 = null; HttpEntity httpEntity1 = null; HttpPost httpPost1 = null; HttpHost httpHost1 = null; DefaultHttpClient httpClient1 = null; File file1 = null; InputStream inputStream1 = null; OutputStream outputStream1 = null; BeanComparator beanComparator1 = null; List<Map<String, Object>> list1 = null, list2 = null; Map<String, Object> map1 = null; Object object1 = null; int toIndex = rows * page; int fromIndex = toIndex - rows; GridModel1 jsonObject1 = null; Gson gson = null; Long long1 = -1L; java.util.Date date1 = null; URIBuilder uriBuilder1 = null; Node node1 = null; Element element1 = null; NodeList nodeList1 = null; Document document1 = null; DocumentBuilder documentBuilder1 = null; DocumentBuilderFactory documentBuilderFactory1 = null; org.joda.time.DateTime dateTime1 = null, dateTime2 = null; try { if (StringUtils.isNotEmpty(sid) && StringUtils.isNotEmpty(uid) && StringUtils.isNotEmpty(pid)) { sid = new String(Base64.decodeBase64(sid.getBytes())); uid = new String(Base64.decodeBase64(uid.getBytes())); pid = new String(Base64.decodeBase64(pid.getBytes())); httpClient1 = new DefaultHttpClient(); url1 = new URL(sid); uriBuilder1 = new URIBuilder(sid); uriBuilder1.setParameter("j_username", uid); uriBuilder1.setParameter("j_password", pid); uriBuilder1.setPath(url1.getPath() + "/rest/resources" + urlString); uriBuilder1.setUserInfo(uid, pid); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); if (int1 == HttpStatus.SC_OK) { httpEntity1 = httpResponse1.getEntity(); inputStream1 = httpResponse1.getEntity().getContent(); if (inputStream1 != null) { documentBuilderFactory1 = DocumentBuilderFactory.newInstance(); documentBuilder1 = documentBuilderFactory1.newDocumentBuilder(); document1 = documentBuilder1.parse(inputStream1); document1.getDocumentElement().normalize(); nodeList1 = document1.getElementsByTagName("resourceDescriptor"); int1 = nodeList1.getLength(); list1 = new ArrayList<Map<String, Object>>(); for (int0 = 0; int0 < int1; int0++) { node1 = nodeList1.item(int0); if (node1.getNodeType() == Node.ELEMENT_NODE) { element1 = (Element) node1; map1 = new HashMap<String, Object>(); map1.put("wsType", element1.getAttribute("wsType")); map1.put("uriString", element1.getAttribute("uriString")); string1 = getTagValue("label", element1); map1.put("label1", StringUtils.defaultString(string1)); string1 = getTagValue("description", element1); map1.put("description", StringUtils.defaultString(string1)); string1 = getTagValue("creationDate", element1); long1 = (string1 == null) ? -1L : NumberUtils.toLong(StringUtils.trim(string1), -1L); if (long1 > 0) { if (StringUtils.isNotBlank(timeZone1)) { dateTime1 = new org.joda.time.DateTime(long1); dateTime2 = dateTime1.withZone(DateTimeZone.forID(timeZone1)); date1 = dateTime2.toLocalDateTime().toDate(); } else { date1 = new java.util.Date(long1); } } else { date1 = null; } map1.put("creationDate", date1); map1.put("type1", getText(element1.getAttribute("wsType"))); list1.add(map1); } } } EntityUtils.consume(httpEntity1); } } } catch (UnsupportedEncodingException | URISyntaxException | ParserConfigurationException | SAXException exception1) { exception1.printStackTrace(); return ERROR; } catch (org.apache.http.conn.HttpHostConnectException | java.net.NoRouteToHostException | java.net.MalformedURLException | java.net.UnknownHostException exception1) { exception1.printStackTrace(); return ERROR; } catch (IOException exception1) { httpGet1.abort(); exception1.printStackTrace(); return ERROR; } finally { if (httpClient1 != null) httpClient1.getConnectionManager().shutdown(); if (list1 != null) { records = list1.size(); if (list1.size() > 0) { if (StringUtils.isNotEmpty(sidx)) { if (StringUtils.equals(sord, "desc")) { beanComparator1 = new BeanComparator(sidx, new ReverseComparator(new ComparableComparator())); } else { beanComparator1 = new BeanComparator(sidx); } Collections.sort(list1, beanComparator1); } if (StringUtils.isNotBlank(searchField) && StringUtils.isNotEmpty(searchOper)) { Iterator iterator1 = list1.iterator(); while (iterator1.hasNext()) { map1 = (Map<String, Object>) iterator1.next(); for (Map.Entry<String, Object> entry1 : map1.entrySet()) { if (StringUtils.equals(entry1.getKey(), searchField)) { object1 = entry1.getValue(); if (searchFilter(searchField, searchOper, searchString, object1)) iterator1.remove(); break; } } } records = list1.size(); } if (toIndex > records) toIndex = records; if (fromIndex > toIndex) { fromIndex = toIndex - rows; if (fromIndex < 0) fromIndex = 0; } if (list1.size() > 0 && fromIndex >= 0 && toIndex <= list1.size() && fromIndex <= toIndex) list2 = list1.subList(fromIndex, toIndex); } total = (int) Math.ceil((double) records / (double) rows); if (page > total) page = total; jsonObject1 = new GridModel1(rows, page, sord, sidx, searchField, searchString, searchOper, total, records, id, list2); gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create(); jsonData = gson.toJson(jsonObject1); } IOUtils.closeQuietly(inputStream1); } return SUCCESS; }
From source file:net.emotivecloud.scheduler.drp4ost.OStackClient.java
public String getAllServers(HashMap options) { String apiAddress = ":8774/v2/" + OS_TENANT_ID + "/servers"; String servers = null;/* w ww . j a v a 2 s . co m*/ //Instantiate an HttpClient HttpClient client = new DefaultHttpClient(); try { // Add the options to the request URIBuilder builder = new URIBuilder(); Iterator it = options.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); builder.setParameter((String) pairs.getKey(), (String) pairs.getValue()); it.remove(); // avoids a ConcurrentModificationException } URI uri = builder.build(); //Instantiate a GET HTTP method HttpGet request = new HttpGet(this.drpHost + apiAddress + uri.toString()); request.setHeader("X-Auth-Token", this.token); //Execute the request, obtain a Response HttpResponse response = client.execute(request); //If the response is not OK, throw an exception if (response.getStatusLine().getStatusCode() != 200) { throw new DRPOSTException(response.getStatusLine().getReasonPhrase(), StatusCodes.BAD_REQUEST); } //Get the Response Content in a String String responseContent = IOUtils.toString(response.getEntity().getContent()); servers = responseContent; } catch (IOException ex) { throw new DRPOSTException("Exception getting all servers", StatusCodes.BAD_REQUEST); } catch (Exception e) { throw new DRPOSTException("Exception getting all servers", StatusCodes.BAD_REQUEST); } return servers; }
From source file:org.georchestra.security.Proxy.java
@RequestMapping(params = "login", method = { GET, POST }) public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, URISyntaxException { String uri = request.getRequestURI(); if (uri.startsWith("sec")) { uri = uri.substring(3);/*from www . j a v a2s.co m*/ } else if (uri.startsWith("/sec")) { uri = uri.substring(4); } URIBuilder uriBuilder = new URIBuilder(uri); Enumeration parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String paramName = (String) parameterNames.nextElement(); if (!"login".equals(paramName)) { String[] paramValues = request.getParameterValues(paramName); for (int i = 0; i < paramValues.length; i++) { uriBuilder.setParameter(paramName, paramValues[i]); } } } redirectStrategy.sendRedirect(request, response, uriBuilder.build().toString()); }
From source file:ch.iterate.openstack.swift.Client.java
/** * @param container The name of the container * @param name The name of the object * @param entity The name of the request entity (make sure to set the Content-Type * @param metadata The metadata for the object * @param md5sum The 32 character hex encoded MD5 sum of the data * @param objectSize The total size in bytes of the object to be stored * @param segmentSize Optional size in bytes of the object segments to be stored (forces large object support) default 4G * @param dynamicLargeObject Optional setting to use dynamic large objects, False/null will use static large objects if required * @param segmentContainer Optional name of container to store file segments, defaults to storing chunks in the same container as the file sill appear * @param segmentFolder Optional name of folder for storing file segments, defaults to ".chunks/" * @param leaveSegments Optional setting to leave segments of large objects in place when the manifest is overwrtten/changed * @return The ETAG if the save was successful, null otherwise * @throws GenericException There was a protocol level error talking to CloudFiles *///from w ww.j av a 2s. c o m public String storeObject(Region region, String container, String name, HttpEntity entity, Map<String, String> metadata, String md5sum, Long objectSize, Long segmentSize, Boolean dynamicLargeObject, String segmentContainer, String segmentFolder, Boolean leaveSegments) throws IOException, InterruptedException { /* * Default values for large object support. We also use the defaults combined with the inputs * to determine whether to store as a large object. */ /* * The maximum size of a single object (5GiB). */ long singleObjectSizeLimit = (long) (5 * Math.pow(1024, 3)); /* * The default minimum segment size (1MiB). */ long minSegmentSize = 1024L * 1024L; /* * Set the segment size. * * Defaults to 4GiB segments, and will not permit smaller than 1MiB segments. */ long actualSegmentSize = (segmentSize == null) ? (long) (4 * Math.pow(1024, 3)) : Math.max(segmentSize, minSegmentSize); /* * Determines if we will store using large objects - we may do this for 3 reasons: * * - A segmentSize has been specified and the object size is greater than the minimum segment size * - If an objectSize is provided and is larger than the single object size limit of 5GiB * - A segmentSize has been specified, but no objectSize given (we take this as a request for segmentation) * * The last case may fail if the user does not provide at least as much data as the minimum segment * size configured on the server, and will always produce a large object structure (even if only one * small segment is required). */ objectSize = (objectSize == null) ? -1 : objectSize; boolean useLargeObject = ((segmentSize != null) && (objectSize > actualSegmentSize)) || (objectSize > singleObjectSizeLimit) || ((segmentSize != null) && (objectSize == -1)); if (!useLargeObject) { return storeObject(region, container, name, entity, metadata, md5sum); } else { /* * We need to upload a large object as defined by the method * parameters. For now this is done sequentially, but a parallel * version using appropriate random access to the underlying data * may be desirable. * * We make the assumption that the given file size will not be * greater than int.MAX_VALUE * segmentSize * */ leaveSegments = (leaveSegments == null) ? Boolean.FALSE : leaveSegments; dynamicLargeObject = (dynamicLargeObject == null) ? Boolean.FALSE : dynamicLargeObject; segmentFolder = (segmentFolder == null) ? ".file-segments" : segmentFolder; segmentContainer = (segmentContainer == null) ? container : segmentContainer; Map<String, List<StorageObject>> oldSegmentsToRemove = null; /* * If we have chosen not to leave existing large object segments in place (default) * then we need to collect information about any existing file segments so that we can * deal with them after we complete the upload of the new manifest. * * We should only delete existing segments after a successful upload of a new manifest file * because this constitutes an object update and the older file should remain available * until the new file can be downloaded. */ if (!leaveSegments) { ObjectMetadata existingMetadata; String manifestDLO = null; Boolean manifestSLO = Boolean.FALSE; try { existingMetadata = getObjectMetaData(region, container, name); if (existingMetadata.getMetaData().containsKey(Constants.MANIFEST_HEADER)) { manifestDLO = existingMetadata.getMetaData().get(Constants.MANIFEST_HEADER); } else if (existingMetadata.getMetaData().containsKey(Constants.X_STATIC_LARGE_OBJECT)) { JSONParser parser = new JSONParser(); String manifestSLOValue = existingMetadata.getMetaData() .get(Constants.X_STATIC_LARGE_OBJECT); manifestSLO = (Boolean) parser.parse(manifestSLOValue); } } catch (NotFoundException e) { /* * Just means no object exists already, so continue */ } catch (ParseException e) { /* * X_STATIC_LARGE_OBJECT header existed but failed to parse. * If a static large object already exists this must be set to "true". * If we got here then the X_STATIC_LARGE_OBJECT header existed, but failed * to parse as a boolean, so fail upload as a precaution. */ return null; } if (manifestDLO != null) { /* * We have found an existing dynamic large object, so use the prefix to get a list of * existing objects. If we're putting up a new dlo, make sure the segment prefixes are * different, then we can delete anything that's not in the new list if necessary. */ String oldContainer = manifestDLO.substring(0, manifestDLO.indexOf('/', 1)); String oldPath = manifestDLO.substring(manifestDLO.indexOf('/', 1), manifestDLO.length()); oldSegmentsToRemove = new HashMap<String, List<StorageObject>>(); oldSegmentsToRemove.put(oldContainer, listObjects(region, oldContainer, oldPath)); } else if (manifestSLO) { /* * We have found an existing static large object, so grab the manifest data that * details the existing segments - delete any later that we don't need any more */ } } int segmentNumber = 1; long timeStamp = System.currentTimeMillis() / 1000L; String segmentBase = String.format("%s/%d/%d", segmentFolder, timeStamp, objectSize); /* * Create subInputStream from the OutputStream we will pass to the * HttpEntity for writing content. */ final PipedInputStream contentInStream = new PipedInputStream(64 * 1024); final PipedOutputStream contentOutStream = new PipedOutputStream(contentInStream); SubInputStream segmentStream = new SubInputStream(contentInStream, actualSegmentSize, false); /* * Fork the call to entity.writeTo() that allows us to grab any exceptions raised */ final HttpEntity e = entity; final Callable<Boolean> writer = new Callable<Boolean>() { public Boolean call() throws Exception { e.writeTo(contentOutStream); return Boolean.TRUE; } }; ExecutorService writeExecutor = Executors.newSingleThreadExecutor(); final Future<Boolean> future = writeExecutor.submit(writer); /* * Check the future for exceptions after we've finished uploading segments */ Map<String, List<StorageObject>> newSegmentsAdded = new HashMap<String, List<StorageObject>>(); List<StorageObject> newSegments = new LinkedList<StorageObject>(); JSONArray manifestSLO = new JSONArray(); boolean finished = false; /* * Upload each segment of the file by reading sections of the content input stream * until the entire underlying stream is complete */ while (!finished) { String segmentName = String.format("%s/%08d", segmentBase, segmentNumber); String etag; boolean error = false; try { etag = storeObject(region, segmentContainer, segmentStream, "application/octet-stream", segmentName, new HashMap<String, String>()); } catch (IOException ex) { // Finished storing the object System.out.println("Caught IO Exception: " + ex.getMessage()); ex.printStackTrace(); throw ex; } String segmentPath = segmentContainer + "/" + segmentName; long bytesUploaded = segmentStream.getBytesProduced(); /* * Create the appropriate manifest structure if we're making a static large * object. * * ETAG returned by the simple upload * total size of segment uploaded * path of segment */ if (!dynamicLargeObject) { JSONObject segmentJSON = new JSONObject(); segmentJSON.put("path", segmentPath); segmentJSON.put("etag", etag); segmentJSON.put("size_bytes", bytesUploaded); manifestSLO.add(segmentJSON); newSegments.add(new StorageObject(segmentName)); } segmentNumber++; if (!finished) { finished = segmentStream.endSourceReached(); } newSegmentsAdded.put(segmentContainer, newSegments); System.out.println("JSON: " + manifestSLO.toString()); if (error) return ""; segmentStream.readMoreBytes(actualSegmentSize); } /* * Attempts to retrieve the return value from the write operation * Any exceptions raised can then be handled appropriately */ try { future.get(); } catch (InterruptedException ex) { /* * The write was interrupted... delete the segments? */ } catch (ExecutionException ex) { /* * This should always be an IOException or a RuntimeException * because the call to entity.writeTo() only throws IOException */ Throwable t = ex.getCause(); if (t instanceof IOException) { throw (IOException) t; } else { throw (RuntimeException) t; } } /* * Create an appropriate manifest depending on our DLO/SLO choice */ String manifestEtag = null; if (dynamicLargeObject) { /* * Empty manifest with header detailing the shared prefix of object segments */ long manifestTimeStamp = System.currentTimeMillis() / 1000L; metadata.put("X-Object-Manifest", segmentBase); metadata.put("x-object-meta-mtime", String.format("%s", manifestTimeStamp)); manifestEtag = storeObject(region, container, new ByteArrayInputStream(new byte[0]), entity.getContentType().getValue(), name, metadata); } else { /* * Manifest containing json list specifying details of the object segments. */ URIBuilder urlBuild = new URIBuilder(region.getStorageUrl(container, name)); urlBuild.setParameter("multipart-manifest", "put"); URI url; try { url = urlBuild.build(); String manifestContent = manifestSLO.toString(); InputStreamEntity manifestEntity = new InputStreamEntity( new ByteArrayInputStream(manifestContent.getBytes()), -1); manifestEntity.setChunked(true); manifestEntity.setContentType(entity.getContentType()); HttpPut method = new HttpPut(url); method.setEntity(manifestEntity); method.setHeader("x-static-large-object", "true"); Response response = this.execute(method, new DefaultResponseHandler()); if (response.getStatusCode() == HttpStatus.SC_CREATED) { manifestEtag = response.getResponseHeader(HttpHeaders.ETAG).getValue(); } else { throw new GenericException(response); } } catch (URISyntaxException ex) { ex.printStackTrace(); } } /* * Delete stale segments of overwritten large object if requested. */ if (!leaveSegments) { /* * Before deleting old segments, remove any objects from the delete list * that are also part of a new static large object that were updated during the upload. */ if (!(oldSegmentsToRemove == null)) { for (String c : oldSegmentsToRemove.keySet()) { List<StorageObject> rmv = oldSegmentsToRemove.get(c); if (newSegmentsAdded.containsKey(c)) { rmv.removeAll(newSegmentsAdded.get(c)); } List<String> rmvNames = new LinkedList<String>(); for (StorageObject s : rmv) { rmvNames.add(s.getName()); } deleteObjects(region, c, rmvNames); } } } return manifestEtag; } }