Exemplo n.º 1
0
 public void upload() throws Exception {
   boolean isMultipart = ServletFileUpload.isMultipartContent(this.request);
   if (!isMultipart) {
     this.state = this.errorInfo.get("NOFILE");
     return;
   }
   DiskFileItemFactory dff = new DiskFileItemFactory();
   String savePath = this.getFolder(this.savePath);
   dff.setRepository(new File(savePath));
   try {
     ServletFileUpload sfu = new ServletFileUpload(dff);
     sfu.setSizeMax(this.maxSize * 1024);
     sfu.setHeaderEncoding("utf-8");
     FileItemIterator fii = sfu.getItemIterator(this.request);
     while (fii.hasNext()) {
       FileItemStream fis = fii.next();
       if (!fis.isFormField()) {
         this.originalName =
             fis.getName()
                 .substring(fis.getName().lastIndexOf(System.getProperty("file.separator")) + 1);
         if (!this.checkFileType(this.originalName)) {
           this.state = this.errorInfo.get("TYPE");
           continue;
         }
         this.fileName = this.getName(this.originalName);
         this.type = this.getFileExt(this.fileName);
         this.url = savePath + "/" + this.fileName;
         BufferedInputStream in = new BufferedInputStream(fis.openStream());
         FileOutputStream out = new FileOutputStream(new File(this.getPhysicalPath(this.url)));
         BufferedOutputStream output = new BufferedOutputStream(out);
         Streams.copy(in, output, true);
         this.state = this.errorInfo.get("SUCCESS");
         // UE中只会处理单张上传,完成后即退出
         break;
       } else {
         String fname = fis.getFieldName();
         // 只处理title,其余表单请自行处理
         if (!fname.equals("pictitle")) {
           continue;
         }
         BufferedInputStream in = new BufferedInputStream(fis.openStream());
         BufferedReader reader = new BufferedReader(new InputStreamReader(in));
         StringBuffer result = new StringBuffer();
         while (reader.ready()) {
           result.append((char) reader.read());
         }
         this.title = new String(result.toString().getBytes(), "utf-8");
         reader.close();
       }
     }
   } catch (SizeLimitExceededException e) {
     this.state = this.errorInfo.get("SIZE");
   } catch (InvalidContentTypeException e) {
     this.state = this.errorInfo.get("ENTYPE");
   } catch (FileUploadException e) {
     this.state = this.errorInfo.get("REQUEST");
   } catch (Exception e) {
     this.state = this.errorInfo.get("UNKNOWN");
   }
 }
