下面列出了javax.servlet.http.HttpServletResponse#SC_UNAUTHORIZED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Deprecated
public Object getEntity(EntityReference ref) {
String id = ref.getId();
if (id == null) {
return new Option();
}
String currentUser = developerHelperService.getCurrentUserReference();
if (currentUser == null) {
throw new EntityException("Anonymous users cannot view specific options", ref.getId(), HttpServletResponse.SC_UNAUTHORIZED);
}
Option option = getOptionById(id);
if (developerHelperService.isEntityRequestInternal(ref.toString())) {
// ok to retrieve internally
} else {
// need to security check
if (developerHelperService.isUserAdmin(currentUser)) {
// ok to view this vote
} else {
// not allowed to view
throw new SecurityException("User ("+currentUser+") cannot view option ("+ref+")");
}
}
return option;
}
public static ServerStatus configureHttpMethod(HttpMethod method, Cloud cloud) throws JSONException {
method.addRequestHeader(new Header("Accept", "application/json"));
method.addRequestHeader(new Header("Content-Type", "application/json"));
//set default socket timeout for connection
HttpMethodParams params = method.getParams();
params.setSoTimeout(DEFAULT_SOCKET_TIMEOUT);
params.setContentCharset("UTF-8");
method.setParams(params);
if (cloud.getAccessToken() != null){
method.addRequestHeader(new Header("Authorization", "bearer " + cloud.getAccessToken().getString("access_token")));
return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK);
}
JSONObject errorJSON = new JSONObject();
try {
errorJSON.put(CFProtocolConstants.V2_KEY_REGION_ID, cloud.getRegion());
errorJSON.put(CFProtocolConstants.V2_KEY_REGION_NAME, cloud.getRegionName() != null ? cloud.getRegionName() : "");
errorJSON.put(CFProtocolConstants.V2_KEY_ERROR_CODE, "CF-NotAuthenticated");
errorJSON.put(CFProtocolConstants.V2_KEY_ERROR_DESCRIPTION, "Not authenticated");
} catch (JSONException e) {
// do nothing
}
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_UNAUTHORIZED, "Not authenticated", errorJSON, null);
}
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
String requestUri = request.getRequestURI();
int status = HttpServletResponse.SC_UNAUTHORIZED;
String message = "访问令牌不合法";
log.error("客户端访问{}请求失败: {}", requestUri, message, authException);
FebsUtil.makeJsonResponse(response, status, new FebsResponse().message(message));
}
@Deprecated
public void deleteEntity(EntityReference ref, Map<String, Object> params) {
String id = ref.getId();
String userReference = developerHelperService.getCurrentUserReference();
if (userReference == null) {
throw new EntityException("Anonymous user cannot delete option", ref.getId(), HttpServletResponse.SC_UNAUTHORIZED);
}
Option option = getOptionById(id);
if (option == null) {
throw new IllegalArgumentException("No option found to delete for the given reference: " + ref);
}
checkOptionPermission(userReference, option);
pollListManager.deleteOption(option);
}
@Deprecated
public List<?> getEntities(EntityReference ref, Search search) {
// get the pollId
Restriction pollRes = search.getRestrictionByProperty("pollId");
if (pollRes == null || pollRes.getSingleValue() == null) {
throw new IllegalArgumentException("Must include a non-null pollId in order to retreive a list of votes");
}
Long pollId = null;
try {
pollId = developerHelperService.convert(pollRes.getSingleValue(), Long.class);
} catch (UnsupportedOperationException e) {
throw new IllegalArgumentException("Invalid: pollId must be a long number: " + e.getMessage(), e);
}
// get the poll
Poll poll = pollListManager.getPollById(pollId);
if (poll == null) {
throw new IllegalArgumentException("pollId ("+pollId+") is invalid and does not match any known polls");
} else {
boolean allowedPublic = pollListManager.isPollPublic(poll);
if (!allowedPublic) {
String userReference = developerHelperService.getCurrentUserReference();
if (userReference == null) {
throw new EntityException("User must be logged in in order to access poll data", ref.getId(), HttpServletResponse.SC_UNAUTHORIZED);
} else {
boolean allowedManage = false;
boolean allowedVote = false;
allowedManage = developerHelperService.isUserAllowedInEntityReference(userReference, PollListManager.PERMISSION_ADD, "/site/" + poll.getSiteId());
allowedVote = developerHelperService.isUserAllowedInEntityReference(userReference, PollListManager.PERMISSION_VOTE, "/site/" + poll.getSiteId());
if ( !(allowedManage || allowedVote)) {
throw new SecurityException("User ("+userReference+") not allowed to access poll data: " + ref);
}
}
}
}
// get the options
List<Option> options = pollListManager.getOptionsForPoll(pollId);
return options;
}
@EntityCustomAction(action = "option-update", viewKey = EntityView.VIEW_EDIT)
public void updateOptionEntity(EntityReference ref,
Map<String, Object> params) {
String id = ref.getId();
if (id == null) {
throw new IllegalArgumentException(
"The reference must include an id for updates (id is currently null)");
}
String userReference = developerHelperService.getCurrentUserReference();
if (userReference == null) {
throw new EntityException("Anonymous user cannot update option",
ref.getId(), HttpServletResponse.SC_UNAUTHORIZED);
}
Option current = getOptionById(id);
if (current == null) {
throw new IllegalArgumentException(
"No option found to update for the given reference: " + ref);
}
Option option = new Option();
// copy from params to Option
copyParamsToObject(params, option);
checkOptionPermission(userReference, current);
developerHelperService.copyBean(option, current, 0, new String[] {
"id", "pollId", "UUId" }, true);
boolean saved = pollListManager.saveOption(current);
if (!saved) {
throw new IllegalStateException("Unable to update option ("
+ option + ") for user (" + userReference + "): " + ref);
}
}
private void validateStatusCode(SimpleHttpResponse httpResponse) throws InvalidResponseException {
final int statusCode = httpResponse.getResponseCode();
final String statusLine = httpResponse.getResponseMessage();
if (statusCode == HttpServletResponse.SC_OK) {
return;
}
if (statusCode == HttpServletResponse.SC_CREATED) {
return;
}
String errMessage;
switch (statusCode) {
case HttpServletResponse.SC_NOT_FOUND:
errMessage = String.format("Requesting path [%s] was not found.", httpResponse.getRequestPath());
break;
case HttpServletResponse.SC_UNAUTHORIZED:
errMessage = String.format("Missing or incorrect credentials for path [%s].", httpResponse.getRequestPath());
break;
case HttpServletResponse.SC_FORBIDDEN:
errMessage = String.format("Unauthorized request to path [%s].", httpResponse.getRequestPath());
break;
default:
errMessage = String.format("Requesting path [%s] returns unexpected response.", httpResponse.getRequestPath());
}
errMessage += String.format(" Service returned [%d] [%s].", statusCode, statusLine);
throw new InvalidResponseException(errMessage);
}
private String getCheckedUser() throws EntityException {
String userId = developerHelperService.getCurrentUserId();
if (userId == null) {
throw new EntityException("You must be logged in", "", HttpServletResponse.SC_UNAUTHORIZED);
}
return userId;
}
private void doTestBasic(String uri,
TestSSOnonLoginAndBasicAuthenticator.BasicCredentials credentials,
boolean useCookie, int expectedRC) throws Exception {
Map<String,List<String>> reqHeaders = new HashMap<>();
Map<String,List<String>> respHeaders = new HashMap<>();
if (useCookie && (cookies != null)) {
addCookies(reqHeaders);
}
else {
if (credentials != null) {
List<String> auth = new ArrayList<>();
auth.add(credentials.getCredentials());
reqHeaders.put(CLIENT_AUTH_HEADER, auth);
}
}
ByteChunk bc = new ByteChunk();
int rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders,
respHeaders);
Assert.assertEquals("Unexpected Return Code", expectedRC, rc);
if (expectedRC != HttpServletResponse.SC_OK) {
Assert.assertTrue(bc.getLength() > 0);
if (expectedRC == HttpServletResponse.SC_UNAUTHORIZED) {
// The server should identify the acceptable method(s)
boolean methodFound = false;
List<String> authHeaders = respHeaders.get(SERVER_AUTH_HEADER);
for (String authHeader : authHeaders) {
if (authHeader.indexOf(NICE_METHOD) > -1) {
methodFound = true;
break;
}
}
Assert.assertTrue(methodFound);
}
}
else {
String thePage = bc.toString();
Assert.assertNotNull(thePage);
Assert.assertTrue(thePage.startsWith("OK"));
if (useCookie) {
List<String> newCookies = respHeaders.get(SERVER_COOKIE_HEADER);
if (newCookies != null) {
// harvest cookies whenever the server sends some new ones
cookies = newCookies;
}
}
else {
encodedURL = "";
final String start = "<a href=\"";
final String end = "\">";
int iStart = thePage.indexOf(start);
int iEnd = 0;
if (iStart > -1) {
iStart += start.length();
iEnd = thePage.indexOf(end, iStart);
if (iEnd > -1) {
encodedURL = thePage.substring(iStart, iEnd);
}
}
}
}
}
@EntityCustomAction(action = "grades", viewKey = EntityView.VIEW_LIST)
public ActionReturn getGrades(Map<String, Object> params) {
String userId = sessionManager.getCurrentSessionUserId();
if (StringUtils.isBlank(userId)) {
log.warn("getGrades attempt when not logged in");
throw new EntityException("You need to be logged in to get grades", "", HttpServletResponse.SC_UNAUTHORIZED);
}
String courseId = (String) params.get("courseId");
String gradableId = (String) params.get("gradableId");
if (StringUtils.isBlank(courseId) || StringUtils.isBlank(gradableId)) {
throw new EntityException("You need to supply a courseId and a gradableId", "", HttpServletResponse.SC_BAD_REQUEST);
}
Site site = null;
try {
site = siteService.getSite(courseId);
} catch (IdUnusedException iue) {
throw new EntityException("The courseId (site id) you supplied is invalid", "", HttpServletResponse.SC_BAD_REQUEST);
}
if (!securityService.unlock(userId, SECURE_GRADE_ASSIGNMENT_SUBMISSION, "/site/" + courseId)) {
throw new EntityException("You don't have permission to get grades", "", HttpServletResponse.SC_FORBIDDEN);
}
Assignment assignment;
try {
assignment = assignmentService.getAssignment(gradableId);
} catch (IdUnusedException idue) {
throw new EntityException("No gradable for id " + gradableId, "", HttpServletResponse.SC_BAD_REQUEST);
} catch (PermissionException pe) {
throw new EntityException("You don't have permission to read the assignment", "", HttpServletResponse.SC_FORBIDDEN);
}
// A map of submissionId -> grade
Map<String, String> grades = assignment.getSubmissions().stream().collect(Collectors.toMap(s -> s.getId(), s -> {
Set<AssignmentSubmissionSubmitter> submitters = s.getSubmitters();
if (submitters.size() > 0) {
if (assignment.getTypeOfGrade() == Assignment.GradeType.PASS_FAIL_GRADE_TYPE) {
return s.getGrade() == null ? "ungraded" : s.getGrade();
} else {
return assignmentService.getGradeDisplay(s.getGrade(), assignment.getTypeOfGrade(), assignment.getScaleFactor());
}
} else {
return "";
}
}));
Map<String, GraderUser> students = new HashMap<>();
try {
for (String studentId : site.getUsersIsAllowed(SECURE_ADD_ASSIGNMENT_SUBMISSION)) {
students.put(studentId, new GraderUser(userDirectoryService.getUser(studentId)));
}
} catch (UserNotDefinedException e) {
throw new EntityException("Failed to setup user", courseId);
}
Map<String, Object> data = new HashMap<>();
data.put("students", students);
data.put("grades", grades);
return new ActionReturn(data);
}
/**
* Process response received from backend service and copy it to origin response of
* client.
*
* @param request
* origin request of this Web application
* @param response
* origin response of this Web application; this is where the
* backend response is copied to
* @param backendResponse
* the response of the backend service
* @param proxyUrl
* the URL that should replace the <code>rewriteUrl</code>
* @param rewriteUrl
* the URL that should be rewritten
*/
private void processBackendResponse(HttpServletRequest request, HttpServletResponse response, HttpResponse backendResponse, String proxyUrl, String rewriteUrl)
throws IOException, ServletException {
// copy response status code
int status = backendResponse.getStatusLine().getStatusCode();
response.setStatus(status);
LOGGER.debug("backend response status code: " + status);
// filter the headers to suppress the authentication dialog (only for
// 401 - unauthorized)
List<String> blockedHeaders = null;
if (status == HttpServletResponse.SC_UNAUTHORIZED && request.getHeader("authorization") != null
&& request.getHeader("suppress-www-authenticate") != null) {
blockedHeaders = Arrays.asList(new String[] { "www-authenticate" });
} else {
// for rewriting the URLs in the response, content-length, content-encoding
// and transfer-encoding (for chunked content) headers are removed and handled specially.
blockedHeaders = Arrays.asList(new String[] { "content-length", "transfer-encoding", "content-encoding" });
}
// copy backend response headers and content
LOGGER.debug("backend response headers: ");
for (Header header : backendResponse.getAllHeaders()) {
if (!blockedHeaders.contains(header.getName().toLowerCase())) {
response.addHeader(header.getName(), header.getValue());
LOGGER.debug(" => " + header.getName() + ": " + header.getValue());
} else {
LOGGER.debug(" => " + header.getName() + ": blocked response header");
}
}
handleContentEncoding(backendResponse);
// pipe and return the response
HttpEntity entity = backendResponse.getEntity();
if (entity != null) {
// rewrite URL in the content of the response to make sure that
// internal URLs point to the proxy servlet as well
// determine charset and content as String
String charset = EntityUtils.getContentCharSet(entity);
String content = EntityUtils.toString(entity);
LOGGER.debug("URL rewriting:");
LOGGER.debug(" => rewriteUrl: " + rewriteUrl);
LOGGER.debug(" => proxyUrl: " + proxyUrl);
// replace the rewriteUrl with the targetUrl
content = content.replaceAll(rewriteUrl, proxyUrl);
// get the bytes and open a stream (by default HttpClient uses ISO-8859-1)
byte[] contentBytes = charset != null ? content.getBytes(charset) : content.getBytes(ISO_8859_1);
InputStream is = new ByteArrayInputStream(contentBytes);
// set the new content length
response.setContentLength(contentBytes.length);
// return the modified content
pipe(is, response.getOutputStream());
}
}
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;
}
@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;
}
private void doTestBasic(String uri,
TestSSOnonLoginAndBasicAuthenticator.BasicCredentials credentials,
boolean useCookie, int expectedRC) throws Exception {
Map<String,List<String>> reqHeaders = new HashMap<String,List<String>>();
Map<String,List<String>> respHeaders = new HashMap<String,List<String>>();
if (useCookie && (cookies != null)) {
reqHeaders.put(CLIENT_COOKIE_HEADER, cookies);
}
else {
if (credentials != null) {
List<String> auth = new ArrayList<String>();
auth.add(credentials.getCredentials());
reqHeaders.put(CLIENT_AUTH_HEADER, auth);
}
}
ByteChunk bc = new ByteChunk();
int rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders,
respHeaders);
assertEquals("Unexpected Return Code", expectedRC, rc);
if (expectedRC != HttpServletResponse.SC_OK) {
assertTrue(bc.getLength() > 0);
if (expectedRC == HttpServletResponse.SC_UNAUTHORIZED) {
// The server should identify the acceptable method(s)
boolean methodFound = false;
List<String> authHeaders = respHeaders.get(SERVER_AUTH_HEADER);
for (String authHeader : authHeaders) {
if (authHeader.indexOf(NICE_METHOD) > -1) {
methodFound = true;
break;
}
}
assertTrue(methodFound);
}
}
else {
String thePage = bc.toString();
assertNotNull(thePage);
assertTrue(thePage.startsWith("OK"));
if (useCookie) {
List<String> newCookies = respHeaders.get(SERVER_COOKIE_HEADER);
if (newCookies != null) {
// harvest cookies whenever the server sends some new ones
cookies = newCookies;
}
}
else {
encodedURL = "";
final String start = "<a href=\"";
final String end = "\">";
int iStart = thePage.indexOf(start);
int iEnd = 0;
if (iStart > -1) {
iStart += start.length();
iEnd = thePage.indexOf(end, iStart);
if (iEnd > -1) {
encodedURL = thePage.substring(iStart, iEnd);
}
}
}
}
}
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;
}
@Override
public void grantRole(final GrantRevokeRoleRequest request) throws Exception {
if(LOG.isDebugEnabled()) {
LOG.debug("==> RangerAdminRESTClient.grantRole(" + request + ")");
}
ClientResponse response = null;
UserGroupInformation user = MiscUtil.getUGILoginUser();
boolean isSecureMode = user != null && UserGroupInformation.isSecurityEnabled();
String relativeURL = RangerRESTUtils.REST_URL_SERVICE_GRANT_ROLE + serviceNameUrlParam;
if (isSecureMode) {
PrivilegedAction<ClientResponse> action = new PrivilegedAction<ClientResponse>() {
public ClientResponse run() {
ClientResponse clientResp = null;
try {
clientResp = restClient.put(relativeURL, null, request);
} catch (Exception e) {
LOG.error("Failed to get response, Error is : "+e.getMessage());
}
return clientResp;
}
};
if (LOG.isDebugEnabled()) {
LOG.debug("grant role as user " + user);
}
response = user.doAs(action);
} else {
response = restClient.put(relativeURL, null, request);
}
if(response != null && response.getStatus() != HttpServletResponse.SC_OK) {
RESTResponse resp = RESTResponse.fromClientResponse(response);
LOG.error("grantRole() 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());
} else if(response == null) {
throw new Exception("unknown error during grantRole. serviceName=" + serviceName);
}
if(LOG.isDebugEnabled()) {
LOG.debug("<== RangerAdminRESTClient.grantRole(" + request + ")");
}
}
@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 String tryGetEntityWithCookie(String apiURL, int retrievedCount) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> PolicyMgrUserGroupBuilder.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 = uGSyncClient.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(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.tryGetEntityWithCookie()");
}
return response;
}
@Override
public int getStatus() {
return HttpServletResponse.SC_UNAUTHORIZED;
}
private Object getTopic(Long topicId,String siteId,String userId) {
if(log.isDebugEnabled()) {
log.debug("getTopic(" + topicId + "," + siteId + "," + userId + ")");
}
// This call gets the attachments for the messages but not the topic. Unexpected, yes. Cool, not.
DiscussionTopic fatTopic = (DiscussionTopic)forumManager.getTopicByIdWithMessagesAndAttachments(topicId);
if(!uiPermissionsManager.isRead(topicId,fatTopic.getDraft(),false,userId,forumManager.getContextForTopicById(topicId))) {
log.error("'" + userId + "' is not authorised to read topic '" + topicId + "'.");
throw new EntityException("You are not authorised to read this topic.","",HttpServletResponse.SC_UNAUTHORIZED);
}
SparseTopic sparseTopic = new SparseTopic(fatTopic);
// Setup the total and read message counts on the topic
List<Long> topicIds = new ArrayList<Long>();
topicIds.add(fatTopic.getId());
List<Object[]> totalCounts = forumManager.getMessageCountsForMainPage(topicIds);
if(totalCounts.size() > 0) {
sparseTopic.setTotalMessages(((Long) totalCounts.get(0)[1]).intValue());
} else {
sparseTopic.setTotalMessages(0);
}
List<Object[]> readCounts = forumManager.getReadMessageCountsForMainPage(topicIds);
if(readCounts.size() > 0) {
sparseTopic.setReadMessages(((Long) readCounts.get(0)[1]).intValue());
} else {
sparseTopic.setReadMessages(0);
}
List<SparseMessage> messages = new ArrayList<SparseMessage>();
for(Message fatMessage : (List<Message>) fatTopic.getMessages()) {
SparseMessage sparseMessage = new SparseMessage(fatMessage,/* readStatus = */ false,/* addAttachments = */ true,developerHelperService.getServerURL());
messages.add(sparseMessage);
}
List<SparseThread> threads = new MessageUtils().getThreadsWithCounts(messages, forumManager, userId);
sparseTopic.setThreads(threads);
return sparseTopic;
}