List of usage examples for javax.servlet.http HttpServletResponse SC_FORBIDDEN
int SC_FORBIDDEN
To view the source code for javax.servlet.http HttpServletResponse SC_FORBIDDEN.
Click Source Link
From source file:com.seajas.search.attender.controller.FeedController.java
/** * Handle the request.//from w w w.jav a 2s .com * * @param request * @param response * @param locale * @throws Exception */ @RequestMapping(method = RequestMethod.GET) public void handleRequest(final HttpServletRequest request, final HttpServletResponse response, final Locale locale) throws Exception { String path = request.getPathInfo(); Integer results = null; String feedType = null; // The number of results may be optionally provided if (!StringUtils.isEmpty(request.getParameter(PARAM_RESULTS))) try { results = Integer.valueOf(request.getParameter(PARAM_RESULTS)); } catch (NumberFormatException e) { throw new Exception("Invalid result number given"); } if (!StringUtils.isEmpty(request.getParameter(PARAM_TYPE))) feedType = request.getParameter(PARAM_TYPE); // Reconstruct the URL from the request String baseUrl = request.getRequestURL().toString(); if (!StringUtils.isEmpty(request.getQueryString())) baseUrl += "?" + request.getQueryString(); if (path != null && path.startsWith("/feed")) path = path.substring(5); if (path != null && path.startsWith("/")) path = path.substring(1); if (!StringUtils.isEmpty(path)) { String[] pathParts = path.split("/"); // The first part should always indicate the UUID String profileUUID = pathParts[0]; // The second part is optional and defines the notification type NotificationType notificationType = pathParts.length > 1 && pathParts[1].equalsIgnoreCase(NotificationType.Weekly.toString()) ? NotificationType.Weekly : NotificationType.Daily; // First retrieve the profile and create the actual feed Profile profile = attenderService.getProfileByUUID(profileUUID); if (profile == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown feed '" + profileUUID + "'"); return; } // Must have at least one confirmed subscriber Boolean isConfirmedOnce = false; for (ProfileSubscriber subscriber : profile.getSubscribers()) if (subscriber.getIsConfirmed()) { isConfirmedOnce = true; break; } if (!isConfirmedOnce) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "This feed has no confirmed subscribers"); return; } SyndFeed result = feedService.createFeed(profile, notificationType, results, baseUrl, locale); // Set the feed type, or revert to the default if (feedType != null && availableFeedTypes.contains(feedType)) result.setFeedType(feedType); else result.setFeedType("rss_2.0"); // Set the response type and write out the result response.setContentType("application/xml; charset=UTF-8"); SyndFeedOutput output = new SyndFeedOutput(); output.output(result, response.getWriter()); } else response.sendError(HttpServletResponse.SC_NOT_FOUND, "No feed given"); }
From source file:com.moss.appkeep.server.HttpPublisher.java
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws java.io.IOException, javax.servlet.ServletException { ComponentRequest cr = parse(request); if (cr != null) { final StoredComponent c = data.components.get(cr.componentId, null, LockMode.DEFAULT); if (c == null) { completeWithError("No such component:" + cr.componentId, HttpServletResponse.SC_BAD_REQUEST, response);/* w w w . j ava 2 s .c om*/ } if (c.type() != cr.componentType) { completeWithError("Invalid type for component: " + cr.componentType, HttpServletResponse.SC_BAD_REQUEST, response); } if (!c.isPublic()) { completeWithError( "ACCESS DENIED: component " + cr.componentId + " is not configured for public access", HttpServletResponse.SC_FORBIDDEN, response); return; } OutputStream out = response.getOutputStream(); // FIND THE COMPONENT InputStream i = tool.getComponent(c, cr.endorsements); // WRITE THE DATA TO THE CLIENT try { byte[] buf = new byte[1024 * 100]; for (int x = i.read(buf); x != -1; x = i.read(buf)) { out.write(buf, 0, x); } out.close(); } finally { i.close(); } } }
From source file:eu.trentorise.smartcampus.permissionprovider.controller.BasicProfileController.java
@RequestMapping(method = RequestMethod.GET, value = "/accountprofile/me") public @ResponseBody AccountProfile findAccountProfile(HttpServletResponse response) throws IOException { try {/*from w w w . ja v a 2 s . c o m*/ Long user = getUserId(); if (user == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); return null; } return profileManager.getAccountProfileById(user.toString()); } catch (Exception e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } }
From source file:com.sap.dirigible.runtime.registry.RegistryServlet.java
@Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { String repositoryPath = null; final String requestPath = request.getPathInfo(); boolean deep = false; if (requestPath == null) { deep = true;/*from w ww . java 2s .c o m*/ } final OutputStream out = response.getOutputStream(); try { repositoryPath = extractRepositoryPath(request); final IEntity entity = getEntity(repositoryPath, request); byte[] data; if (entity != null) { if (entity instanceof IResource) { data = buildResourceData(entity, request, response); } else if (entity instanceof ICollection) { String collectionPath = request.getRequestURI().toString(); String acceptHeader = request.getHeader(ACCEPT_HEADER); if (acceptHeader != null && acceptHeader.contains(JSON)) { if (!collectionPath.endsWith(IRepository.SEPARATOR)) { collectionPath += IRepository.SEPARATOR; } data = buildCollectionData(deep, entity, collectionPath); } else { // welcome file support IResource index = ((ICollection) entity).getResource(INDEX_HTML); if (index.exists() && (collectionPath.endsWith(IRepository.SEPARATOR))) { data = buildResourceData(index, request, response); } else { // listing of collections is forbidden exceptionHandler(response, repositoryPath, HttpServletResponse.SC_FORBIDDEN, LISTING_OF_FOLDERS_IS_FORBIDDEN); return; } } } else { exceptionHandler(response, repositoryPath, HttpServletResponse.SC_FORBIDDEN, LISTING_OF_FOLDERS_IS_FORBIDDEN); return; } } else { exceptionHandler(response, repositoryPath, HttpServletResponse.SC_NOT_FOUND, String.format("Resource at [%s] does not exist", requestPath)); return; } if (entity instanceof IResource) { final IResource resource = (IResource) entity; String mimeType = null; String extension = ContentTypeHelper.getExtension(resource.getName()); if ((mimeType = ContentTypeHelper.getContentType(extension)) != null) { response.setContentType(mimeType); } else { response.setContentType(resource.getContentType()); } } sendData(out, data); } catch (final IllegalArgumentException ex) { exceptionHandler(response, repositoryPath, HttpServletResponse.SC_BAD_REQUEST, ex.getMessage()); } catch (final MissingResourceException ex) { exceptionHandler(response, repositoryPath, HttpServletResponse.SC_NO_CONTENT, ex.getMessage()); } catch (final RuntimeException ex) { exceptionHandler(response, repositoryPath, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()); } finally { out.flush(); out.close(); } }
From source file:com.jaspersoft.jasperserver.rest.services.RESTUser.java
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException { try {//from ww w . j a v a 2 s .c o m String userName = restUtils.extractResourceName(req.getPathInfo()); WSUser user = restUtils.populateServiceObject(restUtils.unmarshal(WSUser.class, req.getInputStream())); if (log.isDebugEnabled()) { log.debug("un Marshaling OK"); } if (validateUserForPutOrUpdate(user)) { if (!isAlreadyAUser(user)) { userAndRoleManagementService.putUser(user); restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, ""); } else { throw new ServiceException(HttpServletResponse.SC_FORBIDDEN, "user " + user.getUsername() + "already exists"); } } else throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "check request parameters"); } catch (AxisFault axisFault) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, axisFault.getLocalizedMessage()); } catch (IOException e) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage()); } catch (JAXBException e) { throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage()); } }
From source file:net.bhira.sample.api.controller.CompanyController.java
/** * Fetch the instance of {@link net.bhira.sample.model.Company} represented by given companyId * and return it as JSON object./*w w w . jav a 2 s. c o m*/ * * @param companyId * the ID for {@link net.bhira.sample.model.Company}. * @param response * the http response to which the results will be written. * @return an instance of {@link net.bhira.sample.model.Company} as JSON. */ @RequestMapping(value = "/company/{companyId}", method = RequestMethod.GET) @ResponseBody public Callable<String> getCompany(@PathVariable long companyId, HttpServletResponse response) { return new Callable<String>() { public String call() throws Exception { String body = ""; try { LOG.debug("servicing GET company/{}", companyId); Company company = companyService.load(companyId); LOG.debug("GET company/{}, found = {}", companyId, company != null); if (company == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { body = JsonUtil.createGson().toJson(company); } } catch (Exception ex) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); body = ex.getLocalizedMessage(); LOG.warn("Error loading company/{}. {}", companyId, body); LOG.debug("Load error stacktrace: ", ex); } return body; } }; }
From source file:iddb.web.security.service.UserServiceFilter.java
private boolean checkRoles(Subject s, HttpServletRequest req, HttpServletResponse resp, String p) throws IOException { if (s.isAuthenticated()) { Set<String> r = urls.get(p); for (String role : r) { if ("*".equals(role) || s.hasRole(role)) { log.debug("Allowed"); return true; }//from w w w. j a v a2s .c o m log.debug("Forbidden"); resp.sendError(HttpServletResponse.SC_FORBIDDEN); } } else { log.debug("Redirect to Login"); UrlReverse reverse = new UrlReverse(this.context); try { resp.sendRedirect(req.getContextPath() + reverse.resolve("login") + "?next=" + URLEncoder.encode(req.getRequestURI(), "UTF-8")); } catch (RuleNotFoundException e) { log.error(e.getMessage()); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } catch (ReverseException e) { log.error(e.getMessage()); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } return false; }
From source file:net.duckling.ddl.service.authenticate.impl.AuthenticationServiceImpl.java
public void commit(HttpServletRequest request, HttpServletResponse response) { String viewUrl = policy.getSavedSuccessURL(request); String failURL = policy.getSavedFailURL(request); try {/*from ww w . j a v a2 s . com*/ Collection<Principal> principals = provider.commit(request); VWBSession vwbsession = VWBSession.findSession(request); if (principals == null || principals.size() == 0) { LOGGER.info("Failed to authenticate user."); vwbsession.setStatus(VWBSession.ANONYMOUS); if (failURL != null) { response.sendRedirect(failURL); } else { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } else { vwbsession.setPrincipals(principals); updateCurrentUserInformation(request); LOGGER.info("Successfully authenticated user."); // Redirect! LOGGER.info("Redirecting user to " + viewUrl); redirect(request, response, viewUrl); } } catch (IOException e) { LOGGER.error("Error ocurred while parse user's credential."); LOGGER.debug("Detail is:", e); } finally { policy.clearUrls(request); } }
From source file:com.smartgwt.extensions.fileuploader.server.DownloadServlet.java
private void reportError(HttpServletResponse response) { try {//from ww w . ja va 2 s. c om response.sendError(HttpServletResponse.SC_FORBIDDEN, "You are not allowed to view that file"); } catch (IOException e) { } }
From source file:org.shredzone.cilla.view.HeaderView.java
/** * Streams the uncropped header image./*w w w . j a va 2 s. co m*/ */ @View(pattern = "/header/full/${header.id}-${#type}.${#suffix(header.headerImage.contentType)}") @View(pattern = "/header/full/${header.id}.${#suffix(header.headerImage.contentType)}") public void headerUncroppedView(@PathPart("header.id") Header header, @Optional @PathPart("#type") String type, HttpServletRequest req, HttpServletResponse resp) throws ViewException, CillaServiceException { if (!headerService.isVisible(header)) { throw new ErrorResponseException(HttpServletResponse.SC_FORBIDDEN); } ImageProcessing ip = null; if (type != null) { ip = imageProcessingManager.createImageProcessing(type); if (ip == null) { throw new ErrorResponseException(HttpServletResponse.SC_NOT_FOUND); } } ResourceDataSource ds = headerService.getFullImage(header, ip); streamDataSource(ds, req, resp); }