Search in sources :

Example 1 with UploadedFile

use of com.liferay.faces.util.model.UploadedFile in project liferay-faces-alloy by liferay.

the class InputFileBackingBean method deleteUploadedFile.

public void deleteUploadedFile(ActionEvent actionEvent) {
    UICommand uiCommand = (UICommand) actionEvent.getComponent();
    String fileId = (String) uiCommand.getValue();
    try {
        List<UploadedFile> uploadedFiles = inputFileModelBean.getUploadedFiles();
        UploadedFile uploadedFileToDelete = null;
        for (UploadedFile uploadedFile : uploadedFiles) {
            if (uploadedFile.getId().equals(fileId)) {
                uploadedFileToDelete = uploadedFile;
                break;
            }
        }
        if (uploadedFileToDelete != null) {
            uploadedFileToDelete.delete();
            uploadedFiles.remove(uploadedFileToDelete);
            logger.debug("Deleted file=[{0}]", uploadedFileToDelete.getName());
        }
    } catch (Exception e) {
        logger.error(e);
    }
}
Also used : UploadedFile(com.liferay.faces.util.model.UploadedFile) UICommand(javax.faces.component.UICommand)

Example 2 with UploadedFile

use of com.liferay.faces.util.model.UploadedFile in project liferay-faces-alloy by liferay.

the class InputFileRenderer method decode.

@Override
public void decode(FacesContext facesContext, UIComponent uiComponent) {
    InputFile inputFile = (InputFile) uiComponent;
    Map<String, List<UploadedFile>> uploadedFileMap = getUploadedFileMap(facesContext, inputFile.getLocation());
    if (uploadedFileMap != null) {
        String clientId = uiComponent.getClientId(facesContext);
        List<UploadedFile> uploadedFiles = uploadedFileMap.get(clientId);
        if ((uploadedFiles != null) && (uploadedFiles.size() > 0)) {
            inputFile.setSubmittedValue(uploadedFiles);
            // ActionListener.
            for (UploadedFile uploadedFile : uploadedFiles) {
                FileUploadEvent fileUploadEvent = new FileUploadEvent(uiComponent, uploadedFile);
                uiComponent.queueEvent(fileUploadEvent);
            }
        } else // FACES-3136: Ensure that the required attribute is enforced.
        {
            inputFile.setSubmittedValue(Collections.emptyList());
        }
    } else // FACES-3136: Ensure that the required attribute is enforced.
    {
        inputFile.setSubmittedValue(Collections.emptyList());
    }
}
Also used : UploadedFile(com.liferay.faces.util.model.UploadedFile) FileUploadEvent(com.liferay.faces.alloy.component.inputfile.FileUploadEvent) List(java.util.List) InputFile(com.liferay.faces.alloy.component.inputfile.InputFile)

Example 3 with UploadedFile

use of com.liferay.faces.util.model.UploadedFile in project liferay-faces-alloy by liferay.

the class InputFile method validateValue.

@Override
protected void validateValue(FacesContext facesContext, Object value) {
    super.validateValue(facesContext, value);
    if (isValid()) {
        Long maxFileSize = getMaxFileSize();
        String contentTypeSet = getContentTypes();
        if ((maxFileSize != null) || (contentTypeSet != null)) {
            Locale locale = facesContext.getViewRoot().getLocale();
            ExternalContext externalContext = facesContext.getExternalContext();
            I18n i18n = I18nFactory.getI18nInstance(externalContext);
            String clientId = getClientId(facesContext);
            @SuppressWarnings("unchecked") List<UploadedFile> uploadedFiles = (List<UploadedFile>) value;
            for (UploadedFile uploadedFile : uploadedFiles) {
                if ((maxFileSize != null) && (maxFileSize >= 0) && (uploadedFile.getSize() > maxFileSize)) {
                    String errorMessage = i18n.getMessage(facesContext, locale, "file-x-is-y-bytes-but-may-not-exceed-z-bytes", uploadedFile.getName(), uploadedFile.getSize(), maxFileSize);
                    handleInvalidFile(facesContext, clientId, uploadedFile, errorMessage);
                }
                String contentType = uploadedFile.getContentType();
                if ((contentType == null) || ((contentTypeSet != null) && !contentTypeSet.contains(contentType))) {
                    String errorMessage = i18n.getMessage(facesContext, locale, "file-x-has-an-invalid-content-type-y", uploadedFile.getName(), contentType);
                    handleInvalidFile(facesContext, clientId, uploadedFile, errorMessage);
                }
            }
        }
    }
}
Also used : Locale(java.util.Locale) UploadedFile(com.liferay.faces.util.model.UploadedFile) ExternalContext(javax.faces.context.ExternalContext) List(java.util.List) I18n(com.liferay.faces.util.i18n.I18n)

