下面列出了javax.servlet.http.HttpServletResponse#SC_NOT_MODIFIED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Performs a number of checks to ensure response saneness according to the rules of RFC2616:
* <ol>
* <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NO_CONTENT} then it is illegal for the body
* to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5
* <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NOT_MODIFIED} then it is illegal for the body
* to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
* </ol>
*
* @param request the client HTTP request
* @param responseStatus the responseStatus
* @return true if the response should be 0, even if it is isn't.
*/
public static boolean shouldBodyBeZero(HttpServletRequest request, int responseStatus) {
//Check for NO_CONTENT
if (responseStatus == HttpServletResponse.SC_NO_CONTENT) {
if (LOG.isDebugEnabled()) {
LOG.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.",
request.getRequestURL(), HttpServletResponse.SC_NO_CONTENT);
}
return true;
}
//Check for NOT_MODIFIED
if (responseStatus == HttpServletResponse.SC_NOT_MODIFIED) {
if (LOG.isDebugEnabled()) {
LOG.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.",
request.getRequestURL(), HttpServletResponse.SC_NOT_MODIFIED);
}
return true;
}
return false;
}
@Override
public boolean handleResult(int returncode, GoPublisher goPublisher) {
if (returncode == HttpServletResponse.SC_NOT_FOUND) {
deleteQuietly(checksumFile);
goPublisher.taggedConsumeLineWithPrefix(GoPublisher.ERR, "[WARN] The md5checksum property file was not found on the server. Hence, Go can not verify the integrity of the artifacts.");
return true;
}
if (returncode == HttpServletResponse.SC_NOT_MODIFIED) {
LOG.info("[Agent Fetch Artifact] Not downloading checksum file as it has not changed");
return true;
}
if (returncode == HttpServletResponse.SC_OK) {
LOG.info("[Agent Fetch Artifact] Saved checksum property file [{}]", checksumFile);
return true;
}
return returncode < HttpServletResponse.SC_BAD_REQUEST;
}
/**
* Performs a number of checks to ensure response saneness according to the rules of RFC2616:
* <ol>
* <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NO_CONTENT} then it is illegal for the body
* to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5
* <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NOT_MODIFIED} then it is illegal for the body
* to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
* </ol>
*
* @param request the client HTTP request
* @param responseStatus the responseStatus
* @return true if the response should be 0, even if it is isn't.
*/
public static boolean shouldBodyBeZero(HttpServletRequest request, int responseStatus) {
//Check for NO_CONTENT
if (responseStatus == HttpServletResponse.SC_NO_CONTENT) {
if (LOG.isDebugEnabled()) {
LOG.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.",
request.getRequestURL(), HttpServletResponse.SC_NO_CONTENT);
}
return true;
}
//Check for NOT_MODIFIED
if (responseStatus == HttpServletResponse.SC_NOT_MODIFIED) {
if (LOG.isDebugEnabled()) {
LOG.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.",
request.getRequestURL(), HttpServletResponse.SC_NOT_MODIFIED);
}
return true;
}
return false;
}
public void publish(int httpCode, File artifact, GoPublisher goPublisher) {
if (!this.md5MismatchPaths.isEmpty()) {
String mismatchedFilePath = md5MismatchPaths.iterator().next();
goPublisher.taggedConsumeLineWithPrefix(GoPublisher.ERR,
String.format("[ERROR] Verification of the integrity of the artifact [%s] failed. The artifact file on the server may have changed since its original upload.", mismatchedFilePath));
throw new RuntimeException(String.format("Artifact download failed for [%s]", mismatchedFilePath));
}
for (String md5NotFoundPath : md5NotFoundPaths) {
goPublisher.taggedConsumeLineWithPrefix(GoPublisher.ERR, String.format("[WARN] The md5checksum value of the artifact [%s] was not found on the server. Hence, Go could not verify the integrity of its contents.", md5NotFoundPath));
}
if (httpCode == HttpServletResponse.SC_NOT_MODIFIED) {
goPublisher.taggedConsumeLineWithPrefix(GoPublisher.OUT, "Artifact is not modified, skipped fetching it");
}
if (httpCode == HttpServletResponse.SC_OK) {
if (md5NotFoundPaths.size() > 0 || md5ChecksumFileWasNotFound) {
goPublisher.taggedConsumeLineWithPrefix(GoPublisher.ERR, String.format("Saved artifact to [%s] without verifying the integrity of its contents.", artifact));
} else {
goPublisher.taggedConsumeLineWithPrefix(GoPublisher.OUT, String.format("Saved artifact to [%s] after verifying the integrity of its contents.", artifact));
}
}
}
/**
* Performs a number of checks to ensure response saneness according to the rules of RFC2616:
* <ol>
* <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NO_CONTENT} then it is illegal for
* the body to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5
* <li>If the response code is {@link javax.servlet.http.HttpServletResponse#SC_NOT_MODIFIED} then it is illegal for
* the body to contain anything. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
* </ol>
* @param request the client HTTP request
* @param responseStatus the responseStatus
* @return true if the response should be 0, even if it is isn't.
*/
public static boolean shouldBodyBeZero(HttpServletRequest request, int responseStatus) {
//Check for NO_CONTENT
if (responseStatus == HttpServletResponse.SC_NO_CONTENT) {
if (log.isDebugEnabled()) {
log.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.",
request.getRequestURL(), HttpServletResponse.SC_NO_CONTENT);
}
return true;
}
//Check for NOT_MODIFIED
if (responseStatus == HttpServletResponse.SC_NOT_MODIFIED) {
if (log.isDebugEnabled()) {
log.debug("{} resulted in a {} response. Removing message body in accordance with RFC2616.",
request.getRequestURL(), HttpServletResponse.SC_NOT_MODIFIED);
}
return true;
}
return false;
}
protected String buildJnlpResponse(JnlpTemplate launcher) throws ServletErrorException {
launcher.rootElt.setAttribute(JNLP_TAG_ATT_CODEBASE,
ServletUtil.getFirstParameter(launcher.parameterMap.get(WeasisConfig.PARAM_CODEBASE)));
launcher.rootElt.removeAttribute(JNLP_TAG_ATT_HREF); // this tag has not to be used inside dynamic JNLP
handleRequestPropertyParameter(launcher);
handleRequestArgumentParameter(launcher);
filterRequestParameterMarker(launcher);
String outputStr = null;
try {
Format format = Format.getPrettyFormat();
// Converts native encodings to ASCII with escaped Unicode like (ô è é...),
// necessary for jnlp
format.setEncoding("US-ASCII");
outputStr = new XMLOutputter(format).outputString(launcher.rootElt);
} catch (Exception e) {
throw new ServletErrorException(HttpServletResponse.SC_NOT_MODIFIED, "Can't build Jnlp launcher ", e);
}
return outputStr;
}
public static void writeResponseContent(HttpServletResponse response, String content) throws IOException {
// check to see if this is chunked
boolean chunked = false;
if (response.containsHeader(PluginHelper.STRING_TRANSFER_ENCODING)
&& response.getHeader(PluginHelper.STRING_TRANSFER_ENCODING).compareTo("chunked") == 0) {
response.setHeader(PluginHelper.STRING_CONNECTION, PluginHelper.STRING_CHUNKED);
chunked = true;
}
// check to see if this content is supposed to be compressed
// if so recompress it
boolean isEncoded = false;
ByteArrayOutputStream out = new ByteArrayOutputStream();
if (response.getHeader("content-encoding") != null &&
response.getHeader("content-encoding").equals("gzip")) {
// GZIP the data
isEncoded = true;
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(content.getBytes());
gzip.close();
out.close();
} else if (response.getHeader("content-encoding") != null &&
response.getHeader("content-encoding").equals("deflate")) {
// Deflate the data
isEncoded = true;
Deflater compressor = new Deflater();
compressor.setInput(content.getBytes());
compressor.finish();
byte[] buffer = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buffer);
out.write(buffer, 0, count);
}
out.close();
compressor.end();
}
// don't do this if we got a HTTP 304 since there is no data to send back
if (response.getStatus() != HttpServletResponse.SC_NOT_MODIFIED) {
if (!chunked) {
// change the content length header to the new length
if (content != null && !isEncoded) {
response.setContentLength(content.getBytes().length);
} else if (isEncoded) {
response.setContentLength(out.toByteArray().length);
}
}
OutputStream outputStreamClientResponse = response.getOutputStream();
response.resetBuffer();
if (content != null && !isEncoded) {
outputStreamClientResponse.write(content.getBytes());
} else if (isEncoded) {
outputStreamClientResponse.write(out.toByteArray());
}
}
}
/**
* @param httpServletResponse
* @param jsonpCallback
* @throws IOException
*/
private void writeResponseOutput(PluginResponse httpServletResponse,
String jsonpCallback) throws IOException {
RequestInformation requestInfo = requestInformation.get();
// check to see if this is chunked
boolean chunked = false;
if (httpServletResponse.containsHeader(HttpUtilities.STRING_TRANSFER_ENCODING)
&& httpServletResponse.getHeader(HttpUtilities.STRING_TRANSFER_ENCODING).compareTo("chunked") == 0) {
httpServletResponse.setHeader(HttpUtilities.STRING_CONNECTION, HttpUtilities.STRING_CHUNKED);
chunked = true;
}
// reattach JSONP if needed
if (httpServletResponse.getOutputStream() != null && jsonpCallback != null) {
String outStr = jsonpCallback + "(" + httpServletResponse.getOutputStream().toString() + ");";
PluginHelper.writeResponseContent(httpServletResponse, outStr);
}
// don't do this if we got a HTTP 304 since there is no data to send back
// TODO: Fix things so chunked encoding can pass through blindly
if (httpServletResponse.getStatus() != HttpServletResponse.SC_NOT_MODIFIED) {
logger.info("Chunked: {}, {}", chunked, httpServletResponse.getBufferSize());
if (!chunked) {
// change the content length header to the new length
if (httpServletResponse.getOutputStream() != null) {
logger.info("Content length: {}", httpServletResponse.getByteOutputStream().toByteArray().length);
httpServletResponse.setContentLength(httpServletResponse.getByteOutputStream().toByteArray().length);
}
}
OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
outputStreamClientResponse.write(httpServletResponse.getByteOutputStream().toByteArray());
logger.info("Done writing");
}
}
protected void forwardResponse(final Routes.Route route, final Response response,
final HttpServletRequest request, final HttpServletResponse resp,
final Function<InputStream, InputStream> responseRewriter) throws IOException {
final int status = response.getStatus();
resp.setStatus(status);
forwardHeaders(route, response, resp);
if (status == HttpServletResponse.SC_NOT_MODIFIED && resp.getHeader(HttpHeaders.CONTENT_LENGTH) == null) {
resp.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
}
forwardCookies(route, response, resp);
writeOutput(resp, responseRewriter.apply(response.readEntity(InputStream.class)));
}
protected boolean doResponseRedirectOrNotModifiedLogic(HttpServletRequest servletRequest,
HttpServletResponse servletResponse, HttpResponse proxyResponse, int statusCode) throws ServletException, IOException {
// Check if the proxy response is a redirect
// The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
&& statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION);
if (locationHeader == null) {
throw new ServletException("Received status code: " + statusCode + " but no " + HttpHeaders.LOCATION
+ " header was found in the response");
}
// Modify the redirect to go to this proxy servlet rather that the proxied host
String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue());
servletResponse.sendRedirect(locStr);
return true;
}
// 304 needs special handling. See:
// http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
// We get a 304 whenever passed an 'If-Modified-Since'
// header and the data on disk has not changed; server
// responds w/ a 304 saying I'm not going to send the
// body because the file has not changed.
if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return true;
}
return false;
}
protected boolean doResponseRedirectOrNotModifiedLogic(
HttpServletRequest servletRequest, HttpServletResponse servletResponse,
HttpResponse proxyResponse, int statusCode)
throws ServletException, IOException {
// Check if the proxy response is a redirect
// The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
if (statusCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
&& statusCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
Header locationHeader = proxyResponse.getLastHeader(HttpHeaders.LOCATION);
if (locationHeader == null) {
throw new ServletException("Received status code: " + statusCode
+ " but no " + HttpHeaders.LOCATION + " header was found in the response");
}
// Modify the redirect to go to this proxy servlet rather that the proxied host
String locStr = rewriteUrlFromResponse(servletRequest, locationHeader.getValue());
servletResponse.sendRedirect(locStr);
return true;
}
// 304 needs special handling. See:
// http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
// We get a 304 whenever passed an 'If-Modified-Since'
// header and the data on disk has not changed; server
// responds w/ a 304 saying I'm not going to send the
// body because the file has not changed.
if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
servletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return true;
}
return false;
}
public XXPolicyExportAudit createPolicyAudit(
final XXPolicyExportAudit xXPolicyExportAudit) {
XXPolicyExportAudit ret = null;
if (xXPolicyExportAudit.getHttpRetCode() == HttpServletResponse.SC_NOT_MODIFIED) {
boolean logNotModified = PropertiesUtil.getBooleanProperty("ranger.log.SC_NOT_MODIFIED", false);
if (!logNotModified) {
logger.debug("Not logging HttpServletResponse."
+ "SC_NOT_MODIFIED, to enable, update "
+ ": ranger.log.SC_NOT_MODIFIED");
} else {
// Create PolicyExportAudit record after transaction is completed. If it is created in-line here
// then the TransactionManager will roll-back the changes because the HTTP return code is
// HttpServletResponse.SC_NOT_MODIFIED
Runnable commitWork = new Runnable() {
@Override
public void run() {
rangerDaoManager.getXXPolicyExportAudit().create(xXPolicyExportAudit);
}
};
activityLogger.commitAfterTransactionComplete(commitWork);
}
} else {
ret = rangerDaoManager.getXXPolicyExportAudit().create(xXPolicyExportAudit);
}
return ret;
}
public NotModifiedException(String message) {
super(HttpServletResponse.SC_NOT_MODIFIED, message, null);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (!isIncluded(httpRequest) && acceptsGZipEncoding(httpRequest) && !response.isCommitted()) {
// Client accepts zipped content
if (log.isTraceEnabled()) {
log.trace("{} Written with gzip compression", httpRequest.getRequestURL());
}
// Create a gzip stream
final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
final GZIPOutputStream gzout = new GZIPOutputStream(compressed);
// Handle the request
final GZipServletResponseWrapper wrapper = new GZipServletResponseWrapper(httpResponse, gzout);
wrapper.setDisableFlushBuffer(true);
chain.doFilter(request, wrapper);
wrapper.flush();
gzout.close();
// double check one more time before writing out
// repsonse might have been committed due to error
if (response.isCommitted()) {
return;
}
// return on these special cases when content is empty or unchanged
switch (wrapper.getStatus()) {
case HttpServletResponse.SC_NO_CONTENT:
case HttpServletResponse.SC_RESET_CONTENT:
case HttpServletResponse.SC_NOT_MODIFIED:
return;
default:
}
// Saneness checks
byte[] compressedBytes = compressed.toByteArray();
boolean shouldGzippedBodyBeZero = GZipResponseUtil.shouldGzippedBodyBeZero(compressedBytes, httpRequest);
boolean shouldBodyBeZero = GZipResponseUtil.shouldBodyBeZero(httpRequest, wrapper.getStatus());
if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
// No reason to add GZIP headers or write body if no content was written or status code specifies no
// content
response.setContentLength(0);
return;
}
// Write the zipped body
GZipResponseUtil.addGzipHeader(httpResponse);
response.setContentLength(compressedBytes.length);
response.getOutputStream().write(compressedBytes);
} else {
// Client does not accept zipped content - don't bother zipping
if (log.isTraceEnabled()) {
log.trace("{} Written without gzip compression because the request does not accept gzip", httpRequest.getRequestURL());
}
chain.doFilter(request, response);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (!isIncluded(httpRequest) && acceptsGZipEncoding(httpRequest) && !response.isCommitted()) {
// Client accepts zipped content
if (log.isTraceEnabled()) {
log.trace("{} Written with gzip compression", httpRequest.getRequestURL());
}
// Create a gzip stream
final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
final GZIPOutputStream gzout = new GZIPOutputStream(compressed);
// Handle the request
final GZipServletResponseWrapper wrapper = new GZipServletResponseWrapper(httpResponse, gzout);
wrapper.setDisableFlushBuffer(true);
chain.doFilter(request, wrapper);
wrapper.flush();
gzout.close();
// double check one more time before writing out
// repsonse might have been committed due to error
if (response.isCommitted()) {
return;
}
// return on these special cases when content is empty or unchanged
switch (wrapper.getStatus()) {
case HttpServletResponse.SC_NO_CONTENT:
case HttpServletResponse.SC_RESET_CONTENT:
case HttpServletResponse.SC_NOT_MODIFIED:
return;
default:
}
// Saneness checks
byte[] compressedBytes = compressed.toByteArray();
boolean shouldGzippedBodyBeZero = GZipResponseUtil.shouldGzippedBodyBeZero(compressedBytes, httpRequest);
boolean shouldBodyBeZero = GZipResponseUtil.shouldBodyBeZero(httpRequest, wrapper.getStatus());
if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
// No reason to add GZIP headers or write body if no content was written or status code specifies no
// content
response.setContentLength(0);
return;
}
// Write the zipped body
GZipResponseUtil.addGzipHeader(httpResponse);
response.setContentLength(compressedBytes.length);
response.getOutputStream().write(compressedBytes);
} else {
// Client does not accept zipped content - don't bother zipping
if (log.isTraceEnabled()) {
log.trace("{} Written without gzip compression because the request does not accept gzip", httpRequest.getRequestURL());
}
chain.doFilter(request, response);
}
}
@GET
@Path(TagRESTConstants.TAGS_DOWNLOAD + "{serviceName}")
@Produces({ "application/json", "application/xml" })
public ServiceTags getServiceTagsIfUpdated(@PathParam("serviceName") String serviceName,
@QueryParam(TagRESTConstants.LAST_KNOWN_TAG_VERSION_PARAM) Long lastKnownVersion,
@DefaultValue("0") @QueryParam(TagRESTConstants.LAST_ACTIVATION_TIME) Long lastActivationTime, @QueryParam("pluginId") String pluginId,
@DefaultValue("false") @QueryParam(RangerRESTUtils.REST_PARAM_SUPPORTS_TAG_DELTAS) Boolean supportsTagDeltas,
@DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities,
@Context HttpServletRequest request) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> TagREST.getServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ", " + pluginId + ", " + supportsTagDeltas + ")");
}
ServiceTags ret = null;
int httpCode = HttpServletResponse.SC_OK;
String logMsg = null;
Long downloadedVersion = null;
String clusterName = null;
if (request != null) {
clusterName = !StringUtils.isEmpty(request.getParameter(SearchFilter.CLUSTER_NAME)) ? request.getParameter(SearchFilter.CLUSTER_NAME) : "";
}
try {
bizUtil.failUnauthenticatedIfNotAllowed();
ret = tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, !supportsTagDeltas);
if (ret == null) {
downloadedVersion = lastKnownVersion;
httpCode = HttpServletResponse.SC_NOT_MODIFIED;
logMsg = "No change since last update";
} else {
downloadedVersion = ret.getTagVersion();
httpCode = HttpServletResponse.SC_OK;
logMsg = "Returning " + (ret.getTags() != null ? ret.getTags().size() : 0) + " tags. Tag version=" + ret.getTagVersion();
}
} catch (WebApplicationException webException) {
httpCode = webException.getResponse().getStatus();
logMsg = webException.getResponse().getEntity().toString();
} catch(Exception excp) {
httpCode = HttpServletResponse.SC_BAD_REQUEST;
logMsg = excp.getMessage();
} finally {
assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_TAGS, downloadedVersion, lastKnownVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities);
}
if(httpCode != HttpServletResponse.SC_OK) {
boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED;
throw restErrorUtil.createRESTException(httpCode, logMsg, logError);
}
if(LOG.isDebugEnabled()) {
LOG.debug("<== TagREST.getServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ", " + pluginId + ", " + supportsTagDeltas + ")");
}
return ret;
}
@GET
@Path(TagRESTConstants.TAGS_SECURE_DOWNLOAD + "{serviceName}")
@Produces({ "application/json", "application/xml" })
public ServiceTags getSecureServiceTagsIfUpdated(@PathParam("serviceName") String serviceName,
@QueryParam(TagRESTConstants.LAST_KNOWN_TAG_VERSION_PARAM) Long lastKnownVersion,
@DefaultValue("0") @QueryParam(TagRESTConstants.LAST_ACTIVATION_TIME) Long lastActivationTime, @QueryParam("pluginId") String pluginId,
@DefaultValue("false") @QueryParam(RangerRESTUtils.REST_PARAM_SUPPORTS_TAG_DELTAS) Boolean supportsTagDeltas,
@DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities,
@Context HttpServletRequest request) {
if(LOG.isDebugEnabled()) {
LOG.debug("==> TagREST.getSecureServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ", " + pluginId + ", " + supportsTagDeltas + ")");
}
ServiceTags ret = null;
int httpCode = HttpServletResponse.SC_OK;
String logMsg = null;
boolean isAllowed = false;
boolean isAdmin = bizUtil.isAdmin();
boolean isKeyAdmin = bizUtil.isKeyAdmin();
Long downloadedVersion = null;
String clusterName = null;
if (request != null) {
clusterName = !StringUtils.isEmpty(request.getParameter(SearchFilter.CLUSTER_NAME)) ? request.getParameter(SearchFilter.CLUSTER_NAME) : "";
}
try {
XXService xService = daoManager.getXXService().findByName(serviceName);
if (xService == null) {
LOG.error("Requested Service not found. serviceName=" + serviceName);
throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_FOUND, "Service:" + serviceName + " not found",
false);
}
XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType());
RangerService rangerService = svcStore.getServiceByName(serviceName);
if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) {
if (isKeyAdmin) {
isAllowed = true;
}else {
isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download);
}
}else{
if (isAdmin) {
isAllowed = true;
}else{
isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Tag_Download);
}
}
if (isAllowed) {
ret = tagStore.getServiceTagsIfUpdated(serviceName, lastKnownVersion, !supportsTagDeltas);
if(ret == null) {
downloadedVersion = lastKnownVersion;
httpCode = HttpServletResponse.SC_NOT_MODIFIED;
logMsg = "No change since last update";
} else {
downloadedVersion = ret.getTagVersion();
httpCode = HttpServletResponse.SC_OK;
logMsg = "Returning " + (ret.getTags() != null ? ret.getTags().size() : 0) + " tags. Tag version=" + ret.getTagVersion();
}
}else{
LOG.error("getSecureServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ") failed as User doesn't have permission to download tags");
httpCode = HttpServletResponse.SC_UNAUTHORIZED;
logMsg = "User doesn't have permission to download tags";
}
} catch (WebApplicationException webException) {
httpCode = webException.getResponse().getStatus();
logMsg = webException.getResponse().getEntity().toString();
} catch (Exception excp) {
httpCode = HttpServletResponse.SC_BAD_REQUEST;
logMsg = excp.getMessage();
} finally {
assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_TAGS, downloadedVersion, lastKnownVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities);
}
if(httpCode != HttpServletResponse.SC_OK) {
boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED;
throw restErrorUtil.createRESTException(httpCode, logMsg, logError);
}
if(LOG.isDebugEnabled()) {
LOG.debug("<== TagREST.getSecureServiceTagsIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ", " + pluginId + ", " + supportsTagDeltas + ")");
}
return ret;
}
@GET
@Path("/secure/download/{serviceName}")
@Produces({ "application/xml", "application/json" })
public RangerUserStore getSecureRangerUserStoreIfUpdated(@PathParam("serviceName") String serviceName,
@QueryParam("lastKnownUserStoreVersion") Long lastKnownUserStoreVersion,
@DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime,
@QueryParam("pluginId") String pluginId,
@DefaultValue("") @QueryParam("clusterName") String clusterName,
@DefaultValue("") @QueryParam(RangerRESTUtils.REST_PARAM_CAPABILITIES) String pluginCapabilities,
@Context HttpServletRequest request) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("==> XUserREST.getSecureRangerUserStoreIfUpdated("
+ serviceName + ", " + lastKnownUserStoreVersion + ", " + lastActivationTime + ")");
}
RangerUserStore ret = null;
int httpCode = HttpServletResponse.SC_OK;
String logMsg = null;
boolean isAllowed = false;
boolean isAdmin = bizUtil.isAdmin();
boolean isKeyAdmin = bizUtil.isKeyAdmin();
Long downloadedVersion = null;
boolean isValid = false;
try {
XXService xService = rangerDaoManager.getXXService().findByName(serviceName);
if (xService != null) {
isValid = true;
}
if (isValid) {
if (lastKnownUserStoreVersion == null) {
lastKnownUserStoreVersion = Long.valueOf(-1);
}
XXServiceDef xServiceDef = rangerDaoManager.getXXServiceDef().getById(xService.getType());
RangerService rangerService = svcStore.getServiceByName(serviceName);
if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) {
if (isKeyAdmin) {
isAllowed = true;
} else {
isAllowed = bizUtil.isUserAllowed(rangerService, USERSTORE_DOWNLOAD_USERS);
}
} else {
if (isAdmin) {
isAllowed = true;
} else {
isAllowed = bizUtil.isUserAllowed(rangerService, USERSTORE_DOWNLOAD_USERS);
}
}
if (isAllowed) {
RangerUserStore rangerUserStore = xUserMgr.getRangerUserStore(lastKnownUserStoreVersion);
if (rangerUserStore == null) {
downloadedVersion = lastKnownUserStoreVersion;
httpCode = HttpServletResponse.SC_NOT_MODIFIED;
logMsg = "No change since last update";
} else {
downloadedVersion = rangerUserStore.getUserStoreVersion();
ret = rangerUserStore;
httpCode = HttpServletResponse.SC_OK;
logMsg = "Returning RangerUserStore =>" + (ret.toString());
}
} else {
logger.error("getSecureRangerUserStoreIfUpdated(" + serviceName + ", " + lastKnownUserStoreVersion + ") failed as User doesn't have permission to download UsersAndGroups");
httpCode = HttpServletResponse.SC_UNAUTHORIZED;
logMsg = "User doesn't have permission to download UsersAndGroups";
}
}
} catch (Throwable excp) {
logger.error("getSecureRangerUserStoreIfUpdated(" + serviceName + ", " + lastKnownUserStoreVersion + ", " + lastActivationTime + ") failed", excp);
httpCode = HttpServletResponse.SC_BAD_REQUEST;
logMsg = excp.getMessage();
}
assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_USERSTORE, downloadedVersion, lastKnownUserStoreVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities);
if (httpCode != HttpServletResponse.SC_OK) {
boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED;
throw restErrorUtil.createRESTException(httpCode, logMsg, logError);
}
if (logger.isDebugEnabled()) {
logger.debug("<== XUserREST.getSecureRangerUserStoreIfUpdated(" + serviceName + ", " + lastKnownUserStoreVersion + ", " + lastActivationTime + ")" + ret);
}
return ret;
}
@GET
@Path("/policies/download/{serviceName}")
@Produces({ "application/json", "application/xml" })
public ServicePolicies getServicePoliciesIfUpdated(
@PathParam("serviceName") String serviceName,
@QueryParam("lastKnownVersion") Long lastKnownVersion,
@DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime,
@QueryParam("pluginId") String pluginId,
@DefaultValue("") @QueryParam("clusterName") String clusterName,
@DefaultValue("") @QueryParam("zoneName") String zoneName,
@DefaultValue("false") @QueryParam("supportsPolicyDeltas") Boolean supportsPolicyDeltas,
@DefaultValue("") @QueryParam("pluginCapabilities") String pluginCapabilities,
@Context HttpServletRequest request) throws Exception {
if (LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.getServicePoliciesIfUpdated("
+ serviceName + ", " + lastKnownVersion + ", "
+ lastActivationTime + ", " + pluginId + ", "
+ clusterName + ", " + supportsPolicyDeltas + ")");
}
ServicePolicies ret = null;
int httpCode = HttpServletResponse.SC_OK;
String logMsg = null;
RangerPerfTracer perf = null;
Long downloadedVersion = null;
boolean isValid = false;
try {
bizUtil.failUnauthenticatedIfNotAllowed();
isValid = serviceUtil.isValidateHttpsAuthentication(serviceName, request);
} catch (WebApplicationException webException) {
httpCode = webException.getResponse().getStatus();
logMsg = webException.getResponse().getEntity().toString();
} catch (Exception e) {
httpCode = HttpServletResponse.SC_BAD_REQUEST;
logMsg = e.getMessage();
}
if (isValid) {
if (lastKnownVersion == null) {
lastKnownVersion = Long.valueOf(-1);
}
try {
if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServicePoliciesIfUpdated(serviceName=" + serviceName + ",lastKnownVersion=" + lastKnownVersion + ",lastActivationTime=" + lastActivationTime + ")");
}
ServicePolicies servicePolicies = svcStore.getServicePoliciesIfUpdated(serviceName, lastKnownVersion, !supportsPolicyDeltas);
if (servicePolicies == null) {
downloadedVersion = lastKnownVersion;
httpCode = HttpServletResponse.SC_NOT_MODIFIED;
logMsg = "No change since last update";
} else {
Map<String, RangerSecurityZone.RangerSecurityZoneService> securityZones = zoneStore.getSecurityZonesForService(serviceName);
ServicePolicies updatedServicePolicies = servicePolicies;
if (MapUtils.isNotEmpty(securityZones)) {
updatedServicePolicies = RangerPolicyAdminCache.getUpdatedServicePoliciesForZones(servicePolicies, securityZones);
patchAssociatedTagServiceInSecurityZoneInfos(updatedServicePolicies);
}
downloadedVersion = updatedServicePolicies.getPolicyVersion();
if (lastKnownVersion == -1L || !supportsPolicyDeltas) {
ret = filterServicePolicies(updatedServicePolicies);
} else {
ret = updatedServicePolicies;
}
ret.setServiceConfig(svcStore.getServiceConfigForPlugin(ret.getServiceId()));
httpCode = HttpServletResponse.SC_OK;
logMsg = "Returning " + (ret.getPolicies() != null ? ret.getPolicies().size() : (ret.getPolicyDeltas() != null ? ret.getPolicyDeltas().size() : 0)) + " policies. Policy version=" + ret.getPolicyVersion();
}
} catch (Throwable excp) {
LOG.error("getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ") failed", excp);
httpCode = HttpServletResponse.SC_BAD_REQUEST;
logMsg = excp.getMessage();
} finally {
createPolicyDownloadAudit(serviceName, lastKnownVersion, pluginId, httpCode, clusterName, zoneName, request);
RangerPerfTracer.log(perf);
}
}
assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_POLICIES, downloadedVersion, lastKnownVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities);
if(httpCode != HttpServletResponse.SC_OK) {
boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED;
throw restErrorUtil.createRESTException(httpCode, logMsg, logError);
}
if(LOG.isDebugEnabled()) {
LOG.debug("<== ServiceREST.getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ", " + pluginId + ", " + clusterName + ", " + supportsPolicyDeltas + "): count=" + ((ret == null || ret.getPolicies() == null) ? 0 : ret.getPolicies().size()));
}
return ret;
}
/**
* Execute a request
*
* @param httpMethodProxyRequest
* @param httpServletRequest
* @param httpServletResponse
* @param history
* @throws Exception
*/
private void executeRequest(HttpMethod httpMethodProxyRequest,
HttpServletRequest httpServletRequest,
PluginResponse httpServletResponse,
History history) throws Exception {
int intProxyResponseCode = 999;
// Create a default HttpClient
HttpClient httpClient = new HttpClient();
HttpState state = new HttpState();
try {
httpMethodProxyRequest.setFollowRedirects(false);
ArrayList<String> headersToRemove = getRemoveHeaders();
httpClient.getParams().setSoTimeout(60000);
httpServletRequest.setAttribute("com.groupon.odo.removeHeaders", headersToRemove);
// exception handling for httpclient
HttpMethodRetryHandler noretryhandler = new HttpMethodRetryHandler() {
public boolean retryMethod(
final HttpMethod method,
final IOException exception,
int executionCount) {
return false;
}
};
httpMethodProxyRequest.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, noretryhandler);
intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest.getHostConfiguration(), httpMethodProxyRequest, state);
} catch (Exception e) {
// Return a gateway timeout
httpServletResponse.setStatus(504);
httpServletResponse.setHeader(Constants.HEADER_STATUS, "504");
httpServletResponse.flushBuffer();
return;
}
logger.info("Response code: {}, {}", intProxyResponseCode,
HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));
// Pass the response code back to the client
httpServletResponse.setStatus(intProxyResponseCode);
// Pass response headers back to the client
Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
for (Header header : headerArrayResponse) {
// remove transfer-encoding header. The http libraries will handle this encoding
if (header.getName().toLowerCase().equals("transfer-encoding")) {
continue;
}
httpServletResponse.setHeader(header.getName(), header.getValue());
}
// there is no data for a HTTP 304 or 204
if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED &&
intProxyResponseCode != HttpServletResponse.SC_NO_CONTENT) {
// Send the content to the client
httpServletResponse.resetBuffer();
httpServletResponse.getOutputStream().write(httpMethodProxyRequest.getResponseBody());
}
// copy cookies to servlet response
for (Cookie cookie : state.getCookies()) {
javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());
if (cookie.getPath() != null) {
servletCookie.setPath(cookie.getPath());
}
if (cookie.getDomain() != null) {
servletCookie.setDomain(cookie.getDomain());
}
// convert expiry date to max age
if (cookie.getExpiryDate() != null) {
servletCookie.setMaxAge((int) ((cookie.getExpiryDate().getTime() - System.currentTimeMillis()) / 1000));
}
servletCookie.setSecure(cookie.getSecure());
servletCookie.setVersion(cookie.getVersion());
if (cookie.getComment() != null) {
servletCookie.setComment(cookie.getComment());
}
httpServletResponse.addCookie(servletCookie);
}
}