List of usage examples for org.apache.commons.httpclient.methods ByteArrayRequestEntity ByteArrayRequestEntity
public ByteArrayRequestEntity(byte[] paramArrayOfByte, String paramString)
From source file:org.apache.jackrabbit.spi2davex.PostMethod.java
@Override protected RequestEntity generateRequestEntity() { if (!this.params.isEmpty()) { // Use a ByteArrayRequestEntity instead of a StringRequestEntity. // This is to avoid potential encoding issues. Form url encoded strings // are ASCII by definition but the content type may not be. Treating the content // as bytes allows us to keep the current charset without worrying about how // this charset will effect the encoding of the form url encoded string. NameValuePair[] mvps = params.toArray(new NameValuePair[params.size()]); String content = EncodingUtil.formUrlEncode(mvps, getRequestCharSet()); ByteArrayRequestEntity entity = new ByteArrayRequestEntity(EncodingUtil.getAsciiBytes(content), FORM_URL_ENCODED_CONTENT_TYPE); return entity; } else {// ww w. j a va2 s . com return super.generateRequestEntity(); } }
From source file:org.apache.jmeter.protocol.amf.sampler.AmfRequest.java
@Override protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { String urlStr = url.toString(); log.debug("Sampling " + urlStr); PostMethod httpMethod = new PostMethod(urlStr); String contentType = AmfResources.getResString("amf_content_type"); String amfXml = getAmfXml();/*from w w w . ja va 2s . c om*/ // Replace properties with override values, if they exist amfXml = overrideProperties(amfXml); if (log.isDebugEnabled()) log.debug("AMF Sample XML: \n" + amfXml); // Create an AMF request from the XML and add it as the POST request body byte[] amfMessage = RawAMF; if (amfMessage != null) { ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(amfMessage, contentType); httpMethod.setRequestEntity(requestEntity); } HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); res.setSampleLabel(urlStr); // May be replaced later res.setHTTPMethod(method); res.setURL(url); res.sampleStart(); // Count the retries as well in the time HttpClient client = null; InputStream instream = null; try { // Set any default request headers setDefaultRequestHeaders(httpMethod); // Setup connection client = setupConnection(url, httpMethod, res); //savedClient = client; // Execute POST int statusCode = client.executeMethod(httpMethod); // Needs to be done after execute to pick up all the headers res.setRequestHeaders(getConnectionHeaders(httpMethod)); // Request sent. Now get the response: instream = httpMethod.getResponseBodyAsStream(); if (instream != null) {// will be null for HEAD Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING); if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) { instream = new GZIPInputStream(instream); } res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setSampleLabel(httpMethod.getURI().toString()); // Pick up Actual path (after redirects) res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE); if (h != null)// Can be missing, e.g. on redirect { ct = h.getValue(); res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } res.setResponseHeaders(getResponseHeaders(httpMethod)); // Store any cookies received in the cookie manager: saveConnectionCookies(httpMethod, res.getURL(), getCookieManager()); // Save cache information final CacheManager cacheManager = getCacheManager(); if (cacheManager != null) { cacheManager.saveDetails(httpMethod, res); } log.debug("Sample Complete"); httpMethod.releaseConnection(); return res; } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); return err; } catch (IOException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); return err; } finally { //savedClient = null; JOrphanUtils.closeQuietly(instream); if (httpMethod != null) { httpMethod.releaseConnection(); } // Post Process the XML into // TODO: Make sure this doesn't change response times String resVar = getResponseVar(); if (resVar != null && !resVar.isEmpty() && res.getBytes() > 0) { log.debug("Decoding response and saving in ${" + resVar + "}"); // Decode response String amfResXml = AmfXmlConverter.convertAmfMessageToXml(res.getResponseData()); JMeterVariables variables = JMeterContextService.getContext().getVariables(); variables.put(resVar, amfResXml); } } }
From source file:org.apache.jmeter.protocol.amf.sampler.AmfSampler.java
@Override protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) { String urlStr = url.toString(); log.debug("Start : sample " + urlStr); log.debug("method " + method); PostMethod httpMethod = new PostMethod(urlStr); String contentType = "application/x-amf"; // Create an encrypted AMF request and add it as the POST request body byte[] amfMessage = amfRequest.createRequest(context); if (amfMessage != null) { ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(amfMessage, contentType); httpMethod.setRequestEntity(requestEntity); }// w w w. j av a2 s . c o m HTTPSampleResult res = new HTTPSampleResult(); res.setMonitor(isMonitor()); res.setSampleLabel(urlStr); // May be replaced later res.setHTTPMethod(method); res.setURL(url); res.sampleStart(); // Count the retries as well in the time HttpClient client = null; InputStream instream = null; try { // Set any default request headers setDefaultRequestHeaders(httpMethod); // Setup connection client = setupConnection(url, httpMethod, res); savedClient = client; // Execute POST int statusCode = client.executeMethod(httpMethod); // Needs to be done after execute to pick up all the headers res.setRequestHeaders(getConnectionHeaders(httpMethod)); // Request sent. Now get the response: instream = httpMethod.getResponseBodyAsStream(); if (instream != null) {// will be null for HEAD Header responseHeader = httpMethod.getResponseHeader(HEADER_CONTENT_ENCODING); if (responseHeader != null && ENCODING_GZIP.equals(responseHeader.getValue())) { instream = new GZIPInputStream(instream); } res.setResponseData(readResponse(res, instream, (int) httpMethod.getResponseContentLength())); } res.sampleEnd(); // Done with the sampling proper. // Now collect the results into the HTTPSampleResult: res.setSampleLabel(httpMethod.getURI().toString()); // Pick up Actual path (after redirects) res.setResponseCode(Integer.toString(statusCode)); res.setSuccessful(isSuccessCode(statusCode)); res.setResponseMessage(httpMethod.getStatusText()); String ct = null; org.apache.commons.httpclient.Header h = httpMethod.getResponseHeader(HEADER_CONTENT_TYPE); if (h != null)// Can be missing, e.g. on redirect { ct = h.getValue(); res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1 res.setEncodingAndType(ct); } res.setResponseHeaders(getResponseHeaders(httpMethod)); // Store any cookies received in the cookie manager: saveConnectionCookies(httpMethod, res.getURL(), getCookieManager()); // Save cache information final CacheManager cacheManager = getCacheManager(); if (cacheManager != null) { cacheManager.saveDetails(httpMethod, res); } log.debug("End : sample"); httpMethod.releaseConnection(); return res; } catch (IllegalArgumentException e)// e.g. some kinds of invalid URL { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); return err; } catch (IOException e) { res.sampleEnd(); HTTPSampleResult err = errorResult(e, res); err.setSampleLabel("Error: " + url.toString()); return err; } finally { savedClient = null; JOrphanUtils.closeQuietly(instream); if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:org.apache.servicemix.http.processors.ProviderProcessor.java
protected RequestEntity writeMessage(SoapWriter writer) throws Exception { if (getConfiguration().isStreamingEnabled()) { return new StreamingRequestEntity(writer); } else {/*from www .j ava 2s . c om*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); writer.write(baos); return new ByteArrayRequestEntity(baos.toByteArray(), writer.getContentType()); } }
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;//from w w w . j a v a 2 s .com } 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.wink.itest.addressbook.StringTest.java
/** * This will drive a POST, GET, UPDATE, and DELETE on the * AddressBookResource//from w w w. j a v a 2 s. c o m */ public void testAddressBookResource() { PostMethod method = null; GetMethod getMethod = null; PutMethod put = null; DeleteMethod deleteMethod = null; try { // make sure everything is clear before testing HttpClient client = new HttpClient(); method = new PostMethod(getBaseURI() + "/fromBody"); String input = "tempAddress&1234 Any Street&AnyTown&90210&TX&US"; RequestEntity entity = new ByteArrayRequestEntity(input.getBytes(), "text/xml"); method.setRequestEntity(entity); client.executeMethod(method); // now let's see if the address we just created is available getMethod = new GetMethod(getBaseURI() + "/tempAddress"); client.executeMethod(getMethod); String responseBody = getMethod.getResponseBodyAsString(); getMethod.releaseConnection(); assertNotNull(responseBody); assertTrue(responseBody, responseBody.contains("tempAddress")); assertTrue(responseBody, responseBody.contains("1234 Any Street")); assertTrue(responseBody, responseBody.contains("AnyTown")); assertTrue(responseBody, responseBody.contains("90210")); assertTrue(responseBody, responseBody.contains("TX")); assertTrue(responseBody, responseBody.contains("US")); // let's update the state String query = "entryName=tempAddress&streetAddress=1234+Any+Street&city=" + "AnyTown&zipCode=90210&state=AL&country=US"; client = new HttpClient(); put = new PutMethod(getBaseURI()); put.setQueryString(query); client.executeMethod(put); // make sure the state has been updated client = new HttpClient(); client.executeMethod(getMethod); responseBody = getMethod.getResponseBodyAsString(); assertNotNull(responseBody); assertTrue(responseBody.contains("tempAddress")); assertFalse(responseBody.contains("TX")); assertTrue(responseBody.contains("AL")); // now let's delete the address client = new HttpClient(); deleteMethod = new DeleteMethod(getBaseURI() + "/tempAddress"); client.executeMethod(deleteMethod); assertEquals(204, deleteMethod.getStatusCode()); // now try to get the address client = new HttpClient(); client.executeMethod(getMethod); assertEquals(404, getMethod.getStatusCode()); responseBody = getMethod.getResponseBodyAsString(); ServerContainerAssertions.assertExceptionBodyFromServer(404, getMethod.getResponseBodyAsString()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } finally { if (method != null) { method.releaseConnection(); } if (getMethod != null) { getMethod.releaseConnection(); } if (put != null) { put.releaseConnection(); } if (deleteMethod != null) { deleteMethod.releaseConnection(); } } }
From source file:org.apache.wink.itest.cachetest.NewsHttpClient.java
public Response addNewsStory(NewsStory story) throws Exception { PostMethod post = new PostMethod(this.baseURI); try {//from w w w . j av a 2 s . co m HttpClient client = new HttpClient(); setRequestHeaders(post); JAXBContext context = JAXBContext.newInstance(NewsStory.class); StringWriter sw = new StringWriter(); context.createMarshaller().marshal(story, sw); RequestEntity entity = new ByteArrayRequestEntity(sw.toString().getBytes(), "text/xml"); post.setRequestEntity(entity); int status = client.executeMethod(post); Map<String, List<Object>> headers = getResponseHeaders(post.getResponseHeaders()); Response resp = Response.status(status).build(); resp.getMetadata().putAll(headers); return resp; } catch (Exception e) { throw e; } finally { if (post != null) { post.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 {/* ww w . ja va 2s .c o 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.contentencoding.ContentEncodingTest.java
/** * Tests sending in small bits of gzip encoded content. * //from w w w . ja v a2s . com * @throws HttpException * @throws IOException */ public void testSendSmallGzipContentEncoded() throws HttpException, IOException { PostMethod postMethod = new PostMethod(BASE_URI + "/bigbook"); postMethod.addRequestHeader("Accept", "text/plain"); postMethod.setRequestHeader("Content-Encoding", "gzip"); postMethod.setRequestHeader("Transfer-Encoding", "chunked"); // postMethod.setRequestHeader("Content-) ByteArrayOutputStream originalContent = new ByteArrayOutputStream(); originalContent.write("Hello world".getBytes("UTF-8")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ChunkedOutputStream chunkedOut = new ChunkedOutputStream(baos); GZIPOutputStream gzipOut = new GZIPOutputStream(chunkedOut); originalContent.writeTo(gzipOut); gzipOut.finish(); chunkedOut.finish(); byte[] content = baos.toByteArray(); postMethod.setRequestEntity(new ByteArrayRequestEntity(content, "text/plain; charset=utf-8")); try { int result = client.executeMethod(postMethod); assertEquals(200, result); String response = postMethod.getResponseBodyAsString(); assertEquals("Hello world" + "helloworld", response); } finally { postMethod.releaseConnection(); } }
From source file:org.apache.wink.itest.contentencoding.ContentEncodingTest.java
/** * Tests sending in small bits of gzip encoded content. * //from ww w .ja v a 2s .c om * @throws HttpException * @throws IOException */ public void testSendLargeGzipContentEncoded() throws HttpException, IOException { PostMethod postMethod = new PostMethod(BASE_URI + "/bigbook/mirror"); postMethod.setContentChunked(true); postMethod.addRequestHeader("Accept", "text/plain"); postMethod.setRequestHeader("Content-Encoding", "gzip"); // postMethod.setRequestHeader("Content-) ByteArrayOutputStream originalContent = new ByteArrayOutputStream(); for (int c = 0; c < 5000000; ++c) { originalContent.write(c); } /* * gzip the contents */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gzipOut = new GZIPOutputStream(baos); originalContent.writeTo(gzipOut); gzipOut.finish(); byte[] content = baos.toByteArray(); postMethod.setRequestEntity(new ByteArrayRequestEntity(content, "text/plain; charset=utf-8")); try { int result = client.executeMethod(postMethod); assertEquals(200, result); InputStream responseStream = postMethod.getResponseBodyAsStream(); for (int c = 0; c < 5000000; ++c) { assertEquals(c % 256, responseStream.read()); } } finally { postMethod.releaseConnection(); } }