List of usage examples for org.apache.commons.httpclient.methods ByteArrayRequestEntity ByteArrayRequestEntity
public ByteArrayRequestEntity(byte[] paramArrayOfByte)
From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpCompressionRequestFilter.java
@Override public void filterAbstractHttpRequest(SubmitContext context, AbstractHttpRequest<?> httpRequest) { Settings settings = httpRequest.getSettings(); String compressionAlg = settings.getString(HttpSettings.REQUEST_COMPRESSION, "None"); if (!"None".equals(compressionAlg)) { try {/*from w w w.j a v a 2s . c o m*/ ExtendedHttpMethod method = (ExtendedHttpMethod) context .getProperty(BaseHttpRequestTransport.HTTP_METHOD); if (method instanceof EntityEnclosingMethod) { RequestEntity requestEntity = method.getRequestEntity(); if (requestEntity != null) { ByteArrayOutputStream tempOut = new ByteArrayOutputStream(); requestEntity.writeRequest(tempOut); byte[] compressedData = CompressionSupport.compress(compressionAlg, tempOut.toByteArray()); ((EntityEnclosingMethod) method) .setRequestEntity(new ByteArrayRequestEntity(compressedData)); } } } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.taobao.metamorphosis.client.http.SimpleHttpProducer.java
/** * // w w w . j a va 2s .c o m * * @param message * @throws MetaClientException */ public SendResult sendMessage(final Message message, final Partition partition) throws MetaClientException { final long start = System.currentTimeMillis(); this.checkMessage(message); final int flag = MessageFlagUtils.getFlag(message); final byte[] data = SimpleMessageProducer.encodeData(message); final String uri = "/put/" + partition.getBrokerId() + "?topic=" + message.getTopic() + "&partition=" + partition.getPartition() + "&flag=" + flag + "&length=" + data.length; final PostMethod postMethod = new PostMethod(uri); try { postMethod.setRequestEntity(new ByteArrayRequestEntity(data)); this.httpclient.executeMethod(postMethod); final String resultStr = postMethod.getResponseBodyAsString(); switch (postMethod.getStatusCode()) { case HttpStatus.Success: { // messageId partition offset final String[] tmps = RESULT_SPLITER.split(resultStr); // idid MessageAccessor.setId(message, Long.parseLong(tmps[0])); return new SendResult(true, new Partition(0, Integer.parseInt(tmps[1])), Long.parseLong(tmps[2]), null); } case HttpStatus.Forbidden: { // , return new SendResult(false, null, -1, String.valueOf(HttpStatus.Forbidden)); } default: return new SendResult(false, null, -1, resultStr); } } catch (final Exception e) { this.logger.error(e.getMessage(), e); throw new MetaClientException(e); } finally { final long duration = System.currentTimeMillis() - start; System.out.println(duration); MetaStatLog.addStatValue2(null, StatConstants.PUT_TIME_STAT, message.getTopic(), duration); postMethod.releaseConnection(); } }
From source file:jails.http.client.CommonsClientHttpRequest.java
@Override public ClientHttpResponse executeInternal(HttpHeaders headers, byte[] output) throws IOException { for (Map.Entry<String, List<String>> entry : headers.entrySet()) { String headerName = entry.getKey(); for (String headerValue : entry.getValue()) { httpMethod.addRequestHeader(headerName, headerValue); }//from w w w . j a va 2 s . c o m } if (this.httpMethod instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) this.httpMethod; RequestEntity requestEntity = new ByteArrayRequestEntity(output); entityEnclosingMethod.setRequestEntity(requestEntity); } this.httpClient.executeMethod(this.httpMethod); return new CommonsClientHttpResponse(this.httpMethod); }
From source file:guru.nidi.atlassian.remote.script.RemoteJira.java
Object executeImpl(String command, Object... parameters) throws RpcException { PostMethod post = new PostMethod(serverUrl + "/rpc/json-rpc/jirasoapservice-v2/" + command); post.setRequestHeader("Content-Type", "application/json"); HttpUtils.setAuthHeader(post, username, password); ObjectMapper mapper = new ObjectMapper(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {/*from www . ja v a 2 s .c o m*/ mapper.writeValue(baos, parameters); post.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray())); int status = client.executeMethod(post); if (status != HttpStatus.SC_OK) { throw new IOException("not ok: " + status + " " + post.getResponseBodyAsString(MAX_RESPONSE_SIZE)); } try { ErrorResponse errorResponse = mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), ErrorResponse.class); throw new RpcException(errorResponse); } catch (JsonParseException e) { //ignore } catch (JsonMappingException e) { //ignore } try { return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), new TypeReference<HashMap<String, Object>>() { }); } catch (JsonParseException e) { //ignore } catch (JsonMappingException e) { //ignore } try { return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), new TypeReference<ArrayList<Object>>() { }); } catch (JsonParseException e) { //ignore } catch (JsonMappingException e) { //ignore } return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), String.class); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return null; }
From source file:com.ibm.hrl.proton.adapters.rest.client.RestClient.java
/** * Put the specified event instance to the specified consumer. * The consumer is specified by the URL (which includes all the relevant info - the web * server name, port name, web service name and the URI path * The content type can be either application/xml,application/json or plain text * The content type will be specified by the specific consumer, and a formatter * will be supplied to format the event instance to that type * //w w w . j a v a 2 s. c o m * @param url * @return * @throws AdapterException * @throws RESTException */ protected static void putEventToConsumer(String url, String eventInstance, String contentType, String authToken) throws RESTException { // Prepare HTTP PUT PostMethod postMethod = new PostMethod(url); if (eventInstance != null) { RequestEntity requestEntity = new ByteArrayRequestEntity(eventInstance.getBytes()); postMethod.setRequestEntity(requestEntity); // Specify content type and encoding // If content encoding is not explicitly specified // ISO-8859-1 is assumed // postMethod.setRequestHeader("Content-Type", contentType+"; charset=ISO-8859-1"); postMethod.setRequestHeader("Content-Type", contentType); if (null != authToken && !authToken.isEmpty()) { postMethod.setRequestHeader("X-Auth-Token", authToken); } // Get HTTP client HttpClient httpclient = new HttpClient(); // Execute request try { int result = httpclient.executeMethod(postMethod); if (result < 200 || result >= 300) { Header[] reqHeaders = postMethod.getRequestHeaders(); StringBuffer headers = new StringBuffer(); for (int i = 0; i < reqHeaders.length; i++) { headers.append(reqHeaders[i].toString()); headers.append("\n"); } throw new RESTException("Could not perform POST of event instance: \n" + eventInstance + "\nwith request headers:\n" + headers + "to consumer " + url + ", responce result: " + result); } } catch (Exception e) { throw new RESTException(e); } finally { // Release current connection to the connection pool // once you are done postMethod.releaseConnection(); } } else { System.out.println("Invalid request"); } // PutMethod putMethod = new PutMethod(url); // // if(eventInstance != null) { // RequestEntity requestEntity = new ByteArrayRequestEntity(eventInstance.getBytes()); // putMethod.setRequestEntity(requestEntity); // // // // Specify content type and encoding // // If content encoding is not explicitly specified // // ISO-8859-1 is assumed // putMethod.setRequestHeader( // "Content-type", contentType+"; charset=ISO-8859-1"); // // // Get HTTP client // HttpClient httpclient = new HttpClient(); // // // Execute request // try { // // int result = httpclient.executeMethod(putMethod); // // if (result < 200 || result >= 300) // { // throw new RESTException("Could not perform PUT of event instance "+eventInstance+" to consumer "+ url+", responce result: "+result); // } // // } catch(Exception e) // { // throw new RESTException(e); // } // finally { // // Release current connection to the connection pool // // once you are done // putMethod.releaseConnection(); // } // } else // { // System.out.println ("Invalid request"); // } }
From source file:guru.nidi.atlassian.remote.script.RemoteConfluence.java
Object executeImpl(String command, Object... parameters) throws RpcException { PostMethod post = new PostMethod(serverUrl + "/rpc/json-rpc/confluenceservice-v2/" + command); post.setRequestHeader("Content-Type", "application/json"); HttpUtils.setAuthHeader(post, username, password); ObjectMapper mapper = new ObjectMapper(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try {//from w ww. j av a 2 s. co m mapper.writeValue(baos, parameters); post.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray())); int status = client.executeMethod(post); if (status != HttpStatus.SC_OK) { throw new IOException("not ok"); } try { ErrorResponse errorResponse = mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), ErrorResponse.class); throw new RpcException(errorResponse); } catch (JsonParseException e) { //ignore } catch (JsonMappingException e) { //ignore } try { return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), new TypeReference<HashMap<String, Object>>() { }); } catch (JsonParseException e) { //ignore } catch (JsonMappingException e) { //ignore } return mapper.readValue(post.getResponseBodyAsString(MAX_RESPONSE_SIZE), new TypeReference<ArrayList<Object>>() { }); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return null; }
From source file:com.moss.jaxwslite.Service.java
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (args == null) { args = new Object[0]; }//from ww w . ja v a 2s . c o m if (method.getName().equals("toString") && args.length == 0) { return url.toString(); } PostMethod post = new PostMethod(url.toString()); final byte[] requestContent = type.request(method, args); RequestEntity requestEntity = new ByteArrayRequestEntity(requestContent); post.setRequestEntity(requestEntity); post.addRequestHeader("Content-Type", "text/xml"); if (log.isDebugEnabled()) { new Thread() { public void run() { try { setPriority(MIN_PRIORITY); ByteArrayOutputStream out = new ByteArrayOutputStream(); JAXBHelper.beautify(new ByteArrayInputStream(requestContent), out); StringBuilder sb = new StringBuilder(); sb.append("Sending post: ").append(url).append("\n"); sb.append(new String(out.toByteArray())); log.debug(sb.toString()); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); } try { int responseCode = client.executeMethod(post); boolean fault = responseCode != 200; final byte[] responseContent; { InputStream in = post.getResponseBodyAsStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 10]; //10k buffer for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) { out.write(buffer, 0, numRead); } responseContent = out.toByteArray(); } if (log.isDebugEnabled()) { new Thread() { public void run() { try { setPriority(MIN_PRIORITY); ByteArrayOutputStream out = new ByteArrayOutputStream(); JAXBHelper.beautify(new ByteArrayInputStream(responseContent), out); StringBuilder sb = new StringBuilder(); sb.append("Receiving post response: ").append(url).append("\n"); sb.append(new String(out.toByteArray())); log.debug(sb.toString()); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); } Object response = type.response(method, responseContent, fault); if (response instanceof Exception) { throw (Exception) response; } else { return response; } } finally { post.releaseConnection(); } }
From source file:net.jadler.JadlerMockingIntegrationTest.java
@Test public void havingRawBody() throws IOException { final PostMethod method = new PostMethod("http://localhost:" + port()); method.setRequestEntity(new ByteArrayRequestEntity(BINARY_BODY)); client.executeMethod(method);//from w ww .jav a 2s . c o m verifyThatRequest().havingRawBodyEqualTo(BINARY_BODY).receivedTimes(equalTo(1)); }
From source file:com.wandisco.s3hdfs.rewrite.redirect.MetadataFileRedirect.java
/** * Sends a PUT command to create an empty file inside of HDFS. * It uses the URL from the original request to do so. * It will then consume the 307 response and write to the DataNode as well. * The data is "small" in hopes that this will be relatively quick. * * @throws IOException/*from w w w .j a v a 2 s. c o m*/ * @throws ServletException */ public void sendCreate(String nnHostAddress, String userName) throws IOException, ServletException { // Set up HttpPut String[] nnHost = nnHostAddress.split(":"); String metapath = replaceUri(request.getRequestURI(), OBJECT_FILE_NAME, META_FILE_NAME); PutMethod httpPut = (PutMethod) getHttpMethod(request.getScheme(), nnHost[0], Integer.decode(nnHost[1]), "CREATE&overwrite=true", userName, metapath, PUT); Enumeration headers = request.getHeaderNames(); Properties metadata = new Properties(); // Set custom metadata headers while (headers.hasMoreElements()) { String key = (String) headers.nextElement(); if (key.startsWith("x-amz-meta-")) { String value = request.getHeader(key); metadata.setProperty(key, value); } } // Include lastModified header SimpleDateFormat rc228 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z"); String modTime = rc228.format(Calendar.getInstance().getTime()); metadata.setProperty("Last-Modified", modTime); // Store metadata headers into serialized HashMap in HttpPut entity. ByteArrayOutputStream baos = new ByteArrayOutputStream(); metadata.store(baos, null); httpPut.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray())); httpPut.setRequestHeader(S3_HEADER_NAME, S3_HEADER_VALUE); httpClient.executeMethod(httpPut); LOG.debug("1st response: " + httpPut.getStatusLine().toString()); boolean containsRedirect = (httpPut.getResponseHeader("Location") != null); if (!containsRedirect) { httpPut.releaseConnection(); LOG.error("1st response did not contain redirect. " + "No metadata will be created."); return; } // Handle redirect header transition assert httpPut.getStatusCode() == 307; Header locationHeader = httpPut.getResponseHeader("Location"); httpPut.setURI(new URI(locationHeader.getValue(), true)); // Consume response and re-allocate connection for redirect httpPut.releaseConnection(); httpClient.executeMethod(httpPut); LOG.debug("2nd response: " + httpPut.getStatusLine().toString()); if (httpPut.getStatusCode() != 200) { LOG.debug("Response not 200: " + httpPut.getResponseBodyAsString()); return; } assert httpPut.getStatusCode() == 200; }
From source file:com.wandisco.s3hdfs.rewrite.redirect.MultiPartFileRedirect.java
/** * Sends a PUT command to create the container directory inside of HDFS. * It uses the URL from the original request to do so. * * @throws IOException//from w w w . j ava2 s .c o m * @throws ServletException */ public void sendInitiate() throws IOException, ServletException { PutMethod httpPut = (PutMethod) getHttpMethod(request.getScheme(), request.getServerName(), request.getServerPort(), "MKDIRS", path.getUserName(), path.getHdfsRootUploadPath(), PUT); //Make /root/user/bucket/object/version/upload directory httpClient.executeMethod(httpPut); httpPut.releaseConnection(); assert httpPut.getStatusCode() == 200; response.setHeader("Set-Cookie", httpPut.getResponseHeader("Set-Cookie").getValue()); // Make /root/user/bucket/object/version/.meta file // Set up HttpPut httpPut = (PutMethod) getHttpMethod(request.getScheme(), request.getServerName(), request.getServerPort(), "CREATE&overwrite=true", path.getUserName(), path.getFullHdfsMetaPath(), PUT); // Set custom metadata headers Enumeration headers = request.getHeaderNames(); Properties metadata = new Properties(); while (headers.hasMoreElements()) { String key = (String) headers.nextElement(); if (key.startsWith("x-amz-meta-")) { metadata.setProperty(key, request.getHeader(key)); } } // Include lastModified header SimpleDateFormat rc228 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z"); String modTime = rc228.format(Calendar.getInstance().getTime()); metadata.setProperty("Last-Modified", modTime); // Store metadata headers into serialized HashMap in HttpPut entity. ByteArrayOutputStream baos = new ByteArrayOutputStream(); metadata.store(baos, null); httpPut.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray())); httpPut.setRequestHeader(S3_HEADER_NAME, S3_HEADER_VALUE); httpClient.executeMethod(httpPut); LOG.debug("1st response: " + httpPut.getStatusLine().toString()); boolean containsRedirect = (httpPut.getResponseHeader("Location") != null); LOG.debug("Contains redirect? " + containsRedirect); if (!containsRedirect) { LOG.error("1st response did not contain redirect. " + "No metadata will be created."); return; } // Handle redirect header transition assert httpPut.getStatusCode() == 307; Header locationHeader = httpPut.getResponseHeader("Location"); httpPut.setURI(new URI(locationHeader.getValue(), true)); // Consume response and re-allocate connection for redirect httpPut.releaseConnection(); httpClient.executeMethod(httpPut); LOG.debug("2nd response: " + httpPut.getStatusLine().toString()); if (httpPut.getStatusCode() != 200) { LOG.debug("Response content: " + httpPut.getResponseBodyAsString()); } // Consume 2nd response, assure it was a 200 httpPut.releaseConnection(); assert httpPut.getStatusCode() == 200; }