protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    super.doPost(request, response);

    try {
      if (!ServletFileUpload.isMultipartContent(request)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
      }

      ServletFileUpload sfU = new ServletFileUpload();
      FileItemIterator items = sfU.getItemIterator(request);
      while (items.hasNext()) {
        FileItemStream item = items.next();
        if (!item.isFormField()) {
          InputStream stream = item.openStream();
          Document doc = editor.toDocument(stream);
          stream.close();
          handleDocument(request, response, doc);
          return;
        }
      }

      response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No XML uploaded");
    } catch (FileUploadException fuE) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, fuE.getMessage());
    } catch (JDOMException jE) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST, jE.getMessage());
    }
  }
Esempio n. 2
0
 /**
  * Convert a String in xs:anyURI to an xs:base64Binary.
  *
  * <p>The URI has to be a URL. It is read entirely
  */
 public static String anyURIToBase64Binary(String value) {
   InputStream is = null;
   try {
     // Read from URL and convert to Base64
     is = URLFactory.createURL(value).openStream();
     final StringBuffer sb = new StringBuffer();
     XMLUtils.inputStreamToBase64Characters(
         is,
         new ContentHandlerAdapter() {
           public void characters(char ch[], int start, int length) {
             sb.append(ch, start, length);
           }
         });
     // Return Base64 String
     return sb.toString();
   } catch (IOException e) {
     throw new OXFException(e);
   } finally {
     if (is != null) {
       try {
         is.close();
       } catch (IOException e) {
         throw new OXFException(e);
       }
     }
   }
 }
Esempio n. 3
0
 public static String readURIToLocalURI(String uri) throws URISyntaxException, IOException {
   final PipelineContext pipelineContext =
       StaticExternalContext.getStaticContext().getPipelineContext();
   final URLConnection urlConnection = new URI(uri).toURL().openConnection();
   InputStream inputStream = null;
   try {
     inputStream = urlConnection.getInputStream();
     return inputStreamToAnyURI(pipelineContext, inputStream, REQUEST_SCOPE);
   } finally {
     if (inputStream != null) inputStream.close();
   }
 }
Esempio n. 4
0
 /**
  * Read a URI into a byte array.
  *
  * @param uri URI to read
  * @return byte array
  */
 public static byte[] uriToByteArray(String uri) {
   InputStream is = null;
   try {
     is = new URI(uri).toURL().openStream();
     return inputStreamToByteArray(is);
   } catch (Exception e) {
     throw new OXFException(e);
   } finally {
     try {
       if (is != null) is.close();
     } catch (IOException e) {
       throw new OXFException(e);
     }
   }
 }
Esempio n. 5
0
 public static void anyURIToOutputStream(String value, OutputStream outputStream) {
   InputStream is = null;
   try {
     is = URLFactory.createURL(value).openStream();
     copyStream(is, outputStream);
   } catch (IOException e) {
     throw new OXFException(e);
   } finally {
     if (is != null) {
       try {
         is.close();
       } catch (IOException e) {
         throw new OXFException(e);
       }
     }
   }
 }
Esempio n. 6
0
  /**
   * Convert a URI to a FileItem.
   *
   * <p>The implementation creates a temporary file. The PipelineContext is required so that the
   * file can be deleted when no longer used.
   */
  public static FileItem anyURIToFileItem(PipelineContext pipelineContext, String uri, int scope) {
    InputStream inputStream = null;
    try {
      inputStream = new URI(uri).toURL().openStream();

      // Get FileItem
      return prepareFileItemFromInputStream(pipelineContext, inputStream, scope);

    } catch (Exception e) {
      throw new OXFException(e);
    } finally {
      try {
        if (inputStream != null) inputStream.close();
      } catch (IOException e) {
        throw new OXFException(e);
      }
    }
  }
