List of usage examples for org.apache.commons.fileupload FileItem getSize
long getSize();
From source file:org.eclipse.kura.web.server.servlet.FileServlet.java
@SuppressWarnings("unchecked") public void parse(HttpServletRequest req) throws FileUploadException { s_logger.debug("upload.getFileSizeMax(): {}", getFileSizeMax()); s_logger.debug("upload.getSizeMax(): {}", getSizeMax()); // Parse the request List<FileItem> items = null; items = parseRequest(req);/*w w w . j ava 2 s .c o m*/ // Process the uploaded items Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); if (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); s_logger.debug("Form field item name: {}, value: {}", name, value); this.formFields.put(name, value); } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); s_logger.debug("File upload item name: {}, fileName: {}, contentType: {}, isInMemory: {}, size: {}", new Object[] { fieldName, fileName, contentType, isInMemory, sizeInBytes }); this.fileItems.add(item); } } }
From source file:org.eclipse.rwt.widgets.upload.servlet.FileUploadServlet.java
/** * Handles the POST to receive the file and saves it to the user TMP * directory.//from w ww . j a v a2 s . c o m * * @param request HTTP request. * @param response HTTP response. */ protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { // Create file upload factory and upload servlet FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // Set file upload progress listener final FileUploadListener listener = new FileUploadListener(); HttpSession session = request.getSession(); session.setAttribute("LISTENER", listener); // Upload servlet allows to set upload listener upload.setProgressListener(listener); FileItem fileItem = null; final File filePath = getUploadTempDir(session); try { // Iterate over all uploaded files final List uploadedItems = upload.parseRequest(request); final Iterator iterator = uploadedItems.iterator(); while (iterator.hasNext()) { fileItem = (FileItem) iterator.next(); if (!fileItem.isFormField() && fileItem.getSize() > 0) { final String myFullFileName = fileItem.getName(); final String slashType = myFullFileName.lastIndexOf("\\") > 0 ? "\\" : "/"; final int startIndex = myFullFileName.lastIndexOf(slashType); // Ignore the path and get the filename String myFileName = myFullFileName.substring(startIndex + 1, myFullFileName.length()); // Write the uploaded file to the system File file = new File(filePath, myFileName); fileItem.write(file); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (final Exception e) { e.printStackTrace(); } }
From source file:org.eclipse.virgo.management.console.UploadServlet.java
File doUpload(FileItem fileItem, File stagingDir) throws Exception { if (!fileItem.isFormField()) { String name = fileItem.getName(); if (name != null && name.length() > 0) { if (name.contains("\\") || name.contains("/")) { throw new IllegalArgumentException("Security violation, file name contains '/' or '\\'"); }//w w w. j av a2 s. co m File uploadedFile = new File(stagingDir, name); fileItem.write(uploadedFile); log.info(String.format("Uploaded artifact of size (%db) to %s", fileItem.getSize(), uploadedFile.getPath())); return uploadedFile; } } return null; }
From source file:org.eclipse.vtp.framework.engine.http.HttpConnector.java
/** * invokeProcessEngine./*from ww w .j av a2s . c o m*/ * * @param req * @param res * @param httpSession * @param pathInfo * @param embeddedInvocation TODO * @throws IOException * @throws ServletException */ private void invokeProcessEngine(HttpServletRequest req, HttpServletResponse res, HttpSession httpSession, String pathInfo, Map<Object, Object> variableValues, @SuppressWarnings("rawtypes") Map<String, String[]> parameterValues, boolean embeddedInvocation) throws IOException, ServletException { boolean newSession = false; Integer depth = (Integer) httpSession.getAttribute("connector.depth"); if (depth == null) { depth = new Integer(0); } String prefix = "connector.attributes."; String fullPrefix = prefix + depth.intValue() + "."; if (embeddedInvocation) httpSession.setAttribute(fullPrefix + "fragment", "true"); Deployment deployment = null; String brand = null; String entryName = null; boolean subdialog = false; if (!pathInfo.startsWith(PATH_PREFIX)) { System.out.println("invoking process engine for new session: " + pathInfo); newSession = true; synchronized (this) { for (String path : deploymentsByPath.keySet()) { System.out.println("Comparing to deployment: " + path); if (pathInfo.equals(path) || pathInfo.startsWith(path) && pathInfo.length() > path.length() && pathInfo.charAt(path.length()) == '/') { deployment = deploymentsByPath.get(path); System.out.println("Matching deployment found: " + deployment); brand = req.getParameter("BRAND"); if (req.getParameter("SUBDIALOG") != null) subdialog = Boolean.parseBoolean(req.getParameter("SUBDIALOG")); if (pathInfo.length() > path.length() + 1) { entryName = pathInfo.substring(path.length() + 1); System.out.println("Entry point name: " + entryName); } break; } } } if (deployment == null) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (entryName == null) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } pathInfo = NEXT_PATH; httpSession.setAttribute(fullPrefix + DEPLOYMENT_ID, deployment.getProcessID()); } else if (pathInfo.equals(LOG_PATH)) { if (req.getParameter("cmd") != null && req.getParameter("cmd").equals("set")) { String level = req.getParameter("level"); if (level == null || (!level.equalsIgnoreCase("ERROR") && !level.equalsIgnoreCase("WARN") && !level.equalsIgnoreCase("INFO") && !level.equalsIgnoreCase("DEBUG"))) level = "INFO"; System.setProperty("org.eclipse.vtp.loglevel", level); } writeLogging(req, res); return; } else { String deploymentID = (String) httpSession.getAttribute(fullPrefix + DEPLOYMENT_ID); synchronized (this) { deployment = deploymentsByID.get(deploymentID); } if (deployment == null) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } if (subdialog) httpSession.setAttribute(fullPrefix + "subdialog", "true"); if (pathInfo.equals(INDEX_PATH)) { writeIndex(res, deployment); return; } ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); if (ServletFileUpload.isMultipartContent(new ServletRequestContext(req))) { System.out.println( "ServletFileUpload.isMultipartContent(new ServletRequestContext(httpRequest)) is true"); try { List items = upload.parseRequest(req); for (int i = 0; i < items.size(); i++) { FileItem fui = (FileItem) items.get(i); if (fui.isFormField() || "text/plain".equals(fui.getContentType())) { System.out.println("Form Field: " + fui.getFieldName() + " | " + fui.getString()); parameterValues.put(fui.getFieldName(), new String[] { fui.getString() }); } else { File temp = File.createTempFile(Guid.createGUID(), ".tmp"); fui.write(temp); parameterValues.put(fui.getFieldName(), new String[] { temp.getAbsolutePath() }); fui.delete(); System.out.println("File Upload: " + fui.getFieldName()); System.out.println("\tTemp file name: " + temp.getAbsolutePath()); System.out.println("\tContent Type: " + fui.getContentType()); System.out.println("\tSize: " + fui.getSize()); } } } catch (Exception e) { e.printStackTrace(); } } for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); parameterValues.put(key, req.getParameterValues(key)); } for (String key : parameterValues.keySet()) { String[] values = parameterValues.get(key); if (values == null || values.length == 0) System.out.println(key + " empty"); else { System.out.println(key + " " + values[0]); for (int i = 1; i < values.length; i++) System.out.println("\t" + values[i]); } } IDocument document = null; if (pathInfo.equals(ABORT_PATH)) document = deployment.abort(httpSession, req, res, prefix, depth.intValue(), variableValues, parameterValues); else if (pathInfo.equals(NEXT_PATH)) { if (brand == null && !newSession) document = deployment.next(httpSession, req, res, prefix, depth.intValue(), variableValues, parameterValues); else document = deployment.start(httpSession, req, res, prefix, depth.intValue(), variableValues, parameterValues, entryName, brand, subdialog); } else { res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (document == null) { res.setStatus(HttpServletResponse.SC_NO_CONTENT); return; } else if (document instanceof ControllerDocument) { ControllerDocument cd = (ControllerDocument) document; if (cd.getTarget() == null) { @SuppressWarnings("unchecked") Map<String, Map<String, Object>> outgoing = (Map<String, Map<String, Object>>) httpSession .getAttribute(fullPrefix + "outgoing-data"); int newDepth = depth.intValue() - 1; if (newDepth == 0) httpSession.removeAttribute("connector.depth"); else httpSession.setAttribute("connector.depth", new Integer(newDepth)); String oldFullPrefix = fullPrefix; fullPrefix = prefix + newDepth + "."; Object[] params = (Object[]) httpSession.getAttribute(fullPrefix + "exitparams"); if (params != null) for (int i = 0; i < params.length; i += 2) parameterValues.put((String) params[i], (String[]) params[i + 1]); String[] paramNames = cd.getParameterNames(); for (int i = 0; i < paramNames.length; ++i) parameterValues.put(paramNames[i], cd.getParameterValues(paramNames[i])); String[] variableNames = cd.getVariableNames(); Map<Object, Object> variables = new HashMap<Object, Object>(variableNames.length); if (outgoing != null) { Map<String, Object> map = outgoing.get(cd.getParameterValues("exit")[0]); if (map != null) { for (int i = 0; i < variableNames.length; ++i) { Object mapping = map.get(variableNames[i]); if (mapping != null) variables.put(mapping, cd.getVariableValue(variableNames[i])); } } } deployment.end(httpSession, prefix, depth.intValue()); for (@SuppressWarnings("rawtypes") Enumeration e = httpSession.getAttributeNames(); e.hasMoreElements();) { String name = (String) e.nextElement(); if (name.startsWith(oldFullPrefix)) httpSession.removeAttribute(name); } invokeProcessEngine(req, res, httpSession, NEXT_PATH, variables, parameterValues, newDepth > 0); return; } else { String[] paramNames = cd.getParameterNames(); Object[] params = new Object[paramNames.length * 2]; for (int i = 0; i < params.length; i += 2) { params[i] = paramNames[i / 2]; params[i + 1] = cd.getParameterValues(paramNames[i / 2]); } httpSession.setAttribute(fullPrefix + "exitparams", params); String[] variableNames = cd.getVariableNames(); Map<Object, Object> variables = new HashMap<Object, Object>(variableNames.length); for (int i = 0; i < variableNames.length; ++i) variables.put(variableNames[i], cd.getVariableValue(variableNames[i])); httpSession.setAttribute("connector.depth", new Integer(depth.intValue() + 1)); fullPrefix = prefix + (depth.intValue() + 1) + "."; String deploymentId = cd.getTarget().substring(0, cd.getTarget().lastIndexOf('(') - 1); String entryPointName = cd.getTarget().substring(cd.getTarget().lastIndexOf('(') + 1, cd.getTarget().length() - 1); httpSession.setAttribute(fullPrefix + DEPLOYMENT_ID, deploymentId); httpSession.setAttribute(fullPrefix + ENTRY_POINT_NAME, entryPointName); Map<String, Map<String, Object>> outgoing = new HashMap<String, Map<String, Object>>(); String[] outPaths = cd.getOutgoingPaths(); for (int i = 0; i < outPaths.length; ++i) { Map<String, Object> map = new HashMap<String, Object>(); String[] names = cd.getOutgoingDataNames(outPaths[i]); for (int j = 0; j < names.length; ++j) map.put(names[j], cd.getOutgoingDataValue(outPaths[i], names[j])); outgoing.put(outPaths[i], map); } httpSession.setAttribute(fullPrefix + "outgoing-data", outgoing); invokeProcessEngine(req, res, httpSession, "/" + deploymentId + "/" + entryPointName, variables, parameterValues, true); return; } } res.setStatus(HttpServletResponse.SC_OK); if (!document.isCachable()) res.setHeader("Cache-Control", "max-age=0, no-cache"); res.setContentType(document.getContentType()); OutputStream writer = res.getOutputStream(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); XMLWriter xmlWriter = new XMLWriter(writer); xmlWriter.setCompactElements(true); transformer.transform(document.toXMLSource(), xmlWriter.toXMLResult()); if (reporter.isSeverityEnabled(IReporter.SEVERITY_INFO) && !document.isSecured()) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); xmlWriter = new XMLWriter(baos); xmlWriter.setCompactElements(true); transformer.transform(document.toXMLSource(), xmlWriter.toXMLResult()); System.out.println(new String(baos.toByteArray(), "UTF-8")); } } catch (TransformerException e) { throw new ServletException(e); } writer.flush(); writer.close(); }
From source file:org.ecocean.servlet.AdoptionAction.java
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String adopterName = ""; String adopterAddress = ""; String adopterEmail = ""; String adopterImage;/*from ww w . ja v a 2 s .c om*/ String adoptionStartDate = ""; String adoptionEndDate = ""; String adopterQuote = ""; String adoptionManager = ""; String shark = ""; String encounter = ""; String notes = ""; String adoptionType = ""; String number = ""; String text = ""; // Saved to the selected shark, not the adoption. String newNickName = ""; // Storing the customer ID here makes the subscription cancellation process easier to do in less moves. String stripeCustomerID = ""; // Stores some wack response string from google recaptcha. String gresp = ""; boolean adoptionSuccess = true; String failureMessage = ""; //set UTF-8 request.setCharacterEncoding("UTF-8"); HttpSession session = request.getSession(true); String context = "context0"; context = ServletUtilities.getContext(request); Shepherd myShepherd = new Shepherd(context); myShepherd.setAction("AdoptionAction.class"); System.out.println("in context " + context); //request.getSession()getServlet().getServletContext().getRealPath("/")); String rootDir = getServletContext().getRealPath("/"); System.out.println("rootDir=" + rootDir); // This value is only stored in the email specific edit form. Boolean emailEdit = false; if ((Boolean) session.getAttribute("emailEdit") != false) { emailEdit = (Boolean) session.getAttribute("emailEdit"); number = (String) session.getAttribute("sessionAdoptionID"); } //setup data dir String rootWebappPath = getServletContext().getRealPath("/"); File webappsDir = new File(rootWebappPath).getParentFile(); File shepherdDataDir = new File(webappsDir, CommonConfiguration.getDataDirectoryName(context)); //if(!shepherdDataDir.exists()){shepherdDataDir.mkdirs();} File adoptionsDir = new File(shepherdDataDir.getAbsolutePath() + "/adoptions"); if (!adoptionsDir.exists()) { adoptionsDir.mkdirs(); } //get the form to read data from // AdoptionForm theForm = (AdoptionForm) form; //set up for response response.setContentType("text/html"); PrintWriter out = response.getWriter(); boolean locked = false; String fileName = "None"; String username = "None"; String fullPathFilename = ""; String id = ""; boolean fileSuccess = false; //kinda pointless now as we just build sentFiles list now at this point (do file work at end) String doneMessage = ""; List<String> filesOK = new ArrayList<String>(); HashMap<String, String> filesBad = new HashMap<String, String>(); List<FileItem> formFiles = new ArrayList<FileItem>(); Calendar date = Calendar.getInstance(); long maxSizeMB = CommonConfiguration.getMaxMediaSizeInMegabytes(context); long maxSizeBytes = maxSizeMB * 1048576; //set form value hashmap HashMap fv = new HashMap(); //else { id = "adpt" + (new Integer(date.get(Calendar.DAY_OF_MONTH))).toString() + (new Integer(date.get(Calendar.MONTH) + 1)).toString() + (new Integer(date.get(Calendar.YEAR))).toString() + (new Integer(date.get(Calendar.HOUR_OF_DAY))).toString() + (new Integer(date.get(Calendar.MINUTE))).toString() + (new Integer(date.get(Calendar.SECOND))).toString(); //} System.out.println("Starting an adoption submission..."); Calendar todayDate = Calendar.getInstance(); if (ServletFileUpload.isMultipartContent(request)) { try { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); upload.setHeaderEncoding("UTF-8"); List<FileItem> multiparts = upload.parseRequest(request); //List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (item.isFormField()) { //plain field fv.put(item.getFieldName(), ServletUtilities.preventCrossSiteScriptingAttacks(item.getString("UTF-8").trim())); //TODO do we want trim() here??? -jon //System.out.println("got regular field (" + item.getFieldName() + ")=(" + item.getString("UTF-8") + ")"); } else { //file //System.out.println("content type???? " + item.getContentType()); TODO note, the helpers only check extension if (item.getSize() > maxSizeBytes) { filesBad.put(item.getName(), "file is larger than " + maxSizeMB + "MB"); } else if (myShepherd.isAcceptableImageFile(item.getName()) || myShepherd.isAcceptableVideoFile(item.getName())) { formFiles.add(item); filesOK.add(item.getName()); } else { filesBad.put(item.getName(), "invalid type of file"); } } } doneMessage = "File Uploaded Successfully"; fileSuccess = true; } catch (Exception ex) { doneMessage = "File Upload Failed due to " + ex; } } else { doneMessage = "Sorry this Servlet only handles file upload request"; } session.setAttribute("filesOKMessage", (filesOK.isEmpty() ? "none" : Arrays.toString(filesOK.toArray()))); String badmsg = ""; for (String key : filesBad.keySet()) { badmsg += key + " (" + getVal(filesBad, key) + ") "; } if (badmsg.equals("")) { badmsg = "none"; } session.setAttribute("filesBadMessage", badmsg); boolean isEdit = false; if (fileSuccess) { if ((fv.get("number") != null) && !fv.get("number").toString().equals("")) { //handle adoption number processing number = fv.get("number").toString(); if ((number != null) && (!number.equals(""))) { isEdit = true; System.out.println("Ping! Hit adoption number recieved by action servlet."); //myShepherd.beginDBTransaction(); } //end adoption number/id processing } if ((fv.get("adopterName") != null) && !fv.get("adopterName").toString().equals("")) { adopterName = fv.get("adopterName").toString().trim(); } if ((fv.get("adopterAddress") != null) && !fv.get("adopterAddress").toString().equals("")) { adopterAddress = fv.get("adopterAddress").toString().trim(); } if ((fv.get("adopterEmail") != null) && !fv.get("adopterEmail").toString().equals("")) { adopterEmail = fv.get("adopterEmail").toString().trim(); } if ((fv.get("adoptionStartDate") != null) && !fv.get("adoptionStartDate").toString().equals("")) { adoptionStartDate = fv.get("adoptionStartDate").toString().trim(); } if ((fv.get("adoptionEndDate") != null) && !fv.get("adoptionEndDate").toString().equals("")) { adoptionEndDate = fv.get("adoptionEndDate").toString().trim(); } if ((fv.get("adopterQuote") != null) && !fv.get("adopterQuote").toString().equals("")) { adopterQuote = fv.get("adopterQuote").toString().trim(); } if ((fv.get("adoptionManager") != null) && !fv.get("adoptionManager").toString().equals("")) { adoptionManager = fv.get("adoptionManager").toString().trim(); } if ((fv.get("shark") != null) && !fv.get("shark").toString().equals("")) { shark = fv.get("shark").toString().trim(); } if ((fv.get("encounter") != null) && !fv.get("encounter").toString().equals("")) { encounter = fv.get("encounter").toString().trim(); } if ((fv.get("notes") != null) && !fv.get("notes").toString().equals("")) { notes = fv.get("notes").toString().trim(); } if ((fv.get("adoptionType") != null) && !fv.get("adoptionType").toString().equals("")) { adoptionType = fv.get("adoptionType").toString().trim(); } if ((fv.get("text") != null) && !fv.get("text").toString().equals("")) { text = fv.get("text").toString().trim(); } // New nickname to save to marked individual object. if ((fv.get("newNickName") != null) && !fv.get("newNickName").toString().equals("")) { newNickName = fv.get("newNickName").toString().trim(); } if ((fv.get("g-recaptcha-response") != null) && !fv.get("g-recaptcha-response").toString().equals("")) { gresp = fv.get("g-recaptcha-response").toString().trim(); } if (isEdit) { id = number; } // Grab the stripe customer out of session. stripeCustomerID = (String) session.getAttribute("stripeID"); File thisAdoptionDir = new File(adoptionsDir.getAbsolutePath() + "/" + id); if (!thisAdoptionDir.exists()) { thisAdoptionDir.mkdirs(); } String baseDir = ServletUtilities.dataDir(context, rootDir); ArrayList<SinglePhotoVideo> images = new ArrayList<SinglePhotoVideo>(); for (FileItem item : formFiles) { /* this will actually write file to filesystem (or [FUTURE] wherever) TODO: either (a) undo this if any failure of writing encounter; or (b) dont write til success of enc. */ //try { //SinglePhotoVideo spv = new SinglePhotoVideo(encID, item, context, encDataDir); //SinglePhotoVideo spv = new SinglePhotoVideo(enc, item, context, baseDir); try { //retrieve the file data ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream stream = item.getInputStream(); //System.out.println(writeFile); //if ((!(file[iter].getFileName().equals(""))) && (file[iter].getFileSize() > 0)) { //write the file to the file specified //String writeName=file[iter].getFileName().replace('#', '_').replace('-', '_').replace('+', '_').replaceAll(" ", "_"); //String writeName=forHTMLTag(file[iter].getFileName()); String writeName = "adopter.jpg"; //String writeName=URLEncoder.encode(file[iter].getFileName(), "UTF-8"); //while (writeName.indexOf(".") != writeName.lastIndexOf(".")) { // writeName = writeName.replaceFirst("\\.", "_"); // } //System.out.println(writeName); OutputStream bos = new FileOutputStream(new File(thisAdoptionDir, writeName)); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.close(); //data = "The file has been written to \"" + id + "\\" + writeName + "\""; adopterImage = writeName; // } //close the stream stream.close(); baos.close(); } catch (FileNotFoundException fnfe) { System.out.println("File not found exception.\n"); fnfe.printStackTrace(); //return null; } catch (IOException ioe) { System.out.println("IO Exception.\n"); ioe.printStackTrace(); //return null; } } // This verifies the user being logged in or passing the recapture. boolean loggedIn = false; try { if (request.getUserPrincipal() != null) { loggedIn = true; } } catch (NullPointerException ne) { System.out.println("Got a null pointer checking for logged in user."); } boolean validCaptcha = false; if (loggedIn != true) { String remoteIP = request.getRemoteAddr(); validCaptcha = ServletUtilities.captchaIsValid(context, gresp, remoteIP); System.out.println("Results from captchaIsValid(): " + validCaptcha); } if ((validCaptcha == true) || (loggedIn == true)) { System.out.println("Ping! Hit the Adoption creation section."); try { Adoption ad = new Adoption(id, adopterName, adopterEmail, adoptionStartDate, adoptionEndDate); if (isEdit || emailEdit) { ad = myShepherd.getAdoption(number); ad.setAdopterName(adopterName); ad.setAdopterEmail(adopterEmail); ad.setAdoptionEndDate(adoptionEndDate); ad.setAdoptionStartDate(adoptionStartDate); } ad.setAdopterQuote(adopterQuote); ad.setAdoptionManager(adoptionManager); ad.setIndividual(shark); ad.setEncounter(encounter); ad.setNotes(notes); ad.setAdoptionType(adoptionType); ad.setAdopterAddress(adopterAddress); ad.setStripeCustomerId(stripeCustomerID); if ((filesOK != null) && (filesOK.size() > 0)) { ad.setAdopterImage(filesOK.get(0)); } myShepherd.beginDBTransaction(); if (adoptionSuccess && !isEdit) { try { myShepherd.storeNewAdoption(ad, id); } catch (Exception e) { adoptionSuccess = false; failureMessage += "Failed to presist the new adoption.<br>"; } } // New logic to change marked individual nickname if necessary in adoption. MarkedIndividual mi = myShepherd.getMarkedIndividual(shark); if (!newNickName.equals("")) { if (adoptionSuccess && !isEdit) { try { mi.setNickName(newNickName); mi.setNickNamer(adopterName); } catch (Exception e) { failureMessage += "Retrieving shark to set nickname failed.<br>"; } } } // Sends a confirmation email to a a new adopter with cancellation and update information. if (emailEdit == false) { try { String emailContext = "context0"; String langCode = "en"; String to = ad.getAdopterEmail(); String type = "adoptionConfirmation"; System.out.println("About to email new adopter."); // Retrieve background service for processing emails ThreadPoolExecutor es = MailThreadExecutorService.getExecutorService(); Map<String, String> tagMap = NotificationMailer.createBasicTagMap(request, mi, ad); NotificationMailer mailer = new NotificationMailer(emailContext, langCode, to, type, tagMap); NotificationMailer adminMailer = new NotificationMailer(emailContext, langCode, CommonConfiguration.getNewSubmissionEmail(emailContext), type, tagMap); es.execute(mailer); es.execute(adminMailer); } catch (Exception e) { System.out.println("Error in sending email confirmation of adoption."); e.printStackTrace(); } } if ((adoptionSuccess && isEdit) || (emailEdit == true)) { myShepherd.commitDBTransaction(); } } catch (Exception e) { System.out.println("The recaptcha passed but something went wrong saving the adoption."); e.printStackTrace(); } } } // Sets adoption paid to false to allow multiple adoptions session.setAttribute("paid", false); //return a forward to display.jsp System.out.println("Ending adoption data submission."); //if((submitterID!=null)&&(submitterID.equals("deepblue"))) { if ((adoptionSuccess) && (emailEdit == false)) { response.sendRedirect(request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/adoptions/adoptionSuccess.jsp?id=" + id); } else if ((adoptionSuccess) && (emailEdit == true)) { response.sendRedirect(request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/adoptions/editSuccess.jsp"); } else { response.sendRedirect(request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/adoptions/adoptionFailure.jsp?message=" + failureMessage); } //} myShepherd.closeDBTransaction(); }
From source file:org.ecocean.servlet.EncounterForm.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); HashMap fv = new HashMap(); //IMPORTANT - processingNotes can be used to add notes on data handling (e.g., poorly formatted dates) that can be reconciled later by the reviewer //Example usage: processingNotes.append("<p>Error encountered processing this date submitted by user: "+getVal(fv, "datepicker")+"</p>"); StringBuffer processingNotes = new StringBuffer(); HttpSession session = request.getSession(true); String context = "context0"; context = ServletUtilities.getContext(request); Shepherd myShepherd = new Shepherd(context); myShepherd.setAction("EncounterForm.class"); System.out.println("in context " + context); //request.getSession()getServlet().getServletContext().getRealPath("/")); String rootDir = getServletContext().getRealPath("/"); System.out.println("rootDir=" + rootDir); /*// w w w.j a v a 2s . c o m Vector<String> fbImages = new Vector<String>(); int fbi = 0; while (request.getParameter("socialphoto_" + fbi) != null) { fbImages.add(request.getParameter("socialphoto_" + fbi)); fbi++; } System.out.println(fbImages); if (fbImages.size() > 0) { FacebookClient fbclient = null; try { fbclient = SocialAuth.getFacebookClient(context); } catch (Exception ex) { System.out.println("SocialAuth.getFacebookClient threw exception " + ex.toString()); } WebContext ctx = new J2EContext(request, response); //String callbackUrl = "http://localhost.wildme.org/a/SocialConnect?type=facebook"; String callbackUrl = "http://" + CommonConfiguration.getURLLocation(request) + "/XXXSocialConnect?type=facebook"; if (request.getParameter("disconnect") != null) callbackUrl += "&disconnect=1"; fbclient.setCallbackUrl(callbackUrl); OAuthCredentials credentials = null; try { credentials = fbclient.getCredentials(ctx); } catch (Exception ex) { System.out.println("caught exception on facebook credentials: " + ex.toString()); } if (credentials != null) { FacebookProfile facebookProfile = fbclient.getUserProfile(credentials, ctx); User fbuser = myShepherd.getUserBySocialId("facebook", facebookProfile.getId()); System.out.println("getId() = " + facebookProfile.getId() + " -> user = " + fbuser); if (fbuser != null) System.out.println("user = " + user.getUsername() + "; fbuser = " + fbuser.getUsername()); if ((fbuser != null) && (fbuser.getUsername().equals(user.getUsername())) && (request.getParameter("disconnect") != null)) { fbuser.unsetSocial("facebook"); //myShepherd.getPM().makePersistent(user); session.setAttribute("message", "disconnected from facebook"); response.sendRedirect("myAccount.jsp"); return; } else if (fbuser != null) { session.setAttribute("error", "looks like this account is already connected to an account"); response.sendRedirect("myAccount.jsp"); return; } else { //lets do this user.setSocial("facebook", facebookProfile.getId()); //myShepherd.getPM().makePersistent(user); session.setAttribute("message", "connected to facebook"); response.sendRedirect("myAccount.jsp"); return; } } else { System.out.println("*** trying redirect?"); try { fbclient.redirect(ctx, false, false); } catch (Exception ex) { System.out.println("caught exception on facebook processing: " + ex.toString()); } return; } } */ //private Map<String, Object> measurements = new HashMap<String, Object>(); //Map<String, Object> metalTags = new HashMap<String, Object>(); /* private String acousticTagSerial = ""; private String acousticTagId = ""; private String satelliteTagSerial = ""; private String satelliteTagArgosPttNumber = ""; private String satelliteTagName = ""; */ //set up for response response.setContentType("text/html"); PrintWriter out = response.getWriter(); boolean locked = false; String fileName = "None"; String username = "None"; String fullPathFilename = ""; boolean fileSuccess = false; //kinda pointless now as we just build sentFiles list now at this point (do file work at end) String doneMessage = ""; List<String> filesOK = new ArrayList<String>(); HashMap<String, String> filesBad = new HashMap<String, String>(); List<FileItem> formFiles = new ArrayList<FileItem>(); List<File> socialFiles = new ArrayList<File>(); //Calendar date = Calendar.getInstance(); long maxSizeMB = CommonConfiguration.getMaxMediaSizeInMegabytes(context); long maxSizeBytes = maxSizeMB * 1048576; if (ServletFileUpload.isMultipartContent(request)) { try { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); upload.setHeaderEncoding("UTF-8"); List<FileItem> multiparts = upload.parseRequest(request); //List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (item.isFormField()) { //plain field fv.put(item.getFieldName(), ServletUtilities.preventCrossSiteScriptingAttacks(item.getString("UTF-8").trim())); //TODO do we want trim() here??? -jon //System.out.println("got regular field (" + item.getFieldName() + ")=(" + item.getString("UTF-8") + ")"); } else if (item.getName().startsWith("socialphoto_")) { System.out.println(item.getName() + ": " + item.getString("UTF-8")); } else { //file //System.out.println("content type???? " + item.getContentType()); TODO note, the helpers only check extension if (item.getSize() > maxSizeBytes) { filesBad.put(item.getName(), "file is larger than " + maxSizeMB + "MB"); } else if (myShepherd.isAcceptableImageFile(item.getName()) || myShepherd.isAcceptableVideoFile(item.getName())) { formFiles.add(item); filesOK.add(item.getName()); } else { filesBad.put(item.getName(), "invalid type of file"); } } } doneMessage = "File Uploaded Successfully"; fileSuccess = true; } catch (Exception ex) { doneMessage = "File Upload Failed due to " + ex; } } else { doneMessage = "Sorry this Servlet only handles file upload request"; } if (fv.get("social_files_id") != null) { //TODO better checking of files (size, type etc) File socDir = new File( ServletUtilities.dataDir(context, rootDir) + "/social_files/" + fv.get("social_files_id")); for (File sf : socDir.listFiles()) { socialFiles.add(sf); filesOK.add(sf.getName()); } filesBad = new HashMap<String, String>(); fileSuccess = true; } session.setAttribute("filesOKMessage", (filesOK.isEmpty() ? "none" : Arrays.toString(filesOK.toArray()))); String badmsg = ""; for (String key : filesBad.keySet()) { badmsg += key + " (" + getVal(filesBad, key) + ") "; } if (badmsg.equals("")) { badmsg = "none"; } session.setAttribute("filesBadMessage", badmsg); if (fileSuccess) { //////////////////////////////////////////// START //{submitterID=tomcat, submitterProject=, photographerEmail=, metalTag(left)=, sex=unknown, measurement(weight)=34234, location=, acousticTagId=, behavior=yow behavior..., measurement(weightunits)=kilograms, acousticTagSerial=, photographerName=, lifeStage=sub-adult, submitterAddress=, satelliteTagSerial=, releaseDate=, photographerPhone=, measurement(lengthunits)=meters, measurement(weightsamplingProtocol)=samplingProtocol0, measurement(length)=, submitterOrganization=, photographerAddress=, longitude=, year=2014, lat=, measurement(lengthsamplingProtocol)=samplingProtocol0, submitterEmail=, minutes=00, elevation=, measurement(height)=, measurement(heightsamplingProtocol)=samplingProtocol0, scars=None, submitterPhone=, submitterName=tomcat, hour=-1, livingStatus=alive, depth=, country=, satelliteTagName=Wild Life Computers, metalTag(right)=, month=1, measurement(heightunits)=meters, Submit=Send encounter report, informothers=, day=0, satelliteTagArgosPttNumber=, comments=} //check for spamBots TODO possibly move this to Util for general/global usage? boolean spamBot = false; String[] spamFieldsToCheck = new String[] { "submitterPhone", "submitterName", "photographerName", "photographerPhone", "location", "comments", "behavior" }; StringBuffer spamFields = new StringBuffer(); for (int i = 0; i < spamFieldsToCheck.length; i++) { spamFields.append(getVal(fv, spamFieldsToCheck[i])); } if (spamFields.toString().toLowerCase().indexOf("porn") != -1) { spamBot = true; } if (spamFields.toString().toLowerCase().indexOf("href") != -1) { spamBot = true; } //else if(spamFields.toString().toLowerCase().indexOf("[url]")!=-1){spamBot=true;} //else if(spamFields.toString().toLowerCase().indexOf("url=")!=-1){spamBot=true;} //else if(spamFields.toString().toLowerCase().trim().equals("")){spamBot=true;} //else if((theForm.getSubmitterID()!=null)&&(theForm.getSubmitterID().equals("N%2FA"))) {spamBot=true;} String locCode = ""; System.out.println(" **** here is what i think locationID is: " + fv.get("locationID")); if ((fv.get("locationID") != null) && !fv.get("locationID").toString().equals("")) { locCode = fv.get("locationID").toString(); } //see if the location code can be determined and set based on the location String reported else if (fv.get("location") != null) { String locTemp = getVal(fv, "location").toLowerCase(); Properties props = new Properties(); try { props = ShepherdProperties.getProperties("submitActionClass.properties", "", context); Enumeration m_enum = props.propertyNames(); while (m_enum.hasMoreElements()) { String aLocationSnippet = ((String) m_enum.nextElement()).trim(); if (locTemp.indexOf(aLocationSnippet) != -1) { locCode = props.getProperty(aLocationSnippet); } } } catch (Exception props_e) { props_e.printStackTrace(); } } //end else //end location code setter fv.put("locCode", locCode); //TODO this should live somewhere else as constant? (e.g. to build in form as well) String[] scarType = new String[] { "None", "Tail (caudal) fin", "1st dorsal fin", "2nd dorsal fin", "Left pectoral fin", "Right pectoral fin", "Head", "Body" }; int scarNum = -1; try { scarNum = Integer.parseInt(getVal(fv, "scars")); } catch (NumberFormatException e) { scarNum = -1; } if ((scarNum < 0) || (scarNum > 7)) { scarNum = -1; } if (scarNum >= 0) { fv.put("scars", scarType[scarNum]); } //System.out.println("about to do int stuff"); //need some ints for day/month/year/hour (other stuff seems to be strings) int day = 0, month = -1, year = 0, hour = 0; String minutes = ""; //try { day = Integer.parseInt(getVal(fv, "day")); } catch (NumberFormatException e) { day = 0; } //try { month = Integer.parseInt(getVal(fv, "month")); } catch (NumberFormatException e) { month = 0; } //try { year = Integer.parseInt(getVal(fv, "year")); } catch (NumberFormatException e) { year = 0; } //switch to datepicker LocalDateTime dt = new LocalDateTime(); if ((getVal(fv, "datepicker") != null) && (!getVal(fv, "datepicker").trim().equals(""))) { //System.out.println("Trying to read date: "+getVal(fv, "datepicker").replaceAll(" ", "T")); //boolean badDate=false; try { DateTimeFormatter parser1 = ISODateTimeFormat.dateOptionalTimeParser(); LocalDateTime reportedDateTime = new LocalDateTime( parser1.parseMillis(getVal(fv, "datepicker").replaceAll(" ", "T"))); StringTokenizer str = new StringTokenizer(getVal(fv, "datepicker").replaceAll(" ", "T"), "-"); int numTokens = str.countTokens(); if (numTokens >= 1) { //try { year = reportedDateTime.getYear(); if (year > (dt.getYear() + 1)) { //badDate=true; year = 0; throw new Exception( " An unknown exception occurred during date processing in EncounterForm. The user may have input an improper format: " + year + " > " + dt.getYear()); } //} catch (Exception e) { year=-1;} } if (numTokens >= 2) { try { month = reportedDateTime.getMonthOfYear(); } catch (Exception e) { month = -1; } } else { month = -1; } //see if we can get a day, because we do want to support only yyy-MM too if (str.countTokens() >= 3) { try { day = reportedDateTime.getDayOfMonth(); } catch (Exception e) { day = 0; } } else { day = 0; } //see if we can get a time and hour, because we do want to support only yyy-MM too StringTokenizer strTime = new StringTokenizer(getVal(fv, "datepicker").replaceAll(" ", "T"), "T"); if (strTime.countTokens() > 1) { try { hour = reportedDateTime.getHourOfDay(); } catch (Exception e) { hour = -1; } try { minutes = (new Integer(reportedDateTime.getMinuteOfHour()).toString()); } catch (Exception e) { } } else { hour = -1; } //System.out.println("At the end of time processing I see: "+year+"-"+month+"-"+day+" "+hour+":"+minutes); } catch (Exception e) { System.out.println( " An unknown exception occurred during date processing in EncounterForm. The user may have input an improper format."); e.printStackTrace(); processingNotes.append("<p>Error encountered processing this date submitted by user: " + getVal(fv, "datepicker") + "</p>"); } } String guess = "no estimate provided"; if ((fv.get("guess") != null) && !fv.get("guess").toString().equals("")) { guess = fv.get("guess").toString(); } //let's handle genus and species for taxonomy String genus = null; String specificEpithet = null; try { //now we have to break apart genus species if (fv.get("genusSpecies") != null) { StringTokenizer tokenizer = new StringTokenizer(fv.get("genusSpecies").toString(), " "); if (tokenizer.countTokens() >= 2) { genus = tokenizer.nextToken(); //enc.setGenus(tokenizer.nextToken()); specificEpithet = tokenizer.nextToken().replaceAll(",", "").replaceAll("_", " "); //enc.setSpecificEpithet(tokenizer.nextToken().replaceAll(",","").replaceAll("_"," ")); } //handle malformed Genus Species formats else { throw new Exception( "The format of the submitted genusSpecies parameter did not have two tokens delimited by a space (e.g., \"Rhincodon typus\"). The submitted value was: " + fv.get("genusSpecies")); } } } catch (Exception le) { } System.out.println("about to do enc()"); Encounter enc = new Encounter(day, month, year, hour, minutes, guess, getVal(fv, "location"), getVal(fv, "submitterName"), getVal(fv, "submitterEmail"), null); boolean llSet = false; //Encounter enc = new Encounter(); //System.out.println("Submission detected date: "+enc.getDate()); String encID = enc.generateEncounterNumber(); enc.setEncounterNumber(encID); System.out.println("hey, i think i may have made an encounter, encID=" + encID); System.out.println("enc ?= " + enc.toString()); AssetStore astore = AssetStore.getDefault(myShepherd); ArrayList<Annotation> newAnnotations = new ArrayList<Annotation>(); for (FileItem item : formFiles) { JSONObject sp = astore.createParameters(new File(enc.subdir() + File.separator + item.getName())); sp.put("key", Util.hashDirectories(encID) + "/" + item.getName()); MediaAsset ma = new MediaAsset(astore, sp); File tmpFile = ma.localPath().toFile(); //conveniently(?) our local version to save ma.cacheLocal() from having to do anything? File tmpDir = tmpFile.getParentFile(); if (!tmpDir.exists()) tmpDir.mkdirs(); //System.out.println("attempting to write uploaded file to " + tmpFile); try { item.write(tmpFile); } catch (Exception ex) { System.out.println("Could not write " + tmpFile + ": " + ex.toString()); } if (tmpFile.exists()) { ma.addLabel("_original"); ma.copyIn(tmpFile); ma.updateMetadata(); newAnnotations.add(new Annotation(Util.taxonomyString(genus, specificEpithet), ma)); } else { System.out.println("failed to write file " + tmpFile); } } ///////////////////TODO social files also!!! if (fv.get("mediaAssetSetId") != null) { MediaAssetSet maSet = ((MediaAssetSet) (myShepherd.getPM().getObjectById( myShepherd.getPM().newObjectIdInstance(MediaAssetSet.class, fv.get("mediaAssetSetId")), true))); if ((maSet != null) && (maSet.getMediaAssets() != null) && (maSet.getMediaAssets().size() > 0)) { int num = maSet.getMediaAssets().size(); for (MediaAsset ma : maSet.getMediaAssets()) { newAnnotations.add(new Annotation(Util.taxonomyString(genus, specificEpithet), ma)); } session.setAttribute("filesOKMessage", num + " " + ((num == 1) ? "file" : "files")); } } enc.setAnnotations(newAnnotations); enc.setGenus(genus); enc.setSpecificEpithet(specificEpithet); /* String baseDir = ServletUtilities.dataDir(context, rootDir); ArrayList<SinglePhotoVideo> images = new ArrayList<SinglePhotoVideo>(); for (FileItem item : formFiles) { // this will actually write file to filesystem (or [FUTURE] wherever) // TODO: either (a) undo this if any failure of writing encounter; or (b) dont write til success of enc. try { //SinglePhotoVideo spv = new SinglePhotoVideo(encID, item, context, encDataDir); SinglePhotoVideo spv = new SinglePhotoVideo(enc, item, context, baseDir); //images.add(spv); enc.addSinglePhotoVideo(spv); } catch (Exception ex) { System.out.println("failed to save " + item.toString() + ": " + ex.toString()); } } for (File sf : socialFiles) { File encDir = new File(enc.dir(baseDir)); if (!encDir.exists()) encDir.mkdirs(); File targetFile = new File(encDir, sf.getName()); System.out.println("socialFile copy: " + sf.toString() + " ---> " + targetFile.toString()); Files.copy(sf.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); SinglePhotoVideo spv = new SinglePhotoVideo(encID, targetFile); enc.addSinglePhotoVideo(spv); } */ //now let's add our encounter to the database enc.setComments(getVal(fv, "comments").replaceAll("\n", "<br>")); if (fv.get("releaseDate") != null && fv.get("releaseDate").toString().length() > 0) { String dateFormatPattern = CommonConfiguration.getProperty("releaseDateFormat", context); try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); enc.setReleaseDate(simpleDateFormat.parse(fv.get("releaseDate").toString()).getTime()); } catch (Exception e) { enc.addComments("<p>Reported release date was problematic: " + fv.get("releaseDate") + "</p>"); } } if (fv.get("behavior") != null && fv.get("behavior").toString().length() > 0) { enc.setBehavior(fv.get("behavior").toString()); } if (fv.get("alternateID") != null && fv.get("alternateID").toString().length() > 0) { enc.setAlternateID(fv.get("alternateID").toString()); } if (fv.get("lifeStage") != null && fv.get("lifeStage").toString().length() > 0) { enc.setLifeStage(fv.get("lifeStage").toString()); } List<MetalTag> metalTags = getMetalTags(fv); for (MetalTag metalTag : metalTags) { enc.addMetalTag(metalTag); } List<Measurement> measurements = getMeasurements(fv, encID, context); for (Measurement measurement : measurements) { enc.setMeasurement(measurement, myShepherd); } enc.setAcousticTag(getAcousticTag(fv)); enc.setSatelliteTag(getSatelliteTag(fv)); enc.setSex(getVal(fv, "sex")); enc.setLivingStatus(getVal(fv, "livingStatus")); if (fv.get("scars") != null) { enc.setDistinguishingScar(fv.get("scars").toString()); } int sizePeriod = 0; if ((fv.get("measureUnits") != null) && fv.get("measureUnits").toString().equals("Feet")) { if ((fv.get("depth") != null) && !fv.get("depth").toString().equals("")) { try { double tempDouble = (new Double(fv.get("depth").toString())).doubleValue() / 3.3; String truncDepth = (new Double(tempDouble)).toString(); sizePeriod = truncDepth.indexOf("."); truncDepth = truncDepth.substring(0, sizePeriod + 2); fv.put("depth", (new Double(truncDepth)).toString()); } catch (java.lang.NumberFormatException nfe) { enc.addComments( "<p>Reported depth was problematic: " + fv.get("depth").toString() + "</p>"); fv.put("depth", ""); } catch (NullPointerException npe) { fv.put("depth", ""); } } System.out.println("depth --> " + fv.get("depth").toString()); if ((fv.get("elevation") != null) && !fv.get("elevation").toString().equals("")) { try { double tempDouble = (new Double(fv.get("elevation").toString())).doubleValue() / 3.3; String truncElev = (new Double(tempDouble)).toString(); //String truncElev = ((new Double(elevation)) / 3.3).toString(); sizePeriod = truncElev.indexOf("."); truncElev = truncElev.substring(0, sizePeriod + 2); fv.put("elevation", (new Double(truncElev)).toString()); } catch (java.lang.NumberFormatException nfe) { enc.addComments("<p>Reported elevation was problematic: " + fv.get("elevation").toString() + "</p>"); fv.put("elevation", ""); } catch (NullPointerException npe) { fv.put("elevation", ""); } } if ((fv.get("size") != null) && !fv.get("size").toString().equals("")) { try { double tempDouble = (new Double(fv.get("size").toString())).doubleValue() / 3.3; String truncSize = (new Double(tempDouble)).toString(); //String truncSize = ((new Double(size)) / 3.3).toString(); sizePeriod = truncSize.indexOf("."); truncSize = truncSize.substring(0, sizePeriod + 2); fv.put("size", (new Double(truncSize)).toString()); } catch (java.lang.NumberFormatException nfe) { enc.addComments("<p>Reported size was problematic: " + fv.get("size").toString() + "</p>"); fv.put("size", ""); } catch (NullPointerException npe) { fv.put("size", ""); } } } //measureUnits if ((fv.get("size") != null) && !fv.get("size").toString().equals("")) { try { enc.setSize(new Double(fv.get("size").toString())); } catch (java.lang.NumberFormatException nfe) { enc.addComments("<p>Reported size was problematic: " + fv.get("size").toString() + "</p>"); fv.put("size", ""); } catch (NullPointerException npe) { fv.put("size", ""); } } if ((fv.get("elevation") != null) && !fv.get("elevation").toString().equals("")) { try { enc.setMaximumElevationInMeters(new Double(fv.get("elevation").toString())); } catch (java.lang.NumberFormatException nfe) { enc.addComments( "<p>Reported elevation was problematic: " + fv.get("elevation").toString() + "</p>"); fv.put("elevatoin", ""); } catch (NullPointerException npe) { fv.put("elevation", ""); } } if ((fv.get("depth") != null) && !fv.get("depth").toString().equals("")) { try { enc.setDepth(new Double(fv.get("depth").toString())); } catch (java.lang.NumberFormatException nfe) { enc.addComments("<p>Reported depth was problematic: " + fv.get("depth").toString() + "</p>"); fv.put("depth", ""); } catch (NullPointerException npe) { fv.put("depth", ""); } } //let's handle the GPS if ((fv.get("lat") != null) && (fv.get("longitude") != null) && !fv.get("lat").toString().equals("") && !fv.get("longitude").toString().equals("")) { //enc.setGPSLatitude(lat + "° " + gpsLatitudeMinutes + "\' " + gpsLatitudeSeconds + "\" " + latDirection); try { double degrees = (new Double(fv.get("lat").toString())).doubleValue(); double position = degrees; /* if (!gpsLatitudeMinutes.equals("")) { double minutes2 = ((new Double(gpsLatitudeMinutes)).doubleValue()) / 60; position += minutes2; } if (!gpsLatitudeSeconds.equals("")) { double seconds2 = ((new Double(gpsLatitudeSeconds)).doubleValue()) / 3600; position += seconds2; } if (latDirection.toLowerCase().equals("south")) { position = position * -1; }*/ enc.setDWCDecimalLatitude(position); double degrees2 = (new Double(fv.get("longitude").toString())).doubleValue(); double position2 = degrees2; enc.setDWCDecimalLongitude(position2); llSet = true; } catch (Exception e) { System.out.println("EncounterSetGPS: problem!"); e.printStackTrace(); } } //enc.setMeasureUnits("Meters"); enc.setSubmitterPhone(getVal(fv, "submitterPhone")); enc.setSubmitterAddress(getVal(fv, "submitterAddress")); enc.setSubmitterOrganization(getVal(fv, "submitterOrganization")); enc.setSubmitterProject(getVal(fv, "submitterProject")); enc.setPhotographerPhone(getVal(fv, "photographerPhone")); enc.setPhotographerAddress(getVal(fv, "photographerAddress")); enc.setPhotographerName(getVal(fv, "photographerName")); enc.setPhotographerEmail(getVal(fv, "photographerEmail")); enc.addComments("<p>Submitted on " + (new java.util.Date()).toString() + " from address: " + request.getRemoteHost() + "</p>"); //enc.approved = false; enc.addComments(processingNotes.toString()); if (CommonConfiguration.getProperty("encounterState0", context) != null) { enc.setState(CommonConfiguration.getProperty("encounterState0", context)); } if (request.getRemoteUser() != null) { enc.setSubmitterID(request.getRemoteUser()); } else { enc.setSubmitterID("N/A"); } if (!getVal(fv, "locCode").equals("")) { enc.setLocationCode(locCode); } if (!getVal(fv, "country").equals("")) { enc.setCountry(getVal(fv, "country")); } if (!getVal(fv, "informothers").equals("")) { enc.setInformOthers(getVal(fv, "informothers")); } // xxxxxxx //add research team for GAq if (!getVal(fv, "researchTeam").equals("")) { enc.setDynamicProperty("Research Team", (getVal(fv, "researchTeam"))); } if (!getVal(fv, "vessel").equals("")) { enc.setDynamicProperty("Vessel", (getVal(fv, "vessel"))); } if (!getVal(fv, "conditions").equals("")) { enc.setDynamicProperty("Conditions", (getVal(fv, "conditions"))); } if (!getVal(fv, "camera").equals("")) { enc.setDynamicProperty("Camera", (getVal(fv, "camera"))); } if (!getVal(fv, "lens").equals("")) { enc.setDynamicProperty("Lens", (getVal(fv, "lens"))); } if (!getVal(fv, "card").equals("")) { enc.setDynamicProperty("Card", (getVal(fv, "card"))); } if (!getVal(fv, "folder").equals("")) { enc.setDynamicProperty("Folder", (getVal(fv, "folder"))); } if (!getVal(fv, "numberOfBoats").equals("")) { enc.setDynamicProperty("Number of boats", (getVal(fv, "numberOfBoats"))); } if (!getVal(fv, "startTime").equals("")) { enc.setDynamicProperty("Start Time", (getVal(fv, "startTime"))); } if (!getVal(fv, "endTime").equals("")) { enc.setDynamicProperty("End Time", (getVal(fv, "endTime"))); } if (!getVal(fv, "endLongitude").equals("")) { enc.setDynamicProperty("End Longitude", (getVal(fv, "endLongitude"))); } if (!getVal(fv, "endLatitude").equals("")) { enc.setDynamicProperty("End Latitude", (getVal(fv, "endLatitude"))); } if (!getVal(fv, "startLongitude").equals("")) { enc.setDynamicProperty("Start Longitude", (getVal(fv, "startLongitude"))); } if (!getVal(fv, "startLatitude").equals("")) { enc.setDynamicProperty("Start Latitude", (getVal(fv, "startLatitude"))); } if (!getVal(fv, "beginWaypoint").equals("")) { enc.setDynamicProperty("Begin Waypoint", (getVal(fv, "beginWaypoint"))); } if (!getVal(fv, "endWaypoint").equals("")) { enc.setDynamicProperty("End Waypoint", (getVal(fv, "endWaypoint"))); } //xxxxxxxx String guid = CommonConfiguration.getGlobalUniqueIdentifierPrefix(context) + encID; //new additions for DarwinCore enc.setDWCGlobalUniqueIdentifier(guid); enc.setDWCImageURL((request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/encounters/encounter.jsp?number=" + encID)); //populate DarwinCore dates DateTimeFormatter fmt = ISODateTimeFormat.date(); String strOutputDateTime = fmt.print(dt); enc.setDWCDateAdded(strOutputDateTime); enc.setDWCDateAdded(new Long(dt.toDateTime().getMillis())); //System.out.println("I set the date as a LONG to: "+enc.getDWCDateAddedLong()); enc.setDWCDateLastModified(strOutputDateTime); //this will try to set from MediaAssetMetadata -- ymmv if (!llSet) enc.setLatLonFromAssets(); if (enc.getYear() < 1) enc.setDateFromAssets(); String newnum = ""; if (!spamBot) { newnum = myShepherd.storeNewEncounter(enc, encID); //enc.refreshAssetFormats(context, ServletUtilities.dataDir(context, rootDir)); enc.refreshAssetFormats(myShepherd); Logger log = LoggerFactory.getLogger(EncounterForm.class); log.info("New encounter submission: <a href=\"" + request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/encounters/encounter.jsp?number=" + encID + "\">" + encID + "</a>"); System.out.println("ENCOUNTER SAVED???? newnum=" + newnum); } if (newnum.equals("fail")) { request.setAttribute("number", "fail"); return; } //return a forward to display.jsp System.out.println("Ending data submission."); if (!spamBot) { response.sendRedirect(request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/confirmSubmit.jsp?number=" + encID); } else { response.sendRedirect( request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/spambot.jsp"); } } //end "if (fileSuccess) myShepherd.closeDBTransaction(); //return null; }
From source file:org.ednovo.gooru.application.server.service.uploadServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { FileItem uploadedFileItem = null; String fileName = ""; JSONArray jsonArray = null;/*from w w w. j a v a 2 s. co m*/ boolean isMultiPart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request)); if (isMultiPart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(31457280); String responsedata = ""; try { try { @SuppressWarnings("rawtypes") java.util.List items = upload.parseRequest(request); ApplicationContext appContext = new ClassPathXmlApplicationContext("gooruContext-service.xml"); Properties restConstants = (Properties) appContext.getBean("restConstants"); for (int i = 0; i < items.size(); i++) { uploadedFileItem = (FileItem) items.get(i); } String stoken = (String) request.getSession(false).getAttribute("gooru-session-token"); try { //This will replace all the non-word characters with '_' excluding the dot. fileName = uploadedFileItem.getName().replaceAll("[^\\w.]", "_"); } catch (Exception e) { logger.error("Exception:::" + e); } String requestData = "uploadFileName=" + fileName + "&imageURL=&sessionToken=" + stoken; String url = UrlGenerator.generateUrl(restConstants.getProperty(REST_ENDPOINT), UrlToken.FILE_UPLOAD_GET_URL, fileName, stoken); try { responsedata = webInvokeForImage("POST", requestData, "multipart/form-data", request, uploadedFileItem.get(), fileName, uploadedFileItem.getSize(), url); jsonArray = new JSONArray(responsedata); } catch (UnsupportedEncodingException e) { logger.error("UnsupportedEncodingException:::" + e); } response.setContentType("text/html"); response.getOutputStream().print(jsonArray.get(0).toString()); response.getOutputStream().flush(); } catch (FileUploadBase.FileSizeLimitExceededException e) { logger.error("FileSizeLimitExceededException:::" + e); responsedata = "file size error"; response.setContentType("text/html"); response.getOutputStream().print(responsedata); response.getOutputStream().flush(); } } catch (Exception e) { logger.error("Global exception:::" + e); } } }
From source file:org.etudes.mneme.impl.AttachmentServiceImpl.java
/** * {@inheritDoc}//ww w . jav a 2s. c o m */ public Reference addAttachment(String application, String context, String prefix, NameConflictResolution onConflict, FileItem file, boolean makeThumb, String altRef) { pushAdvisor(); try { String name = file.getName(); if (name != null) { name = massageName(name); } String type = file.getContentType(); // TODO: change to file.getInputStream() for after Sakai 2.3 more efficient support // InputStream body = file.getInputStream(); byte[] body = file.get(); long size = file.getSize(); // detect no file selected if ((name == null) || (type == null) || (body == null) || (size == 0)) { // TODO: if using input stream, close it // if (body != null) body.close(); return null; } Reference rv = addAttachment(name, name, application, context, prefix, onConflict, type, body, size, makeThumb, altRef); return rv; } finally { popAdvisor(); } }
From source file:org.etudes.tool.melete.AddResourcesPage.java
public String addItems() { byte[] secContentData; String secResourceName;// www . j a va 2 s . c o m String secContentMimeType; FacesContext context = FacesContext.getCurrentInstance(); ResourceLoader bundle = new ResourceLoader("org.etudes.tool.melete.bundle.Messages"); String addCollId = getMeleteCHService().getUploadCollectionId(); //Code that validates required fields int emptyCounter = 0; String linkValue, titleValue; boolean emptyLinkFlag = false; boolean emptyTitleFlag = false; err_fields = null; if (this.fileType.equals("upload")) { for (int i = 1; i <= 10; i++) { org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) context .getExternalContext().getRequestMap().get("file" + i); if (fi == null || fi.getName() == null || fi.getName().length() == 0) { emptyCounter = emptyCounter + 1; } } if (emptyCounter == 10) { FacesContext ctx = FacesContext.getCurrentInstance(); ValueBinding binding = Util.getBinding("#{manageResourcesPage}"); ManageResourcesPage manResPage = (ManageResourcesPage) binding.getValue(ctx); manResPage.resetValues(); return "manage_content"; } /* try { if (emptyCounter == 10) throw new MeleteException("all_uploads_empty"); } catch (MeleteException mex) { String errMsg = bundle.getString(mex.getMessage()); context.addMessage (null, new FacesMessage(FacesMessage.SEVERITY_ERROR,mex.getMessage(),errMsg)); return "failure"; } */ for (int i = 1; i <= 10; i++) { try { org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) context .getExternalContext().getRequestMap().get("file" + i); if (fi != null && fi.getName() != null && fi.getName().length() != 0) { //validate fileName Util.validateUploadFileName(fi.getName()); validateFileSize(fi.getSize()); // filename on the client secResourceName = fi.getName(); if (secResourceName.indexOf("/") != -1) { secResourceName = secResourceName.substring(secResourceName.lastIndexOf("/") + 1); } if (secResourceName.indexOf("\\") != -1) { secResourceName = secResourceName.substring(secResourceName.lastIndexOf("\\") + 1); } if (logger.isDebugEnabled()) logger.debug("Rsrc name is " + secResourceName); if (logger.isDebugEnabled()) logger.debug("upload section content data " + (int) fi.getSize()); secContentData = new byte[(int) fi.getSize()]; InputStream is = fi.getInputStream(); is.read(secContentData); secContentMimeType = fi.getContentType(); if (logger.isDebugEnabled()) logger.debug("file upload success" + secContentMimeType); if (logger.isDebugEnabled()) logger.debug( "new names for upload content is" + secContentMimeType + "," + secResourceName); addItem(secResourceName, secContentMimeType, addCollId, secContentData); if (success_fields == null) success_fields = new ArrayList<String>(); success_fields.add(new Integer(i).toString()); success_fields.add(bundle.getString("add_item_success") + secResourceName); } else { logger.debug("File being uploaded is NULL"); continue; } } catch (MeleteException mex) { String mexMsg = mex.getMessage(); if (mex.getMessage().equals("embed_img_bad_filename")) mexMsg = "img_bad_filename"; String errMsg = bundle.getString(mexMsg); // context.addMessage ("FileUploadForm:chooseFile"+i, new FacesMessage(FacesMessage.SEVERITY_ERROR,mex.getMessage(),errMsg)); // logger.error("error in uploading multiple files" + errMsg); if (err_fields == null) err_fields = new ArrayList<String>(); err_fields.add(new Integer(i).toString()); err_fields.add(errMsg); //return "failure"; } catch (Exception e) { logger.debug("file upload FAILED" + e.toString()); } } if (err_fields != null) { logger.debug("err found in fields" + err_fields.toString()); return "file_upload_view"; } } if (this.fileType.equals("link")) { Iterator utIterator = utList.iterator(); //Finish validating here int count = -1; while (utIterator.hasNext()) { count++; try { UrlTitleObj utObj = (UrlTitleObj) utIterator.next(); if (utObj.title != null) utObj.title = utObj.title.trim(); String linkUrl = utObj.getUrl(); if (linkUrl != null) linkUrl = linkUrl.trim(); String checkUrl = linkUrl; if (checkUrl != null) { checkUrl = checkUrl.replace("http://", ""); checkUrl = checkUrl.replace("https://", ""); } if ((utObj.title == null || utObj.title.length() == 0) && (checkUrl == null || checkUrl.length() == 0)) { utIterator.remove(); continue; } if (utObj.title == null || utObj.title.length() == 0) { context.addMessage("LinkUploadForm:utTable:" + count + ":title", new FacesMessage( FacesMessage.SEVERITY_ERROR, "URL_title_reqd", bundle.getString("URL_title_reqd"))); return "#"; } if (checkUrl == null || checkUrl.length() == 0) { context.addMessage("LinkUploadForm:utTable:" + count + ":url", new FacesMessage( FacesMessage.SEVERITY_ERROR, "URL_reqd", bundle.getString("URL_reqd"))); return "#"; } Util.validateLink(linkUrl); } catch (UserErrorException uex) { String errMsg = bundle.getString(uex.getMessage()); context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "add_section_bad_url_formats", bundle.getString("add_section_bad_url_formats"))); return "failure"; } catch (Exception e) { logger.debug("link upload FAILED" + e.toString()); } } utIterator = utList.iterator(); while (utIterator.hasNext()) { UrlTitleObj utObj = (UrlTitleObj) utIterator.next(); try { secContentMimeType = getMeleteCHService().MIME_TYPE_LINK; String linkUrl = utObj.getUrl(); secResourceName = utObj.getTitle(); if ((linkUrl != null) && (linkUrl.trim().length() > 0) && (secResourceName != null) && (secResourceName.trim().length() > 0)) { secContentData = new byte[linkUrl.length()]; secContentData = linkUrl.getBytes(); addItem(secResourceName, secContentMimeType, addCollId, secContentData); } } catch (MeleteException mex) { String errMsg = bundle.getString(mex.getMessage()); context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, mex.getMessage(), errMsg)); return "failure"; } catch (Exception e) { logger.debug("link upload FAILED" + e.toString()); } } } FacesContext ctx = FacesContext.getCurrentInstance(); ValueBinding binding = Util.getBinding("#{manageResourcesPage}"); ManageResourcesPage manResPage = (ManageResourcesPage) binding.getValue(ctx); manResPage.resetValues(); return "manage_content"; }
From source file:org.etudes.tool.melete.SectionPage.java
public String uploadSectionContent(String fieldname) throws Exception { try {//from w ww .j a va 2 s .com FacesContext context = FacesContext.getCurrentInstance(); org.apache.commons.fileupload.FileItem fi = (org.apache.commons.fileupload.FileItem) context .getExternalContext().getRequestMap().get(fieldname); if (fi != null && fi.getName() != null && fi.getName().length() != 0) { Util.validateUploadFileName(fi.getName()); // filename on the client secResourceName = fi.getName(); if (secResourceName.indexOf("/") != -1) { secResourceName = secResourceName.substring(secResourceName.lastIndexOf("/") + 1); } if (secResourceName.indexOf("\\") != -1) { secResourceName = secResourceName.substring(secResourceName.lastIndexOf("\\") + 1); } if (logger.isDebugEnabled()) logger.debug("Rsrc name is " + secResourceName); if (logger.isDebugEnabled()) logger.debug("upload section content data " + (int) fi.getSize()); this.secContentData = new byte[(int) fi.getSize()]; InputStream is = fi.getInputStream(); is.read(this.secContentData); String secContentMimeType = fi.getContentType(); if (logger.isDebugEnabled()) logger.debug("file upload success" + secContentMimeType); return secContentMimeType; } else { logger.debug("File being uploaded is NULL"); return null; } } catch (MeleteException me) { logger.debug("file upload FAILED" + me.toString()); throw me; } catch (Exception e) { logger.error("file upload FAILED" + e.toString()); return null; } }