Example 4 with UploadedFile

use of com.liferay.faces.util.model.UploadedFile in project liferay-faces-bridge-impl by liferay.

the class MultiPartFormDataProcessorCompatImpl method iterateOver.

/* package-private */
Map<String, List<UploadedFile>> iterateOver(ClientDataRequest clientDataRequest, PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap, File uploadedFilesPath) {
    // Parse the request parameters and save all uploaded files in a map.
    Map<String, List<UploadedFile>> uploadedFileMap = new HashMap<>();
    // Determine the max file upload size threshold (in bytes).
    long defaultMaxFileSize = PortletConfigParam.UploadedFileMaxSize.getDefaultLongValue();
    long uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getLongValue(portletConfig);
    if (defaultMaxFileSize != uploadedFileMaxSize) {
        logger.warn("Ignoring init param {0}=[{1}] since it has been replaced by <multipart-config> in web.xml", PortletConfigParam.UploadedFileMaxSize.getName(), uploadedFileMaxSize);
    }
    // FACES-271: Include name+value pairs found in the ActionRequest/ResourceRequest.
    PortletParameters portletParameters;
    boolean actionPhase;
    if (clientDataRequest instanceof ActionRequest) {
        actionPhase = true;
        ActionRequest actionRequest = (ActionRequest) clientDataRequest;
        portletParameters = actionRequest.getActionParameters();
    } else {
        actionPhase = false;
        ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
        portletParameters = resourceRequest.getResourceParameters();
    }
    Set<String> fullyQualifiedParameterNames = new HashSet<>(Collections.list(clientDataRequest.getParameterNames()));
    Set<String> portletParameterNames = portletParameters.getNames();
    for (String parameterName : portletParameterNames) {
        // the portlet namespace.
        if (!fullyQualifiedParameterNames.contains(parameterName)) {
            String fullyQualifiedParameterName = facesRequestParameterMap.getNamespace() + parameterName;
            if (fullyQualifiedParameterNames.contains(fullyQualifiedParameterName)) {
                parameterName = fullyQualifiedParameterName;
            }
        }
        String[] parameterValues = portletParameters.getValues(parameterName);
        if (parameterValues.length > 0) {
            for (String parameterValue : parameterValues) {
                facesRequestParameterMap.addValue(parameterName, parameterValue);
                if (actionPhase) {
                    logger.debug("Added action parameter name={0} value={1}", parameterName, parameterValue);
                } else {
                    logger.debug("Added resource parameter name={0} value={1}", parameterName, parameterValue);
                }
            }
        }
    }
    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder.getFactory(portletConfig.getPortletContext(), UploadedFileFactory.class);
    // Begin parsing the request for file parts:
    try {
        Collection<Part> parts = clientDataRequest.getParts();
        List<String> fileUploadFieldNames = new ArrayList<String>();
        int totalFiles = 0;
        // For each field found in the request:
        for (Part part : parts) {
            String fieldName = part.getName();
            fileUploadFieldNames.add(fieldName);
            try {
                totalFiles++;
                String characterEncoding = clientDataRequest.getCharacterEncoding();
                String contentDispositionHeader = part.getHeader("content-disposition");
                String fileName = getValidFileName(contentDispositionHeader);
                // If the current field is a simple form-field, then save the form field value in the map.
                if ((fileName != null) && (fileName.length() > 0)) {
                    File uploadedFilePath = new File(uploadedFilesPath, fileName);
                    String uploadedFilePathAbsolutePath = uploadedFilePath.getAbsolutePath();
                    part.write(uploadedFilePathAbsolutePath);
                    // If the copy was successful, then
                    if (uploadedFilePath.exists()) {
                        // If present, build up a map of headers. According to Hypertext Transfer Protocol --
                        // HTTP/1.1 (http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2), header names
                        // are case-insensitive. In order to support this, use a TreeMap with case insensitive
                        // keys.
                        Map<String, List<String>> headersMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
                        Collection<String> headerNames = part.getHeaderNames();
                        for (String headerName : headerNames) {
                            Collection<String> headerValues = part.getHeaders(headerName);
                            List<String> headerValueList = new ArrayList<>();
                            for (String headerValue : headerValues) {
                                headerValueList.add(headerValue);
                            }
                            headersMap.put(headerName, headerValueList);
                        }
                        // 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 id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                        com.liferay.faces.util.model.UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(uploadedFilePathAbsolutePath, attributeMap, characterEncoding, part.getContentType(), headersMap, id, null, fileName, part.getSize(), com.liferay.faces.util.model.UploadedFile.Status.FILE_SAVED);
                        facesRequestParameterMap.addValue(fieldName, uploadedFilePathAbsolutePath);
                        addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                        logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName);
                    } else {
                        if (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)");
                            com.liferay.faces.util.model.UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                        }
                    }
                }
            } catch (Exception e) {
                logger.error(e);
                com.liferay.faces.util.model.UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                String totalFilesfieldName = Integer.toString(totalFiles);
                addUploadedFile(uploadedFileMap, totalFilesfieldName, uploadedFile);
            }
        }
        for (String fileUploadFieldName : fileUploadFieldNames) {
            // value.
            if (!uploadedFileMap.containsKey(fileUploadFieldName)) {
                uploadedFileMap.put(fileUploadFieldName, Collections.<UploadedFile>emptyList());
            }
        }
    }// the map so that the developer can have some idea that something went wrong.
     catch (Exception e) {
        logger.error(e);
        com.liferay.faces.util.model.UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }
    return uploadedFileMap;
}
Also used : HashMap(java.util.HashMap) UploadedFile(com.liferay.faces.util.model.UploadedFile) ArrayList(java.util.ArrayList) PortletParameters(javax.portlet.PortletParameters) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) UploadedFileFactory(com.liferay.faces.util.model.UploadedFileFactory) IOException(java.io.IOException) TreeMap(java.util.TreeMap) IOException(java.io.IOException) UploadedFile(com.liferay.faces.util.model.UploadedFile) ActionRequest(javax.portlet.ActionRequest) Part(javax.servlet.http.Part) ResourceRequest(javax.portlet.ResourceRequest) UploadedFile(com.liferay.faces.util.model.UploadedFile) File(java.io.File)

