List of usage examples for java.net URI toString
public String toString()
From source file:com.eucalyptus.http.MappingHttpRequest.java
/** * Constructor for outbound requests. /*from ww w . j a v a 2s. co m*/ */ public MappingHttpRequest(final HttpVersion httpVersion, final HttpMethod method, final ServiceConfiguration serviceConfiguration, final Object source) { super(httpVersion); this.method = method; URI fullUri = ServiceUris.internal(serviceConfiguration); this.uri = fullUri.toString(); this.servicePath = fullUri.getPath(); this.query = null; this.parameters = null; this.rawParameters = null; this.nonQueryParameterKeys = null; this.formFields = null; this.message = source; if (source instanceof BaseMessage) this.setCorrelationId(((BaseMessage) source).getCorrelationId()); this.addHeader(HttpHeaders.Names.HOST, fullUri.getHost() + ":" + fullUri.getPort()); }
From source file:io.gravitee.gateway.http.core.invoker.DefaultHttpInvoker.java
@Override public ClientRequest invoke(ExecutionContext executionContext, Request serverRequest, Handler<ClientResponse> result) { // Get target if overridden by a policy String targetUri = (String) executionContext.getAttribute(ExecutionContext.ATTR_REQUEST_ENDPOINT); Endpoint<HttpClient> endpoint; // If not defined, use the one provided by the underlying load-balancer if (targetUri == null) { String endpointName = nextEndpoint(executionContext); endpoint = endpointManager.get(endpointName); targetUri = (endpoint != null) ? rewriteURI(serverRequest, endpoint.target()) : null; // Set the final target URI invoked executionContext.setAttribute(ExecutionContext.ATTR_REQUEST_ENDPOINT, targetUri); } else {/* w w w .j a v a 2s . co m*/ // Select a matching endpoint according to the URL // If none, select the first (non-backup) from the endpoint list. String finalTargetUri = targetUri; Optional<String> endpointName = endpointManager.targetByEndpoint().entrySet().stream() .filter(endpointEntry -> finalTargetUri.startsWith(endpointEntry.getValue())) .map(Map.Entry::getValue).findFirst(); endpoint = endpointManager.getOrDefault(endpointName.isPresent() ? endpointName.get() : null); } // No endpoint has been selected by load-balancer strategy nor overridden value if (targetUri == null) { ServiceUnavailableResponse clientResponse = new ServiceUnavailableResponse(); result.handle(clientResponse); clientResponse.endHandler().handle(null); return null; } // Remove duplicate slash targetUri = DUPLICATE_SLASH_REMOVER.matcher(targetUri).replaceAll("/"); URI requestUri = encodeQueryParameters(serverRequest, targetUri); String uri = requestUri.toString(); // Add the endpoint reference in metrics to know which endpoint has been invoked while serving the request serverRequest.metrics().setEndpoint(uri); final boolean enableHttpDump = api.getProxy().isDumpRequest(); final HttpMethod httpMethod = extractHttpMethod(executionContext, serverRequest); ClientRequest clientRequest = invoke0(endpoint.connector(), httpMethod, requestUri, serverRequest, executionContext, (enableHttpDump) ? loggableClientResponse(result, serverRequest) : result); if (enableHttpDump) { HttpDump.logger.info("{}/{} >> Rewriting: {} -> {}", serverRequest.id(), serverRequest.transactionId(), serverRequest.uri(), uri); HttpDump.logger.info("{}/{} >> {} {}", serverRequest.id(), serverRequest.transactionId(), httpMethod, uri); serverRequest.headers() .forEach((headerName, headerValues) -> HttpDump.logger.info("{}/{} >> {}: {}", serverRequest.id(), serverRequest.transactionId(), headerName, headerValues.stream().collect(Collectors.joining(",")))); clientRequest = new LoggableClientRequest(clientRequest, serverRequest); } return clientRequest; }
From source file:com.twinsoft.convertigo.beans.transactions.couchdb.CustomTransaction.java
@Override protected Object invoke() throws Exception { CouchClient provider = getCouchClient(); String evaluatedUrl = eUrl == null ? "" : eUrl.toString(); if (!evaluatedUrl.startsWith("/")) { evaluatedUrl = '/' + evaluatedUrl; }//w w w . j a v a 2 s.com String db = getConnector().getDatabaseName(); URI uri = new URI(provider.getDatabaseUrl(db) + evaluatedUrl); Engine.logBeans.debug("(CustomTransaction) CouchDb request uri: " + uri.toString()); String jsonString = null; Object jsond = toJson(eData); if (jsond != null) { JSONObject jsonData; if (jsond instanceof JSONObject) { // comes from a complex variable jsonData = (JSONObject) jsond; } else { jsonData = new JSONObject(); jsonData.put("data", jsond); } jsonString = jsonData.toString(); Engine.logBeans.debug("(CustomTransaction) CouchDb request data: " + jsonString); } HttpRequestBase request = getHttpVerb().newInstance(); if (request == null) { throw new EngineException("Unsupported HTTP method"); } request.setURI(uri); if (jsonString != null && request instanceof HttpEntityEnclosingRequest) { provider.setJsonEntity((HttpEntityEnclosingRequest) request, jsonString); } return provider.execute(request); }
From source file:com.amazon.s3.http.HttpRequestFactory.java
/** * Creates an HttpClient method object based on the specified request and * populates any parameters, headers, etc. from the original request. * //from w ww . java2s. co m * @param request * The request to convert to an HttpClient method object. * @param previousEntity * The optional, previous HTTP entity to reuse in the new * request. * @param context * The execution context of the HTTP method to be executed * * @return The converted HttpClient method object with any parameters, * headers, etc. from the original request set. */ HttpRequestBase createHttpRequest(Request<?> request, ClientConfiguration clientConfiguration, HttpEntity previousEntity, ExecutionContext context) { URI endpoint = request.getEndpoint(); String uri = endpoint.toString(); if (request.getResourcePath() != null && request.getResourcePath().length() > 0) { if (request.getResourcePath().startsWith("/")) { if (uri.endsWith("/")) { uri = uri.substring(0, uri.length() - 1); } } else if (!uri.endsWith("/")) { uri += "/"; } uri += request.getResourcePath(); } else if (!uri.endsWith("/")) { uri += "/"; } String encodedParams = HttpUtils.encodeParameters(request); /* * For all non-POST requests, and any POST requests that already have a * payload, we put the encoded params directly in the URI, otherwise, * we'll put them in the POST request's payload. */ boolean requestHasNoPayload = request.getContent() != null; boolean requestIsPost = request.getHttpMethod() == HttpMethodName.POST; boolean putParamsInUri = !requestIsPost || requestHasNoPayload; if (encodedParams != null && putParamsInUri) { uri += "?" + encodedParams; } HttpRequestBase httpRequest; if (request.getHttpMethod() == HttpMethodName.POST) { HttpPost postMethod = new HttpPost(uri); /* * If there isn't any payload content to include in this request, * then try to include the POST parameters in the query body, * otherwise, just use the query string. For all AWS Query services, * the best behavior is putting the params in the request body for * POST requests, but we can't do that for S3. */ if (request.getContent() == null && encodedParams != null) { postMethod.setEntity(newStringEntity(encodedParams)); } else { postMethod.setEntity(new RepeatableInputStreamRequestEntity(request)); } httpRequest = postMethod; } else if (request.getHttpMethod() == HttpMethodName.PUT) { HttpPut putMethod = new HttpPut(uri); httpRequest = putMethod; /* * Enable 100-continue support for PUT operations, since this is * where we're potentially uploading large amounts of data and want * to find out as early as possible if an operation will fail. We * don't want to do this for all operations since it will cause * extra latency in the network interaction. */ putMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); if (previousEntity != null) { putMethod.setEntity(previousEntity); } else if (request.getContent() != null) { HttpEntity entity = new RepeatableInputStreamRequestEntity(request); if (request.getHeaders().get("Content-Length") == null) { entity = newBufferedHttpEntity(entity); } putMethod.setEntity(entity); } } else if (request.getHttpMethod() == HttpMethodName.GET) { httpRequest = new HttpGet(uri); } else if (request.getHttpMethod() == HttpMethodName.DELETE) { httpRequest = new HttpDelete(uri); } else if (request.getHttpMethod() == HttpMethodName.HEAD) { httpRequest = new HttpHead(uri); } else { throw new AmazonClientException("Unknown HTTP method name: " + request.getHttpMethod()); } configureHeaders(httpRequest, request, context, clientConfiguration); return httpRequest; }
From source file:com.hortonworks.streamline.streams.metrics.storm.graphite.GraphiteWithStormQuerier.java
/** * {@inheritDoc}//w w w .j a v a2 s . co m */ @Override public Map<String, Map<Long, Double>> getRawMetrics(String metricName, String parameters, long from, long to) { Map<String, String> queryParams = parseParameters(parameters); URI targetUri = composeRawQueryParameters(metricName, queryParams, from, to); log.debug("Calling {} for querying metric", targetUri.toString()); List<Map<String, ?>> responseList = JsonClientUtil.getEntity(client.target(targetUri), List.class); if (responseList.size() > 0) { Map<String, Map<Long, Double>> ret = new HashMap<>(responseList.size()); for (Map<String, ?> metric : responseList) { String target = (String) metric.get("target"); List<List<Number>> dataPoints = (List<List<Number>>) metric.get("datapoints"); Map<Long, Double> pointsForOutput = formatDataPointsFromGraphiteToMap(dataPoints); ret.put(target, pointsForOutput); } return ret; } else { return Collections.emptyMap(); } }
From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.JobSubmitServlet.java
private Long submitJob(HttpServletRequest request, Principal principal) throws FileUploadException, IOException, ClientException, ParseException { DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); /*//from w w w .jav a2 s .com *Set the size threshold, above which content will be stored on disk. */ fileItemFactory.setSizeThreshold(5 * 1024 * 1024); //5 MB /* * Set the temporary directory to store the uploaded files of size above threshold. */ fileItemFactory.setRepository(this.tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); /* * Parse the request */ List items = uploadHandler.parseRequest(request); Properties fields = new Properties(); for (Iterator itr = items.iterator(); itr.hasNext();) { FileItem item = (FileItem) itr.next(); /* * Handle Form Fields. */ if (item.isFormField()) { fields.setProperty(item.getFieldName(), item.getString()); } } JobSpec jobSpec = MAPPER.readValue(fields.getProperty("jobSpec"), JobSpec.class); for (Iterator itr = items.iterator(); itr.hasNext();) { FileItem item = (FileItem) itr.next(); if (!item.isFormField()) { //Handle Uploaded files. log("Spreadsheet upload for user " + principal.getName() + ": Field Name = " + item.getFieldName() + ", File Name = " + item.getName() + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize()); if (item.getSize() > 0) { InputStream is = item.getInputStream(); try { this.servicesClient.upload(FilenameUtils.getName(item.getName()), jobSpec.getSourceConfigId(), item.getFieldName(), is); log("File '" + item.getName() + "' uploaded successfully"); } finally { if (is != null) { try { is.close(); } catch (IOException ignore) { } } } } else { log("File '" + item.getName() + "' ignored because it was zero length"); } } } URI uri = this.servicesClient.submitJob(jobSpec); String uriStr = uri.toString(); Long jobId = Long.valueOf(uriStr.substring(uriStr.lastIndexOf("/") + 1)); log("Job " + jobId + " submitted for user " + principal.getName()); return jobId; }
From source file:com.github.sardine.AuthenticationTest.java
@Test public void testBasicPreemptiveAuthHeader() throws Exception { final HttpClientBuilder client = HttpClientBuilder.create(); client.addInterceptorFirst(new HttpRequestInterceptor() { public void process(final HttpRequest r, final HttpContext context) throws HttpException, IOException { assertNotNull(r.getHeaders(HttpHeaders.AUTHORIZATION)); assertEquals(1, r.getHeaders(HttpHeaders.AUTHORIZATION).length); }//from ww w.jav a 2 s . c o m }); Sardine sardine = new SardineImpl(client); sardine.setCredentials("anonymous", null); // mod_dav supports Range headers for PUT final URI url = URI.create("http://sardine.googlecode.com/svn/trunk/README.html"); sardine.enablePreemptiveAuthentication(url.getHost()); assertTrue(sardine.exists(url.toString())); }
From source file:org.cloudfoundry.maven.Info.java
/** * @FIXME Not sure whether one should be able to overwrite execute() * *///from w w w . jav a2 s. co m @Override public void execute() throws MojoExecutionException, MojoFailureException { if (this.getPassword() == null && this.getUsername() == null) { final URI target = this.getTarget(); Assert.configurationNotNull(target, "target", SystemProperties.TARGET); try { client = new CloudFoundryClient(target.toString()); } catch (MalformedURLException e) { throw new MojoExecutionException(String.format( "Incorrect Cloud Foundry target url, are you sure '%s' is correct? Make sure the url contains a scheme, e.g. http://... ", target), e); } try { super.getLog() .warn("You did not provide a username and password. " + "Showing basic information only."); doExecute(); client.logout(); } catch (RuntimeException e) { throw new MojoExecutionException("An exception was caught while executing Mojo.", e); } } else { super.execute(); } }
From source file:com.mgmtp.jfunk.data.generator.Generator.java
public void parseXml(final IndexedFields theIndexedFields) throws IOException, JDOMException { this.indexedFields = theIndexedFields; final String generatorFile = configuration.get(GeneratorConstants.GENERATOR_CONFIG_FILE); if (StringUtils.isBlank(generatorFile)) { LOGGER.info("No generator configuration file found"); return;/* www.ja v a 2 s . c o m*/ } SAXBuilder builder = new SAXBuilder(); builder.setValidation(true); builder.setIgnoringElementContentWhitespace(false); builder.setFeature("http://apache.org/xml/features/validation/schema/normalized-value", false); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(final String publicId, final String systemId) throws IOException { String resolvedSystemId = configuration.processPropertyValue(systemId); URI uri = URI.create(resolvedSystemId); File file = uri.isAbsolute() ? toFile(uri.toURL()) : new File(uri.toString()); return new InputSource(ResourceLoader.getBufferedReader(file, Charsets.UTF_8.name())); } }); InputStream in = ResourceLoader.getConfigInputStream(generatorFile); Document doc = null; try { String systemId = ResourceLoader.getConfigDir() + '/' + removeExtension(generatorFile) + ".dtd"; doc = builder.build(in, systemId); Element root = doc.getRootElement(); Element charsetsElement = root.getChild(XMLTags.CHARSETS); @SuppressWarnings("unchecked") List<Element> charsetElements = charsetsElement.getChildren(XMLTags.CHARSET); for (Element element : charsetElements) { CharacterSet.initCharacterSet(element); } @SuppressWarnings("unchecked") List<Element> constraintElements = root.getChild(XMLTags.CONSTRAINTS).getChildren(XMLTags.CONSTRAINT); constraints = Lists.newArrayListWithExpectedSize(constraintElements.size()); for (Element element : constraintElements) { constraints.add(constraintFactory.createModel(random, element)); } } finally { closeQuietly(in); } LOGGER.info("Generator was successfully initialized"); }