下面列出了javax.ws.rs.core.Response#hasEntity() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private InternalCoreferenceResponse sendRequest(WebTarget target, InternalCoreferenceRequest request) {
log.debug("Sending coreference request to {}", target.getUri().toString());
final Response response = target
.request(MediaType.APPLICATION_JSON_TYPE)
.accept(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE));
if (response.hasEntity()) {
if (response.getStatusInfo().getStatusCode() == Response.Status.OK.getStatusCode()) {
return response.readEntity(InternalCoreferenceResponse.class);
} else {
log.error(
"A request was sent, but the response code was '{}: {}'",
response.getStatusInfo().getStatusCode(),
response.getStatusInfo().getReasonPhrase());
}
} else {
log.error("The response has no entity.");
}
throw new RuntimeException("The response contained no content.");
}
@Test
public void ChainedResourcePerformanceLogTest() {
final Response response = ClientRequestUtils.propagate(target("testchainedresource").request(), null).get();
if (response.hasEntity()) {
String res = response.readEntity(String.class);
res.length();
}
/*
* There should be at least two messages, but there might be more if
* LogContext reports correlation id generation
*
*/
assertThat(getLogSize(), greaterThanOrEqualTo(2));
assertThat(response.getStatus(), is(200));
/*
* -- correlation id should have been propagated
*/
Set<String> correlationIds = new HashSet<String>();
for (int i = 0; i < getLogSize(); i++) {
String id = getField(Fields.CORRELATION_ID, i);
assertThat(id, not(Defaults.UNKNOWN));
correlationIds.add(id);
}
assertThat(correlationIds.size(), is(1));
assertThat(getField(Fields.TENANT_ID), is(Defaults.UNKNOWN));
}
private <T> T call(
String methodName,
String path,
MultivaluedMap<String, Object> headers,
Map<String, String> queryParams,
Object payload,
String contentType,
Class<T> entityType) throws Exception
{
Response res = call(methodName, path, headers, queryParams, payload, contentType);
if(!res.hasEntity())
{
return null;
}
return (T) res.readEntity(entityType);
}
private boolean checkReply(Response response) {
if (response != null) {
boolean statusCode = checkStatusCode(response.getStatus());
if (!statusCode && response.hasEntity()) {
log.error("Failed request, HTTP error msg : " + response.readEntity(String.class));
}
return statusCode;
}
log.error("Null reply from device");
return false;
}
protected void assertErrror(Response response, String error) {
if (!response.hasEntity()) {
fail("No error message set");
}
ErrorRepresentation errorRepresentation = response.readEntity(ErrorRepresentation.class);
assertEquals(error, errorRepresentation.getErrorMessage());
response.close();
}
protected void assertErrror(Response response, String error) {
if (!response.hasEntity()) {
fail("No error message set");
}
ErrorRepresentation errorRepresentation = response.readEntity(ErrorRepresentation.class);
assertEquals(error, errorRepresentation.getErrorMessage());
}
private static boolean hasNotBeenSaved(final Response response) {
response.bufferEntity();
if ((UNPROCESSABLE_ENTITY_STATUS_CODE == response.getStatus()) && response.hasEntity()) {
final String shopifyErrorResponse = response.readEntity(String.class);
LOGGER.debug(shopifyErrorResponse);
return shopifyErrorResponse.contains(COULD_NOT_BE_SAVED_SHOPIFY_ERROR_MESSAGE);
}
return false;
}
private void assertError(Response response, String error) {
if (!response.hasEntity()) {
fail("No error message set");
}
ErrorRepresentation errorRepresentation = response.readEntity(ErrorRepresentation.class);
assertEquals(error, errorRepresentation.getErrorMessage());
}
public <T> T post(DeviceId device, String request, InputStream payload, MediaType mediaType,
Class<T> responseClass) {
Response response = getResponse(request, payload, mediaType);
if (response != null && response.hasEntity()) {
// Do not read the entity if the responseClass is of type Response. This would allow the
// caller to receive the Response directly and try to read its appropriate entity locally.
return responseClass == Response.class ? (T) response : response.readEntity(responseClass);
}
log.error("Response from device {} for request {} contains no entity", device, request);
return null;
}
private boolean checkReply(Response response) {
if (response != null) {
boolean statusCode = checkStatusCode(response.getStatus());
if (!statusCode && response.hasEntity()) {
log.error("Failed request, HTTP error msg : " + response.readEntity(String.class));
}
return statusCode;
}
log.error("Null reply from device");
return false;
}
/**
* Deserialize response body to Java object according to the Content-Type.
*/
private <T> T deserialize(Response response, TypeRef returnType) throws ApiException {
String contentType = null;
List<Object> contentTypes = response.getHeaders().get("Content-Type");
if (contentTypes != null && !contentTypes.isEmpty()) {
contentType = (String)contentTypes.get(0);
}
if (contentType == null) {
throw new ApiException(500, "missing Content-Type in response");
}
if (contentType.startsWith("application/json")) {
String body;
if (response.hasEntity()) {
body = response.readEntity(String.class);
} else {
body = "";
}
if (body.length() > 0) {
return json.deserialize(body, returnType);
}
return null;
} if (contentType.startsWith("image")) {
return (T) response.readEntity(InputStream.class);
} else {
throw new ApiException(500, "can not deserialize Content-Type: " + contentType);
}
}
@SuppressWarnings({"unchecked"})
private void handleWebApplicationException(WebApplicationException webApplicationException, GenericContainerResponse response) {
LOG.debug("WebApplicationException occurs", webApplicationException);
ErrorPages errorPages = (ErrorPages)EnvironmentContext.getCurrent().get(ErrorPages.class);
Response errorResponse = webApplicationException.getResponse();
int errorStatus = errorResponse.getStatus();
Throwable cause = webApplicationException.getCause();
propagateErrorIfHaveErrorPage(webApplicationException, errorPages);
propagateErrorIfHaveErrorPage(cause, errorPages);
propagateErrorIfHaveErrorPage(errorStatus, errorPages);
if (Tracer.isTracingEnabled()) {
Tracer.trace("WebApplicationException occurs, cause = (%s)", cause);
}
if (errorResponse.hasEntity()) {
setupInternalResponseHeaders(errorStatus, errorResponse.getMetadata());
} else {
ExceptionMapper exceptionMapper = providers.getExceptionMapper(WebApplicationException.class);
if (exceptionMapper != null) {
if (Tracer.isTracingEnabled()) {
Tracer.trace("Found ExceptionMapper for WebApplicationException = (%s)", exceptionMapper);
}
errorResponse = exceptionMapper.toResponse(webApplicationException);
} else if (cause != null) {
if (isNullOrEmpty(cause.getMessage())) {
errorResponse = createErrorResponse(errorStatus, cause.toString());
} else {
errorResponse = createErrorResponse(errorStatus, cause.getMessage());
}
} else if (!isNullOrEmpty(webApplicationException.getMessage())) {
errorResponse = createErrorResponse(errorStatus, webApplicationException.getMessage());
}
}
response.setResponse(errorResponse);
}
/**
* Deserializes a {@link Response} object to POJO of some type.
* @param <T> type
* @param res response
* @param type the type to convert to
* @return a POJO
* @throws WebApplicationException exception on HTTP error response
*/
@SuppressWarnings("unchecked")
public <T> T getEntity(Response res, Class<?> type) throws WebApplicationException {
if (res != null) {
if (res.getStatus() == Response.Status.OK.getStatusCode()
|| res.getStatus() == Response.Status.CREATED.getStatusCode()
|| res.getStatus() == Response.Status.NOT_MODIFIED.getStatusCode()) {
return res.hasEntity() ? res.readEntity((Class<T>) type) : null;
} else if (res.getStatus() != Response.Status.NOT_FOUND.getStatusCode()
&& res.getStatus() != Response.Status.NOT_MODIFIED.getStatusCode()
&& res.getStatus() != Response.Status.NO_CONTENT.getStatusCode()) {
Map<String, Object> error = res.hasEntity() ? res.readEntity(Map.class) : null;
if (error != null && error.containsKey("code")) {
String msg = error.containsKey("message") ? (String) error.get("message") : "error";
WebApplicationException e = new WebApplicationException(msg, (Integer) error.get("code"));
logger.error("{} - {}", error.get("code"), e.getMessage());
if (throwExceptionOnHTTPError) {
throw e;
}
} else {
logger.error("{} - {}", res.getStatus(), res.getStatusInfo().getReasonPhrase());
if (throwExceptionOnHTTPError) {
throw new WebApplicationException(res.getStatusInfo().getReasonPhrase(), res.getStatus());
}
}
}
}
return null;
}
@Test(expected = IllegalStateException.class)
public void testHasEntityAfterClose() {
Response r = new ResponseImpl(200, new ByteArrayInputStream("data".getBytes()));
assertTrue(r.hasEntity());
r.close();
r.hasEntity();
}
protected void assertErrror(Response response, String error) {
if (!response.hasEntity()) {
fail("No error message set");
}
ErrorRepresentation errorRepresentation = response.readEntity(ErrorRepresentation.class);
assertEquals(error, errorRepresentation.getErrorMessage());
response.close();
}
@Override
public void onTrigger(final ReportingContext context) {
final String metricsCollectorUrl = context.getProperty(METRICS_COLLECTOR_URL).evaluateAttributeExpressions().getValue();
final String applicationId = context.getProperty(APPLICATION_ID).evaluateAttributeExpressions().getValue();
final String hostname = context.getProperty(HOSTNAME).evaluateAttributeExpressions().getValue();
final boolean pgIdIsSet = context.getProperty(PROCESS_GROUP_ID).isSet();
final String processGroupId = pgIdIsSet ? context.getProperty(PROCESS_GROUP_ID).evaluateAttributeExpressions().getValue() : null;
final long start = System.currentTimeMillis();
// send the metrics from last execution
if (previousMetrics != null) {
final WebTarget metricsTarget = client.target(metricsCollectorUrl);
final Invocation.Builder invocation = metricsTarget.request();
final Entity<String> entity = Entity.json(previousMetrics.toString());
getLogger().debug("Sending metrics {} to Ambari", new Object[]{entity.getEntity()});
final Response response = invocation.post(entity);
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
final long completedMillis = TimeUnit.NANOSECONDS.toMillis(System.currentTimeMillis() - start);
getLogger().info("Successfully sent metrics to Ambari in {} ms", new Object[]{completedMillis});
} else {
final String responseEntity = response.hasEntity() ? response.readEntity(String.class) : "unknown error";
getLogger().error("Error sending metrics to Ambari due to {} - {}", new Object[]{response.getStatus(), responseEntity});
}
}
// calculate the current metrics, but store them to be sent next time
final ProcessGroupStatus status = processGroupId == null ? context.getEventAccess().getControllerStatus() : context.getEventAccess().getGroupStatus(processGroupId);
if(status != null) {
final Map<String,String> statusMetrics = metricsService.getMetrics(status, pgIdIsSet);
final Map<String,String> jvmMetrics = metricsService.getMetrics(virtualMachineMetrics);
final MetricsBuilder metricsBuilder = new MetricsBuilder(factory);
final JsonObject metricsObject = metricsBuilder
.applicationId(applicationId)
.instanceId(status.getId())
.hostname(hostname)
.timestamp(start)
.addAllMetrics(statusMetrics)
.addAllMetrics(jvmMetrics)
.build();
previousMetrics = metricsObject;
} else {
getLogger().error("No process group status with ID = {}", new Object[]{processGroupId});
previousMetrics = null;
}
}
@Override
public void onTrigger(final ReportingContext context) {
final String metricsCollectorUrl = context.getProperty(METRICS_COLLECTOR_URL).evaluateAttributeExpressions().getValue();
final String applicationId = context.getProperty(APPLICATION_ID).evaluateAttributeExpressions().getValue();
final String hostname = context.getProperty(HOSTNAME).evaluateAttributeExpressions().getValue();
final boolean pgIdIsSet = context.getProperty(PROCESS_GROUP_ID).isSet();
final String processGroupId = pgIdIsSet ? context.getProperty(PROCESS_GROUP_ID).evaluateAttributeExpressions().getValue() : null;
final long start = System.currentTimeMillis();
// send the metrics from last execution
if (previousMetrics != null) {
final WebTarget metricsTarget = client.target(metricsCollectorUrl);
final Invocation.Builder invocation = metricsTarget.request();
final Entity<String> entity = Entity.json(previousMetrics.toString());
getLogger().debug("Sending metrics {} to Ambari", new Object[]{entity.getEntity()});
final Response response = invocation.post(entity);
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
final long completedMillis = TimeUnit.NANOSECONDS.toMillis(System.currentTimeMillis() - start);
getLogger().info("Successfully sent metrics to Ambari in {} ms", new Object[]{completedMillis});
} else {
final String responseEntity = response.hasEntity() ? response.readEntity(String.class) : "unknown error";
getLogger().error("Error sending metrics to Ambari due to {} - {}", new Object[]{response.getStatus(), responseEntity});
}
}
// calculate the current metrics, but store them to be sent next time
final ProcessGroupStatus status = processGroupId == null ? context.getEventAccess().getControllerStatus() : context.getEventAccess().getGroupStatus(processGroupId);
if(status != null) {
final Map<String,String> statusMetrics = metricsService.getMetrics(status, pgIdIsSet);
final Map<String,String> jvmMetrics = metricsService.getMetrics(virtualMachineMetrics);
final MetricsBuilder metricsBuilder = new MetricsBuilder(factory);
final JsonObject metricsObject = metricsBuilder
.applicationId(applicationId)
.instanceId(status.getId())
.hostname(hostname)
.timestamp(start)
.addAllMetrics(statusMetrics)
.addAllMetrics(jvmMetrics)
.build();
previousMetrics = metricsObject;
} else {
getLogger().error("No process group status with ID = {}", new Object[]{processGroupId});
previousMetrics = null;
}
}
/**
* Invoke API by sending HTTP request with the given options.
*
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "POST", "PUT", and "DELETE"
* @param queryParams The query parameters
* @param body The request body object - if it is not binary, otherwise null
* @param binaryBody The request body object - if it is binary, otherwise null
* @param headerParams The header parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
* @param authNames The authentications to apply
* @return The response body in type of string
*/
public <T> T invokeAPI(String path, String method, List<Pair> queryParams, Object body, byte[] binaryBody,
Map<String, String> headerParams, Map<String, Object> formParams, String accept,
String contentType, String[] authNames, TypeRef returnType) throws ApiException {
Response response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams,
accept, contentType, authNames);
statusCode = response.getStatusInfo().getStatusCode();
responseHeaders = response.getHeaders();
if (statusCode == 401) {
throw new ApiException(
response.getStatusInfo().getStatusCode(),
"HTTP Error 401 - Unauthorized: Access is denied due to invalid credentials.",
response.getHeaders(),
null);
} else if (response.getStatusInfo() == Response.Status.NO_CONTENT) {
return null;
} else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) {
if (returnType == null)
return null;
else
return deserialize(response, returnType);
} else {
String message = "error";
String respBody = null;
if (response.hasEntity()) {
try {
respBody = response.readEntity(String.class);
message = respBody;
} catch (RuntimeException e) {
// e.printStackTrace();
}
}
throw new ApiException(
response.getStatusInfo().getStatusCode(),
message,
response.getHeaders(),
respBody);
}
}
@Override
public ServicePolicies getServicePoliciesIfUpdated(final long lastKnownVersion, final long lastActivationTimeInMillis) throws Exception {
if(LOG.isDebugEnabled()) {
LOG.debug("==> RangerAdminJersey2RESTClient.getServicePoliciesIfUpdated(" + lastKnownVersion + ", " + lastActivationTimeInMillis + ")");
}
UserGroupInformation user = MiscUtil.getUGILoginUser();
boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();
String relativeURL = null;
ServicePolicies servicePolicies = null;
Response response = null;
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put(RangerRESTUtils.REST_PARAM_LAST_KNOWN_POLICY_VERSION, Long.toString(lastKnownVersion));
queryParams.put(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME, Long.toString(lastActivationTimeInMillis));
queryParams.put(RangerRESTUtils.REST_PARAM_PLUGIN_ID, _pluginId);
queryParams.put(RangerRESTUtils.REST_PARAM_CLUSTER_NAME, _clusterName);
queryParams.put(RangerRESTUtils.REST_PARAM_SUPPORTS_POLICY_DELTAS, _supportsPolicyDeltas);
queryParams.put(RangerRESTUtils.REST_PARAM_CAPABILITIES, pluginCapabilities);
if (isSecureMode) {
if (LOG.isDebugEnabled()) {
LOG.debug("Checking Service policy if updated as user : " + user);
}
relativeURL = RangerRESTUtils.REST_URL_POLICY_GET_FOR_SECURE_SERVICE_IF_UPDATED + _serviceName;
final String secureRelativeUrl = relativeURL;
PrivilegedAction<Response> action = new PrivilegedAction<Response>() {
public Response run() {
return get(queryParams, secureRelativeUrl);
}
};
response = user.doAs(action);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Checking Service policy if updated with old api call");
}
relativeURL = RangerRESTUtils.REST_URL_POLICY_GET_FOR_SERVICE_IF_UPDATED + _serviceName;
response = get(queryParams, relativeURL);
}
int httpResponseCode = response == null ? -1 : response.getStatus();
String body = null;
switch (httpResponseCode) {
case 200:
body = response.readEntity(String.class);
if (LOG.isDebugEnabled()) {
LOG.debug("Response from 200 server: " + body);
}
Gson gson = getGson();
servicePolicies = gson.fromJson(body, ServicePolicies.class);
if (LOG.isDebugEnabled()) {
LOG.debug("Deserialized response to: " + servicePolicies);
}
break;
case 304:
LOG.debug("Got response: 304. Ok. Returning null");
break;
case -1:
LOG.warn("Unexpected: Null response from policy server while trying to get policies! Returning null!");
break;
case 404: {
if (response.hasEntity()) {
body = response.readEntity(String.class);
if (StringUtils.isNotBlank(body)) {
RangerServiceNotFoundException.throwExceptionIfServiceNotFound(_serviceName, body);
}
}
LOG.warn("Received 404 error code with body:[" + body + "], Ignoring");
break;
}
default:
body = response.readEntity(String.class);
LOG.warn(String.format("Unexpected: Received status[%d] with body[%s] form url[%s]", httpResponseCode, body, relativeURL));
break;
}
if(LOG.isDebugEnabled()) {
LOG.debug("<== RangerAdminJersey2RESTClient.getServicePoliciesIfUpdated(" + lastKnownVersion + ", " + lastActivationTimeInMillis + "): " + servicePolicies);
}
return servicePolicies;
}
@Override
public ServiceTags getServiceTagsIfUpdated(final long lastKnownVersion, final long lastActivationTimeInMillis) throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("==> RangerAdminJersey2RESTClient.getServiceTagsIfUpdated(" + lastKnownVersion + ", " + lastActivationTimeInMillis + ")");
}
UserGroupInformation user = MiscUtil.getUGILoginUser();
boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put(RangerRESTUtils.REST_PARAM_LAST_KNOWN_POLICY_VERSION, Long.toString(lastKnownVersion));
queryParams.put(RangerRESTUtils.REST_PARAM_LAST_ACTIVATION_TIME, Long.toString(lastActivationTimeInMillis));
queryParams.put(RangerRESTUtils.REST_PARAM_PLUGIN_ID, _pluginId);
queryParams.put(RangerRESTUtils.REST_PARAM_SUPPORTS_TAG_DELTAS, _supportsTagDeltas);
queryParams.put(RangerRESTUtils.REST_PARAM_CAPABILITIES, pluginCapabilities);
String relativeURL = null;
ServiceTags serviceTags = null;
Response response = null;
if (isSecureMode) {
if (LOG.isDebugEnabled()) {
LOG.debug("Checking Service tags if updated as user : " + user);
}
relativeURL = RangerRESTUtils.REST_URL_GET_SECURE_SERVICE_TAGS_IF_UPDATED + _serviceName;
final String secureRelativeURLUrl = relativeURL;
PrivilegedAction<Response> action = new PrivilegedAction<Response>() {
public Response run() {
return get(queryParams, secureRelativeURLUrl);
}
};
response = user.doAs(action);
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Checking Service tags if updated with old api call");
}
relativeURL = RangerRESTUtils.REST_URL_GET_SERVICE_TAGS_IF_UPDATED + _serviceName;
response = get(queryParams, relativeURL);
}
int httpResponseCode = response == null ? -1 : response.getStatus();
String body = null;
switch (httpResponseCode) {
case 200:
body = response.readEntity(String.class);
if (LOG.isDebugEnabled()) {
LOG.debug("Response from 200 server: " + body);
}
Gson gson = getGson();
serviceTags = gson.fromJson(body, ServiceTags.class);
if (LOG.isDebugEnabled()) {
LOG.debug("Deserialized response to: " + serviceTags);
}
break;
case 304:
LOG.debug("Got response: 304. Ok. Returning null");
break;
case -1:
LOG.warn("Unexpected: Null response from tag server while trying to get tags! Returning null!");
break;
case 404:
if (response.hasEntity()) {
body = response.readEntity(String.class);
if (StringUtils.isNotBlank(body)) {
RangerServiceNotFoundException.throwExceptionIfServiceNotFound(_serviceName, body);
}
}
LOG.warn("Received 404 error code with body:[" + body + "], Ignoring");
break;
default:
body = response.readEntity(String.class);
LOG.warn(String.format("Unexpected: Received status[%d] with body[%s] form url[%s]", httpResponseCode, body, relativeURL));
break;
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== RangerAdminJersey2RESTClient.getServiceTagsIfUpdated(" + lastKnownVersion + ", " + lastActivationTimeInMillis + "): " + serviceTags);
}
return serviceTags;
}