Java tutorial
/** * Copyright (C) 2013 Seajas, the Netherlands. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.seajas.search.contender.http; import java.io.IOException; import java.net.URI; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ResponseHandler; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Size-restricted HTTP client modifier response handler. * * @author Jasper van Veghel <jasper@seajas.com> */ public class SizeRestrictedResponseHandler implements ResponseHandler<SizeRestrictedHttpResponse> { /** * The logger. */ private static final Logger logger = LoggerFactory.getLogger(SizeRestrictedResponseHandler.class); /** * The maximum content length. */ private final long maximumContentLength; /** * The URI being retrieved (for logging purposes). */ private final URI uri; /** * Default constructor. * * @param maximumContentLength * @param uri */ public SizeRestrictedResponseHandler(final long maximumContentLength, final URI uri) { this.maximumContentLength = maximumContentLength; this.uri = uri; } /** * {@inheritDoc} */ @Override public SizeRestrictedHttpResponse handleResponse(final HttpResponse response) throws IOException { try { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { if (maximumContentLength > 0 && entity.getContentLength() > maximumContentLength) { logger.error("The given stream is too large to process - " + entity.getContentLength() + " > " + maximumContentLength); return null; } return new SizeRestrictedHttpResponse(response.getLastHeader("Content-Type"), EntityUtils.toByteArray(entity)); } else return null; } else { logger.error("Could not retrieve the given stream" + (uri != null ? " for URI '" + uri + "'" : "") + ", status = " + response.getStatusLine()); EntityUtils.consume(response.getEntity()); return null; } } catch (IOException e) { EntityUtils.consume(response.getEntity()); throw e; } } /** * Retrieve the URI. * * @return URI */ public URI getUri() { return uri; } }