Exemplo n.º 2
0
  /** @see org.wyona.yanel.core.api.attributes.CreatableV2#create(HttpServletRequest) */
  public void create(HttpServletRequest request) {
    try {
      Repository repo = getRealm().getRepository();

      if (request instanceof HttpRequest) {
        HttpRequest yanelRequest = (HttpRequest) request;
        if (yanelRequest.isMultipartRequest()) {
          Enumeration parameters = yanelRequest.getFileNames();
          if (parameters.hasMoreElements()) {
            String name = (String) parameters.nextElement();

            Node newNode =
                org.wyona.yanel.core.util.YarepUtil.addNodes(
                    repo, getPath().toString(), org.wyona.yarep.core.NodeType.RESOURCE);
            OutputStream output = newNode.getOutputStream();
            InputStream is = yanelRequest.getInputStream(name);
            Streams.copy(is, output, true);
            uploadMimeType = yanelRequest.getContentType(name);

            String suffix = org.wyona.commons.io.PathUtil.getSuffix(newNode.getPath());
            if (suffix != null) {
              if (!getMimeTypeBySuffix(suffix).equals(uploadMimeType)) {
                log.warn(
                    "Upload request content type '"
                        + uploadMimeType
                        + "' is NOT the same as the guessed mime type '"
                        + getMimeTypeBySuffix(suffix)
                        + "' based on the suffix (Path: "
                        + newNode.getPath()
                        + ")");
              }
            }
            newNode.setMimeType(uploadMimeType);
          }
        } else {
          log.error("this is NOT a multipart request");
        }
      } else {
        log.error("this is NOT a HttpRequest");
      }

      // TODO: Introspection should not be hardcoded!
      /*          String name = new org.wyona.commons.io.Path(getPath()).getName();
      String parent = new org.wyona.commons.io.Path(getPath()).getParent().toString();
      String nameWithoutSuffix = name;
      int lastIndex = name.lastIndexOf(".");
      if (lastIndex > 0) nameWithoutSuffix = name.substring(0, lastIndex);
      String introspectionPath = parent + "/introspection-" + nameWithoutSuffix + ".xml";

      org.wyona.yanel.core.util.YarepUtil.addNodes(repo, introspectionPath, org.wyona.yarep.core.NodeType.RESOURCE);
      writer = new java.io.OutputStreamWriter(repo.getNode(introspectionPath).getOutputStream());
      writer.write(getIntrospection(name));
      writer.close();*/
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
  }
Exemplo n.º 3
0
  /** 上传ruleset */
  public void upRuleset() throws Exception {
    /**
     * form中的enctype必须是multipart/... 组件提供方法检测form表单的enctype属性 在isMultipartContent方法中同时检测了是否是post提交
     * 如果不是post提交则返回false
     */
    if (ServletFileUpload.isMultipartContent(request)) {
      String RulePath = (String) application.getAttribute("Ruleset");
      DiskFileItemFactory factory = new DiskFileItemFactory();
      factory.setRepository(new File(RulePath + "tmp")); // 临时文件目录
      // 内存最大占用
      factory.setSizeThreshold(1024000);
      ServletFileUpload sfu = new ServletFileUpload(factory);
      // 单个文件最大值byte
      sfu.setFileSizeMax(102400000);
      // 所有上传文件的总和最大值byte
      sfu.setSizeMax(204800000);

      List<FileItem> items = null;
      try {
        items = sfu.parseRequest(request);
      } catch (SizeLimitExceededException e) {
        error("size limit exception!");
        return;
      } catch (Exception e) {
        error("Exception:" + e.getMessage());
        return;
      }

      Json j = new Json(1, "ok");
      JsonObjectNode data = j.createData();
      JsonArrayNode files = new JsonArrayNode("filename");
      data.addChild(files);

      Iterator<FileItem> iter = (items == null) ? null : items.iterator();
      while (iter != null && iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        // 文件域
        if (!item.isFormField()) {
          String fileName = item.getName();
          int index = fileName.lastIndexOf("\\");
          if (index < 0) index = 0;
          fileName = fileName.substring(index);
          if (!fileName.endsWith(".xml")) fileName += ".xml";
          BufferedInputStream in = new BufferedInputStream(item.getInputStream());
          BufferedOutputStream out =
              new BufferedOutputStream(new FileOutputStream(new File(RulePath + fileName)));
          Streams.copy(in, out, true);
          files.addItem(new JsonLeafNode("", fileName));
        }
      }

      echo(j.toString());
    } else {
      error("enctype error!");
    }
  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse resp)
      throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();

    // Parse the request
    FileItemIterator iter;
    try {
      iter = upload.getItemIterator(request);

      while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
          System.out.println(
              "Form field " + name + " with value " + Streams.asString(stream) + " detected.");
        } else {
          System.out.println(
              "File field " + name + " with file name " + item.getName() + " detected.");
          // Process the input stream
          int read = 0;
          final byte[] bytes = new byte[1024];
          FileOutputStream fileOut = new FileOutputStream(new File(item.getName()));
          while ((read = stream.read(bytes)) != -1) {
            System.out.println("read " + read + " bytes");
            fileOut.write(bytes, 0, read);
          }
          stream.close();
          fileOut.close();
        }
      }
    } catch (FileUploadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    //		final Part filePart = req.getPart("file");
    //	    int read = 0;
    //        final byte[] bytes = new byte[1024];
    //        InputStream filecontent = filePart.getInputStream();
    //	    final String fileName = getFileName(filePart);
    //        FileOutputStream fileOut = new FileOutputStream(new File(fileName));
    //        while ((read = filecontent.read(bytes)) != -1) {
    //            System.out.println("read " + read + " bytes");
    //            fileOut.write(bytes, 0, read);
    //        }
    //        filecontent.close();
    //        fileOut.close();

  }
  /**
   * Parse request parameters and files.
   *
   * @param request
   * @param response
   */
  protected void parseRequest(HttpServletRequest request, HttpServletResponse response) {
    requestParams = new HashMap<String, Object>();
    listFiles = new ArrayList<FileItemStream>();
    listFileStreams = new ArrayList<ByteArrayOutputStream>();

    // Parse the request
    if (ServletFileUpload.isMultipartContent(request)) {
      // multipart request
      try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
          FileItemStream item = iter.next();
          String name = item.getFieldName();
          InputStream stream = item.openStream();
          if (item.isFormField()) {
            requestParams.put(name, Streams.asString(stream));
          } else {
            String fileName = item.getName();
            if (fileName != null && !"".equals(fileName.trim())) {
              listFiles.add(item);

              ByteArrayOutputStream os = new ByteArrayOutputStream();
              IOUtils.copy(stream, os);
              listFileStreams.add(os);
            }
          }
        }
      } catch (Exception e) {
        logger.error("Unexpected error parsing multipart content", e);
      }
    } else {
      // not a multipart
      for (Object mapKey : request.getParameterMap().keySet()) {
        String mapKeyString = (String) mapKey;

        if (mapKeyString.endsWith("[]")) {
          // multiple values
          String values[] = request.getParameterValues(mapKeyString);
          List<String> listeValues = new ArrayList<String>();
          for (String value : values) {
            listeValues.add(value);
          }
          requestParams.put(mapKeyString, listeValues);
        } else {
          // single value
          String value = request.getParameter(mapKeyString);
          requestParams.put(mapKeyString, value);
        }
      }
    }
  }
