下面列出了怎么用org.apache.http.entity.BufferedHttpEntity的API类实例代码及写法,或者点击链接到github查看源代码。
private void configureSolrClientsForKerberos() throws PermanentBackendException {
String kerberosConfig = System.getProperty("java.security.auth.login.config");
if(kerberosConfig == null) {
throw new PermanentBackendException("Unable to configure kerberos for solr client. System property 'java.security.auth.login.config' is not set.");
}
logger.debug("Using kerberos configuration file located at '{}'.", kerberosConfig);
try(Krb5HttpClientBuilder krbBuild = new Krb5HttpClientBuilder()) {
SolrHttpClientBuilder kb = krbBuild.getBuilder();
HttpClientUtil.setHttpClientBuilder(kb);
HttpRequestInterceptor bufferedEntityInterceptor = new HttpRequestInterceptor() {
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
if(request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest enclosingRequest = ((HttpEntityEnclosingRequest) request);
HttpEntity requestEntity = enclosingRequest.getEntity();
enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity));
}
}
};
HttpClientUtil.addRequestInterceptor(bufferedEntityInterceptor);
HttpRequestInterceptor preemptiveAuth = new PreemptiveAuth(new KerberosScheme());
HttpClientUtil.addRequestInterceptor(preemptiveAuth);
}
}
/**
* Checks for specific outbound response codes/content to trigger a retry or failover
*/
@Override
protected void writeOutboundResponse(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse) throws IOException {
if (inboundResponse.getStatusLine().getStatusCode() == 403) {
BufferedHttpEntity entity = new BufferedHttpEntity(inboundResponse.getEntity());
inboundResponse.setEntity(entity);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
inboundResponse.getEntity().writeTo(outputStream);
String body = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
if (body.contains("StandbyException")) {
throw new StandbyException();
}
if (body.contains("SafeModeException") || body.contains("RetriableException")) {
throw new SafeModeException();
}
}
super.writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
}
/**
* Checks for specific outbound response codes/content to trigger a retry or failover
*/
@Override
protected void writeOutboundResponse(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse, HttpResponse inboundResponse) throws IOException {
int status = inboundResponse.getStatusLine().getStatusCode();
if ( status == 403 || status == 307) {
BufferedHttpEntity entity = new BufferedHttpEntity(inboundResponse.getEntity());
inboundResponse.setEntity(entity);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
inboundResponse.getEntity().writeTo(outputStream);
String body = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
if (body.contains("This is standby RM")) {
throw new StandbyException();
}
}
super.writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
}
/**
* <p>Test for a {@link Request} with a <b>buffered</b> entity.</p>
*
* @since 1.3.0
*/
@Test
public final void testBufferedHttpEntity() throws ParseException, IOException {
Robolectric.getFakeHttpLayer().interceptHttpRequests(false);
String subpath = "/bufferedhttpentity";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("LICENSE.txt");
InputStream parallelInputStream = classLoader.getResourceAsStream("LICENSE.txt");
BasicHttpEntity bhe = new BasicHttpEntity();
bhe.setContent(parallelInputStream);
stubFor(put(urlEqualTo(subpath))
.willReturn(aResponse()
.withStatus(200)));
requestEndpoint.bufferedHttpEntity(inputStream);
verify(putRequestedFor(urlEqualTo(subpath))
.withRequestBody(equalTo(EntityUtils.toString(new BufferedHttpEntity(bhe)))));
}
private byte[] serializeContent(HttpRequest request) {
if (!(request instanceof HttpEntityEnclosingRequest)) {
return new byte[]{};
}
final HttpEntityEnclosingRequest entityWithRequest = (HttpEntityEnclosingRequest) request;
HttpEntity entity = entityWithRequest.getEntity();
if (entity == null) {
return new byte[]{};
}
try {
// Buffer non-repeatable entities
if (!entity.isRepeatable()) {
entityWithRequest.setEntity(new BufferedHttpEntity(entity));
}
return EntityUtils.toByteArray(entityWithRequest.getEntity());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
protected void convertToRepeatableResponseEntity(CloseableHttpResponse response)
throws IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
response.setEntity(new BufferedHttpEntity(entity));
}
}
protected void convertToRepeatableRequestEntity(HttpRequestWrapper request) throws IOException {
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
if (entity != null) {
((HttpEntityEnclosingRequest) request).setEntity(new BufferedHttpEntity(entity));
}
}
}
private HttpResponse sendRequest(HttpRequest request, HttpRequestBase httpRequestBase) throws IOException {
prepare(request, httpRequestBase);
CloseableHttpResponse response = httpClient.execute(httpRequestBase);
if (response.getEntity() != null) {
response.setEntity(new BufferedHttpEntity(response.getEntity()));
EntityUtils.consume(response.getEntity());
}
return new HttpClientResponse(response);
}
private HttpResponse sendMultiPartRequest(HttpRequest request, HttpRequestBase httpRequestBase) throws IOException {
prepare(request, httpRequestBase);
CloseableHttpClient httpClient = null;
try {
httpClient = createHttpClient();
CloseableHttpResponse response = httpClient.execute(httpRequestBase);
response.setEntity(new BufferedHttpEntity(response.getEntity()));
EntityUtils.consume(response.getEntity());
return new HttpClientResponse(response);
} finally {
if (httpClient != null) {
httpClient.close();
}
}
}
protected void sendResponseMessage(HttpResponse response) {
Throwable e;
StatusLine status = response.getStatusLine();
String responseBody = null;
try {
HttpEntity temp = response.getEntity();
if (temp != null) {
HttpEntity entity = new BufferedHttpEntity(temp);
try {
responseBody = EntityUtils.toString(entity, "UTF-8");
} catch (IOException e2) {
e = e2;
HttpEntity httpEntity = entity;
sendFailureMessage(e, null);
if (status.getStatusCode() >= 300) {
sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
} else {
sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
}
}
}
} catch (IOException e3) {
e = e3;
sendFailureMessage(e, null);
if (status.getStatusCode() >= 300) {
sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
} else {
sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
}
}
if (status.getStatusCode() >= 300) {
sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
} else {
sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody);
}
}
/**
* Utility function for creating a new BufferedEntity and wrapping any errors
* as a SdkClientException.
*
* @param entity The HTTP entity to wrap with a buffered HTTP entity.
* @return A new BufferedHttpEntity wrapping the specified entity.
*/
public static HttpEntity newBufferedHttpEntity(HttpEntity entity) {
try {
return new BufferedHttpEntity(entity);
} catch (IOException e) {
throw new UncheckedIOException("Unable to create HTTP entity: " + e.getMessage(), e);
}
}
private String sendHttpPostRequest(HttpPost httpPost) throws IOException {
try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
HttpEntity httpEntity = response.getEntity();
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpEntity);
return EntityUtils.toString(bufferedHttpEntity, StandardCharsets.UTF_8);
}
}
@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
HttpGet httpRequest = new HttpGet(imageUri);
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
return bufHttpEntity.getContent();
}
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request;
HttpEntity requestEntity = enclosingRequest.getEntity();
enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity));
}
}
/**
* Fetch the directions
*
* @param origin Origin address
* @param destination Destination address
* @return Destinations
*/
public List<String> getDirections(String origin, String destination, String language) {
final List<String> responseToUser = new ArrayList<>();
try {
String completURL = BASEURL + "?origin=" + getQuery(origin) + "&destination=" +
getQuery(destination) + PARAMS.replace("@[email protected]", language) + APIIDEND;
HttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completURL);
HttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseContent);
if (jsonObject.getString("status").equals("OK")) {
JSONObject route = jsonObject.getJSONArray("routes").getJSONObject(0);
String startOfAddress = LocalisationService.getString("directionsInit", language);
String partialResponseToUser = String.format(startOfAddress,
route.getJSONArray("legs").getJSONObject(0).getString("start_address"),
route.getJSONArray("legs").getJSONObject(0).getJSONObject("distance").getString("text"),
route.getJSONArray("legs").getJSONObject(0).getString("end_address"),
route.getJSONArray("legs").getJSONObject(0).getJSONObject("duration").getString("text")
);
responseToUser.add(partialResponseToUser);
responseToUser.addAll(getDirectionsSteps(
route.getJSONArray("legs").getJSONObject(0).getJSONArray("steps"), language));
} else {
responseToUser.add(LocalisationService.getString("directionsNotFound", language));
}
} catch (Exception e) {
BotLogger.warn(LOGTAG, e);
responseToUser.add(LocalisationService.getString("errorFetchingDirections", language));
}
return responseToUser;
}
/**
* Fetch the weather of a city for one day
*
* @param cityId City to get the weather
* @return userHash to be send to use
* @note Forecast for the day
*/
public String fetchWeatherAlert(int cityId, int userId, String language, String units) {
String cityFound;
String responseToUser;
try {
String completURL = BASEURL + FORECASTPATH + "?" + getCityQuery(cityId + "") +
ALERTPARAMS.replace("@[email protected]", language).replace("@[email protected]", units) + APIIDEND;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completURL);
CloseableHttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseString);
BotLogger.info(LOGTAG, jsonObject.toString());
if (jsonObject.getInt("cod") == 200) {
cityFound = jsonObject.getJSONObject("city").getString("name") + " (" +
jsonObject.getJSONObject("city").getString("country") + ")";
saveRecentWeather(userId, cityFound, jsonObject.getJSONObject("city").getInt("id"));
responseToUser = String.format(LocalisationService.getString("weatherAlert", language),
cityFound, convertListOfForecastToString(jsonObject, language, units, false));
} else {
BotLogger.warn(LOGTAG, jsonObject.toString());
responseToUser = LocalisationService.getString("cityNotFound", language);
}
} catch (Exception e) {
BotLogger.error(LOGTAG, e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
return responseToUser;
}
/**
* Fetch the weather of a city
*
* @param city City to get the weather
* @return userHash to be send to use
* @note Forecast for the following 3 days
*/
public String fetchWeatherForecast(String city, Integer userId, String language, String units) {
String cityFound;
String responseToUser;
try {
String completURL = BASEURL + FORECASTPATH + "?" + getCityQuery(city) +
FORECASTPARAMS.replace("@[email protected]", language).replace("@[email protected]", units) + APIIDEND;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completURL);
CloseableHttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseString);
BotLogger.info(LOGTAG, jsonObject.toString());
if (jsonObject.getInt("cod") == 200) {
cityFound = jsonObject.getJSONObject("city").getString("name") + " (" +
jsonObject.getJSONObject("city").getString("country") + ")";
saveRecentWeather(userId, cityFound, jsonObject.getJSONObject("city").getInt("id"));
responseToUser = String.format(LocalisationService.getString("weatherForcast", language),
cityFound, convertListOfForecastToString(jsonObject, language, units, true));
} else {
BotLogger.warn(LOGTAG, jsonObject.toString());
responseToUser = LocalisationService.getString("cityNotFound", language);
}
} catch (Exception e) {
BotLogger.error(LOGTAG, e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
return responseToUser;
}
/**
* Fetch the weather of a city
*
* @return userHash to be send to use
* @note Forecast for the following 3 days
*/
public String fetchWeatherForecastByLocation(Float longitude, Float latitude, Integer userId, String language, String units) {
String cityFound;
String responseToUser;
try {
String completURL = BASEURL + FORECASTPATH + "?lat=" + URLEncoder.encode(latitude + "", "UTF-8") + "&lon="
+ URLEncoder.encode(longitude + "", "UTF-8") +
FORECASTPARAMS.replace("@[email protected]", language).replace("@[email protected]", units) + APIIDEND;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completURL);
CloseableHttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseString);
if (jsonObject.getInt("cod") == 200) {
cityFound = jsonObject.getJSONObject("city").getString("name") + " (" +
jsonObject.getJSONObject("city").getString("country") + ")";
saveRecentWeather(userId, cityFound, jsonObject.getJSONObject("city").getInt("id"));
responseToUser = String.format(LocalisationService.getString("weatherForcast", language),
cityFound, convertListOfForecastToString(jsonObject, language, units, true));
} else {
BotLogger.warn(LOGTAG, jsonObject.toString());
responseToUser = LocalisationService.getString("cityNotFound", language);
}
} catch (Exception e) {
BotLogger.error(LOGTAG, e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
return responseToUser;
}
/**
* Fetch the weather of a city
*
* @param city City to get the weather
* @return userHash to be send to use
* @note Forecast for the following 3 days
*/
public String fetchWeatherCurrent(String city, Integer userId, String language, String units) {
String cityFound;
String responseToUser;
Emoji emoji = null;
try {
String completURL = BASEURL + CURRENTPATH + "?" + getCityQuery(city) +
CURRENTPARAMS.replace("@[email protected]", language).replace("@[email protected]", units) + APIIDEND;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completURL);
CloseableHttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseString);
if (jsonObject.getInt("cod") == 200) {
cityFound = jsonObject.getString("name") + " (" +
jsonObject.getJSONObject("sys").getString("country") + ")";
saveRecentWeather(userId, cityFound, jsonObject.getInt("id"));
emoji = getEmojiForWeather(jsonObject.getJSONArray("weather").getJSONObject(0));
responseToUser = String.format(LocalisationService.getString("weatherCurrent", language),
cityFound, convertCurrentWeatherToString(jsonObject, language, units, emoji));
} else {
BotLogger.warn(LOGTAG, jsonObject.toString());
responseToUser = LocalisationService.getString("cityNotFound", language);
}
} catch (Exception e) {
BotLogger.error(LOGTAG, e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
return responseToUser;
}
/**
* Fetch the weather of a city
*
* @return userHash to be send to use
* @note Forecast for the following 3 days
*/
public String fetchWeatherCurrentByLocation(Float longitude, Float latitude, Integer userId, String language, String units) {
String cityFound;
String responseToUser;
try {
String completURL = BASEURL + CURRENTPATH + "?lat=" + URLEncoder.encode(latitude + "", "UTF-8") + "&lon="
+ URLEncoder.encode(longitude + "", "UTF-8") +
CURRENTPARAMS.replace("@[email protected]", language).replace("@[email protected]", units) + APIIDEND;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completURL);
CloseableHttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8");
JSONObject jsonObject = new JSONObject(responseString);
if (jsonObject.getInt("cod") == 200) {
cityFound = jsonObject.getString("name") + " (" +
jsonObject.getJSONObject("sys").getString("country") + ")";
saveRecentWeather(userId, cityFound, jsonObject.getInt("id"));
responseToUser = String.format(LocalisationService.getString("weatherCurrent", language),
cityFound, convertCurrentWeatherToString(jsonObject, language, units, null));
} else {
BotLogger.warn(LOGTAG, jsonObject.toString());
responseToUser = LocalisationService.getString("cityNotFound", language);
}
} catch (Exception e) {
BotLogger.error(LOGTAG, e);
responseToUser = LocalisationService.getString("errorFetchingWeather", language);
}
return responseToUser;
}
public List<RaeResult> getResults(String query) {
List<RaeResult> results = new ArrayList<>();
String completeURL;
try {
completeURL = BASEURL + SEARCHEXACTURL + URLEncoder.encode(query, "UTF-8");
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completeURL);
CloseableHttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8");
Document document = Jsoup.parse(responseString);
Element article = document.getElementsByTag("article").first();
String articleId = null;
if (article != null) {
articleId = article.attributes().get("id");
}
Elements elements = document.select(".j");
if (elements.isEmpty()) {
results = getResultsWordSearch(query);
} else {
results = getResultsFromExactMatch(elements, query, articleId);
}
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
}
return results;
}
private List<RaeResult> getResultsWordSearch(String query) {
List<RaeResult> results = new ArrayList<>();
String completeURL;
try {
completeURL = BASEURL + SEARCHWORDURL + URLEncoder.encode(query, "UTF-8");
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completeURL);
CloseableHttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8");
Document document = Jsoup.parse(responseString);
Element list = document.select("body div ul").first();
if (list != null) {
Elements links = list.getElementsByTag("a");
if (!links.isEmpty()) {
for (Element link : links) {
List<RaeResult> partialResults = fetchWord(URLEncoder.encode(link.attributes().get("href"), "UTF-8"), link.text());
if (!partialResults.isEmpty()) {
results.addAll(partialResults);
}
}
}
}
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
}
return results;
}
private List<RaeResult> fetchWord(String link, String word) {
List<RaeResult> results = new ArrayList<>();
String completeURL;
try {
completeURL = BASEURL + link;
CloseableHttpClient client = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
HttpGet request = new HttpGet(completeURL);
CloseableHttpResponse response = client.execute(request);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseString = EntityUtils.toString(buf, "UTF-8");
Document document = Jsoup.parse(responseString);
Element article = document.getElementsByTag("article").first();
String articleId = null;
if (article != null) {
articleId = article.attributes().get("id");
}
Elements elements = document.select(".j");
if (!elements.isEmpty()) {
results = getResultsFromExactMatch(elements, word, articleId);
}
} catch (IOException e) {
BotLogger.error(LOGTAG, e);
}
return results;
}
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException,
IOException {
if(request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest enclosingRequest = ((HttpEntityEnclosingRequest) request);
HttpEntity requestEntity = enclosingRequest.getEntity();
enclosingRequest.setEntity(new BufferedHttpEntity(requestEntity));
}
}
@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
HttpGet httpRequest = new HttpGet(imageUri);
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
return bufHttpEntity.getContent();
}
private BufferedHttpEntity buffered(HttpEntity entity) {
try {
return new BufferedHttpEntity(entity);
} catch (IOException e) {
throw new RamlCheckerException("Could not read content of entity", e);
}
}
@Override
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
HttpGet httpRequest = new HttpGet(imageUri);
HttpResponse response = httpClient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
return bufHttpEntity.getContent();
}
/**
* <p>Discovers the {@link HttpEntity} which is suitable for wrapping an instance of the given {@link Class}.
* This discovery proceeds in the following order by checking the provided generic type:</p>
*
* <ol>
* <li>org.apache.http.{@link HttpEntity} --> returned as-is.</li>
* <li>{@code byte[]}, {@link Byte}[] --> {@link ByteArrayEntity}</li>
* <li>java.io.{@link File} --> {@link FileEntity}</li>
* <li>java.io.{@link InputStream} --> {@link BufferedHttpEntity}</li>
* <li>{@link CharSequence} --> {@link StringEntity}</li>
* <li>java.io.{@link Serializable} --> {@link SerializableEntity} (with an internal buffer)</li>
* </ol>
*
* @param genericType
* a generic {@link Class} to be translated to an {@link HttpEntity} type
* <br><br>
* @return the {@link Class} of the translated {@link HttpEntity}
* <br><br>
* @throws NullPointerException
* if the supplied generic type was {@code null}
* <br><br>
* @throws EntityResolutionFailedException
* if the given generic {@link Class} failed to be translated to an {@link HttpEntity} type
* <br><br>
* @since 1.3.0
*/
public static final Class<?> resolve(Class<?> genericType) {
assertNotNull(genericType);
try {
Class<?> entityType = HttpEntity.class.isAssignableFrom(genericType)? HttpEntity.class :
(byte[].class.isAssignableFrom(genericType)
|| Byte[].class.isAssignableFrom(genericType))? ByteArrayEntity.class:
File.class.isAssignableFrom(genericType)? FileEntity.class :
InputStream.class.isAssignableFrom(genericType)? BufferedHttpEntity.class :
CharSequence.class.isAssignableFrom(genericType)? StringEntity.class :
Serializable.class.isAssignableFrom(genericType)? SerializableEntity.class: null;
if(entityType == null) {
throw new EntityResolutionFailedException(genericType);
}
return entityType;
}
catch(Exception e) {
throw (e instanceof EntityResolutionFailedException)?
(EntityResolutionFailedException)e :new EntityResolutionFailedException(genericType, e);
}
}
public SimpleResponse(final HttpResponse response) {
this.statusLine = response.getStatusLine();
this.statusCode = this.statusLine.getStatusCode();
final HttpEntity wrappedHttpEntity = response.getEntity();
if (wrappedHttpEntity != null) {
try {
this.entity = new BufferedHttpEntity(wrappedHttpEntity);
} catch (final IOException e) {
this.entity = null;
}
}
}
@Override
public void afterDoCap(InvokeChainContext context, Object[] args) {
if (UAVServer.instance().isExistSupportor("com.creditease.uav.apm.supporters.SlowOperSupporter")) {
Span span = (Span) context.get(InvokeChainConstants.PARAM_SPAN_KEY);
SlowOperContext slowOperContext = new SlowOperContext();
if (Throwable.class.isAssignableFrom(args[0].getClass())) {
Throwable e = (Throwable) args[0];
slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_EXCEPTION, e.toString());
}
else {
HttpResponse response = (HttpResponse) args[0];
slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_HEADER, getResponHeaders(response));
HttpEntity entity = response.getEntity();
if (entity != null) {
// 由于存在读取失败和无法缓存的大entity会使套壳失败,故此处添加如下判断
if (BufferedHttpEntity.class.isAssignableFrom(entity.getClass())) {
Header header = entity.getContentEncoding();
String encoding = header == null ? "utf-8" : header.getValue();
slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_BODY,
getHttpEntityContent(entity, encoding));
}
else {
slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_BODY,
"HttpEntityWrapper failed! Maybe HTTP entity too large to be buffered in memory");
}
}
else {
slowOperContext.put(SlowOperConstants.PROTOCOL_HTTP_BODY, "");
}
}
Object params[] = { span, slowOperContext };
UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.SlowOperSupporter", "runCap",
span.getEndpointInfo().split(",")[0], InvokeChainConstants.CapturePhase.DOCAP, context, params);
}
}