List of usage examples for org.apache.http.client.fluent Request Get
public static Request Get(final String uri)
From source file:org.mule.module.http.functional.listener.HttpListenerWorkerThreadingProfileTestCase.java
private void assertMaxThreadsActive(String flowName, String url, int maxThreadsActive) throws Exception { maxActiveNumberOfRequestExecutedLatch = new CountDownLatch(maxThreadsActive); sendRequestUntilNoMoreWorkers(flowName, url, maxThreadsActive); // Due to differences in buffer sizes, the exception that is caused client side may be one of two different // exceptions. expectedException//from w w w . j a v a 2s .co m .expect(anyOf(instanceOf(NoHttpResponseException.class), instanceOf(SocketException.class))); try { httpClientExecutor.execute(Request.Get(url)); } finally { waitingLatch.release(); } }
From source file:org.obm.servlet.filter.resource.ResourcesFilterTest.java
@Test public void test() throws ClientProtocolException, IOException { Request.Get("http://localhost:" + server.getPort() + "/test").execute(); Request.Get("http://localhost:" + server.getPort() + "/test").execute(); assertThat(IntResource.resources).hasSize(2); assertThat(IntResource.resources.get(0).closed).isTrue(); assertThat(IntResource.resources.get(1).closed).isTrue(); }
From source file:com.qwazr.cluster.client.ClusterSingleClient.java
@Override public String[] getActiveNodesByService(String service_name, String group) { UBuilder uriBuilder = new UBuilder("/cluster/services/", service_name, "/active").setParameter("group", group);//from w w w . j ava2 s.co m Request request = Request.Get(uriBuilder.build()); return commonServiceRequest(request, null, null, String[].class, 200); }
From source file:org.mule.module.http.functional.listener.HttpListenerLifecycleTestCase.java
private void callAndAssertResponseFromUnaffectedListener() throws IOException { final Response response = Request.Get(getUnchangedConfigUrl()).execute(); final HttpResponse httpResponse = response.returnResponse(); assertThat(httpResponse.getStatusLine().getStatusCode(), is(200)); assertThat(IOUtils.toString(httpResponse.getEntity().getContent()), is("works")); }
From source file:com.jkoolcloud.tnt4j.streams.inputs.HttpStreamTest.java
@Test public void httpFormPostTest() throws Exception { FileReader fileReader = new FileReader(new File(samplesDir, "/http-form/form-data.json")); Map<String, ?> jsonMap = Utils.fromJsonToMap(fileReader, false); Utils.close(fileReader);/*from w w w . j a va 2s. co m*/ assertNotNull("Could not load form data from JSON", jsonMap); assertFalse("Loaded form data is empty", jsonMap.isEmpty()); Form form = Form.form(); for (Map.Entry<String, ?> e : jsonMap.entrySet()) { form.add(e.getKey(), String.valueOf(e.getValue())); } try { Thread.sleep(100); Request.Get(makeURI()).execute().returnContent(); } catch (HttpResponseException ex) { } HttpResponse resp = Request.Post(makeURI()).version(HttpVersion.HTTP_1_1).bodyForm(form.build()).execute() .returnResponse(); assertEquals(200, resp.getStatusLine().getStatusCode()); }
From source file:de.elomagic.carafile.client.CaraFileClient.java
/** * Tries to find a file in the registry with the given file identifier. * * @param fileId Identifier of the file/*from w w w. jav a2 s .com*/ * @return Returns the {@link MetaData} of the file or null when not found. * @throws IOException Thrown when unable to call REST service */ public MetaData findFile(final String fileId) throws IOException { if (registryURI == null) { throw new IllegalArgumentException("Parameter 'registryURI' must not be null!"); } if (fileId == null) { throw new IllegalArgumentException("Parameter 'fileId' must not be null!"); } URI uri = CaraFileUtils.buildURI(registryURI, "registry", "findFile", fileId); HttpResponse response = executeRequest(Request.Get(uri)).returnResponse(); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return getMetaDataFromResponse(response); } return null; }
From source file:org.mule.module.http.functional.listener.HttpListenerPersistentConnectionsTestCase.java
private HttpResponse doPerformRequest(int port, HttpVersion httpVersion, boolean keepAlive) throws IOException, ClientProtocolException { String url = String.format("http://localhost:%s/", port); Request request = Request.Get(url).version(httpVersion).connectTimeout(GET_TIMEOUT); if (keepAlive) { request = request.addHeader(CONNECTION, KEEP_ALIVE); }// ww w.j av a2 s . c o m HttpResponse response = request.execute().returnResponse(); assertThat(response.getStatusLine().getStatusCode(), is(HTTP_OK)); return response; }
From source file:eu.esdihumboldt.hale.io.geoserver.rest.AbstractResourceManager.java
/** * @see eu.esdihumboldt.hale.io.geoserver.rest.ResourceManager#list() *///from w ww .ja v a 2 s . c om @Override public Document list() { try { return executor.execute(Request.Get(getResourceListURL())).handleResponse(new XmlResponseHandler()); } catch (Exception e) { throw new ResourceException(e); } }
From source file:photosharing.api.conx.ProfileDefinition.java
/** * retrieves a profile based on the person's userid * /*w ww .ja v a 2s.c o m*/ * @see photosharing.api.base.APIDefinition#run(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void run(HttpServletRequest request, HttpServletResponse response) { /** * check if query is empty, send SC_PRECONDITION_FAILED - 412 */ String query = request.getParameter("uid"); if (query == null || query.isEmpty()) { response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); } /** * get the users bearer token */ HttpSession session = request.getSession(false); Object oData = session.getAttribute(OAuth20Handler.CREDENTIALS); if (oData == null) { logger.warning("OAuth20Data is null"); } OAuth20Data data = (OAuth20Data) oData; String bearer = data.getAccessToken(); try { /** * Example URL: * http://localhost:9080/photoSharing/api/profile?uid=self maps to * https://apps.collabservnext.com/profiles/atom/profileService.do * * and results in an id for the self user, this data is ideally cached on the client. */ if (query.compareTo("self") == 0) { String apiUrl = getApiUrlForServiceDoc(); Request get = Request.Get(apiUrl); get.addHeader("Authorization", "Bearer " + bearer); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired - 403 if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized // SC_UNAUTHORIZED (401) else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Content is returned // OK (200) else if (code == HttpStatus.SC_OK) { InputStream in = hr.getEntity().getContent(); // Converts the XML to JSON // Alternatively, one can parse the XML using XPATH String jsonString = org.apache.wink.json4j.utils.XML.toJson(in); logger.info("json string is " + jsonString); JSONObject jsonObj = new JSONObject(jsonString); JSONObject workspace = jsonObj.getJSONObject("service").getJSONObject("workspace") .getJSONObject("collection"); String id = workspace.getString("userid"); query = id; } else { JSONObject obj = new JSONObject(); obj.put("error", "unexpected content"); } } /** * The query should be cleansed before passing it to the backend * cleansing can incorporate checking that the id is a number * * example URL * http://localhost:9080/photoSharing/api/profile?uid=20131674 maps * to https * ://apps.collabservnext.com/profiles/atom/profile.do?userid * =20131674 * * example response {"img": * "https:\/\/apps.collabservnext.com\/profiles\/photo.do?key=fef1b5f3-586f-4470-ab0a-a9d4251fe1ec&lastMod=1443607729019","name":"P * a u l Demo","email":"demo@us.ibm.com"} * */ String apiUrl = getApiUrl(query); Request get = Request.Get(apiUrl); get.addHeader("Authorization", "Bearer " + bearer); Executor exec = ExecutorUtil.getExecutor(); Response apiResponse = exec.execute(get); HttpResponse hr = apiResponse.returnResponse(); /** * Check the status codes */ int code = hr.getStatusLine().getStatusCode(); // Session is no longer valid or access token is expired // SC_FORBIDDEN (403) if (code == HttpStatus.SC_FORBIDDEN) { response.sendRedirect("./api/logout"); } // User is not authorized // SC_UNAUTHORIZED (401) else if (code == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); } // Content is returned OK (200) else if (code == HttpStatus.SC_OK) { InputStream in = hr.getEntity().getContent(); // Converts the XML to JSON // Alternatively, one can parse the XML using XPATH String jsonString = org.apache.wink.json4j.utils.XML.toJson(in); logger.info("json string is " + jsonString); JSONObject jsonObj = new JSONObject(jsonString); JSONObject entry = jsonObj.getJSONObject("feed").getJSONObject("entry"); logger.info("entry" + entry); // Check if the Entry exists for the given id if (entry != null) { // Start Building the Response String name = ""; String image = ""; String email = ""; JSONObject contributor = entry.getJSONObject("contributor"); name = contributor.getString("name"); email = contributor.getString("email"); JSONArray links = entry.getJSONArray("link"); // Scans through the links and finds the profile image // XPath is much more efficient boolean found = false; int idx = 0; int len = links.length(); while (!found && idx < len) { JSONObject link = links.getJSONObject(idx); String type = link.getString("type"); if (type != null && !type.isEmpty() && type.compareTo("image") == 0) { found = true; image = link.getString("href"); } idx++; } // Build the json to send back JSONObject profile = new JSONObject(); profile.put("name", name); profile.put("email", email); profile.put("img", image); profile.put("userid", query); // Write output streams ServletOutputStream out = response.getOutputStream(); profile.write(out); } else { // There is no Entry for the user with the id. response.setStatus(HttpStatus.SC_NOT_FOUND); PrintWriter out = response.getWriter(); out.println("User does not exist"); } } // Unexpected status else { JSONObject obj = new JSONObject(); obj.put("error", "unexpected content"); //Should serialize result response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (IOException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("IOException " + e.toString()); } catch (JSONException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("JSONException " + e.toString()); } catch (SAXException e) { response.setHeader("X-Application-Error", e.getClass().getName()); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); logger.severe("SAXException " + e.toString()); } }
From source file:com.github.piotrkot.resources.CompilerResource.java
/** * Showing server results.//from ww w. j a v a 2s . c o m * @param user Logged in user. * @param request User request/session. * @return Server compiler results. */ @Path("/result/{request}") @GET @Timed @Produces(MediaType.TEXT_HTML) public ResultView showResults(@Auth final User user, @PathParam("request") final String request) { String results = "Cannot fetch server logs"; try { results = Request.Get(String.format("%s/logs/%s", this.conf.getCompiler(), request)) .setHeader(this.authorization(user)).execute().returnContent().asString(); } catch (final IOException ex) { log.error("Cannot call GET on server", ex); } return new ResultView(user, results); }