List of usage examples for javax.servlet.http HttpServletRequest getParts
public Collection<Part> getParts() throws IOException, ServletException;
multipart/form-data
. From source file:org.apache.wicket.protocol.http.servlet.MultipartServletWebRequestImpl.java
/** * Reads the uploads' parts by using Servlet 3.0 APIs. * * <strong>Note</strong>: By using Servlet 3.0 APIs the application won't be able to use * upload progress updates./*from w w w. j av a 2 s . c om*/ * * @param request * The http request with the upload data * @return A list of {@link FileItem}s * @throws FileUploadException */ private List<FileItem> readServlet3Parts(HttpServletRequest request) throws FileUploadException { List<FileItem> itemsFromParts = new ArrayList<>(); try { Collection<Part> parts = request.getParts(); if (parts != null) { for (Part part : parts) { FileItem fileItem = new ServletPartFileItem(part); itemsFromParts.add(fileItem); } } } catch (IOException | ServletException e) { throw new FileUploadException("An error occurred while reading the upload parts", e); } return itemsFromParts; }
From source file:com.rubinefocus.admin.servlet.UploadServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w w w . j a v a 2 s.c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //processRequest(request, response); try { PrintWriter out = response.getWriter(); File f = new File(this.getServletContext().getRealPath("/admin/assets/images/adminPic")); String savePath = f.getPath(); savePath = savePath.replace("%20", " "); savePath = savePath.replace("build", ""); String fileName = ""; for (Part part : request.getParts()) { fileName = extractFileName(part); fileName = fileName.replace(" ", ""); fileName = fileName.replace("-", ""); fileName = fileName.replace(":", ""); File file = new File(savePath + "/" + fileName); if (file.exists()) { String fileNameWithOutExt = FilenameUtils.removeExtension(fileName); String ext = FilenameUtils.getExtension(fileName); fileName = fileNameWithOutExt + new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date()) + "." + ext; fileName = fileName.replace(" ", ""); fileName = fileName.replace("-", ""); fileName = fileName.replace(":", ""); part.write(savePath + File.separator + fileName); } else { part.write(savePath + File.separator + fileName); } } } catch (Exception ex) { ex.printStackTrace(); } }
From source file:com.shoylpik.controller.AddProduct.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String SAVE_DIRECTORY = "shoylpik_images"; String absolutePath = request.getServletContext().getRealPath(""); String savePath = absolutePath + File.separator + SAVE_DIRECTORY; File imageSaveDirectory = new File(savePath); if (!imageSaveDirectory.exists()) { imageSaveDirectory.mkdir();//from ww w. j a v a2 s . c om } System.out.println("imageSaveDirectory.getAbsolutePath(): " + imageSaveDirectory.getAbsolutePath()); String fileName = null; //Get all the parts from request and write it to the file on server for (Part part : request.getParts()) { fileName = getFileName(part); System.out.println("fileName: " + fileName); part.write(savePath + File.separator + fileName); } try { System.out.println("savePath : " + savePath); String imageName = request.getParameter("IPimage"); System.out.println("imageName: " + imageName); Part filePart = request.getPart("IPimage"); InputStream imageInputStream = filePart.getInputStream(); Product product = new Product(); product.setProductId(Integer.parseInt(request.getParameter("IPID"))); product.setProductName(request.getParameter("IPname")); product.setProductImageName(imageName); product.setProductCategory(request.getParameter("IPcat")); product.setProductPrice(Float.parseFloat(request.getParameter("IPprice"))); product.setProductQuantity(Integer.parseInt(request.getParameter("IPQuant"))); ProductBean pBean = new ProductBean(); pBean.addProduct(product); String fullImagePath = savePath + File.separator + imageName; File file = new File(fullImagePath); System.out.println("fullImagePath : " + fullImagePath); FileOutputStream fos = new FileOutputStream(file); boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (!isMultipart) { } else { System.out.println("Inside else"); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { } Iterator itr = items.iterator(); while (itr.hasNext()) { System.out.println("Inside while"); FileItem item = (FileItem) items.iterator(); item.write(file); } } } catch (SQLException ex) { Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(AddProduct.class.getName()).log(Level.SEVERE, null, ex); } response.sendRedirect("AdministrationPage.jsp"); }
From source file:io.vertigo.struts2.impl.multipartrequest.Servlet3MultiPartRequest.java
@Override protected List<FileItem> parseRequest(final HttpServletRequest servletRequest, final String saveDir) throws FileUploadException { // gestion de la configuration struts.multipart.maxSize if (maxSize >= 0) { final int requestSize = servletRequest.getContentLength(); if (requestSize != -1 && requestSize > maxSize) { throw new FileUploadBase.SizeLimitExceededException(String.format( "the request was rejected because its size (%s) exceeds the configured maximum (%s)", Long.valueOf(requestSize), Long.valueOf(maxSize)), requestSize, maxSize); }/*from ww w .j a v a2 s.c o m*/ } // gestion du contenu de la requete try { final Collection<Part> parts = servletRequest.getParts(); final List<FileItem> ret = new ArrayList<>(parts.size()); for (final Part part : parts) { ret.add(new PartFileItem(part, saveDir)); } return ret; } catch (IOException | ServletException e) { throw new FileUploadException("Impossible de rcuprer les fichiers de la requte en mode Servlet 3", e); } }
From source file:org.codice.ddf.rest.impl.CatalogServiceImplTest.java
@Test public void testParsePartsWithAttributeOverrides() throws Exception { CatalogFramework framework = givenCatalogFramework(); CatalogServiceImpl catalogServiceImpl = new CatalogServiceImpl(framework, attachmentParser, attributeRegistry);// w w w. j ava 2 s. c o m when(attributeRegistry.lookup(Topic.KEYWORD)) .thenReturn(Optional.of(new TopicAttributes().getAttributeDescriptor(Topic.KEYWORD))); when(attributeRegistry.lookup(Core.LOCATION)) .thenReturn(Optional.of(new CoreAttributes().getAttributeDescriptor(Core.LOCATION))); List<Part> parts = new ArrayList<>(); Part part = createPart("parse.resource", new ByteArrayInputStream("Some Text".getBytes()), "form-data; name=parse.resource; filename=/path/to/metacard.txt"); Part part1 = createPart("parse.location", new ByteArrayInputStream("POINT(0 0)".getBytes()), "form-data; name=parse.location"); Part part2 = createPart("parse.topic.keyword", new ByteArrayInputStream("keyword1".getBytes()), "form-data; name=parse.topic.keyword"); Part part3 = createPart("parse.topic.keyword", new ByteArrayInputStream("keyword2".getBytes()), "form-data; name=parse.topic.keyword"); parts.add(part); parts.add(part1); parts.add(part2); parts.add(part3); HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); when(httpServletRequest.getParts()).thenReturn(parts); Map.Entry<AttachmentInfo, Metacard> attachmentInfoAndMetacard = catalogServiceImpl.parseParts(parts, null); Metacard metacard = attachmentInfoAndMetacard.getValue(); assertThat(metacard.getAttribute(Core.LOCATION).getValues(), hasItem("POINT(0 0)")); assertThat(metacard.getAttribute(Topic.KEYWORD).getValues(), hasItems("keyword1", "keyword2")); }
From source file:org.codice.ddf.rest.impl.CatalogServiceImplTest.java
@Test @SuppressWarnings({ "unchecked" }) public void testParseParts() throws IOException, CatalogTransformerException, SourceUnavailableException, IngestException, InvalidSyntaxException, ServletException { CatalogFramework framework = givenCatalogFramework(); BundleContext bundleContext = mock(BundleContext.class); Collection<ServiceReference<InputTransformer>> serviceReferences = new ArrayList<>(); ServiceReference serviceReference = mock(ServiceReference.class); InputTransformer inputTransformer = mock(InputTransformer.class); MetacardImpl metacard = new MetacardImpl(); metacard.setMetadata("Some Text Again"); when(inputTransformer.transform(any())).thenReturn(metacard); when(bundleContext.getService(serviceReference)).thenReturn(inputTransformer); serviceReferences.add(serviceReference); when(bundleContext.getServiceReferences(InputTransformer.class, "(id=xml)")).thenReturn(serviceReferences); CatalogServiceImpl catalogServiceImpl = new CatalogServiceImpl(framework, attachmentParser, attributeRegistry) {//from w ww. ja va 2s. c om @Override BundleContext getBundleContext() { return bundleContext; } }; when(attributeRegistry.lookup(Core.METADATA)) .thenReturn(Optional.of(new CoreAttributes().getAttributeDescriptor(Core.METADATA))); when(attributeRegistry.lookup("foo")).thenReturn(Optional.empty()); addMatchingService(catalogServiceImpl, Collections.singletonList(getSimpleTransformer())); List<Part> parts = new ArrayList<>(); Part part = createPart("parse.resource", new ByteArrayInputStream("Some Text".getBytes()), "form-data; name=parse.resource; filename=C:\\DDF\\metacard.txt"); Part part1 = createPart("parse.metadata", new ByteArrayInputStream("Some Text Again".getBytes()), "form-data; name=parse.metadata; filename=C:\\DDF\\metacard.xml"); parts.add(part); parts.add(part1); HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); when(httpServletRequest.getParts()).thenReturn(parts); Map.Entry<AttachmentInfo, Metacard> attachmentInfoAndMetacard = catalogServiceImpl.parseParts(parts, "xml"); assertThat(attachmentInfoAndMetacard.getValue().getMetadata(), equalTo("Some Text Again")); Part part2 = createPart("metadata", new ByteArrayInputStream("<meta>beta</meta>".getBytes()), "form-data; name=metadata; filename=C:\\DDF\\metacard.xml"); Part part3 = createPart("foo", new ByteArrayInputStream("bar".getBytes()), "form-data; name=foo; filename=C:\\DDF\\metacard.xml"); parts.add(part2); parts.add(part3); attachmentInfoAndMetacard = catalogServiceImpl.parseParts(parts, "xml"); assertThat(attachmentInfoAndMetacard.getValue().getMetadata(), equalTo("<meta>beta</meta>")); assertThat(attachmentInfoAndMetacard.getValue().getAttribute("foo"), equalTo(null)); }
From source file:org.codice.ddf.rest.impl.CatalogServiceImplTest.java
@Test @SuppressWarnings({ "unchecked" }) public void testParsePartsTooLarge() throws IOException, CatalogTransformerException, SourceUnavailableException, IngestException, InvalidSyntaxException, ServletException { CatalogFramework framework = givenCatalogFramework(); BundleContext bundleContext = mock(BundleContext.class); Collection<ServiceReference<InputTransformer>> serviceReferences = new ArrayList<>(); ServiceReference serviceReference = mock(ServiceReference.class); InputTransformer inputTransformer = mock(InputTransformer.class); MetacardImpl metacard = new MetacardImpl(); metacard.setMetadata("Some Text Again"); when(inputTransformer.transform(any())).thenReturn(metacard); when(bundleContext.getService(serviceReference)).thenReturn(inputTransformer); serviceReferences.add(serviceReference); when(bundleContext.getServiceReferences(InputTransformer.class, "(id=xml)")).thenReturn(serviceReferences); CatalogServiceImpl catalogServiceImpl = new CatalogServiceImpl(framework, attachmentParser, attributeRegistry) {//from w ww. ja v a 2 s . c om @Override BundleContext getBundleContext() { return bundleContext; } }; when(attributeRegistry.lookup(Core.METADATA)) .thenReturn(Optional.of(new CoreAttributes().getAttributeDescriptor(Core.METADATA))); when(attributeRegistry.lookup("foo")).thenReturn(Optional.empty()); addMatchingService(catalogServiceImpl, Collections.singletonList(getSimpleTransformer())); List<Part> parts = new ArrayList<>(); Part part = createPart("parse.resource", new ByteArrayInputStream("Some Text".getBytes()), "form-data; name=parse.resource; filename=C:\\DDF\\metacard.txt"); Part part1 = createPart("parse.metadata", new ByteArrayInputStream("Some Text Again".getBytes()), "form-data; name=parse.metadata; filename=C:\\DDF\\metacard.xml"); parts.add(part); parts.add(part1); HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); when(httpServletRequest.getParts()).thenReturn(parts); Map.Entry<AttachmentInfo, Metacard> attachmentInfoAndMetacard = catalogServiceImpl.parseParts(parts, "xml"); assertThat(attachmentInfoAndMetacard.getValue().getMetadata(), equalTo("Some Text Again")); Part part2 = createPart("metadata", new ByteArrayInputStream(Strings.repeat("hi", 100_000).getBytes()), "form-data; name=metadata; filename=C:\\DDF\\metacard.xml"); Part part3 = createPart("foo", new ByteArrayInputStream("bar".getBytes()), "form-data; name=foo; filename=C:\\DDF\\metacard.xml"); parts.add(part2); parts.add(part3); attachmentInfoAndMetacard = catalogServiceImpl.parseParts(parts, "xml"); // Ensure that the metadata was not overriden because it was too large to be parsed assertThat(attachmentInfoAndMetacard.getValue().getMetadata(), equalTo("Some Text Again")); assertThat(attachmentInfoAndMetacard.getValue().getAttribute("foo"), equalTo(null)); }
From source file:com.esri.gpt.control.rest.ManageDocumentServlet.java
/** * Publishes the XML metadata document supplied within the request body. * @param request the servlet request// www . j a v a2s .c o m * @param response the servlet response * @param context the request context * @param publisher the publisher * @throws Exception if an exception occurs */ private void executePut(HttpServletRequest request, HttpServletResponse response, RequestContext context, Publisher publisher) throws Exception { String xml = null; HrRecord record = extractRegistrationInfo(request); //get multipart request for xml creating + upload try { //create mode - xml and zip are sended via parts if (request.getParts().size() > 0) { createAndUpload(request, response, context, publisher); return; } } catch (Exception e) { } //else normal - edit mode (no parts, no zip file - only xml change) if (record == null) { try { xml = this.readInputCharacters(request); } catch (IOException e) { throw new ServletException("400: IOException while reading request body."); } xml = Val.chkStr(Val.removeBOM(xml)); if (xml.length() > 0) { PublicationRequest pubRequest = new PublicationRequest(context, publisher, xml); PublicationRecord pubRecord = pubRequest.getPublicationRecord(); pubRecord.setPublicationMethod(MmdEnums.PublicationMethod.upload.toString()); String pubMethod = Val.chkStr(request.getParameter("publicationMethod")); if (pubMethod.length() > 0) { try { pubMethod = MmdEnums.PublicationMethod.valueOf(Val.chkStr(pubMethod)).toString(); pubRecord.setPublicationMethod(pubMethod); } catch (IllegalArgumentException ex) { } } String asDraft = Val.chkStr(request.getParameter("asDraft")); if (asDraft.equals("true")) { pubRecord.setApprovalStatus(MmdEnums.ApprovalStatus.draft.toString()); } this.determineSourceUri(request, context, pubRequest); try { pubRequest.publish(); //SAVE XML TO ZIP ARCHIVE saveXml2Package(xml, pubRecord.getUuid()); if (!pubRecord.getWasDocumentReplaced()) { response.setStatus(HttpServletResponse.SC_CREATED); } //Validation error triggert via pubRequest.publish /ValidationRequest } catch (ValidationException e) { String sMsg = e.toString(); if (sMsg.contains("XSD violation.")) { throw new ServletException("409: XSD violation."); } else if (sMsg.contains("Invalid metadata document.")) { throw new ServletException("409: Document failed to validate."); } else { throw new ServletException("409: Document failed to validate."); } } catch (SchemaException e) { String sMsg = e.toString(); if (sMsg.contains("Unrecognized metadata schema.")) { throw new ServletException("409: Unrecognized metadata schema."); } else if (sMsg.contains("Unable to parse document.")) { throw new ServletException("409: Unable to parse document as XML."); } else { throw e; } } } else { throw new ServletException("409: Document was empty."); } } else { try { HrCompleteUpdateRequest req = new HrCompleteUpdateRequest(context, record); req.execute(); response.setStatus(HttpServletResponse.SC_CREATED); } catch (HrAssertUrlException e) { throw new ServletException("409: Duplicated resource URL."); } catch (ValidationException e) { String sMsg = e.toString(); if (sMsg.contains("XSD violation.")) { throw new ServletException("409: XSD violation."); } else if (sMsg.contains("Invalid metadata document.")) { throw new ServletException("409: Document failed to validate."); } else { throw new ServletException("409: Document failed to validate."); } } catch (SchemaException e) { String sMsg = e.toString(); if (sMsg.contains("Unrecognized metadata schema.")) { throw new ServletException("409: Unrecognized metadata schema."); } else if (sMsg.contains("Unable to parse document.")) { throw new ServletException("409: Unable to parse document as XML."); } else { throw e; } } catch (Exception ex) { throw new ServletException("409: Unable to register resource."); } } }
From source file:Control.FrontControl.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w . j a va2s. c om*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); //Characterencoding for special characters //This part of the code, checks if there might be files for upload, and seperates them, if that is the case Collection<Part> parts = null; if (ServletFileUpload.isMultipartContent(request)) { parts = request.getParts(); //Extracts the part of the form that has files and parameters } HttpSession sessionObj = request.getSession(); //Get the session DomainFacade df = (DomainFacade) sessionObj.getAttribute("Controller"); //Get the DomainFacede //If it is a new session, create a new DomainFacade Object and put it in the session. sessionObj.setAttribute("testing", testing); if (df == null) { df = DomainFacade.getInstance(); sessionObj.setAttribute("Controller", df); } //Set base url String url = "/index.jsp"; String action = request.getParameter("action"); if (action == null) { action = ""; } String page = request.getParameter("page"); if (testing) { System.out.println("Redirect parameter (page) set to:"); } if (testing) { System.out.println(page); } try { if (page == null) { page = ""; } //For creating a new report if (page.equalsIgnoreCase("newreport")) { url = "/reportJSPs/choosebuilding.jsp"; sessionObj.setAttribute("customerSelcted", false); cuh.chooseCustomer(sessionObj, df); } //For choosing the customer //TODO split redirect and action if (page.equalsIgnoreCase("report_cus_choosen")) { url = "/reportJSPs/choosebuilding.jsp"; bh.loadCustomersBuildings(request, sessionObj, df); } //When building has been chosen, it sets up the report object if (page.equalsIgnoreCase("report_start")) { url = "/reportJSPs/report_start.jsp"; rh.createReport(request, sessionObj, df); } //For choosing room when setting up report, after exterior has been added if (page.equalsIgnoreCase("ChooseRoom")) { url = "/reportJSPs/chooseroom.jsp"; rh.saveReportExterior(request, sessionObj, parts, this); } //For inspecting the chosen room. if (page.equalsIgnoreCase("inspectRoom")) { url = "/reportJSPs/reportaddaroom.jsp"; rh.setUpForRoomInspection(request, sessionObj, df, parts); } //For submitting what is written about the room if (page.equalsIgnoreCase("submittedRoom")) { url = "/reportJSPs/chooseroom.jsp"; rh.createReportRoomElements(request, sessionObj, parts, this); } //Saving finished report and redirection to report view. if (page.equalsIgnoreCase("saveFinishedReport")) { url = "/viewreport.jsp"; rh.finishReportObject(request, sessionObj); int reportId = rh.saveFinishedReport(sessionObj, df); request.getSession().setAttribute("report", df.getReport(reportId)); } if (page.equalsIgnoreCase("toFinishReport")) { url = "/reportJSPs/finishreport.jsp"; } if (page.equalsIgnoreCase("backToChooseRoom")) { url = "/reportJSPs/chooseroom.jsp"; } //For inspecting a room you just added to the building if (page.equalsIgnoreCase("inspectRoomjustCreated")) { url = "/reportJSPs/reportaddaroom.jsp"; bh.createNewRoom(request, sessionObj, df); rh.setUpForRoomInspection(request, sessionObj, df, parts); } //List all reports for all customers if (page.equalsIgnoreCase("listreports")) { sessionObj.setAttribute("reports", df.getListOfReports(1)); response.sendRedirect("viewreports.jsp"); return; } if (page.equalsIgnoreCase("addbuilding")) { url = "/addbuilding.jsp"; } if (page.equalsIgnoreCase("addcustomer")) { url = "/addcustomer.jsp"; } //Viewing the list of all the if (page.equalsIgnoreCase("viewmybuildings")) { bh.findListOfBuilding(request, df, sessionObj); User tempUser = (User) request.getSession().getAttribute("user"); List<Building> buildings = df.getListOfBuildings(tempUser.getCustomerid()); url = "/viewcustomer.jsp"; sessionObj.setAttribute("buildings", buildings); } //Edit a building if (page.equalsIgnoreCase("editBuilding")) { bh.findBuildingToBeEdit(request, sessionObj, df); response.sendRedirect("editBuilding.jsp"); return; } if (page.equalsIgnoreCase("viewreport")) { int reportId = Integer.parseInt(request.getParameter("reportid")); Report report = df.getReport(reportId); sessionObj.setAttribute("report", report); response.sendRedirect("viewreport.jsp"); return; } if (page.equalsIgnoreCase("viewcustomers")) { List<Customer> customers = df.loadAllCustomers(); sessionObj.setAttribute("customers", customers); response.sendRedirect("viewcustomers.jsp"); return; } if (page.equalsIgnoreCase("viewcustomer")) { int custId = Integer.parseInt(request.getParameter("customerid")); sessionObj.setAttribute("customer_id", custId); List<Building> buildings = df.getListOfBuildings(custId); List<Customer> customers = df.loadAllCustomers(); for (Customer customer : customers) { if (customer.getCustomerId() == custId) { sessionObj.setAttribute("customer", customer); } } sessionObj.setAttribute("buildings", buildings); response.sendRedirect("viewcustomer.jsp"); return; } //This gets a Dashboard for a building if (page.equalsIgnoreCase("viewbuildingadmin")) { System.out.println("Did it go here?"); int buildId = Integer.parseInt(request.getParameter("buildingid")); Building b = df.getBuilding(buildId); sessionObj.setAttribute("building", b); response.sendRedirect("viewbuildingadmin.jsp"); return; } //TODO seperate redirect and action if (page.equalsIgnoreCase("newbuilding")) { Building b = bh.createBuilding(request, df, sessionObj, parts, this); response.sendRedirect("viewnewbuilding.jsp"); return; } //TODO: seperate action and redirect if (page.equalsIgnoreCase("vieweditedbuilding")) { Building b = bh.updateBuilding(request, df, sessionObj, parts, this); response.sendRedirect("viewbuildingadmin.jsp"); return; } //TODO: seperate action and redirect if (page.equalsIgnoreCase("submitcustomer")) { cuh.createNewCustomer(request, df, sessionObj, this); response.sendRedirect("customersubmitted.jsp"); return; } if (page.equalsIgnoreCase("addfloorsubmit")) { bh.addFloors(request, df, sessionObj, this); response.sendRedirect("addfloor.jsp"); return; } if (page.equalsIgnoreCase("selBdg")) { bh.selectBuilding(request, df, sessionObj, this); response.sendRedirect("addfloor.jsp"); return; } if (page.equalsIgnoreCase("addfloor")) { sessionObj.setAttribute("customerSelcted", false); cuh.chooseCustomer(sessionObj, df); response.sendRedirect("addfloor.jsp"); return; } if (page.equalsIgnoreCase("selCust")) { bh.loadCustomersBuildings(request, sessionObj, df); response.sendRedirect("addfloor.jsp"); return; } if (page.equalsIgnoreCase("loadFloors")) { bh.loadFloors(request, sessionObj, df, this); response.sendRedirect("addfloor.jsp"); return; } if (page.equalsIgnoreCase("selFlr")) { bh.selectFloor(request, sessionObj, df, this); response.sendRedirect("addroom.jsp"); return; } if (page.equalsIgnoreCase("loadRooms")) { bh.loadRooms(request, sessionObj, df, this); response.sendRedirect("addroom.jsp"); return; } if (page.equalsIgnoreCase("addroomsubmit")) { bh.addRoom(request, sessionObj, df, this); response.sendRedirect("addroom.jsp"); return; } //loading order request page if (page.equalsIgnoreCase("orderRequest")) { bh.loadBuildingsAfterLogIn(sessionObj, df, this); response.sendRedirect("orderRequest.jsp"); return; } //selecting a building for order request if (page.equalsIgnoreCase("selBdgReq")) { bh.selectBuilding(request, df, sessionObj, this); response.sendRedirect("orderRequest.jsp"); return; } //create an order request if (page.equalsIgnoreCase("orderRequestSubmit")) { oh.saveOrder(request, sessionObj, df, this); response.sendRedirect("ordersuccess.jsp"); return; } //displays the order history and order progress if (page.equalsIgnoreCase("orderhistory")) { oh.loadCustomerOrders(sessionObj, df, this); response.sendRedirect("orderhistory.jsp"); return; } //displays the order list and order progress if (page.equalsIgnoreCase("orderslist")) { oh.loadAllOrders(sessionObj, df); response.sendRedirect("orderslist.jsp"); return; } //displays the order details if (page.equalsIgnoreCase("vieworder")) { int orderNumber = Integer.parseInt(request.getParameter("ordernumber")); sessionObj.setAttribute("orderNumber", orderNumber); sessionObj.setAttribute("selectedOrder", df.getOrder(orderNumber)); response.sendRedirect("vieworder.jsp"); return; } //updates the order progress if (page.equalsIgnoreCase("updateStat")) { int newStat = Integer.parseInt(request.getParameter("orderstatus")); Order o = (Order) sessionObj.getAttribute("selectedOrder"); df.updateStatus(o.getOrderNumber(), newStat); oh.loadAllOrders(sessionObj, df); response.sendRedirect("orderslist.jsp"); return; } if (page.equalsIgnoreCase("continue")) { url = "/addroom.jsp"; } if (page.equalsIgnoreCase("login")) { url = "/login.jsp"; } if (page.equalsIgnoreCase("loguserin")) { if (request.getParameter("empOrCus").equals("emp")) { cuh.emplogin(df, request, response); } else { cuh.login(df, request, response); } url = "/login.jsp"; } if (page.equalsIgnoreCase("logout")) { request.setAttribute("user", null); request.setAttribute("loggedin", false); request.getSession().invalidate(); url = "/index.jsp"; } if (page.equalsIgnoreCase("printReport")) { rh.printReport(sessionObj, df, response, this); return; } if (request.getServletPath().equalsIgnoreCase("/viewreports")) { url = "/viewreports.jsp"; } if (request.getServletPath().equalsIgnoreCase("/getreport")) { url = "/viewreport.jsp"; } System.out.println(request.getServletPath()); System.out.println(request.getMethod()); //get the building and send it to the sessionobj System.out.println("test of action: " + action); if (action.equalsIgnoreCase("viewbuildingadmin")) { System.out.println("test!"); int buildId = Integer.parseInt(request.getParameter("buildingid")); Building b = df.getBuilding(buildId); request.getSession().setAttribute("building", b); request.setAttribute("showBuilding", true); url = "/viewbuildingadmin.jsp"; } //retrieve a room from the buildingobject and put it in response. if (action.equalsIgnoreCase("viewroom")) { Building b = (Building) request.getSession().getAttribute("building"); int roomNumber; String viewReportRoomString = request.getParameter("viewroom"); if (viewReportRoomString != null && b != null) { roomNumber = Integer.parseInt(viewReportRoomString); BuildingRoom r = b.returnARoom(roomNumber); request.getSession().setAttribute("room", r); request.getSession().setAttribute("building", b); request.setAttribute("showRoom", true); url = "/viewbuildingadmin.jsp"; } } if (action.equalsIgnoreCase("addfloor")) { request.setAttribute("addFloor", true); url = "/viewbuildingadmin.jsp"; } if (action.equalsIgnoreCase("addroom")) { int floorId = Integer.parseInt(request.getParameter("floor")); request.setAttribute("addRoom", true); request.setAttribute("floorId", floorId); url = "/viewbuildingadmin.jsp"; } if (action.equalsIgnoreCase("listreports")) { request.getSession().setAttribute("reports", df.getSimpleListOfReports()); } if (action.equalsIgnoreCase("addfloorsubmit")) { bh.addFloors(request, df); url = "/viewbuildingadmin.jsp"; } if (action.equalsIgnoreCase("addroomsubmit")) { int floorId = Integer.parseInt(request.getParameter("floorID")); bh.addRoom(request, df, floorId); request.setAttribute("showBuilding", true); url = "/viewbuildingadmin.jsp"; } if (action.equalsIgnoreCase("editbuilding")) { request.setAttribute("editBuilding", true); url = "/viewbuildingadmin.jsp"; } if (action.equalsIgnoreCase("showBuilding")) { request.setAttribute("showBuilding", true); url = "/viewbuildingadmin.jsp"; } if (action.equalsIgnoreCase("showreport")) { int reportId = Integer.parseInt(request.getParameter("reportid")); Report report = df.getReport(reportId); Building b = df.getBuilding(report.getBuildingId()); report.setBuildingName(b.getBuildingName()); // request.getSession().setAttribute("report", report); } if (action.equalsIgnoreCase("reportroom")) { int reportRoomId = Integer.parseInt(request.getParameter("viewroom")); Report report = (Report) request.getSession().getAttribute("report"); ReportRoom rr = report.getReportRoomFromReportFloor(reportRoomId); // request.setAttribute("reportroom", rr); request.setAttribute("showroom", true); url = "/viewreport.jsp"; } //Trying to see if I can work this out if (action.equalsIgnoreCase("roomfiles")) { //int buildId = Integer.parseInt(request.getParameter("buildingid")); request.setAttribute("roomfiles", true); //request.setAttribute("reportroom", report.getReportRoomFromReportFloor(roomId) ); url = "/viewbuildingadmin.jsp"; } if (action.equalsIgnoreCase("addfloorplans")) { Building b = (Building) request.getSession().getAttribute("building"); ArrayList<BuildingFloor> bfList = df.listOfFloors(b.getBdgId()); ArrayList<Floorplan> plans = df.getFloorplans(bfList); request.getSession().setAttribute("floorplans", plans); request.getSession().setAttribute("floorsList", bfList); request.setAttribute("addfloorplans", true); url = "/viewbuildingadmin.jsp"; } if (action.equalsIgnoreCase("addfilessubmit")) { request = nfu.addFiles(request, parts, df, this); url = "/viewbuildingadmin.jsp"; } if (action.equalsIgnoreCase("addfloorplanssubmit")) { request = nfu.addFloorplans(request, parts, df, this); url = "/viewbuildingadmin.jsp"; } if (action.equalsIgnoreCase("addBuilding")) { Building b = new Building(); b.setBuildingName("tempname"); request.getSession().setAttribute("building", b); } if (action.equalsIgnoreCase("viewbuildingadmin")) { int buildId = Integer.parseInt(request.getParameter("buildingid")); Building b = df.getBuilding(buildId); request.getSession().setAttribute("building", b); } if (action.equalsIgnoreCase("viewbuildingreports")) { request.setAttribute("viewbuildingreports", true); url = "/viewbuildingadmin.jsp"; } } catch (PolygonException ex) { Logger.getLogger(FrontControl.class.getName()).log(Level.SEVERE, null, ex); request.setAttribute("errormessage", ex.getMessage()); url = "/errorpage.jsp"; } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); }
From source file:com.kirayim.homesec.service.impl.ImageManagerImpl.java
@Override public Image handleFileUpload(long cameraId, HttpServletRequest request) { String extension = null;/*from w w w . ja va 2 s. c om*/ Date uploadTime = new Date(); String encoding = request.getCharacterEncoding(); if (encoding == null) { try { request.setCharacterEncoding(encoding = "UTF-8"); } catch (UnsupportedEncodingException ex) { logger.warn("Bad encoding", ex); } } User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Camera camera = cameraManager.get(cameraId); if (camera == null) { throw new NotAllowedException("Imvalid camera ID"); } if (!camera.getOwner().equals(user)) { throw new NotAllowedException("Camera doesn't belong to current user"); } /* ------------------------------------------------- * Calculate output file name * ------------------------------------------------- */ String name = String.format("homesec_image_%1$08d_%2$TY%2$Tm%2$Td_%2$TH%2$TM%2$TS%2$TL", camera.getCameraId(), uploadTime); /* ------------------------------------------------- * Get uploaded file and write to destination * ------------------------------------------------- */ try { if (request.getParts().size() > 1) { throw new NotAllowedException("Only one image upload per transaction"); } for (Part part : request.getParts()) { if (!uploadDir.exists()) { uploadDir.mkdirs(); } String contentType = part.getContentType(); if (contentType != null) { try { MimeTypes allTypes = MimeTypes.getDefaultMimeTypes(); MimeType mimeType = allTypes.forName(contentType); extension = mimeType.getExtension(); name += extension; } catch (MimeTypeException mimeTypeException) { logger.warn("Mime? ", mimeTypeException); } } File outputFile = new File(uploadDir, name); OutputStream out = new FileOutputStream(outputFile); InputStream in = part.getInputStream(); IOUtils.copy(in, out); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } catch (IOException | ServletException e) { throw new BadRequestException(e); } /* ------------------------------------------------- * If extension is unknown, re-read file to try * and get extension * ------------------------------------------------- */ if (extension == null) { // TODO: } /* ------------------------------------------------- * Save image record in DB * ------------------------------------------------- */ Image image = new Image(camera, name, uploadTime); dao.save(image); return image; }