Exemplo n.º 6
0
  @POST
  @Path("port")
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public void importData(@Context HttpServletRequest request) throws IcatException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
      throw new IcatException(IcatExceptionType.BAD_PARAMETER, "Multipart content expected");
    }

    ServletFileUpload upload = new ServletFileUpload();
    String jsonString = null;
    String name = null;

    // Parse the request
    try {
      FileItemIterator iter = upload.getItemIterator(request);
      while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String fieldName = item.getFieldName();
        InputStream stream = item.openStream();
        if (item.isFormField()) {
          String value = Streams.asString(stream);
          if (fieldName.equals("json")) {
            jsonString = value;
          } else {
            throw new IcatException(
                IcatExceptionType.BAD_PARAMETER, "Form field " + fieldName + "is not recognised");
          }
        } else {
          if (name == null) {
            name = item.getName();
          }
          porter.importData(jsonString, stream, manager, userTransaction);
        }
      }
    } catch (FileUploadException e) {
      throw new IcatException(IcatExceptionType.INTERNAL, e.getClass() + " " + e.getMessage());
    }
  }
 /**
  * Reads <code>body-data</code> from the current <code>encapsulation</code> and writes its
  * contents into the output <code>Stream</code>.
  *
  * <p>Arbitrary large amounts of data can be processed by this method using a constant size
  * buffer. (see {@link #MultipartStream(InputStream,byte[],int, MultipartStream.ProgressNotifier)
  * constructor}).
  *
  * @param output The <code>Stream</code> to write data into. May be null, in which case this
  *     method is equivalent to {@link #discardBodyData()}.
  * @return the amount of data written.
  * @throws MalformedStreamException if the stream ends unexpectedly.
  * @throws IOException if an i/o error occurs.
  */
 public int readBodyData(OutputStream output) throws MalformedStreamException, IOException {
   final InputStream istream = newInputStream();
   return (int) Streams.copy(istream, output, false);
 }
  @SuppressWarnings("unchecked")
  public RequestParameterMapMultiPartImpl(
      BridgeContext bridgeContext, ClientDataRequest clientDataRequest) {

    try {

      PortletSession portletSession = clientDataRequest.getPortletSession();
      PortletContext portletContext = portletSession.getPortletContext();

      // Determine the uploaded files directory path according to the JSF 2.2 proposal:
      // https://javaserverfaces-spec-public.dev.java.net/issues/show_bug.cgi?id=690
      String uploadedFilesDir = portletContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILES_DIR);

      if (uploadedFilesDir == null) {
        uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);

        if (logger.isDebugEnabled()) {
          logger.debug(
              "The web.xml context-param name=[{0}] not found, using default system property=[{1}] value=[{2}]",
              new Object[] {CONTEXT_PARAM_UPLOADED_FILES_DIR, JAVA_IO_TMPDIR, uploadedFilesDir});
        }
      } else {

        if (logger.isDebugEnabled()) {
          logger.debug(
              "Using web.xml context-param name=[{0}] value=[{1}]",
              new Object[] {CONTEXT_PARAM_UPLOADED_FILES_DIR, uploadedFilesDir});
        }
      }

      // Using the portlet sessionId, determine a unique folder path and create the path if it does
      // not exist.
      String sessionId = portletSession.getId();
      File uploadedFilesPath = new File(uploadedFilesDir, sessionId);

      if (!uploadedFilesPath.exists()) {

        try {
          uploadedFilesPath.mkdirs();
        } catch (SecurityException e) {
          uploadedFilesDir = System.getProperty(JAVA_IO_TMPDIR);
          logger.error(
              "Security exception message=[{0}] when trying to create unique path=[{1}] so using default system property=[{2}] value=[{3}]",
              new Object[] {
                e.getMessage(), uploadedFilesPath.toString(), JAVA_IO_TMPDIR, uploadedFilesDir
              });
          uploadedFilesPath = new File(uploadedFilesDir, sessionId);
          uploadedFilesPath.mkdirs();
        }
      }

      // Initialize commons-fileupload with the file upload path.
      DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
      diskFileItemFactory.setRepository(uploadedFilesPath);

      // Initialize commons-fileupload so that uploaded temporary files are not automatically
      // deleted.
      diskFileItemFactory.setFileCleaningTracker(null);

      // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped
      // to disk
      // instead of staying in memory.
      diskFileItemFactory.setSizeThreshold(0);

      // Determine the max file upload size threshold in bytes.
      String uploadedFilesMaxSize =
          portletContext.getInitParameter(CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE);
      int fileMaxSize = DEFAULT_FILE_MAX_SIZE;

      if (uploadedFilesMaxSize == null) {

        if (logger.isDebugEnabled()) {
          logger.debug(
              "The web.xml context-param name=[{0}] not found, using default=[{1}] bytes",
              new Object[] {CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE});
        }
      } else {

        try {
          fileMaxSize = Integer.parseInt(uploadedFilesMaxSize);

          if (logger.isDebugEnabled()) {
            logger.debug(
                "Using web.xml context-param name=[{0}] value=[{1}] bytes",
                new Object[] {CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, fileMaxSize});
          }
        } catch (NumberFormatException e) {
          logger.error(
              "Invalid value=[{0}] for web.xml context-param name=[{1}] using default=[{2}] bytes.",
              new Object[] {
                uploadedFilesMaxSize, CONTEXT_PARAM_UPLOADED_FILE_MAX_SIZE, DEFAULT_FILE_MAX_SIZE
              });
        }
      }

      // Parse the request parameters and save all uploaded files in a map.
      PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
      portletFileUpload.setFileSizeMax(fileMaxSize);
      requestParameterMap = new HashMap<String, String>();
      requestParameterFileMap = new HashMap<String, List<UploadedFile>>();

      // Get the namespace that might be found in request parameter names.
      String namespace = bridgeContext.getPortletContainer().getResponseNamespace();

      // FACES-271: Include name+value pairs found in the ActionRequest.
      PortletContainer portletContainer = bridgeContext.getPortletContainer();
      Set<Map.Entry<String, String[]>> actionRequestParameterSet =
          clientDataRequest.getParameterMap().entrySet();

      for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {

        String parameterName = mapEntry.getKey();
        int pos = parameterName.indexOf(namespace);

        if (pos >= 0) {
          parameterName = parameterName.substring(pos + namespace.length());
        }

        String[] parameterValues = mapEntry.getValue();

        if (parameterValues.length > 0) {
          String fixedRequestParameterValue =
              portletContainer.fixRequestParameterValue(parameterValues[0]);
          requestParameterMap.put(parameterName, fixedRequestParameterValue);
          logger.debug(
              "Found in ActionRequest: {0}=[{1}]", parameterName, fixedRequestParameterValue);
        }
      }

      UploadedFileFactory uploadedFileFactory =
          (UploadedFileFactory) BridgeFactoryFinder.getFactory(UploadedFileFactory.class);

      // Begin parsing the request for file parts:
      try {
        FileItemIterator fileItemIterator = null;

        if (clientDataRequest instanceof ResourceRequest) {
          ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
          fileItemIterator =
              portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
        } else {
          ActionRequest actionRequest = (ActionRequest) clientDataRequest;
          fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
        }

        boolean optimizeNamespace =
            BooleanHelper.toBoolean(
                bridgeContext.getInitParameter(
                    BridgeConfigConstants.PARAM_OPTIMIZE_PORTLET_NAMESPACE1),
                true);

        if (fileItemIterator != null) {

          int totalFiles = 0;

          // For each field found in the request:
          while (fileItemIterator.hasNext()) {

            try {
              totalFiles++;

              // Get the stream of field data from the request.
              FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

              // Get field name from the field stream.
              String fieldName = fieldStream.getFieldName();

              // If namespace optimization is enabled and the namespace is present in the field
              // name,
              // then remove the portlet namespace from the field name.
              if (optimizeNamespace) {
                int pos = fieldName.indexOf(namespace);

                if (pos >= 0) {
                  fieldName = fieldName.substring(pos + namespace.length());
                }
              }

              // Get the content-type, and file-name from the field stream.
              String contentType = fieldStream.getContentType();
              boolean formField = fieldStream.isFormField();

              String fileName = null;

              try {
                fileName = fieldStream.getName();
              } catch (InvalidFileNameException e) {
                fileName = e.getName();
              }

              // Copy the stream of file data to a temporary file. NOTE: This is necessary even if
              // the
              // current field is a simple form-field because the call below to
              // diskFileItem.getString()
              // will fail otherwise.
              DiskFileItem diskFileItem =
                  (DiskFileItem)
                      diskFileItemFactory.createItem(fieldName, contentType, formField, fileName);
              Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

              // If the current field is a simple form-field, then save the form field value in the
              // map.
              if (diskFileItem.isFormField()) {
                String requestParameterValue =
                    diskFileItem.getString(clientDataRequest.getCharacterEncoding());
                String fixedRequestParameterValue =
                    portletContainer.fixRequestParameterValue(requestParameterValue);
                requestParameterMap.put(fieldName, fixedRequestParameterValue);
                logger.debug("{0}=[{1}]", fieldName, fixedRequestParameterValue);
              } else {

                File tempFile = diskFileItem.getStoreLocation();

                // If the copy was successful, then
                if (tempFile.exists()) {

                  // Copy the commons-fileupload temporary file to a file in the same temporary
                  // location, but with the filename provided by the user in the upload. This has
                  // two
                  // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                  // the file, the developer can have access to a semi-permanent file, because the
                  // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                  // temporary one.
                  String tempFileName = tempFile.getName();
                  String tempFileAbsolutePath = tempFile.getAbsolutePath();

                  String copiedFileName = stripIllegalCharacters(fileName);

                  String copiedFileAbsolutePath =
                      tempFileAbsolutePath.replace(tempFileName, copiedFileName);
                  File copiedFile = new File(copiedFileAbsolutePath);
                  FileUtils.copyFile(tempFile, copiedFile);

                  // If present, build up a map of headers.
                  Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                  FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                  if (fileItemHeaders != null) {
                    Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                    if (headerNameItr != null) {

                      while (headerNameItr.hasNext()) {
                        String headerName = headerNameItr.next();
                        Iterator<String> headerValuesItr = fileItemHeaders.getHeaders(headerName);
                        List<String> headerValues = new ArrayList<String>();

                        if (headerValuesItr != null) {

                          while (headerValuesItr.hasNext()) {
                            String headerValue = headerValuesItr.next();
                            headerValues.add(headerValue);
                          }
                        }

                        headersMap.put(headerName, headerValues);
                      }
                    }
                  }

                  // Put a valid UploadedFile instance into the map that contains all of the
                  // uploaded file's attributes, along with a successful status.
                  Map<String, Object> attributeMap = new HashMap<String, Object>();
                  String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                  String message = null;
                  UploadedFile uploadedFile =
                      uploadedFileFactory.getUploadedFile(
                          copiedFileAbsolutePath,
                          attributeMap,
                          diskFileItem.getCharSet(),
                          diskFileItem.getContentType(),
                          headersMap,
                          id,
                          message,
                          fileName,
                          diskFileItem.getSize(),
                          UploadedFile.Status.FILE_SAVED);

                  requestParameterMap.put(fieldName, copiedFileAbsolutePath);
                  addUploadedFile(fieldName, uploadedFile);
                  logger.debug(
                      "Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName);
                }
              }
            } catch (Exception e) {
              logger.error(e);

              UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
              String fieldName = Integer.toString(totalFiles);
              addUploadedFile(fieldName, uploadedFile);
            }
          }
        }
      }

      // If there was an error in parsing the request for file parts, then put a bogus UploadedFile
      // instance in
      // the map so that the developer can have some idea that something went wrong.
      catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile("unknown", uploadedFile);
      }

      clientDataRequest.setAttribute(PARAM_UPLOADED_FILES, requestParameterFileMap);

      // If not found in the request, Section 6.9 of the Bridge spec requires that the value of the
      // ResponseStateManager.RENDER_KIT_ID_PARAM request parameter be set to the value of the
      // "javax.portlet.faces.<portletName>.defaultRenderKitId" PortletContext attribute.
      String renderKitIdParam = requestParameterMap.get(ResponseStateManager.RENDER_KIT_ID_PARAM);

      if (renderKitIdParam == null) {
        renderKitIdParam = bridgeContext.getDefaultRenderKitId();

        if (renderKitIdParam != null) {
          requestParameterMap.put(ResponseStateManager.RENDER_KIT_ID_PARAM, renderKitIdParam);
        }
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
  }