Esempio n. 7
0
 /**
  * Get the last modification date of a URL.
  *
  * @return last modified timestamp "as is"
  */
 public static long getLastModified(URL url) throws IOException {
   if ("file".equals(url.getProtocol())) {
     // Optimize file: access. Also, this prevents throwing an exception if the file doesn't exist
     // as we try to close the stream below.
     return new File(URLDecoder.decode(url.getFile(), STANDARD_PARAMETER_ENCODING)).lastModified();
   } else {
     // Use URLConnection
     final URLConnection urlConnection = url.openConnection();
     if (urlConnection instanceof HttpURLConnection)
       ((HttpURLConnection) urlConnection).setRequestMethod("HEAD");
     try {
       return getLastModified(urlConnection);
     } finally {
       final InputStream is = urlConnection.getInputStream();
       if (is != null) is.close();
     }
   }
 }
Esempio n. 8
0
  /**
   * Utility method to decode a multipart/fomr-data stream and return a Map of parameters of type
   * Object[], each of which can be a String or FileData.
   */
  public static Map<String, Object[]> getParameterMapMultipart(
      PipelineContext pipelineContext,
      final ExternalContext.Request request,
      String headerEncoding) {

    final Map<String, Object[]> uploadParameterMap = new HashMap<String, Object[]>();
    try {
      // Setup commons upload

      // Read properties
      // NOTE: We use properties scoped in the Request generator for historical reasons. Not too
      // good.
      int maxSize = RequestGenerator.getMaxSizeProperty();
      int maxMemorySize = RequestGenerator.getMaxMemorySizeProperty();

      final DiskFileItemFactory diskFileItemFactory =
          new DiskFileItemFactory(maxMemorySize, SystemUtils.getTemporaryDirectory());

      final ServletFileUpload upload =
          new ServletFileUpload(diskFileItemFactory) {
            protected FileItem createItem(Map headers, boolean isFormField)
                throws FileUploadException {
              if (isFormField) {
                // Handle externalized values
                final String externalizeFormValuesPrefix =
                    org.orbeon.oxf.properties.Properties.instance()
                        .getPropertySet()
                        .getString(ServletExternalContext.EXTERNALIZE_FORM_VALUES_PREFIX_PROPERTY);
                final String fieldName = getFieldName(headers);
                if (externalizeFormValuesPrefix != null
                    && fieldName.startsWith(externalizeFormValuesPrefix)) {
                  // In this case, we do as if the value content is an uploaded file so that it can
                  // be externalized
                  return super.createItem(headers, false);
                } else {
                  // Just create the FileItem using the default way
                  return super.createItem(headers, isFormField);
                }
              } else {
                // Just create the FileItem using the default way
                return super.createItem(headers, isFormField);
              }
            }
          };
      upload.setHeaderEncoding(headerEncoding);
      upload.setSizeMax(maxSize);

      // Add a listener to destroy file items when the pipeline context is destroyed
      pipelineContext.addContextListener(
          new PipelineContext.ContextListenerAdapter() {
            public void contextDestroyed(boolean success) {
              for (final String name : uploadParameterMap.keySet()) {
                final Object values[] = uploadParameterMap.get(name);
                for (final Object currentValue : values) {
                  if (currentValue instanceof FileItem) {
                    final FileItem fileItem = (FileItem) currentValue;
                    fileItem.delete();
                  }
                }
              }
            }
          });

      // Wrap and implement just the required methods for the upload code
      final InputStream inputStream;
      try {
        inputStream = request.getInputStream();
      } catch (IOException e) {
        throw new OXFException(e);
      }

      final RequestContext requestContext =
          new RequestContext() {

            public int getContentLength() {
              return request.getContentLength();
            }

            public InputStream getInputStream() {
              // NOTE: The upload code does not actually check that it doesn't read more than the
              // content-length
              // sent by the client! Maybe here would be a good place to put an interceptor and make
              // sure we
              // don't read too much.
              return new InputStream() {
                public int read() throws IOException {
                  return inputStream.read();
                }
              };
            }

            public String getContentType() {
              return request.getContentType();
            }

            public String getCharacterEncoding() {
              return request.getCharacterEncoding();
            }
          };

      // Parse the request and add file information
      try {
        for (Object o : upload.parseRequest(requestContext)) {
          final FileItem fileItem = (FileItem) o;
          // Add value to existing values if any
          if (fileItem.isFormField()) {
            // Simple form field
            // Assume that form fields are in UTF-8. Can they have another encoding? If so, how is
            // it specified?
            StringUtils.addValueToObjectArrayMap(
                uploadParameterMap,
                fileItem.getFieldName(),
                fileItem.getString(STANDARD_PARAMETER_ENCODING));
          } else {
            // File
            StringUtils.addValueToObjectArrayMap(
                uploadParameterMap, fileItem.getFieldName(), fileItem);
          }
        }
      } catch (FileUploadBase.SizeLimitExceededException e) {
        // Should we do something smart so we can use the Presentation
        // Server error page anyway? Right now, this is going to fail
        // miserably with an error.
        throw e;
      } catch (UnsupportedEncodingException e) {
        // Should not happen
        throw new OXFException(e);
      } finally {
        // Close the input stream; if we don't nobody does, and if this stream is
        // associated with a temporary file, that file may resist deletion
        if (inputStream != null) {
          try {
            inputStream.close();
          } catch (IOException e) {
            throw new OXFException(e);
          }
        }
      }

      return uploadParameterMap;
    } catch (FileUploadException e) {
      throw new OXFException(e);
    }
  }
