List of usage examples for org.apache.http.client.methods HttpUriRequest getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:tech.sirwellington.alchemy.http.VerbAssertions.java
private static void assertRequestWith(HttpVerb verb, Class<? extends HttpUriRequest> type) throws Exception { HttpClient mockClient = mock(HttpClient.class); when(mockClient.execute(any(HttpUriRequest.class))).thenReturn(createFakeApacheResponse()); URI uri = createFakeUri();/*from ww w . j a va2s . co m*/ HttpRequest request = HttpRequest.Builder.newInstance().usingUrl(uri.toURL()).build(); verb.execute(mockClient, request); ArgumentCaptor<HttpUriRequest> captor = forClass(HttpUriRequest.class); verify(mockClient).execute(captor.capture()); HttpUriRequest requestMade = captor.getValue(); assertThat(requestMade, notNullValue()); assertThat(requestMade.getURI(), is(uri)); assertThat(requestMade.getClass(), sameInstance(type)); }
From source file:org.fcrepo.apix.jena.impl.LdpContainerRegistryTest.java
@SuppressWarnings("unchecked") @Test// w w w. ja v a 2 s.c o m public void createWithInitialContentTest() throws Exception { final URI containerURI = URI.create("test:Container"); toTest.setContainer(containerURI); when(entityStatus.getStatusCode()).thenReturn(HttpStatus.SC_CREATED); when(header.getValue()).thenReturn(containerURI.toString()); when(entityResponse.getFirstHeader(HttpHeaders.LOCATION)).thenReturn(header); when(headStatus.getStatusCode()).thenReturn(HttpStatus.SC_NOT_FOUND); toTest.setCreateContainer(true); toTest.setHttpClient(client); toTest.setContainerContent(URI.create("classpath:/objects/service-registry.ttl")); toTest.init(); verify(client, times(1)).execute(requestCaptor.capture(), isA(ResponseHandler.class)); final HttpUriRequest request = requestCaptor.getValue(); assertEquals(HttpPut.class, request.getClass()); assertEquals(containerURI, request.getURI()); final byte[] content = IOUtils.toByteArray(((HttpPut) request).getEntity().getContent()); assertTrue(content.length > 0); }
From source file:org.myrobotlab.service.HttpClient.java
public HttpData processResponse(HttpUriRequest request, HashMap<String, String> fields) throws IOException { HttpData data = new HttpData(request.getURI().toString()); if (fields == null) { fields = formFields;/*from w w w. j a v a2 s . co m*/ } if (request.getClass().equals(HttpPost.class) && formFields.size() > 0) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(fields.size()); for (String nvPairKey : fields.keySet()) { nameValuePairs.add(new BasicNameValuePair(nvPairKey, fields.get(nvPairKey))); ((HttpPost) request).setEntity(new UrlEncodedFormEntity(nameValuePairs)); } } HttpResponse response = client.execute(request); StatusLine statusLine = response.getStatusLine(); data.responseCode = statusLine.getStatusCode(); HttpEntity entity = response.getEntity(); Header header = entity.getContentType(); if (header != null) { data.contentType = header.getValue().toString(); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); response.getEntity().writeTo(baos); data.data = baos.toByteArray(); // publishing invoke("publishHttpData", data); if (data.data != null) { invoke("publishHttpResponse", new String(data.data)); } return data; }
From source file:com.socialize.test.unit.SocializeRequestFactoryTest.java
@SuppressWarnings("unchecked") @UsesMocks({ SocializeObjectFactory.class, JSONObject.class, SocializeSession.class }) public void testPutRequestCreate() throws Exception { SocializeObjectFactory<SocializeObject> factory = AndroidMock.createMock(SocializeObjectFactory.class); SocializeSession session = AndroidMock.createMock(SocializeSession.class); SocializeObject object = new SocializeObject(); final String jsonData = "foobar"; final String endpoint = "foobar/"; /**/* w w w .j a v a2 s . c om*/ * The toString() method can't be mocked by EasyMock (no idea why!) so * we can't use a mock for the JSON object. We'll have to do it * manually. */ JSONObject json = new JSONObject() { @Override public String toString() { return jsonData; } }; AndroidMock.expect(factory.toJSON(object)).andReturn(json); OAuthRequestSigner signer = new OAuthRequestSigner() { @Override public <R extends HttpUriRequest> R sign(SocializeSession session, R request, OAuthSignListener listener) throws SocializeException { HttpPut.class.isInstance(request); assertEquals(request.getURI().toString(), endpoint); addResult(true); return request; } @Override public <R extends HttpUriRequest> R sign(SocializeSession session, R request) throws SocializeException { return sign(session, request, null); } @Override public <R extends HttpUriRequest> R sign(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret, R request, OAuthSignListener listener) throws SocializeException { return null; } }; SocializeRequestFactory<SocializeObject> reqFactory = new DefaultSocializeRequestFactory<SocializeObject>( signer, factory); AndroidMock.replay(factory); HttpUriRequest req = reqFactory.getPutRequest(session, endpoint, object); assertTrue((Boolean) getNextResult()); assertTrue(HttpPut.class.isInstance(req)); assertTrue(HttpEntityEnclosingRequestBase.class.isAssignableFrom(req.getClass())); HttpEntityEnclosingRequestBase post = (HttpEntityEnclosingRequestBase) req; HttpEntity entity = post.getEntity(); assertNotNull(entity); assertTrue(entity instanceof UrlEncodedFormEntity); List<NameValuePair> parsed = URLEncodedUtils.parse(entity); assertEquals(1, parsed.size()); NameValuePair nvp = parsed.get(0); assertEquals("payload", nvp.getName()); assertEquals(jsonData, nvp.getValue()); AndroidMock.verify(factory); }
From source file:com.socialize.test.unit.SocializeRequestFactoryTest.java
@SuppressWarnings("unchecked") @UsesMocks({ SocializeObjectFactory.class, JSONObject.class, SocializeSession.class }) public void testPostRequestCreate() throws Exception { SocializeObjectFactory<SocializeObject> factory = AndroidMock.createMock(SocializeObjectFactory.class); SocializeSession session = AndroidMock.createMock(SocializeSession.class); SocializeObject object = new SocializeObject(); final String jsonData = "{ 'entity': 'http://www.example.com/interesting-story/', 'text': 'this was a great story' }"; final String endpoint = "foobar/"; /**/*from w w w.j a va 2 s . c om*/ * The toString() method can't be mocked by EasyMock (no idea why!) so * we can't use a mock for the JSON object. We'll have to do it * manually. */ JSONObject json = new JSONObject() { @Override public String toString() { return jsonData; } }; AndroidMock.expect(factory.toJSON(object)).andReturn(json); OAuthRequestSigner signer = new OAuthRequestSigner() { @Override public <R extends HttpUriRequest> R sign(SocializeSession session, R request, OAuthSignListener listener) throws SocializeException { HttpPost.class.isInstance(request); assertEquals(request.getURI().toString(), endpoint); addResult(true); return request; } @Override public <R extends HttpUriRequest> R sign(SocializeSession session, R request) throws SocializeException { return sign(session, request, null); } @Override public <R extends HttpUriRequest> R sign(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret, R request, OAuthSignListener listener) throws SocializeException { return null; } }; SocializeRequestFactory<SocializeObject> reqFactory = new DefaultSocializeRequestFactory<SocializeObject>( signer, factory); AndroidMock.replay(factory); HttpUriRequest req = reqFactory.getPostRequest(session, endpoint, object); assertTrue((Boolean) getNextResult()); assertTrue(HttpPost.class.isInstance(req)); assertTrue(HttpEntityEnclosingRequestBase.class.isAssignableFrom(req.getClass())); HttpEntityEnclosingRequestBase post = (HttpEntityEnclosingRequestBase) req; HttpEntity entity = post.getEntity(); assertNotNull(entity); assertTrue(entity instanceof UrlEncodedFormEntity); List<NameValuePair> parsed = URLEncodedUtils.parse(entity); assertEquals(1, parsed.size()); NameValuePair nvp = parsed.get(0); assertEquals("payload", nvp.getName()); assertEquals(jsonData, nvp.getValue()); AndroidMock.verify(factory); }
From source file:com.socialize.test.unit.SocializeRequestFactoryTest.java
@SuppressWarnings("unchecked") @UsesMocks({ SocializeObjectFactory.class, SocializeSession.class }) public void testPutRequestCreateCollection() throws Exception { SocializeObjectFactory<SocializeObject> factory = AndroidMock.createMock(SocializeObjectFactory.class); SocializeSession session = AndroidMock.createMock(SocializeSession.class); SocializeObject object0 = new SocializeObject(); SocializeObject object1 = new SocializeObject(); final String jsonData = "foo"; final String endpoint = "foobar/"; /**// w ww . j a v a 2s . c o m * The toString() method can't be mocked by EasyMock (no idea why!) so * we can't use a mock for the JSON object. We'll have to do it * manually. */ JSONArray jsonArray = new JSONArray() { @Override public String toString() { return jsonData; } }; Collection<SocializeObject> objects = new ArrayList<SocializeObject>(1); objects.add(object0); objects.add(object1); AndroidMock.expect(factory.toJSON(objects)).andReturn(jsonArray); AndroidMock.replay(factory); OAuthRequestSigner signer = new OAuthRequestSigner() { @Override public <R extends HttpUriRequest> R sign(SocializeSession session, R request, OAuthSignListener listener) throws SocializeException { HttpPut.class.isInstance(request); assertEquals(request.getURI().toString(), endpoint); addResult(true); return request; } @Override public <R extends HttpUriRequest> R sign(SocializeSession session, R request) throws SocializeException { return sign(session, request, null); } @Override public <R extends HttpUriRequest> R sign(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret, R request, OAuthSignListener listener) throws SocializeException { return null; } }; SocializeRequestFactory<SocializeObject> reqFactory = new DefaultSocializeRequestFactory<SocializeObject>( signer, factory); HttpUriRequest req = reqFactory.getPutRequest(session, endpoint, objects); assertTrue((Boolean) getNextResult()); assertTrue(HttpPut.class.isInstance(req)); assertTrue(HttpEntityEnclosingRequestBase.class.isAssignableFrom(req.getClass())); HttpEntityEnclosingRequestBase post = (HttpEntityEnclosingRequestBase) req; HttpEntity entity = post.getEntity(); assertNotNull(entity); assertTrue(entity instanceof UrlEncodedFormEntity); List<NameValuePair> parsed = URLEncodedUtils.parse(entity); assertEquals(1, parsed.size()); NameValuePair nvp = parsed.get(0); assertEquals("payload", nvp.getName()); assertEquals(jsonData, nvp.getValue()); AndroidMock.verify(factory); }
From source file:com.socialize.test.unit.SocializeRequestFactoryTest.java
@SuppressWarnings("unchecked") @UsesMocks({ SocializeObjectFactory.class, SocializeSession.class }) public void testPostRequestCreateCollection() throws Exception { SocializeObjectFactory<SocializeObject> factory = AndroidMock.createMock(SocializeObjectFactory.class); SocializeSession session = AndroidMock.createMock(SocializeSession.class); SocializeObject object0 = new SocializeObject(); SocializeObject object1 = new SocializeObject(); final String jsonData = "foo"; final String endpoint = "foobar/"; /**//from ww w . ja v a 2 s .co m * The toString() method can't be mocked by EasyMock (no idea why!) so * we can't use a mock for the JSON object. We'll have to do it * manually. */ JSONArray jsonArray = new JSONArray() { @Override public String toString() { return jsonData; } }; Collection<SocializeObject> objects = new ArrayList<SocializeObject>(1); objects.add(object0); objects.add(object1); AndroidMock.expect(factory.toJSON(objects)).andReturn(jsonArray); AndroidMock.replay(factory); OAuthRequestSigner signer = new OAuthRequestSigner() { @Override public <R extends HttpUriRequest> R sign(SocializeSession session, R request, OAuthSignListener listener) throws SocializeException { HttpPost.class.isInstance(request); assertEquals(request.getURI().toString(), endpoint); addResult(true); return request; } @Override public <R extends HttpUriRequest> R sign(SocializeSession session, R request) throws SocializeException { return sign(session, request, null); } @Override public <R extends HttpUriRequest> R sign(String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret, R request, OAuthSignListener listener) throws SocializeException { return null; } }; SocializeRequestFactory<SocializeObject> reqFactory = new DefaultSocializeRequestFactory<SocializeObject>( signer, factory); HttpUriRequest req = reqFactory.getPostRequest(session, endpoint, objects); assertTrue((Boolean) getNextResult()); assertTrue(HttpPost.class.isInstance(req)); assertTrue(HttpEntityEnclosingRequestBase.class.isAssignableFrom(req.getClass())); HttpEntityEnclosingRequestBase post = (HttpEntityEnclosingRequestBase) req; HttpEntity entity = post.getEntity(); assertNotNull(entity); assertTrue(entity instanceof UrlEncodedFormEntity); List<NameValuePair> parsed = URLEncodedUtils.parse(entity); assertEquals(1, parsed.size()); NameValuePair nvp = parsed.get(0); assertEquals("payload", nvp.getName()); assertEquals(jsonData, nvp.getValue()); AndroidMock.verify(factory); }
From source file:org.elasticsearch.client.RestClientSingleHostTests.java
/** * Verifies the content of the {@link HttpRequest} that's internally created and passed through to the http client *///from www .j a v a 2s .c o m @SuppressWarnings("unchecked") public void testInternalHttpRequest() throws Exception { ArgumentCaptor<HttpAsyncRequestProducer> requestArgumentCaptor = ArgumentCaptor .forClass(HttpAsyncRequestProducer.class); int times = 0; for (String httpMethod : getHttpMethods()) { HttpUriRequest expectedRequest = performRandomRequest(httpMethod); verify(httpClient, times(++times)).<HttpResponse>execute(requestArgumentCaptor.capture(), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class)); HttpUriRequest actualRequest = (HttpUriRequest) requestArgumentCaptor.getValue().generateRequest(); assertEquals(expectedRequest.getURI(), actualRequest.getURI()); assertEquals(expectedRequest.getClass(), actualRequest.getClass()); assertArrayEquals(expectedRequest.getAllHeaders(), actualRequest.getAllHeaders()); if (expectedRequest instanceof HttpEntityEnclosingRequest) { HttpEntity expectedEntity = ((HttpEntityEnclosingRequest) expectedRequest).getEntity(); if (expectedEntity != null) { HttpEntity actualEntity = ((HttpEntityEnclosingRequest) actualRequest).getEntity(); assertEquals(EntityUtils.toString(expectedEntity), EntityUtils.toString(actualEntity)); } } } }
From source file:org.opencastproject.loadtest.engage.util.TrustedHttpClient.java
/** * {@inheritDoc}//from w ww.ja va 2 s . c o m * @see org.opencastproject.loadtest.engage.util.remotetest.util.security.api.TrustedHttpClient#execute(org.apache.http.client.methods.HttpUriRequest) */ public HttpResponse execute(HttpUriRequest httpUriRequest) { // Add the request header to elicit a digest auth response httpUriRequest.addHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH); if ("GET".equalsIgnoreCase(httpUriRequest.getMethod()) || "HEAD".equalsIgnoreCase(httpUriRequest.getMethod())) { // Set the user/pass UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); // Run the request (the http client handles the multiple back-and-forth requests) try { return httpClient.execute(httpUriRequest); } catch (IOException e) { throw new TrustedHttpClientException(e); } } // HttpClient doesn't handle the request dynamics for other verbs (especially when sending a streamed multipart // request), so we need to handle the details of the digest auth back-and-forth manually HttpRequestBase digestRequest; try { digestRequest = (HttpRequestBase) httpUriRequest.getClass().newInstance(); } catch (Exception e) { throw new IllegalStateException("Can not create a new " + httpUriRequest.getClass().getName()); } digestRequest.setURI(httpUriRequest.getURI()); digestRequest.addHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH); String[] realmAndNonce = getRealmAndNonce(digestRequest); if (realmAndNonce != null) { // Set the user/pass UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); // Set up the digest authentication with the required values DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", realmAndNonce[0]); digestAuth.overrideParamter("nonce", realmAndNonce[1]); // Add the authentication header try { httpUriRequest.addHeader(digestAuth.authenticate(creds, httpUriRequest)); } catch (Exception e) { // close the http connection(s) httpClient.getConnectionManager().shutdown(); throw new TrustedHttpClientException(e); } } try { return httpClient.execute(httpUriRequest); } catch (Exception e) { // close the http connection(s) httpClient.getConnectionManager().shutdown(); throw new TrustedHttpClientException(e); } }
From source file:org.opencastproject.kernel.security.TrustedHttpClientImpl.java
/** * Handles the necessary handshake for digest authenticaion in the case where it isn't a GET operation. * //from ww w. j av a 2 s . com * @param httpUriRequest * The request location to get the digest authentication for. * @param httpClient * The client to send the request through. * @throws TrustedHttpClientException * Thrown if the client cannot be shutdown. */ private void manuallyHandleDigestAuthentication(HttpUriRequest httpUriRequest, HttpClient httpClient) throws TrustedHttpClientException { HttpRequestBase digestRequest; try { digestRequest = (HttpRequestBase) httpUriRequest.getClass().newInstance(); } catch (Exception e) { throw new IllegalStateException("Can not create a new " + httpUriRequest.getClass().getName()); } digestRequest.setURI(httpUriRequest.getURI()); digestRequest.setHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH); String[] realmAndNonce = getRealmAndNonce(digestRequest); if (realmAndNonce != null) { // Set the user/pass UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); // Set up the digest authentication with the required values DigestScheme digestAuth = new DigestScheme(); digestAuth.overrideParamter("realm", realmAndNonce[0]); digestAuth.overrideParamter("nonce", realmAndNonce[1]); // Add the authentication header try { httpUriRequest.setHeader(digestAuth.authenticate(creds, httpUriRequest)); } catch (Exception e) { // close the http connection(s) httpClient.getConnectionManager().shutdown(); throw new TrustedHttpClientException(e); } } }