public HttpParams(HttpServletRequest request) throws UnsupportedEncodingException {
    // 检测是否是一个文件上传请求
    this.request = request;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setHeaderEncoding("UTF-8");
      RequestContext requestContext = new ServletRequestContext(request);
      try {
        List<FileItem> items = upload.parseRequest(requestContext);
        Iterator<FileItem> itr = items.iterator();
        avs = new HashMap<String, String>();
        fileitemMap = new HashMap<String, FileItem>();
        while (itr.hasNext()) {
          FileItem item = (FileItem) itr.next();
          String fieldName = item.getFieldName();
          if (item.isFormField()) {
            avs.put(fieldName, item.getString("UTF-8"));
          } else {
            fileitemMap.put(fieldName, item);
          }
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    } else { // 非文件上传请求  (参数加密)
      request.setCharacterEncoding("utf-8");
      String s = request.getParameter("__");
      // s = URLDecoder.decode(s,"UTF-8");
      // logger.info("http reqeust params: "+s);
      if (s != null && !s.equals("")) {
        try {
          encoded = true;
          //					String str = DataUtil.decodeECBString(password, DataUtil.HexString2Bytes(s));
          String str = DataUtil.decodeECBString(password, DataUtil.decodeBase64(s));
          String[] pairs = str.split("&");
          params = new HashMap<String, String>();

          for (int i = 0; i < pairs.length; i++) {
            // String[] tokens = pairs[i].split("=");
            int index = pairs[i].indexOf("=");
            String key = pairs[i].substring(0, index);
            String value = pairs[i].substring(index + 1, pairs[i].length());
            params.put(key, URLDecoder.decode(value, "UTF-8"));
          }
        } catch (Exception ex) {
          ex.printStackTrace();
        }
      }
    }
  }
 private void analyzeRequest(HttpServletRequest request) {
   // TODO Auto-generated method stub
   isMultipart = ServletFileUpload.isMultipartContent(request);
   userName = request.getParameter(USER_NAME);
   lat = Double.parseDouble(request.getParameter(LAT));
   lng = Double.parseDouble(request.getParameter(LNG));
   cautionType = Short.parseShort(request.getParameter(CAUTION_TYPE));
   comment = request.getParameter(COMMENT);
 }
Example #3
0
  @Override
  public void execute(HttpServletRequest request) {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    Logger.debug("UploadImageCmd - request: " + request);
    if (!isMultipart) {
      Logger.debug("UploadImageCmd - nao multipart");
    } else {
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload upload = new ServletFileUpload(factory);
      List<FileItem> items = null;

      try {
        items = upload.parseRequest(request);
        Logger.debug("itens: " + items);
      } catch (FileUploadException e) {
        Logger.error("Upload de imagem falhou", e);
      }
      Iterator<FileItem> itr = items.iterator();
      while (itr.hasNext()) {
        FileItem item = itr.next();
        if (item.isFormField()) {
          String name = item.getFieldName();
          String value = item.getString();
          Logger.debug("Campo de formulario: " + name + " = " + value);
        } else {
          try {
            String mimetype = item.getContentType();
            Logger.debug("Mimetype: " + mimetype);
            if (StringUtils.isEmpty(mimetype) || !mimetype.startsWith("image/")) {
              Logger.warning("Mimetype invalido.");
              continue;
            }

            // Vamos reimensionar a imagem caso necessario (para que ela nao fique muito grande)
            BufferedImage img = resizeImg(item.getInputStream());

            String itemName = item.getName();
            Random generator = new Random();
            int r = generator.nextInt(Integer.MAX_VALUE);

            String reg = "[.*]";
            String replacingtext = "";

            Pattern pattern = Pattern.compile(reg);
            Matcher matcher = pattern.matcher(itemName);
            StringBuffer buffer = new StringBuffer();

            while (matcher.find()) {
              matcher.appendReplacement(buffer, replacingtext);
            }
            int indexOf = itemName.indexOf(".");
            String extension = itemName.substring(indexOf + 1);
            Logger.debug("extensao: " + extension);

            String finalImage = buffer.toString() + "_" + r + "." + extension;
            Logger.debug("Imagem Final === " + finalImage);

            String path = request.getServletContext().getRealPath("/pictures");
            File savedFile = new File(path + "/" + finalImage);
            ImageIO.write(img, extension, savedFile);

            mImagePath = savedFile.getAbsolutePath();
            request.setAttribute("img", "pictures/" + finalImage);
            Logger.debug("Imagem salva em: " + mImagePath);
          } catch (Exception e) {
            Logger.error("Erro no upload da imagem", e);
          }
        }
      }
    }
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException {
    // Verify the post has the correct encoding
    if (!ServletFileUpload.isMultipartContent(request)) {
      sendErrMsg(response, "Invalid request contents format for this service.");
      return;
    }

    // Get the contents from the post request
    String username = null;
    try {
      username = DashboardUtils.cleanUsername(request.getUserPrincipal().getName().trim());
    } catch (Exception ex) {; // leave username null for error message later
    }

    // Get the contents from the post request
    String expocodes = null;
    String uploadTimestamp = null;
    String omeIndicator = null;
    FileItem metadataItem = null;
    try {
      Map<String, List<FileItem>> paramMap = metadataUpload.parseParameterMap(request);
      try {
        List<FileItem> itemList;

        itemList = paramMap.get("expocodes");
        if ((itemList != null) && (itemList.size() == 1)) {
          expocodes = itemList.get(0).getString();
        }

        itemList = paramMap.get("timestamp");
        if ((itemList != null) && (itemList.size() == 1)) {
          uploadTimestamp = itemList.get(0).getString();
        }

        itemList = paramMap.get("ometoken");
        if ((itemList != null) && (itemList.size() == 1)) {
          omeIndicator = itemList.get(0).getString();
        }

        itemList = paramMap.get("metadataupload");
        if ((itemList != null) && (itemList.size() == 1)) {
          metadataItem = itemList.get(0);
        }

      } finally {
        // Delete everything except for the uploaded metadata file
        for (List<FileItem> itemList : paramMap.values()) {
          for (FileItem item : itemList) {
            if (!item.equals(metadataItem)) {
              item.delete();
            }
          }
        }
      }
    } catch (Exception ex) {
      if (metadataItem != null) metadataItem.delete();
      sendErrMsg(response, "Error processing the request\n" + ex.getMessage());
      return;
    }

    // Verify page contents seem okay
    DashboardConfigStore configStore = DashboardConfigStore.get(true);
    if ((username == null)
        || (expocodes == null)
        || (uploadTimestamp == null)
        || (omeIndicator == null)
        || (metadataItem == null)
        || (!(omeIndicator.equals("false") || omeIndicator.equals("true")))
        || !configStore.validateUser(username)) {
      if (metadataItem != null) metadataItem.delete();
      sendErrMsg(response, "Invalid request contents for this service.");
      return;
    }
    // Extract the cruise expocodes from the expocodes string
    TreeSet<String> cruiseExpocodes = new TreeSet<String>();
    try {
      cruiseExpocodes.addAll(DashboardUtils.decodeStringArrayList(expocodes));
      if (cruiseExpocodes.size() < 1) throw new IllegalArgumentException();
    } catch (IllegalArgumentException ex) {
      metadataItem.delete();
      sendErrMsg(response, "Invalid request contents for this service.");
      return;
    }

    boolean isOme = omeIndicator.equals("true");
    String version = configStore.getUploadVersion();

    MetadataFileHandler metadataHandler = configStore.getMetadataFileHandler();
    CruiseFileHandler cruiseHandler = configStore.getCruiseFileHandler();
    DatabaseRequestHandler dbHandler = configStore.getDatabaseRequestHandler();
    DsgNcFileHandler dsgFileHandler = configStore.getDsgNcFileHandler();
    OmePdfGenerator omePdfGenerator = configStore.getOmePdfGenerator();
    String uploadFilename;
    if (isOme) {
      // Save under the PI_OME_FILENAME at this time.
      // When CDIAC OME incorporated, change to OME_FILENAME
      uploadFilename = DashboardUtils.PI_OME_FILENAME;
    } else {
      uploadFilename = DashboardUtils.baseName(metadataItem.getName());
      if (uploadFilename.equals(DashboardUtils.OME_FILENAME)
          || uploadFilename.equals(DashboardUtils.OME_PDF_FILENAME)
          || uploadFilename.equals(DashboardUtils.PI_OME_FILENAME)
          || uploadFilename.equals(DashboardUtils.PI_OME_PDF_FILENAME)) {
        metadataItem.delete();
        sendErrMsg(
            response,
            "Name of the uploaded file cannot be "
                + DashboardUtils.OME_FILENAME
                + " nor "
                + DashboardUtils.OME_PDF_FILENAME
                + " nor "
                + DashboardUtils.PI_OME_FILENAME
                + " nor "
                + DashboardUtils.PI_OME_PDF_FILENAME
                + "\nPlease rename the file and try again.");
      }
    }

    DashboardMetadata metadata = null;
    for (String expo : cruiseExpocodes) {
      try {
        // Save the metadata document for this cruise
        if (metadata == null) {
          metadata =
              metadataHandler.saveMetadataFileItem(
                  expo, username, uploadTimestamp, uploadFilename, version, metadataItem);
        } else {
          metadata = metadataHandler.copyMetadataFile(expo, metadata, true);
        }
        // Update the metadata documents associated with this cruise
        DashboardCruise cruise;
        if (isOme) {
          // Make sure the contents are valid OME XML
          DashboardOmeMetadata omedata;
          try {
            omedata = new DashboardOmeMetadata(metadata, metadataHandler);
          } catch (IllegalArgumentException ex) {
            // Problems with the file - delete it
            metadataHandler.removeMetadata(username, expo, metadata.getFilename());
            throw new IllegalArgumentException("Invalid OME metadata file: " + ex.getMessage());
          }
          cruise = cruiseHandler.addAddlDocToCruise(expo, omedata);
          try {
            // This is using the PI OME XML file at this time
            omePdfGenerator.createPiOmePdf(expo);
          } catch (Exception ex) {
            throw new IllegalArgumentException(
                "Unable to create the PDF from the OME XML: " + ex.getMessage());
          }
        } else {
          cruise = cruiseHandler.addAddlDocToCruise(expo, metadata);
        }
        if (!Boolean.TRUE.equals(cruise.isEditable())) {
          QCEvent qcEvent = new QCEvent();
          qcEvent.setExpocode(expo);
          qcEvent.setFlag(DashboardUtils.QC_UPDATED_FLAG);
          qcEvent.setFlagDate(new Date());
          qcEvent.setRegionID(DashboardUtils.GLOBAL_REGION_ID);
          qcEvent.setVersion(version);
          qcEvent.setUsername(username);
          String comment;
          if (isOme) comment = "Update of OME metadata.  ";
          else comment = "Update of metadata file \"" + uploadFilename + "\".  ";
          comment += "Data and WOCE flags were not changed.";
          qcEvent.setComment(comment);
          try {
            // Add the 'U' QC flag
            dbHandler.addQCEvent(qcEvent);
            dsgFileHandler.updateQCFlag(qcEvent);
            // Update the dashboard status for the 'U' QC flag
            cruise.setQcStatus(DashboardUtils.QC_STATUS_SUBMITTED);
            // If archived, reset the archived status so the updated metadata will be archived
            if (cruise.getArchiveStatus().equals(DashboardUtils.ARCHIVE_STATUS_ARCHIVED))
              cruise.setArchiveStatus(DashboardUtils.ARCHIVE_STATUS_WITH_SOCAT);
            cruiseHandler.saveCruiseInfoToFile(cruise, comment);
          } catch (Exception ex) {
            // Should not fail.
            // If does, do not delete the file since it is okay, and ignore the failure.
            ;
          }
        }
      } catch (Exception ex) {
        metadataItem.delete();
        sendErrMsg(response, ex.getMessage());
        return;
      }
    }

    // Send the success response
    response.setStatus(HttpServletResponse.SC_OK);
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter respWriter = response.getWriter();
    respWriter.println(DashboardUtils.FILE_CREATED_HEADER_TAG);
    response.flushBuffer();
  }
Example #5
0
  private void updateCover(
      HttpServletRequest request, HttpServletResponse response, final String method)
      throws FileUploadException, ServletException, IOException, IllegalAccessException,
          InvocationTargetException {
    List<String> types = Arrays.asList(".jpg", ".gif", ".png", ".jpeg"); // supported
    // type

    DiskFileItemFactory dfi = new DiskFileItemFactory(); // apache's
    // component

    dfi.setSizeThreshold(1024 * 1024); // 1M, and default is 10k, and
    // excessed will be saved in the
    // cache file
    String path = getServletContext().getRealPath("/WEB-INF/temp");
    dfi.setRepository(new File(path)); // temporary cached file

    ServletFileUpload sf = new ServletFileUpload(dfi);
    sf.setHeaderEncoding("utf-8");
    // sf.setFileSizeMax(1024*1024*5); //set single file's max size

    List<FileItem> lf = sf.parseRequest(new ServletRequestContext(request));
    Map<String, String> map = new HashMap<String, String>();
    List<String> idf = new LinkedList<String>();
    FileItem fi = null; // for stream file
    String ids[];

    for (FileItem item : lf) {
      if (item.isFormField()) { // ordinary input
        String name = item.getFieldName();
        String value = item.getString("utf-8");
        map.put(name, value);
        if ("category".equals(name)) {
          idf.add(value);
        }
        System.out.println(name + " " + value);
      } else { // stream
        String name = item.getName();
        if (name == null || "".equals(name)) {
          continue;
        }
        String ext = name.substring(name.lastIndexOf("."));
        System.out.println(ext);
        if (!types.contains(ext.toLowerCase())) {
          request.setAttribute("message", "sorryia..  i don't support type " + ext);
          return;
        }

        fi = item;
      }
    }

    Book book = new Book();
    ConvertUtils.register(new DateLocaleConverter(), Date.class);
    BeanUtils.populate(book, map);
    BookDaoImpl bdi = new BookDaoImpl();
    ids = new String[idf.size()];
    idf.toArray(ids);
    int id;

    if (method.equals(BOOK_ADD)) {
      id = bdi.add(book, ids);
      request.setAttribute("message", "add book successfully...");
    } else {
      id = Integer.parseInt(map.get("id"));
      book.setId(id);
      bdi.update(book);
      bdi.updateCategory(id, ids);
      request.setAttribute("message", "update book successfully...");
    }

    if (fi != null) { // upload file
      InputStream is = fi.getInputStream();
      String Spath = getServletContext().getRealPath("/img/bookcover/");
      System.out.println(Spath);
      FileOutputStream fos = new FileOutputStream(new File(Spath + id + ".jpg"));
      byte[] b = new byte[1024];
      int len = 0;
      while ((len = is.read(b)) > 0) {
        fos.write(b, 0, len);
      }
      fos.close();
      is.close();
      fi.delete(); // the temporary file would be deleted.
    }
  }
Example #6
0
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    logger.info("post: " + req.getQueryString());

    String sessionId = req.getParameter("sessionId");
    if (!Utils.isNullOrEmpty(sessionId)) {
      Session session = getSessionCache().getSessionForSessionId(sessionId);
      if (session.getUserProfile() != null) {
        String uploadType = req.getParameter("upload");
        logger.info("got uploadrequest, type: " + uploadType);
        String response = "success";
        String callbackName = "";
        try {
          // Create a factory for disk-based file items
          FileItemFactory factory = new DiskFileItemFactory();

          // Create a new file upload handler
          ServletFileUpload upload = new ServletFileUpload(factory);
          upload.setSizeMax(1024 * 1024);
          upload.setFileSizeMax(1024 * 1024 * 500);
          // Parse the request
          List<FileItem> /* FileItem */ items = upload.parseRequest(req);

          Iterator<FileItem> iter = items.iterator();
          while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
              logger.info("formfield " + item.getFieldName());
              if ("callbackName".equals(item.getFieldName())) callbackName = item.getString();
            } else {
              logger.info("filefield " + item.getFieldName());
              if ("userPicture".equals(uploadType)) {
                logger.info("Setting new user picture for " + session.getUserProfile());

                UserCredentials userCredentials = session.getUserProfile().getUserCredentials();
                // creating the small image
                ByteArrayOutputStream bo = new ByteArrayOutputStream();
                scalePictureToMax(new ByteArrayInputStream(item.get()), bo, 50, 50);
                userCredentials.setSmallPicture(bo.toByteArray());
                // creating big picture
                bo = new ByteArrayOutputStream();
                scalePictureToMax(new ByteArrayInputStream(item.get()), bo, 500, 500);
                userCredentials.setPicture(bo.toByteArray());

                session.getUserProfile().setUserCredentials(userCredentials);
              }
            }
          }

        } catch (Exception e) {
          logger.error("error sending user picture", e);
          response = "Error, for details see the server log files.";
        }

        logger.info("Callback name: " + callbackName);
        resp.getWriter()
            .print(
                "<script type=\"text/javascript\">window.top."
                    + callbackName
                    + "('"
                    + response
                    + "');</script>");
      }
    } else super.doPost(req, resp);
  }
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub
    String message = "File upload.";
    List<String> filenames = null;
    isMultipart = ServletFileUpload.isMultipartContent(request);
    HttpSession session = request.getSession(false);
    User loggedUser = null;
    if (session != null) loggedUser = (User) session.getAttribute("loggedUser");
    if (loggedUser == null) {
      request.getRequestDispatcher("login.jsp").forward(request, response);
    } else {
      Book book = new Book();
      if (isMultipart) {
        ServletContext context = this.getServletConfig().getServletContext();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        File repoPath = (File) context.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repoPath);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        try {
          List<FileItem> fileItems = upload.parseRequest(new ServletRequestContext(request));
          filePath = request.getServletContext().getRealPath("/") + "picture/";
          filenames = new ArrayList<String>();

          for (FileItem fi : fileItems) {
            if (!fi.isFormField()) {
              // Get the uploaded file parameters
              String fieldName = fi.getFieldName();
              if (fi.getName() != null && !fi.getName().equals("")) {
                String fileName = URLEncoder.encode(fi.getName(), "UTF-8");

                String contentType = fi.getContentType();

                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                file = new File(filePath + fileName);
                fi.write(file);
                book.setPictureURL("picture/" + fileName);
              }
            } else {
              String fieldName = fi.getFieldName();
              String fieldValue = fi.getString();
              if (fieldName.equals("title")) {
                if (fieldValue != null) {
                  book.setTitle(fieldValue);
                  ;
                }
              }
              if (fieldName.equals("authors")) book.setAuthors(fieldValue);
              if (fieldName.equals("publisher")) book.setPublisher(fieldValue);
              if (fieldName.equals("description"))
                if (fieldValue != null) {
                  book.setDescription(fieldValue);
                }
              if (fieldName.equals("genre")) book.setGenre(fieldValue);
              if (fieldName.equals("numberInStock"))
                book.setNumberInStock(Integer.parseInt(fieldValue));
              if (fieldName.equals("publicationYear"))
                book.setPublicationYear(Integer.parseInt(fieldValue));
              if (fieldName.equals("price")) book.setPrice(Double.parseDouble(fieldValue));
            }
          }
        } catch (Exception ex) {
          System.out.println(ex);
        }
      }

      BookDAO bookDao = new BookDAO();
      bookDao.add(book);

      response.sendRedirect("LoginBookPreviewViewController");
    }
  }
