List of usage examples for org.apache.commons.httpclient.methods PutMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:org.apache.sling.commons.testing.integration.SlingIntegrationTestClient.java
/** Upload a file to the Sling repository * @return the HTTP status code/* ww w . jav a 2 s .c o m*/ */ public int upload(String toUrl, InputStream is) throws IOException { final PutMethod put = new PutMethod(toUrl); put.setRequestEntity(new InputStreamRequestEntity(is)); return httpClient.executeMethod(put); }
From source file:org.apache.sling.discovery.impl.topology.connector.TopologyConnectorClient.java
/** ping the server and pass the announcements between the two **/ void ping(final boolean force) { if (autoStopped) { // then we suppress any further pings! logger.debug("ping: autoStopped=true, hence suppressing any further pings."); return;/* w w w.ja v a 2 s. co m*/ } if (force) { backoffPeriodEnd = -1; } else if (backoffPeriodEnd > 0) { if (System.currentTimeMillis() < backoffPeriodEnd) { logger.debug("ping: not issueing a heartbeat due to backoff instruction from peer."); return; } else { logger.debug("ping: backoff period ended, issuing another ping now."); } } final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json"; if (logger.isDebugEnabled()) { logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri); } HttpClient httpClient = new HttpClient(); final PutMethod method = new PutMethod(uri); Announcement resultingAnnouncement = null; try { String userInfo = connectorUrl.getUserInfo(); if (userInfo != null) { Credentials c = new UsernamePasswordCredentials(userInfo); httpClient.getState() .setCredentials(new AuthScope(method.getURI().getHost(), method.getURI().getPort()), c); } Announcement topologyAnnouncement = new Announcement(clusterViewService.getSlingId()); topologyAnnouncement.setServerInfo(serverInfo); final ClusterView clusterView = clusterViewService.getClusterView(); topologyAnnouncement.setLocalCluster(clusterView); if (force) { logger.debug("ping: sending a resetBackoff"); topologyAnnouncement.setResetBackoff(true); } announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() { public boolean accept(final String receivingSlingId, final Announcement announcement) { // filter out announcements that are of old cluster instances // which I dont really have in my cluster view at the moment final Iterator<InstanceDescription> it = clusterViewService.getClusterView().getInstances() .iterator(); while (it.hasNext()) { final InstanceDescription instance = it.next(); if (instance.getSlingId().equals(receivingSlingId)) { // then I have the receiving instance in my cluster view // all fine then return true; } } // looks like I dont have the receiving instance in my cluster view // then I should also not propagate that announcement anywhere return false; } }); final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON()); if (logger.isDebugEnabled()) { logger.debug("ping: topologyAnnouncement json is: " + p); } requestValidator.trustMessage(method, p); if (config.isGzipConnectorRequestsEnabled()) { // tell the server that the content is gzipped: method.addRequestHeader("Content-Encoding", "gzip"); // and gzip the body: final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final GZIPOutputStream gzipOut = new GZIPOutputStream(baos); gzipOut.write(p.getBytes("UTF-8")); gzipOut.close(); final byte[] gzippedEncodedJson = baos.toByteArray(); method.setRequestEntity(new ByteArrayRequestEntity(gzippedEncodedJson, "application/json")); lastRequestEncoding = "gzip"; } else { // otherwise plaintext: method.setRequestEntity(new StringRequestEntity(p, "application/json", "UTF-8")); lastRequestEncoding = "plaintext"; } // independent of request-gzipping, we do accept the response to be gzipped, // so indicate this to the server: method.addRequestHeader("Accept-Encoding", "gzip"); DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false); httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler); httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(1000 * config.getConnectionTimeout()); httpClient.getHttpConnectionManager().getParams().setSoTimeout(1000 * config.getSoTimeout()); method.getParams().setSoTimeout(1000 * config.getSoTimeout()); httpClient.executeMethod(method); if (logger.isDebugEnabled()) { logger.debug("ping: done. code=" + method.getStatusCode() + " - " + method.getStatusText()); } lastStatusCode = method.getStatusCode(); lastResponseEncoding = null; if (method.getStatusCode() == HttpServletResponse.SC_OK) { final Header contentEncoding = method.getResponseHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue() != null && contentEncoding.getValue().contains("gzip")) { lastResponseEncoding = "gzip"; } else { lastResponseEncoding = "plaintext"; } String responseBody = requestValidator.decodeMessage(method); // limiting to 16MB, should be way enough if (logger.isDebugEnabled()) { logger.debug("ping: response body=" + responseBody); } if (responseBody != null && responseBody.length() > 0) { Announcement inheritedAnnouncement = Announcement.fromJSON(responseBody); final long backoffInterval = inheritedAnnouncement.getBackoffInterval(); if (backoffInterval > 0) { // then reset the backoffPeriodEnd: /* minus 1 sec to avoid slipping the interval by a few millis */ this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000; logger.debug("ping: servlet instructed to backoff: backoffInterval=" + backoffInterval + ", resulting in period end of " + new Date(backoffPeriodEnd)); } else { logger.debug("ping: servlet did not instruct any backoff-ing at this stage"); this.backoffPeriodEnd = -1; } if (inheritedAnnouncement.isLoop()) { if (logger.isDebugEnabled()) { logger.debug( "ping: connector response indicated a loop detected. not registering this announcement from " + inheritedAnnouncement.getOwnerId()); } if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) { // SLING-3316 : local-loop detected. Check config to see if we should stop this connector if (config.isAutoStopLocalLoopEnabled()) { inheritedAnnouncement = null; // results in connected -> false and representsloop -> true autoStopped = true; // results in isAutoStopped -> true } } } else { inheritedAnnouncement.setInherited(true); if (announcementRegistry.registerAnnouncement(inheritedAnnouncement) == -1) { if (logger.isDebugEnabled()) { logger.debug( "ping: connector response is from an instance which I already see in my topology" + inheritedAnnouncement); } statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)"; return; } } resultingAnnouncement = inheritedAnnouncement; statusDetails = null; } else { statusDetails = "no response body received"; } } else { statusDetails = "got HTTP Status-Code: " + lastStatusCode; } // SLING-2882 : reset suppressPingWarnings_ flag in success case suppressPingWarnings_ = false; } catch (URIException e) { logger.warn("ping: Got URIException: " + e + ", uri=" + uri); statusDetails = e.toString(); } catch (IOException e) { // SLING-2882 : set/check the suppressPingWarnings_ flag if (suppressPingWarnings_) { if (logger.isDebugEnabled()) { logger.debug("ping: got IOException: " + e + ", uri=" + uri); } } else { suppressPingWarnings_ = true; logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri); } statusDetails = e.toString(); } catch (JSONException e) { logger.warn("ping: got JSONException: " + e); statusDetails = e.toString(); } catch (RuntimeException re) { logger.warn("ping: got RuntimeException: " + re, re); statusDetails = re.toString(); } finally { method.releaseConnection(); lastInheritedAnnouncement = resultingAnnouncement; lastPingedAt = System.currentTimeMillis(); } }
From source file:org.apache.sling.maven.bundlesupport.AbstractBundleInstallMojo.java
private int performPut(String targetURL, File file) throws HttpException, IOException { PutMethod filePut = new PutMethod(getURLWithFilename(targetURL, file.getName())); try {//from w w w . j a v a2 s .c om filePut.setRequestEntity(new FileRequestEntity(file, mimeType)); return getHttpClient().executeMethod(filePut); } finally { filePut.releaseConnection(); } }
From source file:org.apache.wink.itest.cachetest.NewsHttpClient.java
public Response updateNewsStory(NewsStory story) throws Exception { PutMethod put = new PutMethod(this.baseURI); try {/*from ww w . j av a2 s . co m*/ HttpClient client = new HttpClient(); setRequestHeaders(put); JAXBContext context = JAXBContext.newInstance(NewsStory.class); StringWriter sw = new StringWriter(); context.createMarshaller().marshal(story, sw); RequestEntity entity = new ByteArrayRequestEntity(sw.toString().getBytes(), "text/xml"); put.setRequestEntity(entity); int status = client.executeMethod(put); Map<String, List<Object>> headers = getResponseHeaders(put.getResponseHeaders()); Response resp = Response.status(status).build(); resp.getMetadata().putAll(headers); return resp; } catch (Exception e) { throw e; } finally { if (put != null) { put.releaseConnection(); } } }
From source file:org.apache.wink.itest.exceptionmappers.JAXRSExceptionsMappedProvidersTest.java
/** * Tests a method that throws a checked exception. * //from ww w.j a va2s .co m * @throws Exception */ public void testCheckExceptionMappedProvider() throws Exception { HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(getBaseURI() + "/-99999"); putMethod.setRequestEntity(new StringRequestEntity( "<comment><id></id><message></message><author></author></comment>", "text/xml", null)); client.executeMethod(putMethod); assertEquals(454, putMethod.getStatusCode()); CommentError c = (CommentError) JAXBContext.newInstance(CommentError.class.getPackage().getName()) .createUnmarshaller().unmarshal(putMethod.getResponseBodyAsStream()); assertEquals("Unexpected ID.", c.getErrorMessage()); }
From source file:org.apache.wink.itest.exceptionmappers.JAXRSExceptionsNoMapperTest.java
/** * Tests a method that throws a checked exception. * // w w w . ja v a 2 s .co m * @throws Exception */ public void testCheckExceptionNoMappingProvider() throws Exception { HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(getBaseURI() + "/-99999"); putMethod.setRequestEntity(new StringRequestEntity( "<comment><id></id><message></message><author></author></comment>", "text/xml", null)); client.executeMethod(putMethod); assertEquals(500, putMethod.getStatusCode()); // assertLogContainsException("jaxrs.tests.exceptions.nomapping.server.GuestbookException: Unexpected ID."); }
From source file:org.apache.wink.itest.exceptions.ExceptionsWhileTargettingTest.java
/** * Tests that a 415 error is thrown when request entity data sent is not * acceptable by the resource.// w w w. java2 s .co m * * @throws Exception */ public void test415WhenResourceMethodDoesNotAcceptRequestEntity() throws Exception { PutMethod putMethod = new PutMethod(getBaseURI() + "/targeting/resourcewithmethod"); try { putMethod.setRequestEntity(new StringRequestEntity("some content", "text/plain", "UTF-8")); client.executeMethod(putMethod); assertEquals(200, putMethod.getStatusCode()); assertEquals("some content", putMethod.getResponseBodyAsString()); } finally { putMethod.releaseConnection(); } putMethod = new PutMethod(getBaseURI() + "/targeting/resourcewithmethod"); try { putMethod.setRequestEntity(new StringRequestEntity("some content", "customplain/something", "UTF-8")); client.executeMethod(putMethod); assertEquals(415, putMethod.getStatusCode()); ServerContainerAssertions.assertExceptionBodyFromServer(415, putMethod.getResponseBodyAsString()); } finally { putMethod.releaseConnection(); } }
From source file:org.apache.wink.itest.exceptions.ExceptionsWhileTargettingTest.java
/** * Tests that a 406 error is produced if server side cannot produce any * acceptable content type./*from w w w . ja va2s . c o m*/ * * @throws Exception */ public void test406WhenResourceMethodDoesNotProduceResponseEntityType() throws Exception { PutMethod putMethod = new PutMethod(getBaseURI() + "/targeting/resourcewithmethod"); try { putMethod.addRequestHeader("Accept", "text/plain"); putMethod.setRequestEntity(new StringRequestEntity("some content", "text/plain", "UTF-8")); client.executeMethod(putMethod); assertEquals(200, putMethod.getStatusCode()); assertEquals("some content", putMethod.getResponseBodyAsString()); } finally { putMethod.releaseConnection(); } putMethod = new PutMethod(getBaseURI() + "/targeting/resourcewithmethod"); try { putMethod.addRequestHeader("Accept", "text/customplain"); putMethod.setRequestEntity(new StringRequestEntity("some content", "text/plain", "UTF-8")); client.executeMethod(putMethod); assertEquals(406, putMethod.getStatusCode()); ServerContainerAssertions.assertExceptionBodyFromServer(406, putMethod.getResponseBodyAsString()); } finally { putMethod.releaseConnection(); } }
From source file:org.apache.wink.itest.request.RequestMethodsTest.java
private void checkIfModifiedSinceUsingSuppliedDateFormat(SimpleDateFormat formatter) throws IOException, HttpException { HttpClient client = new HttpClient(); /*//from ww w . ja v a 2 s . com * get the time zone for the server */ GetMethod getMethod = new GetMethod(getBaseURI() + "/context/request/timezone"); try { client.executeMethod(getMethod); assertEquals(200, getMethod.getStatusCode()); } finally { getMethod.releaseConnection(); } PutMethod putMethod = new PutMethod(getBaseURI() + "/context/request/date"); Date d2 = new Date(System.currentTimeMillis() - 120000); Date d = new Date(System.currentTimeMillis() - 60000); DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); // DateFormat.getDateTimeInstance(); String date = dateFormat.format(d); putMethod.setRequestEntity(new StringRequestEntity(date, "text/string", "UTF-8")); try { /* * sets a last modified date */ client.executeMethod(putMethod); assertEquals(204, putMethod.getStatusCode()); } finally { putMethod.releaseConnection(); } formatter.setTimeZone(TimeZone.getTimeZone("GMT")); getMethod = new GetMethod(getBaseURI() + "/context/request/date"); getMethod.setRequestHeader("If-Modified-Since", formatter.format(d)); try { /* * verifies that if the exact date is sent in and used in * If-Modified-Since header, then the server will be ok and that it * will return 304 */ client.executeMethod(getMethod); assertEquals(304, getMethod.getStatusCode()); } finally { getMethod.releaseConnection(); } getMethod = new GetMethod(getBaseURI() + "/context/request/date"); try { /* * verifies that if no If-Modified-Since header is sent, then the * server will be ok and the Request instance won't build a * response. */ client.executeMethod(getMethod); assertEquals(200, getMethod.getStatusCode()); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); assertEquals("the date: " + rfc1123Format.format(d), getMethod.getResponseBodyAsString()); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); assertEquals(rfc1123Format.format(d), getMethod.getResponseHeader("Last-Modified").getValue()); rfc1123Format.setTimeZone(TimeZone.getDefault()); } finally { getMethod.releaseConnection(); } String lastModified = getMethod.getResponseHeader("Last-Modified").getValue(); getMethod = new GetMethod(getBaseURI() + "/context/request/date"); getMethod.setRequestHeader("If-Modified-Since", lastModified); try { /* * verifies that using Last-Modified response header sent by server * as If-Modified-Since request header, then the server will return * a 304 */ client.executeMethod(getMethod); assertEquals(304, getMethod.getStatusCode()); } finally { getMethod.releaseConnection(); } formatter.setTimeZone(TimeZone.getTimeZone("GMT")); getMethod = new GetMethod(getBaseURI() + "/context/request/date"); getMethod.setRequestHeader("If-Modified-Since", formatter.format(d2)); try { /* * verifies that using a If-Modified-Since earlier than the * Last-Modified response header sent by server then the server will * return a 200 with entity */ client.executeMethod(getMethod); assertEquals(200, getMethod.getStatusCode()); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); assertEquals("the date: " + rfc1123Format.format(d), getMethod.getResponseBodyAsString()); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); assertEquals(rfc1123Format.format(d), getMethod.getResponseHeader("Last-Modified").getValue()); rfc1123Format.setTimeZone(TimeZone.getDefault()); } finally { getMethod.releaseConnection(); } formatter.setTimeZone(TimeZone.getTimeZone("GMT")); getMethod = new GetMethod(getBaseURI() + "/context/request/date"); getMethod.setRequestHeader("If-Modified-Since", formatter.format(new Date())); try { /* * verifies that using a If-Modified-Since later than the * Last-Modified response header sent by server, then the server * will return a 304 */ client.executeMethod(getMethod); assertEquals(304, getMethod.getStatusCode()); } finally { getMethod.releaseConnection(); } }
From source file:org.apache.wink.itest.request.RequestMethodsTest.java
private void checkIfUnmodifiedSinceUsingSuppliedDateFormat(SimpleDateFormat formatter) throws IOException, HttpException { HttpClient client = new HttpClient(); /*/*from ww w . j av a 2s . co m*/ * get the time zone for the server */ GetMethod getMethod = new GetMethod(getBaseURI() + "/context/request/timezone"); try { client.executeMethod(getMethod); assertEquals(200, getMethod.getStatusCode()); } finally { getMethod.releaseConnection(); } PutMethod putMethod = new PutMethod(getBaseURI() + "/context/request/date"); Date d2 = new Date(System.currentTimeMillis() - 120000); Date d = new Date(System.currentTimeMillis() - 60000); DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH); // DateFormat.getDateTimeInstance(); String date = dateFormat.format(d); putMethod.setRequestEntity(new StringRequestEntity(date, "text/string", "UTF-8")); try { /* * sets a last modified date */ client.executeMethod(putMethod); assertEquals(204, putMethod.getStatusCode()); } finally { putMethod.releaseConnection(); } formatter.setTimeZone(TimeZone.getTimeZone("GMT")); getMethod = new GetMethod(getBaseURI() + "/context/request/date"); getMethod.setRequestHeader("If-Unmodified-Since", formatter.format(d)); try { /* * verifies that if the exact date is sent in and used in * If-Unmodified-Since header, then the server will be ok and that * it will return 200 */ client.executeMethod(getMethod); assertEquals(200, getMethod.getStatusCode()); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); assertEquals("the date: " + rfc1123Format.format(d), getMethod.getResponseBodyAsString()); rfc1123Format.setTimeZone(TimeZone.getDefault()); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); assertEquals(rfc1123Format.format(d), getMethod.getResponseHeader("Last-Modified").getValue()); rfc1123Format.setTimeZone(TimeZone.getDefault()); } finally { getMethod.releaseConnection(); } getMethod = new GetMethod(getBaseURI() + "/context/request/date"); try { /* * verifies that if no If-Unmodified-Since header is sent, then the * server will be ok and the Request instance won't build a * response. */ client.executeMethod(getMethod); assertEquals(200, getMethod.getStatusCode()); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); assertEquals("the date: " + rfc1123Format.format(d), getMethod.getResponseBodyAsString()); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); assertEquals(rfc1123Format.format(d), getMethod.getResponseHeader("Last-Modified").getValue()); rfc1123Format.setTimeZone(TimeZone.getDefault()); } finally { getMethod.releaseConnection(); } String lastModified = getMethod.getResponseHeader("Last-Modified").getValue(); getMethod = new GetMethod(getBaseURI() + "/context/request/date"); getMethod.setRequestHeader("If-Unmodified-Since", lastModified); try { /* * verifies that using Last-Modified response header sent by server * as If-Unmodified-Since request header, then the server will * return the entity */ client.executeMethod(getMethod); assertEquals(200, getMethod.getStatusCode()); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); assertEquals("the date: " + rfc1123Format.format(d), getMethod.getResponseBodyAsString()); rfc1123Format.setTimeZone(TimeZone.getDefault()); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); assertEquals(rfc1123Format.format(d), getMethod.getResponseHeader("Last-Modified").getValue()); rfc1123Format.setTimeZone(TimeZone.getDefault()); } finally { getMethod.releaseConnection(); } formatter.setTimeZone(TimeZone.getTimeZone("GMT")); getMethod = new GetMethod(getBaseURI() + "/context/request/date"); getMethod.setRequestHeader("If-Unmodified-Since", formatter.format(d2)); try { /* * verifies that using a If-Unmodified-Since earlier than the * Last-Modified response header sent by server then the server will * return a 412 */ client.executeMethod(getMethod); assertEquals(412, getMethod.getStatusCode()); } finally { getMethod.releaseConnection(); } formatter.setTimeZone(TimeZone.getTimeZone("GMT")); getMethod = new GetMethod(getBaseURI() + "/context/request/date"); getMethod.setRequestHeader("If-Unmodified-Since", formatter.format(new Date())); try { /* * verifies that using a If-Unmodified-Since later than the * Last-Modified response header sent by server, then the server * will return 200 and the entity */ client.executeMethod(getMethod); assertEquals(200, getMethod.getStatusCode()); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); assertEquals("the date: " + rfc1123Format.format(d), getMethod.getResponseBodyAsString()); rfc1123Format.setTimeZone(TimeZone.getDefault()); rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT")); assertEquals(rfc1123Format.format(d), getMethod.getResponseHeader("Last-Modified").getValue()); rfc1123Format.setTimeZone(TimeZone.getDefault()); } finally { getMethod.releaseConnection(); } }