Example 5 with UploadedFile

use of com.liferay.faces.util.model.UploadedFile in project liferay-faces-bridge-impl by liferay.

the class UploadedFileWrapper method getFile.

/**
 * Since the PrimeFaces UploadedFile interface does not provide a method for deleting the file, Liferay Faces Bridge
 * automatically deletes it when the wrappedUploadedFile.getContents() method is called.
 */
protected File getFile(String uniqueFolderName) {
    File file = null;
    try {
        File tempFolder = new File(System.getProperty("java.io.tmpdir"));
        File uniqueFolder = new File(tempFolder, uniqueFolderName);
        if (!uniqueFolder.exists()) {
            uniqueFolder.mkdirs();
        }
        String fileNamePrefix = "attachment" + getId();
        String fileNameSuffix = ".dat";
        file = File.createTempFile(fileNamePrefix, fileNameSuffix, uniqueFolder);
        OutputStream outputStream = new FileOutputStream(file);
        outputStream.write(wrappedUploadedFile.getContent());
        outputStream.close();
    // Temporary file maintained by PrimeFaces is automatically deleted. See JavaDoc comments above.
    } catch (Exception e) {
        logger.error(e);
    }
    return file;
}
Also used : OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) RandomAccessFile(java.io.RandomAccessFile) UploadedFile(com.liferay.faces.util.model.UploadedFile) File(java.io.File) IOException(java.io.IOException)

Aggregations

UploadedFile (com.liferay.faces.util.model.UploadedFile)10 File (java.io.File)6 IOException (java.io.IOException)5 List (java.util.List)5 UploadedFileFactory (com.liferay.faces.util.model.UploadedFileFactory)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 ExternalContext (javax.faces.context.ExternalContext)3 FacesContext (javax.faces.context.FacesContext)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 Part (javax.servlet.http.Part)2 FileUploadEvent (com.liferay.faces.alloy.component.inputfile.FileUploadEvent)1 InputFile (com.liferay.faces.alloy.component.inputfile.InputFile)1 Attachment (com.liferay.faces.demos.applicant.alloy.facelets.dto.Attachment)1 I18n (com.liferay.faces.util.i18n.I18n)1 FileOutputStream (java.io.FileOutputStream)1 OutputStream (java.io.OutputStream)1 RandomAccessFile (java.io.RandomAccessFile)1 HashSet (java.util.HashSet)1 Locale (java.util.Locale)1