use of org.apache.commons.httpclient.methods.InputStreamRequestEntity in project camel by apache.
the class HttpProducer method createRequestEntity.
/**
* Creates a holder object for the data to send to the remote server.
*
* @param exchange the exchange with the IN message with data to send
* @return the data holder
* @throws CamelExchangeException is thrown if error creating RequestEntity
*/
protected RequestEntity createRequestEntity(Exchange exchange) throws CamelExchangeException {
Message in = exchange.getIn();
if (in.getBody() == null) {
return null;
}
RequestEntity answer = in.getBody(RequestEntity.class);
if (answer == null) {
try {
Object data = in.getBody();
if (data != null) {
String contentType = ExchangeHelper.getContentType(exchange);
if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
if (!getEndpoint().getComponent().isAllowJavaSerializedObject()) {
throw new CamelExchangeException("Content-type " + HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed", exchange);
}
// serialized java object
Serializable obj = in.getMandatoryBody(Serializable.class);
// write object to output stream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
HttpHelper.writeObjectToStream(bos, obj);
answer = new ByteArrayRequestEntity(bos.toByteArray(), HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
IOHelper.close(bos);
} else if (data instanceof File || data instanceof GenericFile) {
// file based (could potentially also be a FTP file etc)
File file = in.getBody(File.class);
if (file != null) {
answer = new FileRequestEntity(file, contentType);
}
} else if (data instanceof String) {
// be a bit careful with String as any type can most likely be converted to String
// so we only do an instanceof check and accept String if the body is really a String
// do not fallback to use the default charset as it can influence the request
// (for example application/x-www-form-urlencoded forms being sent)
String charset = IOHelper.getCharsetName(exchange, false);
answer = new StringRequestEntity((String) data, contentType, charset);
}
// fallback as input stream
if (answer == null) {
// force the body as an input stream since this is the fallback
InputStream is = in.getMandatoryBody(InputStream.class);
answer = new InputStreamRequestEntity(is, contentType);
}
}
} catch (UnsupportedEncodingException e) {
throw new CamelExchangeException("Error creating RequestEntity from message body", exchange, e);
} catch (IOException e) {
throw new CamelExchangeException("Error serializing message body", exchange, e);
}
}
return answer;
}
use of org.apache.commons.httpclient.methods.InputStreamRequestEntity in project openhab1-addons by openhab.
the class AbstractRequest method executeUrl.
/**
* Executes the given <code>url</code> with the given <code>httpMethod</code>. In the case of httpMethods that do
* not support automatic redirection, manually handle the HTTP temporary redirect (307) and retry with the new URL.
*
* @param httpMethod
* the HTTP method to use
* @param url
* the url to execute (in milliseconds)
* @param contentString
* the content to be sent to the given <code>url</code> or <code>null</code> if no content should be
* sent.
* @param contentType
* the content type of the given <code>contentString</code>
* @return the response body or <code>NULL</code> when the request went wrong
*/
protected final String executeUrl(final String httpMethod, final String url, final String contentString, final String contentType) {
HttpClient client = new HttpClient();
HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
method.getParams().setSoTimeout(httpRequestTimeout);
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
for (String httpHeaderKey : HTTP_HEADERS.stringPropertyNames()) {
method.addRequestHeader(new Header(httpHeaderKey, HTTP_HEADERS.getProperty(httpHeaderKey)));
}
// add content if a valid method is given ...
if (method instanceof EntityEnclosingMethod && contentString != null) {
EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
InputStream content = new ByteArrayInputStream(contentString.getBytes());
eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
}
if (logger.isDebugEnabled()) {
try {
logger.trace("About to execute '" + method.getURI().toString() + "'");
} catch (URIException e) {
logger.trace(e.getMessage());
}
}
try {
int statusCode = client.executeMethod(method);
if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
// perfectly fine but we cannot expect any answer...
return null;
}
// Manually handle 307 redirects with a little tail recursion
if (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
Header[] headers = method.getResponseHeaders("Location");
String newUrl = headers[headers.length - 1].getValue();
return executeUrl(httpMethod, newUrl, contentString, contentType);
}
if (statusCode != HttpStatus.SC_OK) {
logger.warn("Method failed: " + method.getStatusLine());
}
InputStream tmpResponseStream = method.getResponseBodyAsStream();
Header encodingHeader = method.getResponseHeader("Content-Encoding");
if (encodingHeader != null) {
for (HeaderElement ehElem : encodingHeader.getElements()) {
if (ehElem.toString().matches(".*gzip.*")) {
tmpResponseStream = new GZIPInputStream(tmpResponseStream);
logger.trace("GZipped InputStream from {}", url);
} else if (ehElem.toString().matches(".*deflate.*")) {
tmpResponseStream = new InflaterInputStream(tmpResponseStream);
logger.trace("Deflated InputStream from {}", url);
}
}
}
String responseBody = IOUtils.toString(tmpResponseStream);
if (!responseBody.isEmpty()) {
logger.trace(responseBody);
}
return responseBody;
} catch (HttpException he) {
logger.error("Fatal protocol violation: {}", he.toString());
} catch (IOException ioe) {
logger.error("Fatal transport error: {}", ioe.toString());
} finally {
method.releaseConnection();
}
return null;
}
use of org.apache.commons.httpclient.methods.InputStreamRequestEntity in project zm-mailbox by Zimbra.
the class UserServlet method putRemoteResource.
public static Pair<Header[], HttpInputStream> putRemoteResource(ZAuthToken authToken, String url, InputStream req, Header[] headers) throws ServiceException, IOException {
StringBuilder u = new StringBuilder(url);
u.append("?").append(QP_AUTH).append('=').append(AUTH_COOKIE);
PutMethod method = new PutMethod(u.toString());
String contentType = "application/octet-stream";
if (headers != null) {
for (Header hdr : headers) {
String name = hdr.getName();
method.addRequestHeader(hdr);
if (name.equals("Content-Type"))
contentType = hdr.getValue();
}
}
method.setRequestEntity(new InputStreamRequestEntity(req, contentType));
Pair<Header[], HttpMethod> pair = doHttpOp(authToken, method);
return new Pair<Header[], HttpInputStream>(pair.getFirst(), new HttpInputStream(pair.getSecond()));
}
use of org.apache.commons.httpclient.methods.InputStreamRequestEntity in project zm-mailbox by Zimbra.
the class ZimbraServlet method proxyServletRequest.
public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, Server server, String uri, AuthToken authToken) throws IOException, ServiceException {
if (server == null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "cannot find remote server");
return;
}
HttpMethod method;
String url = getProxyUrl(req, server, uri);
mLog.debug("Proxy URL = %s", url);
if (req.getMethod().equalsIgnoreCase("GET")) {
method = new GetMethod(url.toString());
} else if (req.getMethod().equalsIgnoreCase("POST") || req.getMethod().equalsIgnoreCase("PUT")) {
PostMethod post = new PostMethod(url.toString());
post.setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
method = post;
} else {
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "cannot proxy method: " + req.getMethod());
return;
}
HttpState state = new HttpState();
String hostname = method.getURI().getHost();
if (authToken != null) {
authToken.encode(state, false, hostname);
}
try {
proxyServletRequest(req, resp, method, state);
} finally {
method.releaseConnection();
}
}
use of org.apache.commons.httpclient.methods.InputStreamRequestEntity in project zm-mailbox by Zimbra.
the class TestZimbraHttpConnectionManager method testSoTimeoutViaHttpPostMethod.
// @Test
public void testSoTimeoutViaHttpPostMethod() throws Exception {
int serverPort = 7778;
String resourceToPost = "/opt/zimbra/unittest/rights-unittest.xml";
// delay 10 seconds in server
long delayInServer = 100000;
// 3000; // 3 seconds, 0 for infinite wait
int soTimeout = 60000;
String qp = "?" + SimpleHttpServer.DelayWhen.BEFORE_WRITING_RESPONSE_HEADERS.name() + "=" + delayInServer;
String uri = "http://localhost:" + serverPort + resourceToPost + qp;
// start a http server for testing
SimpleHttpServer.start(serverPort);
// post the exported content to the target server
HttpClient httpClient = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
PostMethod method = new PostMethod(uri);
// infinite wait because it can take a long time to import a large mailbox
method.getParams().setSoTimeout(soTimeout);
File file = new File(resourceToPost);
FileInputStream fis = null;
long startTime = System.currentTimeMillis();
long endTime;
try {
fis = new FileInputStream(file);
InputStreamRequestEntity isre = new InputStreamRequestEntity(fis, file.length(), MimeConstants.CT_APPLICATION_OCTET_STREAM);
method.setRequestEntity(isre);
int respCode = httpClient.executeMethod(method);
dumpResponse(respCode, method, "");
// nope, it should have timed out
Assert.fail();
} catch (java.net.SocketTimeoutException e) {
e.printStackTrace();
// good, just what we want
endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println("Client timed out after " + elapsedTime + " msecs");
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
} finally {
method.releaseConnection();
}
// shutdown the server
SimpleHttpServer.shutdown();
}
Aggregations