List of usage examples for org.apache.http.client.utils URIBuilder setHost
public URIBuilder setHost(final String host)
From source file:com.envirover.spl.SPLGroungControlTest.java
@Test public void testMOMessagePipeline() throws URISyntaxException, ClientProtocolException, IOException, InterruptedException { System.out.println("MO TEST: Testing MO message pipeline..."); Thread.sleep(1000);/*from w ww . java 2 s.c o m*/ Thread mavlinkThread = new Thread(new Runnable() { public void run() { Socket client = null; try { System.out.printf("MO TEST: Connecting to tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort()); System.out.println(); client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort()); System.out.printf("MO TEST: Connected tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort()); System.out.println(); Parser parser = new Parser(); DataInputStream in = new DataInputStream(client.getInputStream()); while (true) { MAVLinkPacket packet; do { int c = in.readUnsignedByte(); packet = parser.mavlink_parse_char(c); } while (packet == null); System.out.printf("MO TEST: MAVLink message received: msgid = %d", packet.msgid); System.out.println(); Thread.sleep(100); } } catch (InterruptedException ex) { return; } catch (Exception ex) { ex.printStackTrace(); } finally { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } } }); mavlinkThread.start(); HttpClient httpclient = HttpClients.createDefault(); URIBuilder builder = new URIBuilder(); builder.setScheme("http"); builder.setHost(InetAddress.getLocalHost().getHostAddress()); builder.setPort(config.getRockblockPort()); builder.setPath(config.getHttpContext()); URI uri = builder.build(); HttpPost httppost = new HttpPost(uri); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(2); params.add(new BasicNameValuePair("imei", config.getRockBlockIMEI())); params.add(new BasicNameValuePair("momsn", "12345")); params.add(new BasicNameValuePair("transmit_time", "12-10-10 10:41:50")); params.add(new BasicNameValuePair("iridium_latitude", "52.3867")); params.add(new BasicNameValuePair("iridium_longitude", "0.2938")); params.add(new BasicNameValuePair("iridium_cep", "9")); params.add(new BasicNameValuePair("data", Hex.encodeHexString(getSamplePacket().encodePacket()))); httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); // Execute and get the response. System.out.printf("MO TEST: Sending test message to %s", uri.toString()); System.out.println(); HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != 200) { fail(String.format("RockBLOCK HTTP message handler status code = %d.", response.getStatusLine().getStatusCode())); } HttpEntity entity = response.getEntity(); if (entity != null) { InputStream responseStream = entity.getContent(); try { String responseString = IOUtils.toString(responseStream); System.out.println(responseString); } finally { responseStream.close(); } } Thread.sleep(1000); mavlinkThread.interrupt(); System.out.println("MO TEST: Complete."); }
From source file:com.liferay.ide.core.remote.RemoteConnection.java
protected Object httpJSONAPI(Object... args) throws APIException { if (!(args[0] instanceof HttpRequestBase)) { throw new IllegalArgumentException("First argument must be a HttpRequestBase."); //$NON-NLS-1$ }//from w ww .j ava 2s . c om Object retval = null; String api = null; Object[] params = new Object[0]; final HttpRequestBase request = (HttpRequestBase) args[0]; final boolean isPostRequest = request instanceof HttpPost; if (args[1] instanceof String) { api = args[1].toString(); } else if (args[1] instanceof Object[]) { params = (Object[]) args[1]; api = params[0].toString(); } else { throw new IllegalArgumentException("2nd argument must be either String or Object[]"); //$NON-NLS-1$ } try { final URIBuilder builder = new URIBuilder(); builder.setScheme("http"); //$NON-NLS-1$ builder.setHost(getHost()); builder.setPort(getHttpPort()); builder.setPath(api); List<NameValuePair> postParams = new ArrayList<NameValuePair>(); if (params.length >= 3) { for (int i = 1; i < params.length; i += 2) { String name = null; String value = StringPool.EMPTY; if (params[i] != null) { name = params[i].toString(); } if (params[i + 1] != null) { value = params[i + 1].toString(); } if (isPostRequest) { postParams.add(new BasicNameValuePair(name, value)); } else { builder.setParameter(name, value); } } } if (isPostRequest) { HttpPost postRequest = ((HttpPost) request); if (postRequest.getEntity() == null) { postRequest.setEntity(new UrlEncodedFormEntity(postParams)); } } request.setURI(builder.build()); String response = getHttpResponse(request); if (response != null && response.length() > 0) { Object jsonResponse = getJSONResponse(response); if (jsonResponse == null) { throw new APIException(api, "Unable to get response: " + response); //$NON-NLS-1$ } else { retval = jsonResponse; } } } catch (APIException e) { throw e; } catch (Exception e) { throw new APIException(api, e); } finally { try { request.releaseConnection(); } finally { // no need to log error } } return retval; }
From source file:name.richardson.james.maven.plugins.uploader.UploadMojo.java
public void execute() throws MojoExecutionException { this.getLog().info("Uploading project to BukkitDev"); final String gameVersion = this.getGameVersion(); final URIBuilder builder = new URIBuilder(); final MultipartEntity entity = new MultipartEntity(); HttpPost request;/*from w w w .j av a2 s . co m*/ // create the request builder.setScheme("http"); builder.setHost("dev.bukkit.org"); builder.setPath("/" + this.projectType + "/" + this.slug.toLowerCase() + "/upload-file.json"); try { entity.addPart("file_type", new StringBody(this.getFileType())); entity.addPart("name", new StringBody(this.project.getArtifact().getVersion())); entity.addPart("game_versions", new StringBody(gameVersion)); entity.addPart("change_log", new StringBody(this.changeLog)); entity.addPart("known_caveats", new StringBody(this.knownCaveats)); entity.addPart("change_markup_type", new StringBody(this.markupType)); entity.addPart("caveats_markup_type", new StringBody(this.markupType)); entity.addPart("file", new FileBody(this.getArtifactFile(this.project.getArtifact()))); } catch (final UnsupportedEncodingException e) { throw new MojoExecutionException(e.getMessage()); } // create the actual request try { request = new HttpPost(builder.build()); request.setHeader("User-Agent", "MavenCurseForgeUploader/1.0"); request.setHeader("X-API-Key", this.key); request.setEntity(entity); } catch (final URISyntaxException exception) { throw new MojoExecutionException(exception.getMessage()); } this.getLog().debug(request.toString()); // send the request and handle any replies try { final HttpClient client = new DefaultHttpClient(); final HttpResponse response = client.execute(request); switch (response.getStatusLine().getStatusCode()) { case 201: this.getLog().info("File uploaded successfully."); break; case 403: this.getLog().error( "You have not specifed your API key correctly or do not have permission to upload to that project."); break; case 404: this.getLog().error("Project was not found. Either it is specified wrong or been renamed."); break; case 422: this.getLog().error("There was an error in uploading the plugin"); this.getLog().debug(request.toString()); this.getLog().debug(EntityUtils.toString(response.getEntity())); break; default: this.getLog().warn("Unexpected response code: " + response.getStatusLine().getStatusCode()); break; } } catch (final ClientProtocolException exception) { throw new MojoExecutionException(exception.getMessage()); } catch (final IOException exception) { throw new MojoExecutionException(exception.getMessage()); } }
From source file:uk.ac.susx.tag.method51.webapp.handler.CodingInstanceHandler.java
/** * Re-issue the request to an instance.//from w ww . ja v a 2 s . c o m * * @param target * @param baseRequest * @param request * @param response * @throws IOException */ private void coding(final String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { new DoSomethingWithTheSpecifiedJobID(request, response) { public void something(String jid) throws IOException { Integer port = project.m51(jid).getPort(); //int port = ((Number)j.getMeta("port")).intValue(); HttpClient httpclient = new DefaultHttpClient(); String method = request.getMethod(); String target = "/coding" + request.getParameter("_target"); URIBuilder builder = new URIBuilder(); Set<String> ignore = new HashSet<>(); ignore.add("id"); ignore.add("_target"); builder.setHost("localhost").setScheme("http").setPort(port).setPath(target); try { HttpUriRequest uriRequest; if ("GET".equals(method)) { for (Map.Entry<String, String[]> e : request.getParameterMap().entrySet()) { String key = e.getKey(); if (!ignore.contains(key)) { builder.setParameter(e.getKey(), e.getValue()[0]); } } URI uri = builder.build(); uriRequest = new HttpGet(uri); } else { URI uri = builder.build(); List<NameValuePair> params = new ArrayList<>(); for (Map.Entry<String, String[]> e : request.getParameterMap().entrySet()) { String key = e.getKey(); if (!ignore.contains(key)) { params.add(new BasicNameValuePair(key, e.getValue()[0])); } } uriRequest = new HttpPost(uri); ((HttpPost) uriRequest).setEntity(new UrlEncodedFormEntity(params)); } LOG.info("re-issuing request: {}", uriRequest.toString()); HttpResponse r = httpclient.execute(uriRequest); StatusLine statusLine = r.getStatusLine(); HttpEntity entity = r.getEntity(); if (statusLine.getStatusCode() >= 400) { try { ContentType contentType = ContentType.get(entity); String responseBody = EntityUtils.toString(entity, contentType.getCharset()); throw new RequestException(statusLine.getReasonPhrase() + responseBody, statusLine.getStatusCode()); } catch (IOException | ParseException | NullPointerException e) { EntityUtils.consume(entity); throw new RequestException(statusLine.getReasonPhrase(), statusLine.getStatusCode()); } } response.setStatus(statusLine.getStatusCode()); ContentType contentType = ContentType.get(entity); if (contentType == null) { error("null content type!", response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else { String responseBody = EntityUtils.toString(entity, contentType.getCharset()); response.setContentType(contentType.toString()); response.setCharacterEncoding(contentType.getCharset().toString()); response.getWriter().print(responseBody); } } catch (URISyntaxException e) { error(e.getMessage(), response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }; }
From source file:org.apache.ambari.server.controller.metrics.ganglia.GangliaPropertyProvider.java
/** * Get the spec to locate the Ganglia stream from the given * request info.//from w w w .java 2 s . c o m * * @param clusterName the cluster name * @param clusterSet the set of ganglia cluster names * @param hostSet the set of host names * @param metricSet the set of metric names * @param temporalInfo the temporal information * * @return the spec, like http://example.com/path?param1=val1¶mn=valn * * @throws org.apache.ambari.server.controller.spi.SystemException if unable to get the Ganglia Collector host name */ private String getSpec(String clusterName, Set<String> clusterSet, Set<String> hostSet, Set<String> metricSet, TemporalInfo temporalInfo) throws SystemException { String clusters = getSetString(clusterSet, -1); String hosts = getSetString(hostSet, -1); String metrics = getSetString(metricSet, -1); URIBuilder uriBuilder = new URIBuilder(); if (configuration.isHttpsEnabled()) { uriBuilder.setScheme("https"); } else { uriBuilder.setScheme("http"); } uriBuilder.setHost(hostProvider.getCollectorHostName(clusterName, GANGLIA)); uriBuilder.setPath("/cgi-bin/rrd.py"); uriBuilder.setParameter("c", clusters); if (hosts.length() > 0) { uriBuilder.setParameter("h", hosts); } if (metrics.length() > 0) { uriBuilder.setParameter("m", metrics); } else { // get all metrics uriBuilder.setParameter("m", ".*"); } if (temporalInfo != null) { long startTime = temporalInfo.getStartTime(); if (startTime != -1) { uriBuilder.setParameter("s", String.valueOf(startTime)); } long endTime = temporalInfo.getEndTime(); if (endTime != -1) { uriBuilder.setParameter("e", String.valueOf(endTime)); } long step = temporalInfo.getStep(); if (step != -1) { uriBuilder.setParameter("r", String.valueOf(step)); } } else { uriBuilder.setParameter("e", "now"); uriBuilder.setParameter("pt", "true"); } return uriBuilder.toString(); }
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. ja v a 2 s. c o 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:org.apache.ambari.server.controller.ganglia.GangliaPropertyProvider.java
/** * Get the spec to locate the Ganglia stream from the given * request info./*from www . j av a 2 s . c om*/ * * @param clusterName the cluster name * @param clusterSet the set of ganglia cluster names * @param hostSet the set of host names * @param metricSet the set of metric names * @param temporalInfo the temporal information * * @return the spec, like http://example.com/path?param1=val1¶mn=valn * * @throws org.apache.ambari.server.controller.spi.SystemException if unable to get the Ganglia Collector host name */ private String getSpec(String clusterName, Set<String> clusterSet, Set<String> hostSet, Set<String> metricSet, TemporalInfo temporalInfo) throws SystemException { String clusters = getSetString(clusterSet, -1); String hosts = getSetString(hostSet, -1); String metrics = getSetString(metricSet, -1); URIBuilder uriBuilder = new URIBuilder(); if (configuration.isGangliaSSL()) { uriBuilder.setScheme("https"); } else { uriBuilder.setScheme("http"); } uriBuilder.setHost(hostProvider.getGangliaCollectorHostName(clusterName)); uriBuilder.setPath("/cgi-bin/rrd.py"); uriBuilder.setParameter("c", clusters); if (hosts.length() > 0) { uriBuilder.setParameter("h", hosts); } if (metrics.length() > 0) { uriBuilder.setParameter("m", metrics); } else { // get all metrics uriBuilder.setParameter("m", ".*"); } if (temporalInfo != null) { long startTime = temporalInfo.getStartTime(); if (startTime != -1) { uriBuilder.setParameter("s", String.valueOf(startTime)); } long endTime = temporalInfo.getEndTime(); if (endTime != -1) { uriBuilder.setParameter("e", String.valueOf(endTime)); } long step = temporalInfo.getStep(); if (step != -1) { uriBuilder.setParameter("r", String.valueOf(step)); } } else { uriBuilder.setParameter("e", "now"); uriBuilder.setParameter("pt", "true"); } return uriBuilder.toString(); }
From source file:org.testmp.datastore.client.DataStoreClient.java
@SuppressWarnings("unused") private URIBuilder getCustomURIBuilder() { URIBuilder builder = new URIBuilder(); builder.setScheme(dataStoreURL.getScheme()); builder.setHost(dataStoreURL.getHost()); builder.setPort(dataStoreURL.getPort()); builder.setPath(dataStoreURL.getPath()); return builder; }
From source file:org.apache.ambari.server.controller.ganglia.GangliaPropertyProviderTest.java
@Test public void testPopulateManyResources() throws Exception { TestStreamProvider streamProvider = new TestStreamProvider("temporal_ganglia_data_1.txt"); TestGangliaHostProvider hostProvider = new TestGangliaHostProvider(); GangliaPropertyProvider propertyProvider = new GangliaHostPropertyProvider( PropertyHelper.getGangliaPropertyIds(Resource.Type.Host), streamProvider, configuration, hostProvider, CLUSTER_NAME_PROPERTY_ID, HOST_NAME_PROPERTY_ID); Set<Resource> resources = new HashSet<Resource>(); // host//from w ww . j a va 2 s .c om Resource resource = new ResourceImpl(Resource.Type.Host); resource.setProperty(HOST_NAME_PROPERTY_ID, "domU-12-31-39-0E-34-E1.compute-1.internal"); resources.add(resource); resource = new ResourceImpl(Resource.Type.Host); resource.setProperty(HOST_NAME_PROPERTY_ID, "domU-12-31-39-0E-34-E2.compute-1.internal"); resources.add(resource); resource = new ResourceImpl(Resource.Type.Host); resource.setProperty(HOST_NAME_PROPERTY_ID, "domU-12-31-39-0E-34-E3.compute-1.internal"); resources.add(resource); // only ask for one property Map<String, TemporalInfo> temporalInfoMap = new HashMap<String, TemporalInfo>(); temporalInfoMap.put(PROPERTY_ID, new TemporalInfoImpl(10L, 20L, 1L)); Request request = PropertyHelper.getReadRequest(Collections.singleton(PROPERTY_ID), temporalInfoMap); Assert.assertEquals(3, propertyProvider.populateResources(resources, request, null).size()); URIBuilder uriBuilder = new URIBuilder(); uriBuilder.setScheme((configuration.isGangliaSSL() ? "https" : "http")); uriBuilder.setHost("domU-12-31-39-0E-34-E1.compute-1.internal"); uriBuilder.setPath("/cgi-bin/rrd.py"); uriBuilder.setParameter("c", "HDPJobTracker,HDPHBaseMaster,HDPKafka,HDPResourceManager,HDPFlumeServer,HDPSlaves,HDPHistoryServer,HDPJournalNode,HDPTaskTracker,HDPHBaseRegionServer,HDPNameNode"); uriBuilder.setParameter("h", "domU-12-31-39-0E-34-E3.compute-1.internal,domU-12-31-39-0E-34-E1.compute-1.internal,domU-12-31-39-0E-34-E2.compute-1.internal"); uriBuilder.setParameter("m", "jvm.metrics.gcCount"); uriBuilder.setParameter("s", "10"); uriBuilder.setParameter("e", "20"); uriBuilder.setParameter("r", "1"); String expected = uriBuilder.toString(); Assert.assertEquals(expected, streamProvider.getLastSpec()); for (Resource res : resources) { Assert.assertEquals(2, PropertyHelper.getProperties(res).size()); Assert.assertNotNull(res.getPropertyValue(PROPERTY_ID)); } }
From source file:org.apache.ambari.server.controller.ganglia.GangliaPropertyProviderTest.java
@Test public void testPopulateResources__LargeNumberOfHostResources() throws Exception { TestStreamProvider streamProvider = new TestStreamProvider("temporal_ganglia_data.txt"); TestGangliaHostProvider hostProvider = new TestGangliaHostProvider(); GangliaPropertyProvider propertyProvider = new GangliaHostPropertyProvider( PropertyHelper.getGangliaPropertyIds(Resource.Type.Host), streamProvider, configuration, hostProvider, CLUSTER_NAME_PROPERTY_ID, HOST_NAME_PROPERTY_ID); Set<Resource> resources = new HashSet<Resource>(); StringBuilder hostsList = new StringBuilder(); for (int i = 0; i < 150; ++i) { Resource resource = new ResourceImpl(Resource.Type.Host); resource.setProperty(HOST_NAME_PROPERTY_ID, "host" + i); resources.add(resource);//from w ww.jav a 2 s.co m if (hostsList.length() != 0) hostsList.append("," + "host" + i); else hostsList.append("host" + i); } // only ask for one property Map<String, TemporalInfo> temporalInfoMap = new HashMap<String, TemporalInfo>(); temporalInfoMap.put(PROPERTY_ID, new TemporalInfoImpl(10L, 20L, 1L)); Request request = PropertyHelper.getReadRequest(Collections.singleton(PROPERTY_ID), temporalInfoMap); Assert.assertEquals(150, propertyProvider.populateResources(resources, request, null).size()); URIBuilder expectedUri = new URIBuilder(); expectedUri.setScheme((configuration.isGangliaSSL() ? "https" : "http")); expectedUri.setHost("domU-12-31-39-0E-34-E1.compute-1.internal"); expectedUri.setPath("/cgi-bin/rrd.py"); expectedUri.setParameter("c", "HDPJobTracker,HDPHBaseMaster,HDPKafka,HDPResourceManager,HDPFlumeServer,HDPSlaves,HDPHistoryServer,HDPJournalNode,HDPTaskTracker,HDPHBaseRegionServer,HDPNameNode"); expectedUri.setParameter("h", hostsList.toString()); expectedUri.setParameter("m", "jvm.metrics.gcCount"); expectedUri.setParameter("s", "10"); expectedUri.setParameter("e", "20"); expectedUri.setParameter("r", "1"); URIBuilder actualUri = new URIBuilder(streamProvider.getLastSpec()); Assert.assertEquals(expectedUri.getScheme(), actualUri.getScheme()); Assert.assertEquals(expectedUri.getHost(), actualUri.getHost()); Assert.assertEquals(expectedUri.getPath(), actualUri.getPath()); Assert.assertTrue(isUrlParamsEquals(actualUri, expectedUri)); }