use of org.apache.http.entity.BufferedHttpEntity in project connect-sdk-java by Ingenico-ePayments.
the class DefaultConnection method logRequest.
// logging code
private void logRequest(final HttpRequest request, final String requestId, final CommunicatorLogger logger) {
try {
RequestLine requestLine = request.getRequestLine();
String method = requestLine.getMethod();
String uri = requestLine.getUri();
final RequestLogMessageBuilder logMessageBuilder = new RequestLogMessageBuilder(requestId, method, uri);
addHeaders(logMessageBuilder, request.getAllHeaders());
if (request instanceof HttpEntityEnclosingRequest) {
final HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) request;
HttpEntity entity = entityEnclosingRequest.getEntity();
if (entity != null && !entity.isRepeatable()) {
entity = new BufferedHttpEntity(entity);
entityEnclosingRequest.setEntity(entity);
}
setBody(logMessageBuilder, entity, request.getFirstHeader(HttpHeaders.CONTENT_TYPE));
}
logger.log(logMessageBuilder.getMessage());
} catch (Exception e) {
logger.log(String.format("An error occurred trying to log request '%s'", requestId), e);
return;
}
}
use of org.apache.http.entity.BufferedHttpEntity in project kylo by Teradata.
the class CustomApacheConnector method getHttpEntity.
private HttpEntity getHttpEntity(final ClientRequest clientRequest, final boolean bufferingEnabled) {
final Object entity = clientRequest.getEntity();
if (entity == null) {
return null;
}
final AbstractHttpEntity httpEntity = new AbstractHttpEntity() {
@Override
public boolean isRepeatable() {
return false;
}
@Override
public long getContentLength() {
return -1;
}
@Override
public InputStream getContent() throws IOException, IllegalStateException {
if (bufferingEnabled) {
final ByteArrayOutputStream buffer = new ByteArrayOutputStream(512);
writeTo(buffer);
return new ByteArrayInputStream(buffer.toByteArray());
} else {
return null;
}
}
@Override
public void writeTo(final OutputStream outputStream) throws IOException {
clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
@Override
public OutputStream getOutputStream(final int contentLength) throws IOException {
return outputStream;
}
});
clientRequest.writeEntity();
}
@Override
public boolean isStreaming() {
return false;
}
};
if (bufferingEnabled) {
try {
return new BufferedHttpEntity(httpEntity);
} catch (final IOException e) {
throw new ProcessingException(LocalizationMessages.ERROR_BUFFERING_ENTITY(), e);
}
} else {
return httpEntity;
}
}
use of org.apache.http.entity.BufferedHttpEntity in project 9GAG by Mixiaoxiao.
the class HttpClientUtil method download.
/**
* <pre>���d</pre>
*
* @param url
* @param saveFile
* @param params
* @param isPost
* @return ���saveFile==null�t��inputstream, ��t��saveFile
* @throws Exception
*/
public static Object download(final String url, final File saveFile, final Map<String, String> params, final boolean isPost) throws Exception {
boolean saveToFile = saveFile != null;
// check dir exist ??
if (saveToFile && saveFile.getParentFile().exists() == false) {
saveFile.getParentFile().mkdirs();
}
Exception err = null;
HttpRequestBase request = null;
HttpResponse response = null;
HttpEntity entity = null;
FileOutputStream fos = null;
Object result = null;
try {
// create request
if (isPost) {
request = new HttpPost(url);
} else {
request = new HttpGet(url);
}
// add header & params
addHeaderAndParams(request, params);
// connect
response = httpclient.execute(request);
entity = response.getEntity();
entity = new BufferedHttpEntity(entity);
// get result
if (saveToFile) {
// save to disk
fos = new FileOutputStream(saveFile);
IOUtils.copy(entity.getContent(), fos);
result = saveFile;
} else {
// warp to inpustream
result = new BufferedInputStream(entity.getContent());
}
} catch (Exception e) {
err = e;
} finally {
// close
IOUtils.closeQuietly(fos);
// clear
request = null;
response = null;
entity = null;
if (err != null) {
throw err;
}
return result;
}
}
use of org.apache.http.entity.BufferedHttpEntity in project openkit-android by OpenKit.
the class BinaryHttpResponseHandler method sendResponseMessage.
// Interface to AsyncHttpRequest
void sendResponseMessage(HttpResponse response) {
StatusLine status = response.getStatusLine();
Header[] contentTypeHeaders = response.getHeaders("Content-Type");
byte[] responseBody = null;
if (contentTypeHeaders.length != 1) {
// malformed/ambiguous HTTP Header, ABORT!
sendFailureMessage(new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"), responseBody);
return;
}
Header contentTypeHeader = contentTypeHeaders[0];
boolean foundAllowedContentType = false;
for (String anAllowedContentType : mAllowedContentTypes) {
if (anAllowedContentType.equals(contentTypeHeader.getValue())) {
foundAllowedContentType = true;
}
}
if (!foundAllowedContentType) {
// Content-Type not in allowed list, ABORT!
sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"), responseBody);
return;
}
try {
HttpEntity entity = null;
HttpEntity temp = response.getEntity();
if (temp != null) {
entity = new BufferedHttpEntity(temp);
}
responseBody = EntityUtils.toByteArray(entity);
} catch (IOException e) {
sendFailureMessage(e, (byte[]) null);
}
if (status.getStatusCode() >= 300) {
sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
} else {
sendSuccessMessage(status.getStatusCode(), responseBody);
}
}
use of org.apache.http.entity.BufferedHttpEntity in project c-geo by just-radovan.
the class cgHtmlImg method getDrawable.
@Override
public BitmapDrawable getDrawable(String url) {
Bitmap imagePre = null;
String dirName = null;
String fileName = null;
String fileNameSec = null;
if (url == null || url.length() == 0) {
return null;
}
final String[] urlParts = url.split("\\.");
String urlExt = null;
if (urlParts.length > 1) {
urlExt = "." + urlParts[(urlParts.length - 1)];
if (urlExt.length() > 5) {
urlExt = "";
}
} else {
urlExt = "";
}
if (geocode != null && geocode.length() > 0) {
dirName = settings.getStorage() + geocode + "/";
fileName = settings.getStorage() + geocode + "/" + cgBase.md5(url) + urlExt;
fileNameSec = settings.getStorageSec() + geocode + "/" + cgBase.md5(url) + urlExt;
} else {
dirName = settings.getStorage() + "_others/";
fileName = settings.getStorage() + "_others/" + cgBase.md5(url) + urlExt;
fileNameSec = settings.getStorageSec() + "_others/" + cgBase.md5(url) + urlExt;
}
File dir = null;
dir = new File(settings.getStorage());
if (dir.exists() == false) {
dir.mkdirs();
}
dir = new File(dirName);
if (dir.exists() == false) {
dir.mkdirs();
}
dir = null;
// load image from cache
if (onlySave == false) {
try {
final Date now = new Date();
final File file = new File(fileName);
if (file.exists() == true) {
final long imageSize = file.length();
// large images will be downscaled on input to save memory
if (imageSize > (6 * 1024 * 1024)) {
bfOptions.inSampleSize = 48;
} else if (imageSize > (4 * 1024 * 1024)) {
bfOptions.inSampleSize = 16;
} else if (imageSize > (2 * 1024 * 1024)) {
bfOptions.inSampleSize = 10;
} else if (imageSize > (1 * 1024 * 1024)) {
bfOptions.inSampleSize = 6;
} else if (imageSize > (0.5 * 1024 * 1024)) {
bfOptions.inSampleSize = 2;
}
if (reason > 0 || file.lastModified() > (now.getTime() - (24 * 60 * 60 * 1000))) {
imagePre = BitmapFactory.decodeFile(fileName, bfOptions);
}
}
if (imagePre == null) {
final File fileSec = new File(fileNameSec);
if (fileSec.exists() == true) {
final long imageSize = fileSec.length();
// large images will be downscaled on input to save memory
if (imageSize > (6 * 1024 * 1024)) {
bfOptions.inSampleSize = 48;
} else if (imageSize > (4 * 1024 * 1024)) {
bfOptions.inSampleSize = 16;
} else if (imageSize > (2 * 1024 * 1024)) {
bfOptions.inSampleSize = 10;
} else if (imageSize > (1 * 1024 * 1024)) {
bfOptions.inSampleSize = 6;
} else if (imageSize > (0.5 * 1024 * 1024)) {
bfOptions.inSampleSize = 2;
}
if (reason > 0 || file.lastModified() > (now.getTime() - (24 * 60 * 60 * 1000))) {
imagePre = BitmapFactory.decodeFile(fileNameSec, bfOptions);
}
}
}
} catch (Exception e) {
Log.w(cgSettings.tag, "cgHtmlImg.getDrawable (reading cache): " + e.toString());
}
}
// download image and save it to the cache
if ((imagePre == null && reason == 0) || onlySave == true) {
Uri uri = null;
HttpClient client = null;
HttpGet getMethod = null;
HttpResponse httpResponse = null;
HttpEntity entity = null;
BufferedHttpEntity bufferedEntity = null;
try {
// check if uri is absolute or not, if not attach geocaching.com hostname and scheme
uri = Uri.parse(url);
if (uri.isAbsolute() == false) {
url = "http://www.geocaching.com" + url;
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgHtmlImg.getDrawable (parse URL): " + e.toString());
}
if (uri != null) {
for (int i = 0; i < 2; i++) {
if (i > 0) {
Log.w(cgSettings.tag, "cgHtmlImg.getDrawable: Failed to download data, retrying. Attempt #" + (i + 1));
}
try {
client = new DefaultHttpClient();
getMethod = new HttpGet(url);
httpResponse = client.execute(getMethod);
entity = httpResponse.getEntity();
bufferedEntity = new BufferedHttpEntity(entity);
final long imageSize = bufferedEntity.getContentLength();
// large images will be downscaled on input to save memory
if (imageSize > (6 * 1024 * 1024)) {
bfOptions.inSampleSize = 48;
} else if (imageSize > (4 * 1024 * 1024)) {
bfOptions.inSampleSize = 16;
} else if (imageSize > (2 * 1024 * 1024)) {
bfOptions.inSampleSize = 10;
} else if (imageSize > (1 * 1024 * 1024)) {
bfOptions.inSampleSize = 6;
} else if (imageSize > (0.5 * 1024 * 1024)) {
bfOptions.inSampleSize = 2;
}
if (bufferedEntity != null) {
imagePre = BitmapFactory.decodeStream(bufferedEntity.getContent(), null, bfOptions);
}
if (imagePre != null) {
break;
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgHtmlImg.getDrawable (downloading from web): " + e.toString());
}
}
}
try {
// save to memory/SD cache
if (bufferedEntity != null) {
final InputStream is = (InputStream) bufferedEntity.getContent();
final FileOutputStream fos = new FileOutputStream(fileName);
try {
final byte[] buffer = new byte[4096];
int l;
while ((l = is.read(buffer)) != -1) {
fos.write(buffer, 0, l);
}
} catch (IOException e) {
Log.e(cgSettings.tag, "cgHtmlImg.getDrawable (saving to cache): " + e.toString());
} finally {
is.close();
fos.flush();
fos.close();
}
}
} catch (Exception e) {
Log.e(cgSettings.tag, "cgHtmlImg.getDrawable (saving to cache): " + e.toString());
}
entity = null;
bufferedEntity = null;
}
if (onlySave == true) {
return null;
}
// get image and return
if (imagePre == null) {
Log.d(cgSettings.tag, "cgHtmlImg.getDrawable: Failed to obtain image");
if (placement == false) {
imagePre = BitmapFactory.decodeResource(activity.getResources(), R.drawable.image_no_placement);
} else {
imagePre = BitmapFactory.decodeResource(activity.getResources(), R.drawable.image_not_loaded);
}
}
final int imgWidth = imagePre.getWidth();
final int imgHeight = imagePre.getHeight();
if (imgWidth > maxWidth || imgHeight > maxHeight) {
if ((maxWidth / imgWidth) > (maxHeight / imgHeight)) {
ratio = (double) maxHeight / (double) imgHeight;
} else {
ratio = (double) maxWidth / (double) imgWidth;
}
width = (int) Math.ceil(imgWidth * ratio);
height = (int) Math.ceil(imgHeight * ratio);
try {
imagePre = Bitmap.createScaledBitmap(imagePre, width, height, true);
} catch (Exception e) {
Log.d(cgSettings.tag, "cgHtmlImg.getDrawable: Failed to scale image");
return null;
}
} else {
width = imgWidth;
height = imgHeight;
}
final BitmapDrawable image = new BitmapDrawable(imagePre);
image.setBounds(new Rect(0, 0, width, height));
return image;
}
Aggregations