List of usage examples for javax.servlet.http HttpServletResponse SC_BAD_REQUEST
int SC_BAD_REQUEST
To view the source code for javax.servlet.http HttpServletResponse SC_BAD_REQUEST.
Click Source Link
From source file:com.climate.oada.controller.OADAAPIController.java
@Override public List<IResource> getResources(@RequestHeader(value = "Authorization") String accessToken, @RequestParam(value = "resourceType", required = false) String[] resourceTypes, HttpServletRequest request, HttpServletResponse response) throws Exception { List<IResource> retval = null; Long userId = extractUserId(accessToken); if (userId != null) { List<String> requestedResourceTypes = new ArrayList<String>(); if (resourceTypes != null) { requestedResourceTypes = Arrays.asList(resourceTypes); } else {/*from ww w. j av a 2 s .c o m*/ requestedResourceTypes.add(IOADAAPI.OADA_FIELDS_CONTENT_TYPE); requestedResourceTypes.add(IOADAAPI.OADA_PRESCRIPTIONS_CONTENT_TYPE); } retval = new ArrayList<IResource>(); for (String type : requestedResourceTypes) { if (IOADAAPI.OADA_FIELDS_CONTENT_TYPE.equalsIgnoreCase(type)) { retval.addAll(getFieldsResourceDAO().getLandUnits(userId)); } else if (isFileType(type)) { retval.addAll(getS3DAO().getFileUrls(userId, type)); } } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, OADAAPIUtils.INVALID_ACCESS_TOKEN); } return retval; }
From source file:com.haulmont.cuba.restapi.DataServiceController.java
@RequestMapping(value = "/api/find.{type}", method = RequestMethod.GET) public void find(@PathVariable String type, @RequestParam(value = "e") String entityRef, @RequestParam(value = "s") String sessionId, @RequestParam(value = "dynamicAttributes", required = false) Boolean dynamicAttributes, HttpServletRequest request, HttpServletResponse response) throws IOException, InvocationTargetException, NoSuchMethodException, IllegalAccessException { if (!connect(sessionId, response)) return;// w w w . j a v a 2s. c o m try { EntityLoadInfo loadInfo = EntityLoadInfo.parse(entityRef); if (loadInfo == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } MetaClass metaClass = loadInfo.getMetaClass(); if (!readPermitted(metaClass)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } Object objectId = loadInfo.getId(); LoadContext loadCtx = new LoadContext(metaClass); loadCtx.setLoadDynamicAttributes(Boolean.TRUE.equals(dynamicAttributes)); loadCtx.setId(objectId); if (loadInfo.getViewName() != null) { loadCtx.setView(loadInfo.getViewName()); } else { View view = metadata.getViewRepository().getView(metaClass, View.LOCAL); loadCtx.setView(new View(view, "local-with-system-props", true)); } Entity entity = dataService.load(loadCtx); if (entity == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { Converter converter = conversionFactory.getConverter(type); String result = converter.process(entity, metaClass, loadCtx.getView()); writeResponse(response, result, converter.getMimeType()); } } catch (Throwable e) { sendError(request, response, e); } finally { authentication.end(); } }
From source file:de.yaio.services.webshot.server.controller.WebshotController.java
@ExceptionHandler(IOExceptionWithCause.class) public void handleCustomException(final HttpServletRequest request, final IOExceptionWithCause e, final HttpServletResponse response) throws IOException { LOGGER.info("Exception while running request:" + createRequestLogMessage(request), e); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().append("url-get failed while webshoting resource:"); response.getWriter().append(e.getCause().getMessage()); }
From source file:org.energyos.espi.thirdparty.web.BatchRESTController.java
@RequestMapping(value = Routes.BATCH_DOWNLOAD_MY_DATA_MEMBER, method = RequestMethod.GET, produces = "application/atom+xml") @ResponseBody//from ww w . ja v a 2 s . c o m public void download_member(HttpServletResponse response, @PathVariable Long retailCustomerId, @PathVariable Long usagePointId, @RequestParam Map<String, String> params) throws IOException, FeedException { response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE); response.addHeader("Content-Disposition", "attachment; filename=GreenButtonDownload.xml"); try { // TODO -- need authorization hook exportService.exportUsagePointFull(0L, retailCustomerId, usagePointId, response.getOutputStream(), new ExportFilter(params)); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } }
From source file:org.openxdata.server.servlet.StudyExportServlet.java
private void setBadRequest(HttpServletResponse response, String message) throws IOException { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.setContentType("text/plain"); response.getOutputStream().println(message); }
From source file:contestTabulation.Setup.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { Queue queue = QueueFactory.getDefaultQueue(); TaskOptions options = null;/*from w ww. ja v a 2s . c o m*/ for (Level level : Level.values()) { String docName = req.getParameter("doc" + level.getName()); if (docName != null) { options = withUrl("/createSpreadsheet").param("doc" + level.getName(), docName); break; } } if (options != null) { queue.add(options); } else { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Spreadsheet creation request must have document name parameter set"); } }
From source file:com.jaspersoft.jasperserver.rest.services.RESTResources.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServiceException { // Extract the uri from which list the resources... String uri = restUtils.extractRepositoryUri(req.getPathInfo()); // "resources" is a REST service path if (uri == null || "resources".equals(uri)) uri = "/"; // Extract the criteria String queryString = req.getParameter("q"); if (queryString == null || queryString.length() == 0) { queryString = null;/*from w ww .j a va 2 s .c o m*/ } List<String> resourceTypes = new ArrayList<String>(); String[] resourceTypesArray = req.getParameterValues("type"); if (resourceTypesArray != null) { resourceTypes.addAll(Arrays.asList(resourceTypesArray)); } Iterator<String> itr = resourceTypes.iterator(); while (itr.hasNext()) { String resourceType = itr.next(); if (!(resourceType != null && resourceType.length() != 0)) { itr.remove(); } } int limit = 0; if (req.getParameter("limit") != null && req.getParameter("limit").length() > 0) { try { limit = Integer.parseInt(req.getParameter("limit")); if (limit < 0) throw new Exception(); } catch (Throwable ex) { restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "Invalid value set for parameter limit."); return; } } int startIndex = 0; if (req.getParameter("startIndex") != null && req.getParameter("startIndex").length() > 0) { try { startIndex = Integer.parseInt(req.getParameter("startIndex")); if (startIndex < 0) throw new Exception(); } catch (Throwable ex) { restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "Invalid value set for parameter startIndex."); return; } } List list = new ArrayList(); // If not a search, just list the content of the specified folder... if (queryString == null && (resourceTypes.size() == 0)) { list = resourcesListRemoteService.listResources(uri, limit); } else { boolean recursive = false; if (req.getParameter("recursive") != null && (req.getParameter("recursive").equals("1") || req.getParameter("recursive").equalsIgnoreCase("true") || req.getParameter("recursive").equalsIgnoreCase("yes"))) { recursive = true; } //list = service.getResources(criteria, limit, resourceTypes == null ? null : Arrays.asList(resourceTypes)); list = resourcesListRemoteService.getResources(uri, queryString, resourceTypes.size() == 0 ? null : resourceTypes, recursive, limit, startIndex); } StringBuilder xml = new StringBuilder(); Marshaller m = new Marshaller(); xml.append("<resourceDescriptors>\n"); if (list != null && !list.isEmpty()) for (Object rd : list) { // we assume the objects are actually resource descriptors... xml.append(m.writeResourceDescriptor((ResourceDescriptor) rd)); } xml.append("</resourceDescriptors>"); restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, xml.toString()); }
From source file:fr.gael.dhus.api.UploadController.java
@SuppressWarnings("unchecked") @PreAuthorize("hasRole('ROLE_UPLOAD')") @RequestMapping(value = "/upload", method = { RequestMethod.POST }) public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException { // process only multipart requests if (ServletFileUpload.isMultipartContent(req)) { User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal(); // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try {//from w ww. j a v a 2 s .c o m ArrayList<Long> collectionIds = new ArrayList<>(); FileItem product = null; List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { if (COLLECTIONSKEY.equals(item.getFieldName())) { if (item.getString() != null && !item.getString().isEmpty()) { for (String cid : item.getString().split(",")) { collectionIds.add(new Long(cid)); } } } else if (PRODUCTKEY.equals(item.getFieldName())) { product = item; } } if (product == null) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Your request is missing a product file to upload."); return; } productUploadService.upload(user.getId(), product, collectionIds); res.setStatus(HttpServletResponse.SC_CREATED); res.getWriter().print("The file was created successfully."); res.flushBuffer(); } catch (FileUploadException e) { logger.error("An error occurred while parsing request.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while parsing request : " + e.getMessage()); } catch (UserNotExistingException e) { logger.error("You need to be connected to upload a product.", e); res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product."); } catch (UploadingException e) { logger.error("An error occurred while uploading the product.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while uploading the product : " + e.getMessage()); } catch (RootNotModifiableException e) { logger.error("An error occurred while uploading the product.", e); res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while uploading the product : " + e.getMessage()); } catch (ProductNotAddedException e) { logger.error("Your product can not be read by the system.", e); res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system."); } } else { res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet."); } }
From source file:org.mypackage.spring.controllers.ContactsSpringController.java
@RequestMapping(value = "/contacts/{id}", method = RequestMethod.GET) public ModelAndView getAContact(@PathVariable String id) { ModelAndView modelAndView = new ModelAndView(); try {/* w w w . j av a 2 s . c o m*/ Contact contact = contactsController.getContact(id); modelAndView.addObject("contact", contact); List<Email> emailsList = contactsController.retrieveAllEmails(id); modelAndView.addObject("emailList", emailsList); modelAndView.addObject("contactId", id); modelAndView.setViewName("/viewContact.jsp"); } catch (DalException ex) { logger.error("A database error occured.", ex); modelAndView.addObject("errorCode", HttpServletResponse.SC_INTERNAL_SERVER_ERROR); modelAndView.addObject("errorMessage", "There was a an internal database error."); modelAndView.setViewName("/errorPage.jsp"); } catch (MalformedIdentifierException ex) { modelAndView.addObject("errorCode", HttpServletResponse.SC_BAD_REQUEST); modelAndView.addObject("errorMessage", "An error occured because of a malformed id (caused by id = " + id + "). Please use only numeric values."); modelAndView.setViewName("/errorPage.jsp"); } catch (ResourceNotFoundException ex) { modelAndView.addObject("errorCode", HttpServletResponse.SC_NOT_FOUND); modelAndView.addObject("errorMessage", "Requested contact (with id = " + id + ") does not exist."); modelAndView.setViewName("/errorPage.jsp"); } return modelAndView; }
From source file:com.thinkberg.moxo.dav.LockHandler.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { FileObject object = getResourceManager().getFileObject(request.getPathInfo()); try {/*from w w w. j a v a2 s . c om*/ Lock lock = LockManager.getInstance().checkCondition(object, getIf(request)); if (lock != null) { sendLockAcquiredResponse(response, lock); return; } } catch (LockException e) { // handle locks below } try { SAXReader saxReader = new SAXReader(); Document lockInfo = saxReader.read(request.getInputStream()); //log(lockInfo); Element rootEl = lockInfo.getRootElement(); String lockScope = null, lockType = null; Object owner = null; Iterator elIt = rootEl.elementIterator(); while (elIt.hasNext()) { Element el = (Element) elIt.next(); if (TAG_LOCKSCOPE.equals(el.getName())) { lockScope = el.selectSingleNode("*").getName(); } else if (TAG_LOCKTYPE.equals(el.getName())) { lockType = el.selectSingleNode("*").getName(); } else if (TAG_OWNER.equals(el.getName())) { // TODO correctly handle owner Node subEl = el.selectSingleNode("*"); if (subEl != null && TAG_HREF.equals(subEl.getName())) { owner = new URL(el.selectSingleNode("*").getText()); } else { owner = el.getText(); } } } log("LOCK(" + lockType + ", " + lockScope + ", " + owner + ")"); Lock requestedLock = new Lock(object, lockType, lockScope, owner, getDepth(request), getTimeout(request)); try { LockManager.getInstance().acquireLock(requestedLock); sendLockAcquiredResponse(response, requestedLock); } catch (LockConflictException e) { response.sendError(SC_LOCKED); } catch (IllegalArgumentException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); } } catch (DocumentException e) { e.printStackTrace(); response.sendError(HttpServletResponse.SC_BAD_REQUEST); } }