下面列出了javax.servlet.http.HttpServletResponse#SC_NO_CONTENT 实例代码,或者点击链接到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;
}
/**
* 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;
}
/**
* 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;
}
private ClientResponse tryWithCred(ServiceTags serviceTags) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> tryWithCred");
}
ClientResponse clientResponsebyCred = uploadTagsWithCred(serviceTags);
if (clientResponsebyCred != null && clientResponsebyCred.getStatus() != HttpServletResponse.SC_NO_CONTENT
&& clientResponsebyCred.getStatus() != HttpServletResponse.SC_BAD_REQUEST
&& clientResponsebyCred.getStatus() != HttpServletResponse.SC_OK) {
sessionId = null;
clientResponsebyCred = null;
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== tryWithCred");
}
return clientResponsebyCred;
}
private ClientResponse tryWithCookie(ServiceTags serviceTags) {
ClientResponse clientResponsebySessionId = uploadTagsWithCookie(serviceTags);
if (clientResponsebySessionId != null
&& clientResponsebySessionId.getStatus() != HttpServletResponse.SC_NO_CONTENT
&& clientResponsebySessionId.getStatus() != HttpServletResponse.SC_BAD_REQUEST
&& clientResponsebySessionId.getStatus() != HttpServletResponse.SC_OK) {
sessionId = null;
isValidRangerCookie = false;
clientResponsebySessionId = null;
}
return clientResponsebySessionId;
}
private synchronized ClientResponse uploadTagsWithCred(ServiceTags serviceTags) {
if (sessionId == null) {
tagRESTClient.resetClient();
ClientResponse response = null;
try {
response = tagRESTClient.put(REST_URL_IMPORT_SERVICETAGS_RESOURCE, null, serviceTags);
} catch (Exception e) {
LOG.error("Failed to get response, Error is : "+e.getMessage());
}
if (response != null) {
if (!(response.toString().contains(REST_URL_IMPORT_SERVICETAGS_RESOURCE))) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
} else if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
LOG.warn("Credentials response from ranger is 401.");
} else if (response.getStatus() == HttpServletResponse.SC_OK
|| response.getStatus() == HttpServletResponse.SC_NO_CONTENT) {
cookieList = response.getCookies();
// save cookie received from credentials session login
for (NewCookie cookie : cookieList) {
if (cookie.getName().equalsIgnoreCase(rangerAdminCookieName)) {
sessionId = cookie.toCookie();
isValidRangerCookie = true;
break;
} else {
isValidRangerCookie = false;
}
}
}
}
return response;
} else {
ClientResponse clientResponsebySessionId = uploadTagsWithCookie(serviceTags);
if (!(clientResponsebySessionId.toString().contains(REST_URL_IMPORT_SERVICETAGS_RESOURCE))) {
clientResponsebySessionId.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
return clientResponsebySessionId;
}
}
private ClientResponse uploadTagsWithCookie(ServiceTags serviceTags) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> uploadTagsWithCookie");
}
ClientResponse response = null;
try {
response = tagRESTClient.put(REST_URL_IMPORT_SERVICETAGS_RESOURCE, serviceTags, sessionId);
} catch (Exception e) {
LOG.error("Failed to get response, Error is : "+e.getMessage());
}
if (response != null) {
if (!(response.toString().contains(REST_URL_IMPORT_SERVICETAGS_RESOURCE))) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
sessionId = null;
isValidRangerCookie = false;
} else if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
sessionId = null;
isValidRangerCookie = false;
} else if (response.getStatus() == HttpServletResponse.SC_NO_CONTENT
|| response.getStatus() == HttpServletResponse.SC_OK) {
List<NewCookie> respCookieList = response.getCookies();
for (NewCookie respCookie : respCookieList) {
if (respCookie.getName().equalsIgnoreCase(rangerAdminCookieName)) {
if (!(sessionId.getValue().equalsIgnoreCase(respCookie.toCookie().getValue()))) {
sessionId = respCookie.toCookie();
}
isValidRangerCookie = true;
break;
}
}
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== uploadTagsWithCookie");
}
return response;
}
private String tryUploadEntityWithCred(Object obj,String apiURL){
if(LOG.isDebugEnabled()){
LOG.debug("==> PolicyMgrUserGroupBuilder.tryUploadEntityInfoWithCred()");
}
String response = null;
ClientResponse clientResp = null;
Gson gson = new GsonBuilder().create();
String jsonString = gson.toJson(obj);
if ( LOG.isDebugEnabled() ) {
LOG.debug("USER GROUP MAPPING" + jsonString);
}
try{
clientResp = uGSyncClient.post(apiURL, null, obj);
}
catch(Throwable t){
LOG.error("Failed to get response, Error is : ", t);
}
if (clientResp != null) {
if (!(clientResp.toString().contains(apiURL))) {
clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND);
} else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
LOG.warn("Credentials response from ranger is 401.");
} else if (clientResp.getStatus() == HttpServletResponse.SC_OK || clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT) {
cookieList = clientResp.getCookies();
for (NewCookie cookie : cookieList) {
if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) {
sessionId = cookie.toCookie();
isValidRangerCookie = true;
LOG.info("valid cookie saved ");
break;
}
}
}
if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT
&& clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
sessionId = null;
isValidRangerCookie = false;
}
clientResp.bufferEntity();
response = clientResp.getEntity(String.class);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== PolicyMgrUserGroupBuilder.tryUploadEntityInfoWithCred()");
}
return response;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
chain.doFilter(request, response);
// Defect 491041: post check to ensure every response includes a Content-Type header.
if (httpResponse.getStatus() != HttpServletResponse.SC_NO_CONTENT) {
String contentType = httpResponse.getContentType();
if (contentType == null) {
String requestURI = httpRequest.getRequestURI();
if (requestURI != null) {
String[] pathInfoParts = requestURI.split("\\/");
if (pathInfoParts.length == 0) {
return;
}
String filename = pathInfoParts[pathInfoParts.length - 1];
if (filename.equals("defaults.pref") || filename.endsWith(".json") || filename.endsWith(".launch")) {
httpResponse.setContentType(ProtocolConstants.CONTENT_TYPE_JSON);
} else if (filename.endsWith(".md") || filename.endsWith(".yml")) {
httpResponse.setContentType(ProtocolConstants.CONTENT_TYPE_PLAIN_TEXT);
} else if (filename.endsWith(".css")) {
httpResponse.setContentType(ProtocolConstants.CONTENT_TYPE_CSS);
} else if (filename.endsWith(".js")) {
httpResponse.setContentType(ProtocolConstants.CONTENT_TYPE_JAVASCRIPT);
} else if (filename.endsWith(".woff")) {
httpResponse.setContentType(ProtocolConstants.CONTENT_TYPE_FONT);
} else {
// see if we have a mime type to use as the content type
String mimeType = httpRequest.getServletContext().getMimeType(filename);
if (mimeType != null) {
String newContentType = mimeType + "; charset=UTF-8";
httpResponse.setContentType(newContentType);
} else {
// fall back to using plain text content type
httpResponse.setContentType(ProtocolConstants.CONTENT_TYPE_PLAIN_TEXT);
}
}
}
}
}
}
public NoContentException(String message) {
super(HttpServletResponse.SC_NO_CONTENT, message, null);
}
private String tryGetEntityWithCred(String apiURL, int retrievedCount) {
if(LOG.isDebugEnabled()){
LOG.debug("==> PolicyMgrUserGroupBuilder.tryGetEntityWithCred()");
}
String response = null;
ClientResponse clientResp = null;
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("pageSize", recordsToPullPerCall);
queryParams.put("startIndex", String.valueOf(retrievedCount));
try{
clientResp = uGSyncClient.get(apiURL, queryParams);
}
catch(Throwable t){
LOG.error("Failed to get response, Error is : ", t);
}
if (clientResp != null) {
if (!(clientResp.toString().contains(apiURL))) {
clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND);
} else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
LOG.warn("Credentials response from ranger is 401.");
} else if (clientResp.getStatus() == HttpServletResponse.SC_OK || clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT) {
cookieList = clientResp.getCookies();
for (NewCookie cookie : cookieList) {
if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) {
sessionId = cookie.toCookie();
isValidRangerCookie = true;
LOG.info("valid cookie saved ");
break;
}
}
}
if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT
&& clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
sessionId = null;
isValidRangerCookie = false;
}
clientResp.bufferEntity();
response = clientResp.getEntity(String.class);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== PolicyMgrUserGroupBuilder.tryGetEntityWithCred()");
}
return 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);
}
}
private String tryUploadEntityWithCookie(Object obj, String apiURL) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> PolicyMgrUserGroupBuilder.tryUploadEntityWithCookie()");
}
String response = null;
ClientResponse clientResp = null;
try{
clientResp = uGSyncClient.post(apiURL, null, obj, sessionId);
}
catch(Throwable t){
LOG.error("Failed to get response, Error is : ", t);
}
if (clientResp != null) {
if (!(clientResp.toString().contains(apiURL))) {
clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND);
sessionId = null;
isValidRangerCookie = false;
} else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
sessionId = null;
isValidRangerCookie = false;
} else if (clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT || clientResp.getStatus() == HttpServletResponse.SC_OK) {
List<NewCookie> respCookieList = clientResp.getCookies();
for (NewCookie cookie : respCookieList) {
if (cookie.getName().equalsIgnoreCase(RANGER_ADMIN_COOKIE_NAME)) {
if (!(sessionId.getValue().equalsIgnoreCase(cookie.toCookie().getValue()))) {
sessionId = cookie.toCookie();
}
isValidRangerCookie = true;
break;
}
}
}
if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT
&& clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
sessionId = null;
isValidRangerCookie = false;
}
clientResp.bufferEntity();
response = clientResp.getEntity(String.class);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== PolicyMgrUserGroupBuilder.tryUploadEntityWithCookie()");
}
return response;
}
/**
* 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);
}
}
private String tryGetEntityWithCookie(String apiURL, int retrievedCount) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> LdapPolicyMgrUserGroupBuilder.tryGetEntityWithCookie()");
}
String response = null;
ClientResponse clientResp = null;
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("pageSize", recordsToPullPerCall);
queryParams.put("startIndex", String.valueOf(retrievedCount));
try {
clientResp = ldapUgSyncClient.get(apiURL, queryParams, sessionId);
}
catch(Throwable t){
LOG.error("Failed to get response, Error is : ", t);
}
if (clientResp != null) {
if (!(clientResp.toString().contains(apiURL))) {
clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND);
sessionId = null;
isValidRangerCookie = false;
} else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
sessionId = null;
isValidRangerCookie = false;
} else if (clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT || clientResp.getStatus() == HttpServletResponse.SC_OK) {
List<NewCookie> respCookieList = clientResp.getCookies();
for (NewCookie cookie : respCookieList) {
if (cookie.getName().equalsIgnoreCase(rangerCookieName)) {
if (!(sessionId.getValue().equalsIgnoreCase(cookie.toCookie().getValue()))) {
sessionId = cookie.toCookie();
}
isValidRangerCookie = true;
break;
}
}
}
if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT
&& clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
sessionId = null;
isValidRangerCookie = false;
}
clientResp.bufferEntity();
response = clientResp.getEntity(String.class);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== LdapPolicyMgrUserGroupBuilder.tryGetEntityWithCookie()");
}
return response;
}
@Override
public void dropRole(final String execUser, final String roleName) throws Exception {
if(LOG.isDebugEnabled()) {
LOG.debug("==> RangerAdminRESTClient.dropRole(" + roleName + ")");
}
ClientResponse response = null;
UserGroupInformation user = MiscUtil.getUGILoginUser();
boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put(RangerRESTUtils.SERVICE_NAME_PARAM, serviceNameUrlParam);
queryParams.put(RangerRESTUtils.REST_PARAM_EXEC_USER, execUser);
String relativeURL = RangerRESTUtils.REST_URL_SERVICE_DROP_ROLE + roleName;
if (isSecureMode) {
PrivilegedAction<ClientResponse> action = new PrivilegedAction<ClientResponse>() {
public ClientResponse run() {
ClientResponse clientRes = null;
try {
clientRes = restClient.delete(relativeURL, queryParams);
} catch (Exception e) {
LOG.error("Failed to get response, Error is : "+e.getMessage());
}
return clientRes;
}
};
if (LOG.isDebugEnabled()) {
LOG.debug("drop role as user " + user);
}
response = user.doAs(action);
} else {
response = restClient.delete(relativeURL, queryParams);
}
if(response == null) {
throw new Exception("unknown error during deleteRole. roleName=" + roleName);
} else if(response.getStatus() != HttpServletResponse.SC_OK && response.getStatus() != HttpServletResponse.SC_NO_CONTENT) {
RESTResponse resp = RESTResponse.fromClientResponse(response);
LOG.error("createRole() failed: HTTP status=" + response.getStatus() + ", message=" + resp.getMessage() + ", isSecure=" + isSecureMode + (isSecureMode ? (", user=" + user) : ""));
if(response.getStatus()==HttpServletResponse.SC_UNAUTHORIZED) {
throw new AccessControlException();
}
throw new Exception("HTTP " + response.getStatus() + " Error: " + resp.getMessage());
}
if(LOG.isDebugEnabled()) {
LOG.debug("<== RangerAdminRESTClient.deleteRole(" + roleName + ")");
}
}
private void delXGroupUserInfo(String groupName, String userName) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> LdapPolicyMgrUserGroupBuilder.delXUserGroupInfo()");
}
try {
ClientResponse response = null;
String relativeUrl = PM_DEL_USER_GROUP_LINK_URI.replaceAll(Pattern.quote("${groupName}"),
URLEncoderUtil.encodeURIParam(groupName)).replaceAll(Pattern.quote("${userName}"), URLEncoderUtil.encodeURIParam(userName));
if (isRangerCookieEnabled) {
if (sessionId != null && isValidRangerCookie) {
response = ldapUgSyncClient.delete(relativeUrl, null, sessionId);
if (response != null) {
if (!(response.toString().contains(relativeUrl))) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
sessionId = null;
isValidRangerCookie = false;
} else if (response.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
LOG.warn("response from ranger is 401 unauthorized");
sessionId = null;
isValidRangerCookie = false;
} else if (response.getStatus() == HttpServletResponse.SC_NO_CONTENT
|| response.getStatus() == HttpServletResponse.SC_OK) {
cookieList = response.getCookies();
for (NewCookie cookie : cookieList) {
if (cookie.getName().equalsIgnoreCase(rangerCookieName)) {
sessionId = cookie.toCookie();
isValidRangerCookie = true;
break;
}
}
}
if (response.getStatus() != HttpServletResponse.SC_OK && response.getStatus() != HttpServletResponse.SC_NO_CONTENT
&& response.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
sessionId = null;
isValidRangerCookie = false;
}
}
}
}
else {
response = ldapUgSyncClient.delete(relativeUrl, null);
}
if ( LOG.isDebugEnabled() ) {
LOG.debug("RESPONSE: [" + response.toString() + "]");
}
} catch (Exception e) {
LOG.warn( "ERROR: Unable to delete GROUP: " + groupName + " from USER:" + userName , e);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== LdapPolicyMgrUserGroupBuilder.delXUserGroupInfo()");
}
}
private String tryUploadEntityWithCookie(Object obj, String apiURL) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> LdapPolicyMgrUserGroupBuilder.tryUploadEntityWithCookie()");
}
String response = null;
ClientResponse clientResp = null;
try {
clientResp = ldapUgSyncClient.post(apiURL, null, obj, sessionId);
}
catch(Throwable t){
LOG.error("Failed to get response, Error is : ", t);
}
if (clientResp != null) {
if (!(clientResp.toString().contains(apiURL))) {
clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND);
sessionId = null;
isValidRangerCookie = false;
} else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
sessionId = null;
isValidRangerCookie = false;
} else if (clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT || clientResp.getStatus() == HttpServletResponse.SC_OK) {
List<NewCookie> respCookieList = clientResp.getCookies();
for (NewCookie cookie : respCookieList) {
if (cookie.getName().equalsIgnoreCase(rangerCookieName)) {
if (!(sessionId.getValue().equalsIgnoreCase(cookie.toCookie().getValue()))) {
sessionId = cookie.toCookie();
}
isValidRangerCookie = true;
break;
}
}
}
if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT
&& clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
sessionId = null;
isValidRangerCookie = false;
}
clientResp.bufferEntity();
response = clientResp.getEntity(String.class);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== LdapPolicyMgrUserGroupBuilder.tryUploadEntityWithCookie()");
}
return response;
}
private String tryUploadEntityWithCred(Object obj, String apiURL){
if(LOG.isDebugEnabled()){
LOG.debug("==> LdapPolicyMgrUserGroupBuilder.tryUploadEntityInfoWithCred()");
}
String response = null;
ClientResponse clientResp = null;
Gson gson = new GsonBuilder().create();
String jsonString = gson.toJson(obj);
if ( LOG.isDebugEnabled() ) {
LOG.debug("USER GROUP MAPPING" + jsonString);
}
try{
clientResp = ldapUgSyncClient.post(apiURL, null, obj);
}
catch(Throwable t){
LOG.error("Failed to get response, Error is : ", t);
}
if (clientResp != null) {
if (!(clientResp.toString().contains(apiURL))) {
clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND);
} else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
LOG.warn("Credentials response from ranger is 401.");
} else if (clientResp.getStatus() == HttpServletResponse.SC_OK || clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT) {
cookieList = clientResp.getCookies();
for (NewCookie cookie : cookieList) {
if (cookie.getName().equalsIgnoreCase(rangerCookieName)) {
sessionId = cookie.toCookie();
isValidRangerCookie = true;
LOG.info("valid cookie saved ");
break;
}
}
}
if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT
&& clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
sessionId = null;
isValidRangerCookie = false;
}
clientResp.bufferEntity();
response = clientResp.getEntity(String.class);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== LdapPolicyMgrUserGroupBuilder.tryUploadEntityInfoWithCred()");
}
return response;
}
private String tryGetEntityWithCred(String apiURL, int retrievedCount) {
if(LOG.isDebugEnabled()){
LOG.debug("==> LdapPolicyMgrUserGroupBuilder.tryGetEntityWithCred()");
}
String response = null;
ClientResponse clientResp = null;
Map<String, String> queryParams = new HashMap<String, String>();
queryParams.put("pageSize", recordsToPullPerCall);
queryParams.put("startIndex", String.valueOf(retrievedCount));
try{
clientResp = ldapUgSyncClient.get(apiURL, queryParams);
}
catch(Throwable t){
LOG.error("Failed to get response, Error is : ", t);
}
if (clientResp != null) {
if (!(clientResp.toString().contains(apiURL))) {
clientResp.setStatus(HttpServletResponse.SC_NOT_FOUND);
} else if (clientResp.getStatus() == HttpServletResponse.SC_UNAUTHORIZED) {
LOG.warn("Credentials response from ranger is 401.");
} else if (clientResp.getStatus() == HttpServletResponse.SC_OK || clientResp.getStatus() == HttpServletResponse.SC_NO_CONTENT) {
cookieList = clientResp.getCookies();
for (NewCookie cookie : cookieList) {
if (cookie.getName().equalsIgnoreCase(rangerCookieName)) {
sessionId = cookie.toCookie();
isValidRangerCookie = true;
LOG.info("valid cookie saved ");
break;
}
}
}
if (clientResp.getStatus() != HttpServletResponse.SC_OK && clientResp.getStatus() != HttpServletResponse.SC_NO_CONTENT
&& clientResp.getStatus() != HttpServletResponse.SC_BAD_REQUEST) {
sessionId = null;
isValidRangerCookie = false;
}
clientResp.bufferEntity();
response = clientResp.getEntity(String.class);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== LdapPolicyMgrUserGroupBuilder.tryGetEntityWithCred()");
}
return response;
}