Package com.liferay.faces.util.model

Examples of com.liferay.faces.util.model.UploadedFileFactory


          facesRequestParameterMap.addValue(parameterName, parameterValue);
        }
      }
    }

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder.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 = PortletConfigParam.OptimizePortletNamespace.getBooleanValue(portletConfig);

      if (fileItemIterator != null) {

        int totalFiles = 0;
        String namespace = facesRequestParameterMap.getNamespace();

        // 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 characterEncoding = clientDataRequest.getCharacterEncoding();
              String requestParameterValue = null;

              if (characterEncoding == null) {
                requestParameterValue = diskFileItem.getString();
              }
              else {
                requestParameterValue = diskFileItem.getString(characterEncoding);
              }

              facesRequestParameterMap.addValue(fieldName, requestParameterValue);
            }
            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);

                facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath);
                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                  fileName);
              }
              else {

                if ((fileName != null) && (fileName.trim().length() > 0)) {
                  Exception e = new IOException("Failed to copy the stream of uploaded file=[" +
                      fileName + "] to a temporary file (possibly a zero-length uploaded file)");
                  UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                  addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
              }
            }
          }
          catch (Exception e) {
            logger.error(e);

            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
            String fieldName = Integer.toString(totalFiles);
            addUploadedFile(uploadedFileMap, 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(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
  }
View Full Code Here


      uploadedFilesPath.mkdirs();
    }

    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

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

    // Begin parsing the request for file parts:
    try {

      HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
      Collection<Part> parts = httpServletRequest.getParts();
      int totalFiles = 0;

      // For each part found in the multipart/form-data request:
      for (Part part : parts) {

        try {
          totalFiles++;

          // Get field name and file name of the current part.
          String fieldName = null;
          String fileName = null;
          String safeFileName = null;

          String contentDispositionHeader = part.getHeader(HttpHeaders.CONTENT_DISPOSITION);
          String[] keyValuePairs = contentDispositionHeader.split(StringPool.SEMICOLON);

          for (String keyValuePair : keyValuePairs) {
            String trimmedKeyValuePair = keyValuePair.trim();

            if (trimmedKeyValuePair.startsWith("filename")) {
              int equalsPos = trimmedKeyValuePair.indexOf(StringPool.EQUAL);
              fileName = trimmedKeyValuePair.substring(equalsPos + 2, trimmedKeyValuePair.length() - 1);
              safeFileName = stripIllegalCharacters(fileName);
            }
            else if (trimmedKeyValuePair.startsWith(StringPool.NAME)) {
              int equalsPos = trimmedKeyValuePair.indexOf(StringPool.EQUAL);
              fieldName = trimmedKeyValuePair.substring(equalsPos + 2, trimmedKeyValuePair.length() - 1);
            }
          }

          if (fileName != null) {

            try {

              // Copy the stream of file data to a file.
              File copiedFile = new File(uploadedFilesPath, safeFileName);
              String copiedFileAbsolutePath = copiedFile.getAbsolutePath();
              part.write(copiedFileAbsolutePath);

              // If present, build up a map of headers.
              Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
              Collection<String> headerNames = part.getHeaderNames();

              for (String headerName : headerNames) {
                List<String> headerValues = new ArrayList<String>(part.getHeaders(headerName));
                headersMap.put(headerName, headerValues);
              }

              // Get the Content-Type header
              String contentType = part.getContentType();

              // Get the charset from the Content-Type header
              String charSet = null;

              if (contentType != null) {
                keyValuePairs = contentType.split(StringPool.SEMICOLON);

                for (String keyValuePair : keyValuePairs) {
                  String trimmedKeyValuePair = keyValuePair.trim();

                  if (trimmedKeyValuePair.startsWith("charset")) {
                    int equalsPos = trimmedKeyValuePair.indexOf(StringPool.EQUAL);
                    charSet = trimmedKeyValuePair.substring(equalsPos + 2,
                        trimmedKeyValuePair.length() - 1);
                  }
                }
              }

              // 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, charSet, contentType, headersMap, id, message, fileName,
                  part.getSize(), UploadedFile.Status.FILE_SAVED);

              addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
              logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName);

              // Delete temporary file created by the Servlet API.
              part.delete();
            }
            catch (IOException e) {
              UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
              addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
            }
          }
        }
        catch (Exception e) {
          logger.error(e);

          UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
          String fieldName = Integer.toString(totalFiles);
          addUploadedFile(uploadedFileMap, 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(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
  }
View Full Code Here

TOP

Related Classes of com.liferay.faces.util.model.UploadedFileFactory

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.