Esempio n. 9
0
  /**
   * 文件的上传服务
   *
   * @param request
   * @return
   * @throws FileUploadException
   * @throws IOException
   */
  public FileRepository uploadFile(HttpServletRequest request)
      throws FileUploadException, IOException {

    boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
    FileRepository fileRepository = null;
    if (isMultipartContent) {
      FileItemFactory factory = new DiskFileItemFactory();
      ServletFileUpload upload = new ServletFileUpload(factory);
      List<FileItem> items = upload.parseRequest(request);
      for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext(); ) {
        FileItem item = iterator.next();
        InputStream inputStream = item.getInputStream();
        // 获得文件名
        String fileName = item.getName();
        String fileExtension = FileUtil.getFileExtension(fileName);
        // 获得文件的Extension类型
        MimeTypeExtension mimeTypeExtension =
            mimeTypeExtensionService.findByMimeTypeExtensionName(fileExtension);
        fileRepository = new FileRepository();
        FixEntityUtil.fixEntity(fileRepository);
        String fileRepoId = fileRepository.getId();
        fileRepository.setMimeTypeExtensionName(fileExtension);
        if (mimeTypeExtension.getMimeType() != null) {
          fileRepository.setMimeTypeName(mimeTypeExtension.getMimeType().getMimeTypeName());
        }
        fileRepository.setFileName(fileName);
        String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        String saveFilePath = Config.UPLOAD_FILE_PATH + "/" + datePath + "/";
        File file = new File(saveFilePath);
        if (!file.exists()) {
          file.mkdirs();
        }

        file = new File(saveFilePath + fileRepoId + ".xzsoft");
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int byteRead = 0;
        byte[] buffer = new byte[8192];
        while ((byteRead = inputStream.read(buffer, 0, 8192)) != -1) {
          out.write(buffer, 0, byteRead);
        }

        inputStream.close();
        // 将上传的文件变Base64加密过的字符串
        String content = Base64.encode(out.toByteArray());
        out.close();

        // 将加密过后的数据存储到硬盘中
        FileWriter fileWriter = new FileWriter(file);
        BufferedWriter bw = new BufferedWriter(fileWriter);
        bw.write(content);
        bw.flush();
        fileWriter.flush();
        bw.close();
        fileWriter.close();
      }

    } else {
      throw new NotMultipartRequestException("上传的文件里面没有Multipart内容");
    }

    return fileRepository;
  }