下面列出了javax.servlet.http.HttpServletResponse#SC_BAD_REQUEST 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@EntityCustomAction(action = "post", viewKey = EntityView.VIEW_LIST)
public ActionReturn getPost(EntityView view, Map<String, Object> params) {
String userId = getCheckedUser();
String postId = (String) params.get("postId");
if (StringUtils.isBlank(postId)) {
throw new EntityException("You must supply a postId" , "", HttpServletResponse.SC_BAD_REQUEST);
}
Optional<Post> opPost = commonsManager.getPost(postId, true);
if (opPost.isPresent()) {
return new ActionReturn(opPost.get());
} else {
throw new EntityException("No post with id '" + postId + "'" , "", HttpServletResponse.SC_NOT_FOUND);
}
}
@Override
protected IStatus validateParams() {
try {
/* read deploy parameters */
ManifestParseTree manifest = application.getManifest();
ManifestParseTree app = manifest.get("applications").get(0); //$NON-NLS-1$
if (application.getName() != null) {
appName = application.getName();
return Status.OK_STATUS;
}
appName = app.get(CFProtocolConstants.V2_KEY_NAME).getValue();
return Status.OK_STATUS;
} catch (InvalidAccessException e) {
return new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, e.getMessage(), null);
}
}
@EntityCustomAction(action = "deletePost", viewKey = EntityView.VIEW_LIST)
public ActionReturn handleDeletePost(Map<String, Object> params) {
log.debug("handleDeletePost");
getCheckedUser();
String postId = (String) params.get("postId");
String commonsId = (String) params.get("commonsId");
String siteId = (String) params.get("siteId");
if (StringUtils.isBlank(postId) || StringUtils.isBlank(commonsId) || StringUtils.isBlank(siteId)) {
throw new EntityException("You must supply a postId, a commonsId and a siteId."
, "", HttpServletResponse.SC_BAD_REQUEST);
}
if (commonsManager.deletePost(postId)) {
String reference = PostReferenceFactory.getReference(commonsId, postId);
sakaiProxy.postEvent(CommonsEvents.POST_DELETED,
reference,
siteId);
return new ActionReturn("SUCCESS");
} else {
return new ActionReturn("FAIL");
}
}
@Test
public void testCommitOnComplete() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
AsyncStatusServlet asyncStatusServlet =
new AsyncStatusServlet(HttpServletResponse.SC_BAD_REQUEST);
Wrapper wrapper =
Tomcat.addServlet(ctx, "asyncStatusServlet", asyncStatusServlet);
wrapper.setAsyncSupported(true);
ctx.addServletMapping("/asyncStatusServlet", "asyncStatusServlet");
TesterAccessLogValve alv = new TesterAccessLogValve();
ctx.getPipeline().addValve(alv);
tomcat.start();
StringBuilder url = new StringBuilder(48);
url.append("http://localhost:");
url.append(getPort());
url.append("/asyncStatusServlet");
int rc = getUrl(url.toString(), new ByteChunk(), null);
assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);
// Without this test may complete before access log has a chance to log
// the request
Thread.sleep(REQUEST_TIME);
// Check the access log
alv.validateAccessLog(1, HttpServletResponse.SC_BAD_REQUEST, 0,
REQUEST_TIME);
}
@EntityCustomAction(action = "userPerms", viewKey = EntityView.VIEW_LIST)
public Set<String> handleUserPermsGet(EntityView view, Map<String, Object> params) {
String userId = getCheckedUser();
String siteId = (String) params.get("siteId");
String embedder = (String) params.get("embedder");
if (StringUtils.isBlank(siteId) || StringUtils.isBlank(embedder)) {
throw new EntityException("No siteId or embedder supplied", "", HttpServletResponse.SC_BAD_REQUEST);
}
return sakaiProxy.getSitePermissionsForCurrentUser(siteId, embedder);
}
private static int getErrorCode(Exception e) {
if (e instanceof IllegalArgumentException) {
return HttpServletResponse.SC_BAD_REQUEST;
} else if (e instanceof ProducerBusyException) {
return HttpServletResponse.SC_CONFLICT;
} else if (e instanceof ProducerBlockedQuotaExceededError || e instanceof ProducerBlockedQuotaExceededException) {
return HttpServletResponse.SC_SERVICE_UNAVAILABLE;
} else {
return HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
}
}
@Override
protected Map<String, Object> executeImpl(final WebScriptRequest req, Status status, Cache cache)
{
// create map of params (template vars)
Map<String, String> params = req.getServiceMatch().getTemplateVars();
final NodeRef nodeRef = WebScriptUtil.getNodeRef(params);
if (nodeRef == null)
{
String msg = "A valid NodeRef must be specified!";
throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, msg);
}
try
{
Map<String, Object> model = quickShareService.getMetaData(nodeRef);
if (logger.isDebugEnabled())
{
logger.debug("Retrieved limited metadata: "+nodeRef+" ["+model+"]");
}
return model;
}
catch (InvalidNodeRefException inre)
{
logger.error("Unable to find node: "+inre.getNodeRef());
throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find nodeRef: "+inre.getNodeRef());
}
}
@Test
public void testCommitOnComplete() throws Exception {
// Setup Tomcat instance
Tomcat tomcat = getTomcatInstance();
// No file system docBase required
Context ctx = tomcat.addContext("", null);
AsyncStatusServlet asyncStatusServlet =
new AsyncStatusServlet(HttpServletResponse.SC_BAD_REQUEST);
Wrapper wrapper =
Tomcat.addServlet(ctx, "asyncStatusServlet", asyncStatusServlet);
wrapper.setAsyncSupported(true);
ctx.addServletMapping("/asyncStatusServlet", "asyncStatusServlet");
TesterAccessLogValve alv = new TesterAccessLogValve();
ctx.getPipeline().addValve(alv);
tomcat.start();
StringBuilder url = new StringBuilder(48);
url.append("http://localhost:");
url.append(getPort());
url.append("/asyncStatusServlet");
int rc = getUrl(url.toString(), new ByteChunk(), null);
assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);
// Without this test may complete before access log has a chance to log
// the request
Thread.sleep(REQUEST_TIME);
// Check the access log
alv.validateAccessLog(1, HttpServletResponse.SC_BAD_REQUEST, 0,
REQUEST_TIME);
}
/**
* Creates a new site configuration with the given name, a generated id, and the rest of its
* properties given by <code>object</code>.
* @param user User creating the SiteConfiguration
* @param name Name for the SiteConfiguration
* @param workspace Workspace the SiteConfiguration is associated to
* @param object Object from which other properties will be drawn
* @return The created SiteConfiguration.
*/
public static SiteInfo createFromJSON(UserInfo user, String name, String workspace, JSONObject object) throws CoreException {
if (name == null || name.length() == 0)
throw new CoreException(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Name is missing", null));
else if (workspace == null || name.length() == 0)
throw new CoreException(new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, "Workspace is missing", null));
SiteInfo site = SiteInfo.newSiteConfiguration(user, name, workspace);
copyProperties(object, site, false);
site.save(user);
return site;
}
@EntityCustomAction(action = "deleteComment", viewKey = EntityView.VIEW_LIST)
public ActionReturn handleDeleteComment(Map<String, Object> params) {
log.debug("handleDeleteComment");
getCheckedUser();
String siteId = (String) params.get("siteId");
String commonsId = (String) params.get("commonsId");
String postId = (String) params.get("postId");
String embedder = (String) params.get("embedder");
String commentId = (String) params.get("commentId");
String commentCreatorId = (String) params.get("commentCreatorId");
String postCreatorId = (String) params.get("postCreatorId");
if (StringUtils.isBlank(siteId) || StringUtils.isBlank(commonsId) || StringUtils.isBlank(postId)
|| StringUtils.isBlank(embedder) || StringUtils.isBlank(commentId)
|| StringUtils.isBlank(commentCreatorId) || StringUtils.isBlank(postCreatorId)) {
throw new EntityException("You must supply siteId, commonsId, postId, embedder, commentId, commentCreatorId and postCreatorId"
, "", HttpServletResponse.SC_BAD_REQUEST);
}
if (commonsManager.deleteComment(siteId, commonsId, embedder, commentId, commentCreatorId, postCreatorId)) {
String reference = CommonsManager.REFERENCE_ROOT + "/" + commonsId + "/posts/" + postId + "/comments/" + commentId;
sakaiProxy.postEvent(CommonsEvents.COMMENT_DELETED, reference, siteId);
return new ActionReturn("SUCCESS");
} else {
return new ActionReturn("FAIL");
}
}
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;
}
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()");
}
}
/**
* @see org.springframework.extensions.webscripts.WebScript#execute(WebScriptRequest, WebScriptResponse)
*/
public void execute(WebScriptRequest req, WebScriptResponse res)
throws IOException
{
// create map of args
String[] names = req.getParameterNames();
Map<String, String> args = new HashMap<String, String>(names.length, 1.0f);
for (String name : names)
{
args.put(name, req.getParameter(name));
}
// create map of template vars
Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
// create object reference from url
ObjectReference reference = createObjectReferenceFromUrl(args, templateVars);
NodeRef nodeRef = reference.getNodeRef();
if (nodeRef == null)
{
throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find " + reference.toString());
}
// determine attachment
boolean attach = Boolean.valueOf(req.getParameter("a"));
// render content
QName propertyQName = ContentModel.PROP_CONTENT;
String contentPart = templateVars.get("property");
if (contentPart.length() > 0 && contentPart.charAt(0) == ';')
{
if (contentPart.length() < 2)
{
throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "Content property malformed");
}
String propertyName = contentPart.substring(1);
if (propertyName.length() > 0)
{
propertyQName = QName.createQName(propertyName, namespaceService);
}
}
// Stream the content
streamContentLocal(req, res, nodeRef, attach, propertyQName, null);
}
@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);
}
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 IOAuth2Response buildRequestTokenErrorResponse(OAuth2ProtocolException ex)
throws ResponseBuilderException {
return new RequestTokenErrorResponse(HttpServletResponse.SC_BAD_REQUEST, ex);
}
@Override
public void execute(final WebScriptRequest req, final WebScriptResponse res) throws IOException
{
if (! isEnabled())
{
throw new WebScriptException(HttpServletResponse.SC_FORBIDDEN, "QuickShare is disabled system-wide");
}
// create map of template vars (params)
final Map<String, String> params = req.getServiceMatch().getTemplateVars();
final String sharedId = params.get("shared_id");
if (sharedId == null)
{
throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, "A valid sharedId must be specified !");
}
try
{
Pair<String, NodeRef> pair = quickShareSerivce.getTenantNodeRefFromSharedId(sharedId);
final String tenantDomain = pair.getFirst();
final NodeRef nodeRef = pair.getSecond();
TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>()
{
public Void doWork() throws Exception
{
if (! nodeService.getAspects(nodeRef).contains(QuickShareModel.ASPECT_QSHARE))
{
throw new InvalidNodeRefException(nodeRef);
}
// MNT-21118 (XSS prevention)
// Force the attachment in case of asking for the content file only
// (will be overridden for thumbnails)
executeImpl(nodeRef, params, req, res, null, true);
return null;
}
}, tenantDomain);
if (logger.isDebugEnabled())
{
logger.debug("QuickShare - retrieved content: "+sharedId+" ["+nodeRef+"]");
}
}
catch (InvalidSharedIdException ex)
{
logger.error("Unable to find: "+sharedId);
throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find: "+sharedId);
}
catch (InvalidNodeRefException inre)
{
logger.error("Unable to find: "+sharedId+" ["+inre.getNodeRef()+"]");
throw new WebScriptException(HttpServletResponse.SC_NOT_FOUND, "Unable to find: "+sharedId);
}
}
@Override
public boolean handleResult(int httpCode, GoPublisher goPublisher) {
checksumValidationPublisher.publish(httpCode, destOnAgent, goPublisher);
return httpCode < HttpServletResponse.SC_BAD_REQUEST;
}
/**
* Runs a particular report
*/
@EntityCustomAction(action = "runreport", viewKey = EntityView.VIEW_LIST)
public List<StrippedStat> handleRunReport(EntityView view, Map<String, Object> params) {
String userId = developerHelperService.getCurrentUserId();
if (userId == null || userId.length() <= 0) {
throw new EntityException("You must be logged in to list the reportes", "", HttpServletResponse.SC_FORBIDDEN);
}
String siteId = view.getPathSegment(2);
if (log.isDebugEnabled()) {
log.debug("SITE ID:" + siteId);
}
if (!developerHelperService.isUserAllowedInEntityReference("/user/" + userId, "sitestats.view", "/site/" + siteId)) {
throw new EntityException("You don't have access to sitestats in this site", "", HttpServletResponse.SC_FORBIDDEN);
}
String reportIdString = (String) params.get("id");
if (reportIdString == null || reportIdString.length() <= 0) {
throw new EntityException("You must supply a numeric report id", "", HttpServletResponse.SC_BAD_REQUEST);
}
if (log.isDebugEnabled()) {
log.debug("REPORT ID:" + reportIdString);
}
long reportId = -1;
try {
reportId = Long.parseLong(reportIdString);
} catch (NumberFormatException nfe) {
throw new EntityException("You must supply a numeric report id", "", HttpServletResponse.SC_BAD_REQUEST);
}
ReportDef reportDef = reportManager.getReportDefinition(reportId);
if (reportDef == null) {
throw new EntityException("Report with id '" + reportId + "' doesn't exist.", "", HttpServletResponse.SC_BAD_REQUEST);
}
// system-wide reports will not have siteID set, and will try to run across all sites--which is bad
if (StringUtils.isBlank(reportDef.getReportParams().getSiteId())) {
reportDef.getReportParams().setSiteId(siteId);
}
Report report = reportManager.getReport(reportDef, true);
List<StrippedStat> stripped = new ArrayList<StrippedStat>();
for (Stat stat : report.getReportData()) {
stripped.add(new StrippedStat(stat));
}
return stripped;
}
public RequestException ( final String message )
{
this ( HttpServletResponse.SC_BAD_REQUEST, message );
}