Example #8
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();

    String idx = request.getParameter("idx");

    // 获得磁盘文件条目工厂
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // 获取文件需要上传到的路径
    String rootPath = getServletContext().getRealPath("/upload");

    // 如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
    // 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
    /** 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的 然后再将其真正写到 对应目录的硬盘上 */
    File uploadDir = new File(rootPath);
    if (!uploadDir.exists()) {
      uploadDir.mkdirs();
    }
    factory.setRepository(uploadDir);
    // 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
    factory.setSizeThreshold(1024 * 1024);

    boolean isUpload = ServletFileUpload.isMultipartContent(request);
    // 高水平的API文件上传处理
    ServletFileUpload upload = new ServletFileUpload(factory);

    try {
      // 可以上传多个文件
      List<FileItem> list = (List<FileItem>) upload.parseRequest(request);

      for (FileItem item : list) {
        // 获取表单的属性名字
        String fileName = item.getName();

        // 如果获取的 表单信息是普通的 文本 信息
        if (item.isFormField()) {
        }
        // 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些
        else {

          String md5Name = MD5Code.getInstance().getCode(fileName + System.currentTimeMillis());
          String fiffux = fileName.substring(fileName.lastIndexOf("."));

          // 真正写到磁盘上
          // 它抛出的异常 用exception 捕捉
          File f = new File(rootPath + File.separatorChar, md5Name + fiffux);

          if (!f.exists()) {
            f.createNewFile();
          }
          item.write(f); // 第三方提供的

          JSONObject result = new JSONObject();
          JSONObject payload = new JSONObject();

          responseJavaScript(
              out, "parent.uploadImageComplete('" + idx + "','" + (md5Name + fiffux) + "')");

          out.close();
        }
      }

    } catch (FileUploadException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }