List of usage examples for javax.servlet.http HttpServletRequest getServletContext
public ServletContext getServletContext();
From source file:edu.chalmers.dat076.moviefinder.controller.FileController.java
/** * Process the actual request./*from w w w . ja v a 2 s .c om*/ * * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not * (HEAD). * @throws IOException If something fails at I/O level. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content, String path, String defaultContentType) throws IOException { // Validate the requested file ------------------------------------------------------------ // URL-decode the file name (might contain spaces and on) and prepare file object. File file = new File(path); // Check if file actually exists in filesystem. if (!file.exists()) { // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + FileControllerUtils.DEFAULT_EXPIRE_TIME; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && FileControllerUtils.matches(ifNoneMatch, eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !FileControllerUtils.matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = FileControllerUtils.sublong(part, 0, part.indexOf("-")); long end = FileControllerUtils.sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = request.getServletContext().getMimeType(fileName); boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. //if (contentType == null) { contentType = defaultContentType; //} // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && FileControllerUtils.accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && FileControllerUtils.accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(FileControllerUtils.DEFAULT_BUFFER_SIZE); //response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. RandomAccessFile input = null; OutputStream output = null; try { // Open streams. input = new RandomAccessFile(file, "r"); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, FileControllerUtils.DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. FileControllerUtils.copy(input, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. FileControllerUtils.copy(input, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + FileControllerUtils.MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + FileControllerUtils.MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. FileControllerUtils.copy(input, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + FileControllerUtils.MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. FileControllerUtils.close(output); FileControllerUtils.close(input); } }
From source file:org.auraframework.http.AuraTestFilter.java
private void innerFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; TestContext testContext = getTestContext(request); boolean doResetTest = testReset.get(request, false); if (testContext != null && doResetTest) { testContext.getLocalDefs().clear(); }/*www. ja v a 2s . co m*/ // Check for requests to execute a JSTest, i.e. initial component GETs with particular parameters. if ("GET".equals(request.getMethod())) { DefDescriptor<?> targetDescriptor = getTargetDescriptor(request); if (targetDescriptor != null) { // Check if a single jstest is being requested. String testToRun = jstestToRun.get(request); if (testToRun != null && !testToRun.isEmpty() && !NO_RUN.equals(testToRun)) { AuraContext context = contextService.getCurrentContext(); Format format = context.getFormat(); switch (format) { case HTML: LOG.info(this + " jstest request: " + request.getRequestURL() + "?" + request.getQueryString(), new Error()); TestCaseDef testDef; String targetUri; try { TestSuiteDef suiteDef = getTestSuite(targetDescriptor); testDef = getTestCase(suiteDef, testToRun); testDef.validateDefinition(); if (testContext == null) { testContext = testContextAdapter.getTestContext(testDef.getQualifiedName()); } targetUri = buildJsTestTargetUri(targetDescriptor, testDef); } catch (QuickFixException e) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); servletUtilAdapter.setNoCache(response); response.setContentType(servletUtilAdapter.getContentType(Format.HTML)); response.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING); response.getWriter().append(e.getMessage()); exceptionAdapter.handleException(e); return; } // Load any test mocks. Collection<Definition> mocks = testDef.getLocalDefs(); testContext.getLocalDefs().addAll(mocks); loadTestMocks(context, true, testContext.getLocalDefs()); // Capture the response and inject tags to load jstest. String capturedResponse = captureResponse(request, response, testToRun, targetUri); if (capturedResponse != null) { servletUtilAdapter.setNoCache(response); response.setContentType(servletUtilAdapter.getContentType(Format.HTML)); response.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING); if (!contextService.isEstablished()) { // There was an error in the original response, so just write the response out. response.getWriter().write(capturedResponse); } else { int timeout = testTimeout.get(request, DEFAULT_JSTEST_TIMEOUT); String testTag = buildJsTestScriptTag(targetDescriptor, testToRun, timeout, capturedResponse); injectScriptTags(response.getWriter(), capturedResponse, testTag); } return; } case JS: servletUtilAdapter.setNoCache(response); response.setContentType(servletUtilAdapter.getContentType(Format.JS)); response.setCharacterEncoding(AuraBaseServlet.UTF_ENCODING); int timeout = testTimeout.get(request, DEFAULT_JSTEST_TIMEOUT); writeJsTestScript(response.getWriter(), targetDescriptor, testToRun, timeout); return; default: // Pass it on. } } else if (testToRun != null && testToRun.isEmpty()) { Object origRequest = request.getAttribute(AuraResourceServlet.ORIG_REQUEST_URI); LOG.error(this + " empty jstestrun: " + request.getRequestURL() + "?" + request.getQueryString() + " original request: " + origRequest, new Error()); } // aurajstest:jstest app is invokable in the following ways: // ?aura.mode=JSTEST - run all tests // ?aura.mode JSTEST&test=XXX - run single test // ?aura.jstest - run all tests // ?aura.jstest=XXX - run single test // TODO: delete JSTEST mode String jstestAppRequest = jstestAppFlag.get(request); Mode mode = AuraContextFilter.mode.get(request, Mode.PROD); if (mode == Mode.JSTEST || mode == Mode.JSTESTDEBUG || jstestAppRequest != null) { mode = mode.toString().endsWith("DEBUG") ? Mode.AUTOJSTESTDEBUG : Mode.AUTOJSTEST; String qs = String.format("descriptor=%s&defType=%s", targetDescriptor.getDescriptorName(), targetDescriptor.getDefType().name()); String testName = null; if (jstestAppRequest != null && !jstestAppRequest.isEmpty()) { testName = jstestAppRequest; } else if (testToRun != null && !testToRun.isEmpty()) { testName = testToRun; } if (testName != null) { qs = qs + "&test=" + testName; } String newUri = createURI("aurajstest", "jstest", DefType.APPLICATION, mode, Format.HTML, Authentication.AUTHENTICATED.name(), NO_RUN, qs); RequestDispatcher dispatcher = request.getServletContext().getContext(newUri) .getRequestDispatcher(newUri); if (dispatcher != null) { dispatcher.forward(request, response); return; } } } } // Handle mock definitions specified in the tests. if (testContext == null) { // During manual testing, the test context adapter may not always get cleared. testContextAdapter.clear(); } else { if (!contextService.isEstablished()) { LOG.error(this + " Aura context is not established! New context will NOT be created."); chain.doFilter(request, response); return; } AuraContext context = contextService.getCurrentContext(); // Reset mocks if requested, or for the initial GET. loadTestMocks(context, doResetTest, testContext.getLocalDefs()); } chain.doFilter(request, response); }
From source file:com.krawler.esp.servlets.AdminServlet.java
public static String editCompanyDetails(Connection conn, HttpServletRequest request, String companyid) throws ServiceException, SessionExpiredException { String status = "failure"; // int notificationduration = 0; int notificationtype = 0; double activity = 0; String sd = ""; String companyEmail = ""; DiskFileUpload fu = new DiskFileUpload(); HashMap arrParam = new HashMap(); FileItem fi1 = null;/*w ww .j a v a2 s . co m*/ String logouploadmsg = ""; List fileItems = null; try { fileItems = fu.parseRequest(request); } catch (FileUploadException e) { throw ServiceException.FAILURE("Admin.createUser", e); } for (Iterator k = fileItems.iterator(); k.hasNext();) { fi1 = (FileItem) k.next(); arrParam.put(fi1.getFieldName(), fi1.getString()); } try { String ipAddress = AuthHandler.getIPAddress(request); int auditMode = 0; String loginid = AuthHandler.getUserid(request); String params = AuthHandler.getAuthor(conn, loginid) + " (" + AuthHandler.getUserName(request) + ")"; int editAll = Integer.parseInt(request.getParameter("editAll")); // if(editAll >= 1) { // PreparedStatement pstmt = conn.prepareStatement("SELECT subdomain FROM company WHERE companyid=?"); // pstmt.setString(1, companyid); // ResultSet rs = pstmt.executeQuery(); // String subdomain = ""; // if (rs.next()) { // subdomain = rs.getString("subdomain"); // } // boolean domainflag = true; // sd = StringUtil.serverHTMLStripper(arrParam.get("domainname").toString().toLowerCase()); // if (!subdomain.equals(arrParam.get("domainname"))) { // if (SignupHandler.subdomainIsAvailable(conn, sd).equalsIgnoreCase("failure") || StringUtil.isNullOrEmpty(sd)) { // domainflag = false; // } else { // //mailtoAllOnSubdomainChange(conn, subdomain, sd, request); TODO: commented for now. need to implement. - brajesh@090909 // } // } // companyEmail = StringUtil.serverHTMLStripper(arrParam.get("mail").toString().trim()); // String companyname = StringUtil.serverHTMLStripper(arrParam.get("companyname").toString()); // String address = StringUtil.serverHTMLStripper(arrParam.get("address").toString()); // String city = StringUtil.serverHTMLStripper(arrParam.get("city").toString()); // String state = StringUtil.serverHTMLStripper(arrParam.get("state").toString()); // String country = StringUtil.serverHTMLStripper(arrParam.get("country").toString()); // String phone = StringUtil.serverHTMLStripper(arrParam.get("phone").toString()); // String fax = StringUtil.serverHTMLStripper(arrParam.get("fax").toString()); // String zip = StringUtil.serverHTMLStripper(arrParam.get("zip").toString()); // String timezone = StringUtil.serverHTMLStripper(arrParam.get("timezone").toString()); // String website = StringUtil.serverHTMLStripper(arrParam.get("website").toString()); // String currency = StringUtil.serverHTMLStripper(arrParam.get("currency").toString()); // notificationduration = Integer.parseInt(arrParam.get("dur").toString()); if (arrParam.containsKey("1")) { activity = Double.parseDouble("1"); activity = Math.pow(2, activity); notificationtype += activity; } if (arrParam.containsKey("2")) { activity = Double.parseDouble("2"); activity = Math.pow(2, activity); notificationtype += activity; } // if (!(StringUtil.isNullOrEmpty(sd)) && !(StringUtil.isNullOrEmpty(companyname)) && !(StringUtil.isNullOrEmpty(country)) && !(StringUtil.isNullOrEmpty(timezone)) && !(StringUtil.isNullOrEmpty(currency))) { // if (domainflag) { DbUtil.executeUpdate(conn, "update company set notificationtype=? where companyid=?;", new Object[] { notificationtype, companyid }); int o_diff = Constants.DEFAULT_PERT_DURATION_DIFF, p_diff = Constants.DEFAULT_PERT_DURATION_DIFF; if (arrParam.containsKey("optimisticdiff")) { o_diff = Integer.parseInt(arrParam.get("optimisticdiff").toString()); } if (arrParam.containsKey("pessimisticdiff")) { p_diff = Integer.parseInt(arrParam.get("pessimisticdiff").toString()); } DbUtil.executeUpdate(conn, "update pertdefaults_company set o_diff=?, p_diff=? where companyid=?", new Object[] { o_diff, p_diff, companyid }); boolean val = false; if (arrParam.containsKey("milestonewidget")) { if ("on".equals(arrParam.get("milestonewidget").toString())) val = true; } DbUtil.executeUpdate(conn, "UPDATE company SET milestonewidget = ? WHERE companyid = ?", new Object[] { val, companyid }); WidgetStateHandler.updateCustomWidgetSetting(conn, companyid, val); val = false; if (arrParam.containsKey("checklist")) { if ("on".equals(arrParam.get("checklist").toString())) { val = true; new CheckListManager().calculateAllTasksProgresses(conn, companyid); } } DbUtil.executeUpdate(conn, "UPDATE company SET checklist = ? WHERE companyid = ?", new Object[] { val, companyid }); val = false; if (arrParam.containsKey("docaccess")) { if ("on".equals(arrParam.get("docaccess").toString())) { val = true; OpenOfficeServiceResolver resolver = OpenOfficeServiceResolver.get(request.getServletContext()); DocsConversionHandler.convertDocs(companyid, resolver); } } DbUtil.executeUpdate(conn, "UPDATE company SET docaccess = ? WHERE companyid = ?", new Object[] { val, companyid }); // pst = conn.prepareStatement("Select activityid,featureid from activitieslist where activityname=?"); // pst.setString(1, "ChangeCompanyLogo"); // ResultSet rset = pst.executeQuery(); // if (rset.next()) { // int actid = rset.getInt("activityid"); // int featid = rset.getInt("featureid"); // pst = conn.prepareStatement("SELECT permissions FROM userpermissions WHERE userid = ? and featureid=?"); // pst.setString(1, AuthHandler.getUserid(request)); // pst.setInt(2, featid); // ResultSet rset1 = pst.executeQuery(); // if (rset1.next()) { // int perm = rset1.getInt("permissions"); // int num = (int) Math.pow(2, actid); // if ((perm & num) == num) { // res = true; // } // } // } // if (res && editAll == 1) { // if (arrParam.get("logo").toString().length() != 0) { // genericFileUpload uploader = new genericFileUpload(); // uploader.doPostCompay(fileItems, companyid, StorageHandler.GetProfileImgStorePath()); // if (uploader.isUploaded()) { // DbUtil.executeUpdate(conn, "UPDATE company set image=? where companyid = ?", // new Object[]{ProfileImageServlet.ImgBasePath + companyid + uploader.getCompanyImageExt(), companyid}); // } // logouploadmsg = uploader.ErrorMsg; // // AuditTrail.insertLog(conn, "331", loginid, "", "", companyid, // params, ipAddress, auditMode); // } // } String holidaysJson = arrParam.get("holidays").toString(); com.krawler.utils.json.base.JSONObject holidays = new JSONObject(holidaysJson); String qry1 = "SELECT holiday,description FROM companyholidays where companyid=?"; DbResults rs = DbUtil.executeQuery(conn, qry1, companyid); List hDays = new ArrayList(); while (rs.next()) { hDays.add(rs.getObject("holiday").toString()); } DbUtil.executeUpdate(conn, "DELETE FROM companyholidays WHERE companyid = ?", new Object[] { companyid }); String qry = "INSERT INTO companyholidays (companyid, holiday, description) VALUES (?,?,?)"; com.krawler.utils.json.base.JSONArray jarr = holidays.getJSONArray("data"); for (int k = 0; k < jarr.length(); k++) { com.krawler.utils.json.base.JSONObject jobj = jarr.getJSONObject(k); DbUtil.executeUpdate(conn, qry, new Object[] { companyid, jobj.getString("day"), jobj.getString("description") }); } if (hDays.size() != jarr.length()) { AuditTrail.insertLog(conn, "333", loginid, "", "", companyid, params, ipAddress, auditMode); } AuditTrail.insertLog(conn, "332", loginid, "", "", companyid, params, ipAddress, auditMode); /* // notification config options String updateqry = "UPDATE notification set notifysum = ? where companyid = ? and nid = ?"; String insertqry = "INSERT INTO notification (companyid, nid, notifysum) VALUES (?,?,?)"; qry = "SELECT count(*) as count from notification where companyid = ? and nid = ?"; String notifyJson = arrParam.get("notifyconf").toString(); JSONObject notifyJObj = new JSONObject(notifyJson); jarr = notifyJObj.getJSONArray("data"); for (int k = 0; k < jarr.length(); k++) { JSONObject jobj = jarr.getJSONObject(k); String nid = jobj.getString("nid"); int type = 1; int sum = 0; while (true) { if (jobj.has(String.valueOf(type))) { if (jobj.getBoolean(String.valueOf(type))) { sum += Math.pow(2, type); } type++; } else { break; } } pstmt = conn.prepareStatement(qry); pstmt.setString(1, companyid); pstmt.setString(2, nid); ResultSet notifySet = pstmt.executeQuery(); if (notifySet.next()) { if (notifySet.getInt("count") > 0) { DbUtil.executeUpdate(conn, updateqry, new Object[]{sum, companyid, nid}); } else { DbUtil.executeUpdate(conn, insertqry, new Object[]{companyid, nid, sum}); } } } */ // status = "success" + "," + logouploadmsg; // } else { // status = "success" + "," + "Subdomain is already registered."; // } // } // } else if (arrParam.get("logo").toString().length() != 0) { // status = editCompanyLogo(conn, fileItems, companyid, AuthHandler.getUserid(request)); // AuditTrail.insertLog(conn, "331", loginid, "", "", companyid, // params, ipAddress, auditMode); // } status = "success"; } catch (JSONException ex) { Logger.getLogger(AdminServlet.class.getName()).log(Level.SEVERE, null, ex); } return status; }
From source file:Admin.products.ProductUpdateS.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w . jav a 2 s.c o m * * @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 { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { try { String product_id = null; String product_name = null; String description = null; String specifications_name = null; //[] String specifications_value = null;//[] String specifications_unit = null;//[] String purchase_date = null; String MFD = null; String EXP = null; String purchase_price = null; // String old_price = null; String discount = null; String selling_price = null; String w_years = null; String w_months = null; String w_dates = null; String QTY = null; String pickup = null; String delivery_pond = null; String delivery_days = null; String delivery_area = null;//[] String images0 = null; String images = null;//[] String rurl = null; Collecter01.i = 0; // ilagata sepe collect karanna kalin Collecter01.specifications.clear(); Collecter01.delivery_areas = ""; Collecter01.product_images.clear(); FileItemFactory item = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(item); List<FileItem> list = upload.parseRequest(request); for (FileItem fileItem : list) { if (fileItem.isFormField()) { //form field switch (fileItem.getFieldName()) { case "hid01n": System.out.println("PRODUCT_ID---------:" + fileItem.getString()); product_id = fileItem.getString(); if (checkDigit(product_id)) { rurl = "04_admin/product/product_update.jsp?upd01n=" + product_id + "&"; } else { rurl = "04_admin/product/product_update.jsp?upd01n=" + product_id + "&"; response.sendRedirect(rurl + "msg=Please enter the product id"); } break; case "txf01n": System.out.println("PRODUCT_NAME---------:" + fileItem.getString()); product_name = fileItem.getString(); if (checkString(product_name.trim())) { } else { response.sendRedirect(rurl + "msg=Please enter the product name"); } break; case "txa01n": System.out.println("DESCRIPTION----------:" + fileItem.getString()); description = fileItem.getString(); if (checkString(description.trim())) { } else { response.sendRedirect(rurl + "msg=Please enter the description"); } break; case "spe01n": System.out.println("SPECIFICATION_NAME----------:" + fileItem.getString()); specifications_name = fileItem.getString(); if (checkString(specifications_name.trim())) { Collecter01.collectSpec(specifications_name.trim()); } else { response.sendRedirect(rurl + "msg=Please enter the specifications name"); } break; case "spe02n": System.out.println("SPECIFICATION_VALUE---------:" + fileItem.getString()); specifications_value = fileItem.getString(); if (checkString(specifications_value.trim())) { Collecter01.collectSpec(specifications_value.trim()); } else { response.sendRedirect(rurl + "msg=Please enter the specifications value"); } break; case "spe03n": System.out.println("SPECIFICATION_UNIT----------:" + fileItem.getString()); specifications_unit = fileItem.getString(); if (specifications_unit == null || specifications_unit.equals("")) { specifications_unit = ""; } else { Collecter01.collectSpec(specifications_unit.trim()); } break; case "dat01n": System.out.println("PURCHASE_DATE--------:" + fileItem.getString()); purchase_date = fileItem.getString(); if (checkString(purchase_date)) { } else { response.sendRedirect(rurl + "msg=Please select the purchase date"); } break; case "dat02n": System.out.println("MFD------------------:" + fileItem.getString()); MFD = fileItem.getString(); if (checkString(MFD)) { } else { response.sendRedirect(rurl + "msg=Please select the MFD"); } break; case "dat03n": System.out.println("EXP------------------:" + fileItem.getString()); EXP = fileItem.getString(); if (checkString(EXP)) { } else { response.sendRedirect(rurl + "msg=Please enter the EXP"); } break; case "num01n": System.out.println("PURCHASE_price-------:" + fileItem.getString()); purchase_price = fileItem.getString(); if (checkDigit(purchase_price)) { } else { response.sendRedirect(rurl + "msg=Please enter the purchase price"); } break; case "num03n": System.out.println("DISCOUNT-------------:" + fileItem.getString() + " %"); discount = fileItem.getString(); if (checkDigit(discount)) { } else { response.sendRedirect(rurl + "msg=Please enter the discount"); } break; case "num04n": System.out.println("SELLING_PRICE--------:" + fileItem.getString()); selling_price = fileItem.getString(); if (checkDigit(selling_price)) { } else { response.sendRedirect(rurl + "msg=Please enter the selling price value"); } break; case "num05n": System.out.println("W_YEARS--------------:" + fileItem.getString()); w_years = fileItem.getString(); if (checkDigit(w_years)) { } else { response.sendRedirect(rurl + "msg=Please enter the warrenty years"); } break; case "num06n": System.out.println("W_MONTS--------------:" + fileItem.getString()); w_months = fileItem.getString(); if (checkDigit(w_months)) { } else { response.sendRedirect(rurl + "msg=Please enter the warrenty months"); } break; case "num07n": System.out.println("W_DATES--------------:" + fileItem.getString()); w_dates = fileItem.getString(); if (checkDigit(w_dates)) { } else { response.sendRedirect(rurl + "msg=Please enter th warrenty dates"); } break; case "num08n": System.out.println("QTY------------------:" + fileItem.getString()); QTY = fileItem.getString(); if (checkDigit(QTY)) { } else { response.sendRedirect(rurl + "msg=Please enter the QTY"); } break; case "sel05n": System.out.println("PICKUP---------------:" + fileItem.getString()); pickup = fileItem.getString(); if (checkString(pickup)) { } else { response.sendRedirect(rurl + "msg=Please select the pickup"); } break; case "sel06n": System.out.println("DELIVERY_POND--------:" + fileItem.getString()); delivery_pond = fileItem.getString(); if (checkString(delivery_pond)) { } else { response.sendRedirect(rurl + "msg=Please select the pay on delivery"); } break; case "num09n": System.out.println("DELIVERY_DAYS--------:" + fileItem.getString()); if (delivery_pond.trim().equals("Yes")) { delivery_days = fileItem.getString(); if (checkDigit(delivery_days)) { } else { response.sendRedirect(rurl + "msg=Please add the delivery dates"); } } else { } break; case "sel07n": System.out.println("DELIVERY_AREA--------:" + fileItem.getString());//[] if (delivery_pond.trim().equals("Yes")) { delivery_area = fileItem.getString(); if (checkString(delivery_area)) { // Collecter01.collectDeliveryArea(delivery_area.trim()); } else { response.sendRedirect(rurl + "msg=Please select the delivery areas"); } } else { } break; case "hid02n": System.out.println("DELETE--------:" + fileItem.getString()); images0 = fileItem.getString(); if (checkString(images0)) { for (String imn : images0.split(">")) { System.out.println(imn); } } else { System.out.println("delete natha"); // response.sendRedirect(rurl + "msg=Please select the pay on delivery"); } break; default: break; } } else { images = fileItem.getName(); System.out.println(images); if (checkString(images)) { Long time = System.currentTimeMillis(); System.out.println("IMAGES_name----------:" + time); String apath = request.getServletContext().getRealPath("/04_admin/product/img/") + "\\" + time + ".jpg"; System.out.println("IMAGES_AP------------:" + apath); String rpath = "04_admin\\product\\img\\" + time + ".jpg"; System.out.println("IMAGES_RP------------:" + rpath); fileItem.write(new File(apath)); Collecter01.collectImages(rpath); } else { // response.sendRedirect(rurl + "msg=Please select images"); } } } System.out.println(checkString(product_id)); System.out.println(checkString(product_name)); System.out.println(checkString(description)); // System.out.println(specifications_name); //null // System.out.println(specifications_value); //null // System.out.println(specifications_unit); //null System.out.println(checkString(purchase_date)); System.out.println(checkString(MFD)); System.out.println(checkString(EXP)); System.out.println(checkDigit(purchase_price)); System.out.println(checkDigit(selling_price)); System.out.println(checkDigit(discount)); System.out.println(checkDigit(w_years)); System.out.println(checkDigit(w_months)); System.out.println(checkDigit(w_dates)); System.out.println(checkDigit(QTY)); System.out.println(checkString(pickup)); System.out.println(checkString(delivery_pond)); System.out.println(delivery_pond.trim().equals("Yes") ? checkDigit(delivery_days) : true); System.out.println(delivery_pond.trim().equals("Yes") ? checkString(delivery_area) : true); System.out.println(checkString(images)); if (checkDigit(product_id) && checkString(product_name) && checkString(description) && checkString(purchase_date) && checkString(MFD) && checkString(EXP) && checkDigit(purchase_price) && checkDigit(selling_price) && checkDigit(discount) && checkDigit(w_years) && checkDigit(w_months) && checkDigit(w_dates) && checkDigit(QTY) && checkString(pickup) && checkString(delivery_pond) && delivery_pond.trim().equals("Yes") ? checkDigit(delivery_days) : true && delivery_pond.trim().equals("Yes") ? checkString(delivery_area) : true) { System.out.println( "UPDATE VALIDATION OK---------------------------------------------------------------------"); try { String sql00 = "UPDATE product SET name=?, description=? WHERE idproduct=?"; PreparedStatement ps00 = Controller.DB.con().prepareStatement(sql00); ps00.setString(1, product_name); ps00.setString(2, description); ps00.setInt(3, Integer.parseInt(product_id)); System.out.println(ps00); int x = ps00.executeUpdate(); if (x == 1) { try { String sql01 = "UPDATE stock SET purchase_date=?, purchase_price=?, discount=?, selling_price=?, warranty=?, QTY=?, pickup=?, MFD=?, EXP=? WHERE product_idproduct=?"; PreparedStatement ps01 = Controller.DB.con().prepareStatement(sql01); ps01.setString(1, purchase_date); ps01.setInt(2, Integer.parseInt(purchase_price)); ps01.setInt(3, Integer.parseInt(discount)); ps01.setInt(4, Integer.parseInt(selling_price)); ps01.setString(5, w_years + "," + w_months + "," + w_dates); ps01.setInt(6, Integer.parseInt(QTY)); ps01.setString(7, pickup); ps01.setInt(6, Integer.parseInt(QTY)); ps01.setString(7, pickup); ps01.setString(8, MFD); ps01.setString(9, EXP); ps01.setInt(10, Integer.parseInt(product_id)); System.out.println(ps01); int x1 = ps01.executeUpdate(); if (x1 == 1) { try { String sql04 = "SELECT * FROM delivery WHERE product_idproduct=?"; PreparedStatement ps04 = Controller.DB.con().prepareStatement(sql04); ps04.setInt(1, Integer.parseInt(product_id)); System.out.println(ps04); ResultSet rs04 = ps04.executeQuery(); if (rs04.next()) { System.out.println("update karanna delivery id ata"); try { String sql02 = "UPDATE delivery SET pay_on_delivery=?, days=?, area=? WHERE product_idproduct=?"; PreparedStatement ps02 = Controller.DB.con() .prepareStatement(sql02); try { if (delivery_pond.equals("Yes")) { ps02.setString(1, delivery_pond); ps02.setInt(2, Integer.parseInt(delivery_days)); ps02.setString(3, Collecter01.delivery_areas.substring(1)); ps02.setInt(4, Integer.parseInt(product_id)); } else { ps02.setString(1, "No"); ps02.setInt(2, 0); ps02.setString(3, "No"); ps02.setInt(4, Integer.parseInt(product_id)); } System.out.println(ps02); ps02.executeUpdate(); } catch (Exception e) { } finally { try { for (String imn : images0.split(">")) { if (imn.trim().equals("")) { } else { String sql5 = "DELETE FROM image WHERE path LIKE ?;"; PreparedStatement ps5 = Controller.DB.con() .prepareStatement(sql5); ps5.setString(1, "%" + imn + "%"); System.out.println(ps5); ps5.executeUpdate(); } } for (String img_path : Collecter01.product_images) { String sql4 = "INSERT INTO image VALUES (?,?)"; PreparedStatement ps4 = Controller.DB.con() .prepareStatement(sql4); ps4.setInt(1, Integer.parseInt(product_id)); ps4.setString(2, img_path); System.out.println(ps4); ps4.executeUpdate(); } } catch (Exception e) { } finally { try { String sql5 = "SELECT idSpecifications FROM specifications WHERE name=?"; PreparedStatement ps5 = Controller.DB.con() .prepareStatement(sql5); for (Map.Entry<String, List> entry : Collecter01.specifications .entrySet()) { System.out.println(entry.getKey() + "---" + entry.getValue().get(0) + "---" + entry.getValue().get(1)); ps5.setString(1, entry.getKey()); System.out.println(ps5); ResultSet rs5 = ps5.executeQuery(); // int idSpecifications = 0; try { if (rs5.first()) { System.out.println( "Specifications name/id ata____1"); // idSpecifications = rs5.getInt(1); } else { try { System.out.println( "Specifications name/id na____2"); String sql6 = "INSERT INTO specifications VALUES (null,?)"; PreparedStatement ps6 = Controller.DB .con().prepareStatement(sql6); ps6.setString(1, entry.getKey()); System.out.println(ps6); ps6.executeUpdate(); System.out.println( "Specifications new add karanawa____2-1"); try { String sql7 = "SELECT idSpecifications FROM specifications WHERE name=?"; PreparedStatement ps7 = Controller.DB .con() .prepareStatement(sql7); ps7.setString(1, entry.getKey()); System.out.println(ps7); ResultSet rs7 = ps7.executeQuery(); if (rs7.first()) { System.out.println( "new Specifications name/id ata____3-1"); // idSpecifications = rs7.getInt(1); } else { } } catch (Exception e9) { System.out.println( "new Specifications name/id na____3-2"); } } catch (Exception e8) { System.out.println( "Specifications new add fail____2-2"); } } } catch (Exception e7) { } finally { try { String sql8 = "DELETE FROM product_has_specifications WHERE product_idproduct=?;"; PreparedStatement ps8 = Controller.DB.con() .prepareStatement(sql8); ps8.setInt(1, Integer.parseInt(product_id)); System.out.println(ps8); ps8.executeUpdate(); } catch (Exception e) { } } } try { for (Map.Entry<String, List> entry : Collecter01.specifications .entrySet()) { // System.out.println(product_id); // System.out.println(entry.getKey()); // System.out.println(entry.getValue().get(0)); // System.out.println(entry.getValue().get(1)); int idSpecifications = 0; try { String sql9 = "SELECT idSpecifications FROM specifications WHERE name=?"; PreparedStatement ps9 = Controller.DB.con() .prepareStatement(sql9); ps9.setString(1, entry.getKey()); // System.out.println(ps7); ResultSet rs9 = ps9.executeQuery(); if (rs9.first()) { // System.out.println("new Specifications name/id ata____3-1"); idSpecifications = rs9.getInt(1); } else { } } catch (Exception e) { } // System.out.println(product_id); // System.out.println(idSpecifications); // System.out.println(entry.getValue().get(0)); // System.out.println(entry.getValue().get(1)); try { String sql10 = "INSERT INTO product_has_specifications VALUES (?,?,?,?)"; PreparedStatement ps10 = Controller.DB.con() .prepareStatement(sql10); ps10.setInt(1, Integer.parseInt(product_id)); ps10.setInt(2, idSpecifications); ps10.setString(3, (String) entry.getValue().get(0)); ps10.setString(4, (String) entry.getValue().get(1)); System.out.println(ps10); ps10.executeUpdate(); System.out.println("spec value save kara"); } catch (Exception e) { System.out.println("spec value save fail"); } } } catch (Exception e) { } } catch (Exception e) { } finally { String xv = rurl + "msg=Product update successful&cl=00bf6f"; response.sendRedirect(xv); } } } } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("update karanna delivery id eka na"); } } catch (Exception e) { } } else { System.out.println("stock update fail"); } } catch (Exception e) { } } else { System.out.println("product update fail"); } } catch (Exception e) { } } else { } } catch (Exception e) { } } }
From source file:Admin.products.ProductSaveS.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w. java 2 s .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 { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { try { String brand_id = null; String category_1_id = null; String category_2_id = null; String category_3_id = null; String product_name = null; String description = null; String specifications_name = null; //[] String specifications_value = null;//[] String specifications_unit = null;//[] String purchase_date = null; String MFD = null; String EXP = null; String purchase_price = null; // String old_price = null; String discount = null; String selling_price = null; String w_years = null; String w_months = null; String w_dates = null; String QTY = null; String pickup = null; String delivery_pond = null; String delivery_days = null; String delivery_area = null;//[] String images = null;//[] String rurl = "04_admin/product/product_save.jsp?"; Collecter01.i = 0; // ilagata sepe collect karanna kalin Collecter01.specifications.clear(); Collecter01.delivery_areas = ""; Collecter01.product_images.clear(); FileItemFactory item = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(item); List<FileItem> list = upload.parseRequest(request); for (FileItem fileItem : list) { if (fileItem.isFormField()) { //form field switch (fileItem.getFieldName()) { case "sel01n": System.out.println("BRAND_ID-------------:" + fileItem.getString()); brand_id = fileItem.getString(); if (checkDigit(brand_id.trim())) { } else { response.sendRedirect(rurl + "msg=Please select the brand"); } break; case "sel02n": System.out.println("CATEGORY1_ID---------:" + fileItem.getString()); category_1_id = fileItem.getString(); if (checkDigit(category_1_id.trim())) { } else { response.sendRedirect(rurl + "msg=Please select the category 1"); } break; case "sel03n": System.out.println("CATEGORY2_ID---------:" + fileItem.getString()); category_2_id = fileItem.getString(); if (checkDigit(category_2_id.trim())) { } else { response.sendRedirect(rurl + "msg=Please select the category 2"); } break; case "sel04n": System.out.println("CATEGORY3_ID---------:" + fileItem.getString()); category_3_id = fileItem.getString(); if (checkDigit(category_3_id.trim())) { } else { response.sendRedirect(rurl + "msg=Please select the category 3"); } break; case "txf01n": System.out.println("PRODUCT_NAME---------:" + fileItem.getString()); product_name = fileItem.getString(); if (checkString(product_name.trim())) { } else { response.sendRedirect(rurl + "msg=Please enter the product name"); } break; case "txa01n": System.out.println("DESCRIPTION----------:" + fileItem.getString()); description = fileItem.getString(); if (checkString(description.trim())) { } else { response.sendRedirect(rurl + "msg=Please enter the description"); } break; case "spe01n": System.out.println("SPECIFICATION_NAME----------:" + fileItem.getString()); specifications_name = fileItem.getString(); if (checkString(specifications_name.trim())) { Collecter01.collectSpec(specifications_name.trim()); } else { response.sendRedirect(rurl + "msg=Please enter the specifications name"); } break; case "spe02n": System.out.println("SPECIFICATION_VALUE---------:" + fileItem.getString()); specifications_value = fileItem.getString(); if (checkString(specifications_value.trim())) { Collecter01.collectSpec(specifications_value.trim()); } else { response.sendRedirect(rurl + "msg=Please enter the specifications value"); } break; case "spe03n": System.out.println("SPECIFICATION_UNIT----------:" + fileItem.getString()); specifications_unit = fileItem.getString(); if (specifications_unit == null || specifications_unit.equals("")) { specifications_unit = ""; } else { Collecter01.collectSpec(specifications_unit.trim()); } break; case "dat01n": System.out.println("PURCHASE_DATE--------:" + fileItem.getString()); purchase_date = fileItem.getString(); if (checkString(purchase_date)) { } else { response.sendRedirect(rurl + "msg=Please select the purchase date"); } break; case "dat02n": System.out.println("MFD------------------:" + fileItem.getString()); MFD = fileItem.getString(); if (checkString(MFD)) { } else { response.sendRedirect(rurl + "msg=Please select the MFD"); } break; case "dat03n": System.out.println("EXP------------------:" + fileItem.getString()); EXP = fileItem.getString(); if (checkString(EXP)) { } else { response.sendRedirect(rurl + "msg=Please enter the EXP"); } break; case "num01n": System.out.println("PURCHASE_price-------:" + fileItem.getString()); purchase_price = fileItem.getString(); if (checkDigit(purchase_price)) { } else { response.sendRedirect(rurl + "msg=Please enter the purchase price"); } break; case "num03n": System.out.println("DISCOUNT-------------:" + fileItem.getString() + " %"); discount = fileItem.getString(); if (checkDigit(discount)) { } else { response.sendRedirect(rurl + "msg=Please enter the discount"); } break; case "num04n": System.out.println("SELLING_PRICE--------:" + fileItem.getString()); selling_price = fileItem.getString(); if (checkDigit(selling_price)) { } else { response.sendRedirect(rurl + "msg=Please enter the selling price value"); } break; case "num05n": System.out.println("W_YEARS--------------:" + fileItem.getString()); w_years = fileItem.getString(); if (checkDigit(w_years)) { } else { response.sendRedirect(rurl + "msg=Please enter the warrenty years"); } break; case "num06n": System.out.println("W_MONTS--------------:" + fileItem.getString()); w_months = fileItem.getString(); if (checkDigit(w_months)) { } else { response.sendRedirect(rurl + "msg=Please enter the warrenty months"); } break; case "num07n": System.out.println("W_DATES--------------:" + fileItem.getString()); w_dates = fileItem.getString(); if (checkDigit(w_dates)) { } else { response.sendRedirect(rurl + "msg=Please enter th warrenty dates"); } break; case "num08n": System.out.println("QTY------------------:" + fileItem.getString()); QTY = fileItem.getString(); if (checkDigit(QTY)) { } else { response.sendRedirect(rurl + "msg=Please enter the QTY"); } break; case "sel05n": System.out.println("PICKUP---------------:" + fileItem.getString()); pickup = fileItem.getString(); if (checkString(pickup)) { } else { response.sendRedirect(rurl + "msg=Please select the pickup"); } break; case "sel06n": System.out.println("DELIVERY_POND--------:" + fileItem.getString()); delivery_pond = fileItem.getString(); if (checkString(delivery_pond)) { } else { response.sendRedirect(rurl + "msg=Please select the pay on delivery"); } break; case "num09n": System.out.println("DELIVERY_DAYS--------:" + fileItem.getString()); if (delivery_pond.trim().equals("Yes")) { delivery_days = fileItem.getString(); if (checkDigit(delivery_days)) { } else { response.sendRedirect(rurl + "msg=Please add the delivery dates"); } } else { } break; case "sel07n": System.out.println("DELIVERY_AREA--------:" + fileItem.getString());//[] if (delivery_pond.trim().equals("Yes")) { delivery_area = fileItem.getString(); if (checkString(delivery_area)) { // Collecter01.collectDeliveryArea(delivery_area.trim()); } else { response.sendRedirect(rurl + "msg=Please select the delivery areas"); } } else { delivery_area = fileItem.getString(); } break; default: break; } } else { images = fileItem.getName(); System.out.println(images); if (checkString(images)) { Long time = System.currentTimeMillis(); System.out.println("IMAGES_name----------:" + time); String apath = request.getServletContext().getRealPath("/04_admin/product/img/") + "\\" + time + ".jpg"; System.out.println("IMAGES_AP------------:" + apath); String rpath = "04_admin\\product\\img\\" + time + ".jpg"; System.out.println("IMAGES_RP------------:" + rpath); fileItem.write(new File(apath)); Collecter01.collectImages(rpath); } else { response.sendRedirect(rurl + "msg=Please select images"); } } } // if (checkDigit(brand_id)) { // // } else { System.out.println(checkDigit(brand_id)); System.out.println(checkString(category_1_id)); System.out.println(checkString(category_2_id)); System.out.println(checkString(category_3_id)); // System.out.println(specifications_name); //null // System.out.println(specifications_value); //null // System.out.println(specifications_unit); //null System.out.println(checkString(purchase_date)); System.out.println(checkString(MFD)); System.out.println(checkString(EXP)); System.out.println(checkDigit(purchase_price)); System.out.println(checkDigit(selling_price)); System.out.println(checkDigit(discount)); System.out.println(checkDigit(w_years)); System.out.println(checkDigit(w_months)); System.out.println(checkDigit(w_dates)); System.out.println(checkDigit(QTY)); System.out.println(checkString(pickup)); System.out.println(checkString(delivery_pond)); System.out.println(delivery_pond.trim().equals("Yes") ? checkDigit(delivery_days) : true); System.out.println(delivery_pond.trim().equals("Yes") ? checkString(delivery_area) : true); System.out.println(checkString(images)); if (checkDigit(brand_id) && checkString(category_1_id) && checkString(category_2_id) && checkString(category_3_id) && checkString(purchase_date) && checkString(MFD) && checkString(EXP) && checkDigit(purchase_price) && checkDigit(selling_price) && checkDigit(discount) && checkDigit(w_years) && checkDigit(w_months) && checkDigit(w_dates) && checkDigit(QTY) && checkString(pickup) && checkString(delivery_pond) && delivery_pond.trim().equals("Yes") ? checkDigit(delivery_days) : true && delivery_pond.trim().equals("Yes") ? checkString(delivery_area) : true && checkString(images)) { System.out.println( "VALIDATION OK---------------------------------------------------------------------"); // try { // String sql0 = "SELECT * FROM product WHERE name=?"; // PreparedStatement ps0 = Controller.DB.con().prepareStatement(sql0); // ps0.setString(1, product_name); // System.out.println(ps0); // ResultSet rs0 = ps0.executeQuery(); // // if (rs0.first()) { // response.sendRedirect(rurl + "msg=Can't save This product allready in data base&color=red"); // } else { // System.out.println("product eka na"); try { String sql1 = "INSERT INTO product VALUES (null,?,?,?,?)"; PreparedStatement ps1 = Controller.DB.con().prepareStatement(sql1); ps1.setString(1, product_name); ps1.setString(2, description); ps1.setInt(3, Integer.parseInt(brand_id)); ps1.setInt(4, Integer.parseInt(category_3_id)); System.out.println(ps1); ps1.executeUpdate(); try { String sql2 = "SELECT MAX(idproduct) FROM product WHERE name=?"; PreparedStatement ps2 = Controller.DB.con().prepareStatement(sql2); ps2.setString(1, product_name); System.out.println(ps2); ResultSet rs2 = ps2.executeQuery(); while (rs2.next()) { System.out.println(rs2.getInt(1)); //--------------------------------STOCK------------------------------- try { String sql3 = "INSERT INTO stock VALUES (null,?,?,?,?,?,?,?,?,?,?)"; PreparedStatement ps3 = Controller.DB.con().prepareStatement(sql3); ps3.setString(1, purchase_date); ps3.setInt(2, Integer.parseInt(purchase_price)); // ps3.setInt(3, Integer.parseInt(old_price)); ps3.setInt(3, Integer.parseInt(discount)); ps3.setInt(4, Integer.parseInt(selling_price)); ps3.setString(5, w_years + "," + w_months + "," + w_dates); ps3.setInt(6, Integer.parseInt(QTY)); ps3.setString(7, pickup); ps3.setString(8, MFD); ps3.setString(9, EXP); ps3.setInt(10, rs2.getInt(1)); System.out.println(ps3); ps3.executeUpdate(); //----------------------------------IMAGES-------------------------------------------------------------- try { for (String img_path : Collecter01.product_images) { String sql4 = "INSERT INTO image VALUES (?,?)"; PreparedStatement ps4 = Controller.DB.con().prepareStatement(sql4); ps4.setInt(1, rs2.getInt(1)); ps4.setString(2, img_path); System.out.println(ps4); ps4.executeUpdate(); } //----------------------------------DELIVERY------------------------------------------------------------ try { String sql5 = "INSERT INTO delivery VALUES (?,?,?,?)"; PreparedStatement ps5 = Controller.DB.con().prepareStatement(sql5); ps5.setInt(1, rs2.getInt(1)); if (delivery_pond.equals("Yes")) { System.out.println("delivery pay yes"); ps5.setString(2, delivery_pond); ps5.setInt(3, Integer.parseInt(delivery_days)); ps5.setString(4, Collecter01.delivery_areas.substring(1)); System.out.println(ps5); ps5.executeUpdate(); } else { System.out.println("delivery info na save karanna"); ps5.setString(2, delivery_pond); ps5.setInt(3, 0); ps5.setString(4, "No"); System.out.println(ps5); ps5.executeUpdate(); } //----------------------------------SPECIFICATIONS------------------------------------------------------------ try { String sql6 = "SELECT idSpecifications FROM specifications WHERE name=?"; PreparedStatement ps6 = Controller.DB.con().prepareStatement(sql6); for (Map.Entry<String, List> entry : Collecter01.specifications .entrySet()) { System.out.println( entry.getKey() + "---" + entry.getValue().get(0) + "---" + entry.getValue().get(1)); ps6.setString(1, entry.getKey()); System.out.println(ps6); ResultSet rs6 = ps6.executeQuery(); int idSpecifications = 0; try { if (rs6.first()) { System.out.println("Specifications name/id ata____1"); idSpecifications = rs6.getInt(1); } else { System.out.println("Specifications name/id na____2"); try { String sql7 = "INSERT INTO specifications VALUES (null,?)"; PreparedStatement ps7 = Controller.DB.con() .prepareStatement(sql7); ps7.setString(1, entry.getKey()); System.out.println(ps7); ps7.executeUpdate(); System.out.println( "Specifications new add karanawa____2-1"); try { String sql8 = "SELECT idSpecifications FROM specifications WHERE name=?"; PreparedStatement ps8 = Controller.DB.con() .prepareStatement(sql8); ps8.setString(1, entry.getKey()); System.out.println(ps8); ResultSet rs8 = ps8.executeQuery(); if (rs8.first()) { System.out.println( "new Specifications name/id ata____3-1"); idSpecifications = rs8.getInt(1); } else { } } catch (Exception e9) { System.out.println( "new Specifications name/id na____3-2"); } } catch (Exception e8) { System.out.println( "Specifications new add fail____2-2"); } } } catch (Exception e7) { } finally { try { String sql9 = "INSERT INTO product_has_specifications VALUES (?,?,?,?)"; PreparedStatement ps9 = Controller.DB.con() .prepareStatement(sql9); ps9.setInt(1, rs2.getInt(1)); ps9.setInt(2, idSpecifications); ps9.setString(3, (String) entry.getValue().get(0)); ps9.setString(4, (String) entry.getValue().get(1)); System.out.println(ps9); ps9.executeUpdate(); System.out.println("spec value save kara"); } catch (Exception e10) { System.out.println("spec value save fail"); } } } } catch (Exception e6) { System.out.println("specifications id load fail fail"); } finally { response.sendRedirect( rurl + "msg=product successfully saved !&cl=00bf6f"); System.out.println( "SAVE COMPLETE---------------------------------------------------------------------"); } //----------------------------------SPECIFICATIONS------------------------------------------------------------ } catch (Exception e5) { System.out.println("delivery info save fail"); } //----------------------------------DELIVERY------------------------------------------------------------ } catch (Exception e4) { System.out.println("images data save fail"); } //----------------------------------IMAGES-------------------------------------------------------------- } catch (Exception e3) { System.out.println("stock eke data save fail"); } //----------------------------------STOCK--------------------------------------------------------------- } } catch (Exception e2) { System.out.println("product eke id eka load fail"); } } catch (Exception e1) { System.out.println("product ekata data save fail"); } // }// // } catch (Exception e) {// // // }// } else { System.out.println( "VALIDATION FAIL---------------------------------------------------------------------"); } // } } catch (Exception e) { throw new ServletException(e); } } }