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:de.mpg.escidoc.pubman.sword.PubManDepositServlet.java
/** * Process a POST request./*from w w w. j ava2 s .c o m*/ * @param HttpServletRequest * @param HttpServletResponse * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.pubMan = new PubManSwordServer(); SwordUtil util = new SwordUtil(); Deposit deposit = new Deposit(); AccountUserVO user = null; this.errorDoc = new PubManSwordErrorDocument(); DepositResponse dr = null; // Authentification --------------------------------------------- String usernamePassword = this.getUsernamePassword(request); if (usernamePassword == null) { this.errorDoc.setSummary("No user credentials provided."); this.errorDoc.setErrorDesc(swordError.ErrorBadRequest); this.validDeposit = false; } else { int p = usernamePassword.indexOf(":"); if (p != -1) { deposit.setUsername(usernamePassword.substring(0, p)); deposit.setPassword(usernamePassword.substring(p + 1)); user = util.getAccountUser(deposit.getUsername(), deposit.getPassword()); this.pubMan.setCurrentUser(user); } } try { // Deposit -------------------------------------------------- //Check if login was successfull if (this.pubMan.getCurrentUser() == null && this.validDeposit) { this.errorDoc.setSummary("Login user: " + deposit.getUsername() + " failed."); this.errorDoc.setErrorDesc(swordError.AuthentificationFailure); this.validDeposit = false; } //Check if collection was provided this.collection = request.getParameter("collection"); if ((this.collection == null || this.collection.equals("")) && this.validDeposit) { this.collection = request.getParameter("collection"); this.errorDoc.setSummary("No collection provided in request."); this.errorDoc.setErrorDesc(swordError.ErrorBadRequest); this.validDeposit = false; } //Check if user has depositing rights for this collection else { if (!util.checkCollection(this.collection, user) && this.validDeposit) { this.errorDoc.setSummary("User: " + deposit.getUsername() + " does not have depositing rights for collection " + this.collection + "."); this.errorDoc.setErrorDesc(swordError.AuthorisationFailure); this.validDeposit = false; } } deposit.setFile(request.getInputStream()); deposit = this.readHttpHeader(deposit, request); //Check if metadata format is supported if (!util.checkMetadatFormat(deposit.getFormatNamespace())) { throw new SWORDContentTypeException(); } if (this.validDeposit) { // Get the DepositResponse dr = this.pubMan.doDeposit(deposit, this.collection); } } catch (SWORDAuthenticationException sae) { response.sendError(HttpServletResponse.SC_FORBIDDEN, this.getError()); this.logger.error(sae.toString()); this.validDeposit = false; } catch (SWORDContentTypeException e) { this.errorDoc.setSummary("File format not supported."); this.errorDoc.setErrorDesc(swordError.ErrorContent); this.validDeposit = false; } catch (ContentStreamNotFoundException e) { this.errorDoc.setSummary("No metadata File was found."); this.errorDoc.setErrorDesc(swordError.ErrorBadRequest); this.validDeposit = false; } catch (ItemInvalidException e) { ValidationReportItemVO itemReport = null; ValidationReportVO report = e.getReport(); String error = ""; for (int i = 0; i < report.getItems().size(); i++) { itemReport = report.getItems().get(i); error += itemReport.getContent() + "\n"; } this.errorDoc.setSummary(error); this.errorDoc.setErrorDesc(swordError.ValidationFailure); this.validDeposit = false; } catch (PubItemStatusInvalidException e) { logger.error("Error in sword processing", e); this.errorDoc.setSummary("Provided item has wrong status."); this.errorDoc.setErrorDesc(swordError.ErrorBadRequest); this.validDeposit = false; } catch (Exception ioe) { logger.error("Error in sword processing", ioe); this.errorDoc.setSummary("An internal server error occurred."); this.errorDoc.setErrorDesc(swordError.InternalError); this.validDeposit = false; } try { //Write response atom if (this.validDeposit) { response.setStatus(dr.getHttpResponse()); response.setContentType("application/xml"); response.setCharacterEncoding("UTF-8"); response.setHeader("Location", dr.getEntry().getContent().getSource()); PrintWriter out = response.getWriter(); out.write(dr.marshall()); out.flush(); } //Write error document else { String errorXml = this.errorDoc.createErrorDoc(); response.setStatus(this.errorDoc.getStatus()); response.setContentType("application/xml"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.write(errorXml); out.flush(); } } catch (Exception e) { this.logger.error("Error document could not be created.", e); throw new RuntimeException(); } this.pubMan.setCurrentUser(null); this.validDeposit = true; }
From source file:net.bhira.sample.api.controller.EmployeeController.java
/** * Fetch the instance of {@link net.bhira.sample.model.Employee} represented by given employeeId * and return it as JSON object./*from w ww . j av a 2 s . c om*/ * * @param employeeId * the ID for {@link net.bhira.sample.model.Employee}. * @param response * the http response to which the results will be written. * @return an instance of {@link net.bhira.sample.model.Employee} as JSON. */ @RequestMapping(value = "/employee/{employeeId}", method = RequestMethod.GET) @ResponseBody public Callable<String> getEmployee(@PathVariable long employeeId, HttpServletResponse response) { return new Callable<String>() { public String call() throws Exception { String body = ""; try { LOG.debug("servicing GET employee/{}", employeeId); Employee employee = employeeService.load(employeeId); LOG.debug("GET employee/{}, found = {}", employeeId, employee != null); if (employee == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { body = JsonUtil.createGson().toJson(employee); } } catch (Exception ex) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); body = ex.getLocalizedMessage(); LOG.warn("Error loading employee/{}. {}", employeeId, body); LOG.debug("Load error stacktrace: ", ex); } return body; } }; }
From source file:edu.vt.middleware.servlet.filter.RequestMethodFilter.java
/** * Handle all requests sent to this filter. * * @param request <code>ServletRequest</code> * @param response <code>ServletResponse</code> * @param chain <code>FilterChain</code> * * @throws ServletException if an error occurs * @throws IOException if an error occurs *///from w w w. j a v a 2 s . co m public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { Set<Map.Entry<String, Method>> entries = null; if (request instanceof HttpServletRequest) { entries = this.httpServletMethods.entrySet(); } else { entries = this.servletMethods.entrySet(); } for (Map.Entry<String, Method> entry : entries) { final String methodName = entry.getKey(); if (LOG.isDebugEnabled()) { if (this.arguments.get(methodName) != null) { if (LOG.isDebugEnabled()) { LOG.debug("Calling " + methodName + " with these arguments " + Arrays.asList((Object[]) this.arguments.get(methodName))); } } else { if (LOG.isDebugEnabled()) { LOG.debug("Calling " + methodName + " with no arguments"); } } } String methodResult = null; try { methodResult = String .valueOf(entry.getValue().invoke(request, (Object[]) this.arguments.get(methodName))); if (LOG.isDebugEnabled()) { LOG.debug(methodName + " returned " + methodResult); } } catch (InvocationTargetException e) { if (LOG.isErrorEnabled()) { LOG.error("Could not invoke method " + methodName, e); } } catch (IllegalAccessException e) { if (LOG.isErrorEnabled()) { LOG.error("Could not access method " + methodName, e); } } if (!this.verifyResult(methodName, methodResult)) { if (response instanceof HttpServletResponse) { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN, "Request blocked by filter"); return; } else { throw new ServletException("Request blocked by filter"); } } } chain.doFilter(request, response); }
From source file:com.eucalyptus.www.X509Download.java
public void doGet(HttpServletRequest request, HttpServletResponse response) { String code = request.getParameter(PARAMETER_CODE); String userName = request.getParameter(PARAMETER_USERNAME); String accountName = request.getParameter(PARAMETER_ACCOUNTNAME); String mimetype = "application/zip"; if (accountName == null || "".equals(accountName)) { hasError(HttpServletResponse.SC_BAD_REQUEST, "No account name provided", response); return;/*from w ww . j a va2s. c o m*/ } if (userName == null || "".equals(userName)) { hasError(HttpServletResponse.SC_BAD_REQUEST, "No user name provided", response); return; } if (code == null || "".equals(code)) { hasError(HttpServletResponse.SC_BAD_REQUEST, "Wrong user security code", response); return; } User user = null; try { Account account = Accounts.lookupAccountByName(accountName); user = account.lookupUserByName(userName); if (!user.isEnabled() || !RegistrationStatus.CONFIRMED.equals(user.getRegistrationStatus())) { hasError(HttpServletResponse.SC_FORBIDDEN, "Access is not authorized", response); return; } } catch (AuthException e) { hasError(HttpServletResponse.SC_BAD_REQUEST, "User does not exist", response); return; } catch (Exception e) { hasError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Fail to retrieve user data", response); return; } try { if (!code.equals(user.resetToken())) { hasError(HttpServletResponse.SC_FORBIDDEN, "Access is not authorized", response); return; } } catch (Exception e) { hasError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Can not reset user security code", response); return; } response.setContentType(mimetype); response.setHeader("Content-Disposition", "attachment; filename=\"" + X509Download.NAME_SHORT + "-" + userName + "-x509.zip\""); LOG.info("pushing out the X509 certificate for user " + userName); byte[] x509zip = null; try { x509zip = getX509Zip(user); } catch (Exception e) { LOG.debug(e, e); hasError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Fail to return user credentials", response); return; } try { ServletOutputStream op = response.getOutputStream(); response.setContentLength(x509zip.length); op.write(x509zip); op.flush(); } catch (Exception e) { LOG.error(e, e); } }
From source file:com.streamsets.pipeline.stage.origin.ipctokafka.IpcToKafkaServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String requestor = req.getRemoteAddr() + ":" + req.getRemotePort(); if (shuttingDown) { LOG.debug("Shutting down, discarding incoming request from '{}'", requestor); resp.setStatus(HttpServletResponse.SC_GONE); } else {//from ww w .j a v a2 s. com String appId = req.getHeader(Constants.X_SDC_APPLICATION_ID_HEADER); String compression = req.getHeader(Constants.X_SDC_COMPRESSION_HEADER); String contentType = req.getContentType(); String json1Fragmentable = req.getHeader(Constants.X_SDC_JSON1_FRAGMENTABLE_HEADER); if (!Constants.APPLICATION_BINARY.equals(contentType)) { invalidRequestMeter.mark(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, Utils.format( "Wrong content-type '{}', expected '{}'", contentType, Constants.APPLICATION_BINARY)); } else if (!"true".equals(json1Fragmentable)) { invalidRequestMeter.mark(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, Utils.format( "RPC client is not using a fragmentable JSON1 encoding, client;s SDC must be upgraded")); } else if (!configs.appId.equals(appId)) { invalidRequestMeter.mark(); LOG.warn("IPC from '{}' invalid appId '{}', rejected", requestor, appId); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid 'appId'"); } else { long start = System.currentTimeMillis(); LOG.debug("Request accepted from '{}'", requestor); try (InputStream in = req.getInputStream()) { InputStream is = in; boolean processRequest = true; if (compression != null) { switch (compression) { case Constants.SNAPPY_COMPRESSION: is = new SnappyFramedInputStream(is, true); break; default: invalidRequestMeter.mark(); LOG.warn("Invalid compression '{}' in request from '{}', returning error", compression, requestor); resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported compression: " + compression); processRequest = false; } } if (processRequest) { LOG.debug("Processing request from '{}'", requestor); List<byte[]> messages = SdcStreamFragmenter.fragment(is, maxMessageSize, maxRpcRequestSize); LOG.debug("Request from '{}' broken into '{}' messages", requestor, messages.size()); long kStart = System.currentTimeMillis(); SdcKafkaProducer producer = getKafkaProducer(); long kafkaTime = System.currentTimeMillis() - kStart; try { for (byte[] message : messages) { // we are using round robing partition strategy, partition key is ignored kStart = System.currentTimeMillis(); producer.enqueueMessage(kafkaConfigBean.kafkaConfig.topic, message, ""); kafkaTime += System.currentTimeMillis() - kStart; } kStart = System.currentTimeMillis(); producer.write(); kafkaTime += System.currentTimeMillis() - kStart; resp.setStatus(HttpServletResponse.SC_OK); requestMeter.mark(); } catch (StageException ex) { LOG.warn("Kakfa producer error: {}", ex.toString(), ex); errorQueue.offer(ex); errorRequestMeter.mark(); LOG.warn("Error while reading payload from '{}': {}", requestor, ex.toString(), ex); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString()); } finally { kStart = System.currentTimeMillis(); releaseKafkaProducer(producer); kafkaTime += System.currentTimeMillis() - kStart; } kafkaTimer.update(kafkaTime, TimeUnit.MILLISECONDS); kafkaMessagesMeter.mark(messages.size()); } } catch (Exception ex) { errorRequestMeter.mark(); LOG.warn("Error while reading payload from '{}': {}", requestor, ex.toString(), ex); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.toString()); } finally { requestTimer.update(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS); } } } }
From source file:eu.dasish.annotation.backend.rest.AnnotationResource.java
/** * /*from www. j a va 2 s . c o m*/ * @param externalIdentifier the string representing the UUID of an annotation. * @return the xml element representing the list of h-references of the targets of the annotation with "externalIdentifier". * @throws IOException if sending an error fails. */ @GET @Produces(MediaType.TEXT_XML) @Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/targets") @Transactional(readOnly = true) public JAXBElement<ReferenceList> getAnnotationTargets(@PathParam("annotationid") String externalIdentifier) throws IOException { Map params = new HashMap(); try { ReferenceList result = (ReferenceList) (new RequestWrappers(this)).wrapRequestResource(params, new GetTargetList(), Resource.ANNOTATION, Access.READ, externalIdentifier); if (result != null) { return (new ObjectFactory()).createTargetList(result); } else { return (new ObjectFactory()).createTargetList(new ReferenceList()); } } catch (NotInDataBaseException e1) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage()); return (new ObjectFactory()).createReferenceList(new ReferenceList()); } catch (ForbiddenException e2) { httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage()); return (new ObjectFactory()).createReferenceList(new ReferenceList()); } }
From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java
@Override public void doExceptionAction(final HttpServletResponse httpResponse, final RuntimeException e) throws IOException { LOGGER.error("Error in Authentication", e); httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Error in Authentication"); }
From source file:com.google.appengine.tools.mapreduce.MapReduceServlet.java
/** * Checks to ensure that the current request was sent via the task queue. * * If the request is not in the task queue, returns false, and sets the * response status code to 403. This protects against CSRF attacks against * task queue-only handlers./*from w ww.jav a 2s.c om*/ * * @return true if the request is a task queue request */ private boolean checkForTaskQueue(HttpServletRequest request, HttpServletResponse response) { if (request.getHeader("X-AppEngine-QueueName") == null) { log.log(Level.SEVERE, "Received unexpected non-task queue request. Possible CSRF attack."); try { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Received unexpected non-task queue request."); } catch (IOException ioe) { throw new RuntimeException("Encountered error writing error", ioe); } return false; } return true; }
From source file:com.jaspersoft.jasperserver.rest.RESTServlet.java
/** * The REST servlet check for the resource type that has been requested.<br> * The resource is represented by the url i.e. /rest/<b>resource</b> or /rest/<b>report</b> * The resource logic is implemented by extending a RESTService.<br> * The RESTService handled for a specific request is configured in the file shared-config\applicationContext-rest-services.xml. It is a map which * binds urls to RESTServices. The RESTService implementation is in charge to accept or not the specific method type. * * @param req HttpServletRequest//from w w w . jav a 2 s . com * @param resp HttpServletResponse * @throws ServletException * @throws IOException */ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (log.isDebugEnabled()) { log.debug("-------------------------------------------------------------------------------- "); } // This print writer is used only in case of exception, but in general exception should be always // handled inside the RESTService implementation, if available. PrintWriter pw = null; String serviceName = null; String path = null; try { // Get the name of the service requested by the user path = req.getPathInfo(); if (path == null) { // error... log.error("request params: Path: " + path); utils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, "Service not valid"); return; } serviceName = utils.extractServiceName(path); // If the service name is null or empty, return an error. if (serviceName == null || serviceName.length() == 0) { log.error("request params: Service" + serviceName + " Path: " + path); utils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, "Service not valid"); return; } RESTService service = registry.getService(serviceName); if (service == null) { log.error("request params: Path: " + path + " Requested Service: " + serviceName); utils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, "Service not valid"); return; } if (log.isDebugEnabled()) { log.debug("request params: Path: " + path + " Requested Service: " + serviceName + " Service from registry: " + service.getClass()); } resp.setContentType("text/xml; charset=UTF-8"); service.execute(req, resp); } catch (ServiceException ex) { if (log.isDebugEnabled()) log.debug("Error executing a REST service: " + ex.getErrorCode(), ex); // The servlet is able to map common ServiceException errors with most appropriate REST (HTTP) error codes... // This should be really just the latest case, when a more specific error is not available. // In general the service implementation should take care to send to the client the proper response. switch (ex.getErrorCode()) { case ServiceException.RESOURCE_NOT_FOUND: { log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: " + HttpServletResponse.SC_NOT_FOUND + " error: " + ex.getMessage(), ex); utils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, ""); break; } case ServiceException.RESOURCE_BAD_REQUEST: { log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: " + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex); utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, ex.getMessage()); break; } case ServiceException.FORBIDDEN: { log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: " + HttpServletResponse.SC_FORBIDDEN + " error: " + ex.getMessage(), ex); utils.setStatusAndBody(HttpServletResponse.SC_FORBIDDEN, resp, ex.getMessage()); break; } default: { log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: " + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex); utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, ""); } } } catch (UnsupportedOperationException ex) { log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: " + HttpServletResponse.SC_NOT_IMPLEMENTED + " error: " + ex.getMessage(), ex); utils.setStatusAndBody(HttpServletResponse.SC_NOT_IMPLEMENTED, resp, ""); } catch (ReportJobNotFoundException ex) { log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: " + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex); utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, ""); } catch (JSExceptionWrapper ex) { Exception e = ex.getOriginalException(); if (e instanceof ConstraintViolationException || e instanceof DataIntegrityViolationException) { log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: " + HttpServletResponse.SC_FORBIDDEN + " error: " + ex.getMessage(), ex); utils.setStatusAndBody(HttpServletResponse.SC_FORBIDDEN, resp, ""); } else { log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: " + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex); utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, ""); } } catch (JSValidationException ex) { log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: " + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex); utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, ""); } catch (AccessDeniedException ex) { log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: " + HttpServletResponse.SC_FORBIDDEN + " error: " + ex.getMessage(), ex); utils.setStatusAndBody(HttpServletResponse.SC_FORBIDDEN, resp, ex.getMessage()); } catch (IllegalStateException ex) { log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: " + HttpServletResponse.SC_BAD_REQUEST + " error: " + ex.getMessage(), ex); utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, ""); } catch (IllegalArgumentException ex) { log.error("request params: Path: " + path + " Requested Service: " + serviceName + " httpStatus: " + HttpServletResponse.SC_BAD_REQUEST + " Error: " + ex.getMessage(), ex); utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, ""); } catch (Exception ex) { // This should Never happen. If it does, it's probably an implementation bug, or the remote service // implementation did not provide a better or specific error. log.error("Error executing a REST service", ex); utils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, ""); } }
From source file:eu.dasish.annotation.backend.rest.DebugResource.java
/** * //from ww w . j a va 2 s . c om * @param principalId the external UUID of a principal whose account type must be updated. * @param account the new account type (admin, developer, user). * @return a message telling if the account has been updated or not. * @throws IOException if sending an error fails. */ @PUT @Produces(MediaType.TEXT_XML) @Path("/account/{principalId}/make/{account}") @Transactional(readOnly = true) public String updatePrincipalsAccount(@PathParam("principalId") String principalId, @PathParam("account") String account) throws IOException { Number remotePrincipalID = this.getPrincipalID(); if (remotePrincipalID == null) { return " "; } String typeOfAccount = dbDispatcher.getTypeOfPrincipalAccount(remotePrincipalID); if (typeOfAccount.equals(admin)) { try { final boolean update = dbDispatcher.updateAccount(UUID.fromString(principalId), account); return (update ? "The account is updated" : "The account is not updated, see the log."); } catch (NotInDataBaseException e) { httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return e.toString(); } } else { this.ADMIN_RIGHTS_EXPECTED(); httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN); return "Coucou."; } }