Example usage for com.liferay.portal.kernel.util FileUtil getExtension

List of usage examples for com.liferay.portal.kernel.util FileUtil getExtension

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.util FileUtil getExtension.

Prototype

public static String getExtension(String fileName) 

Source Link

Usage

From source file:com.bemis.portal.fileuploader.service.impl.FileUploaderLocalServiceImpl.java

License:Open Source License

public void uploadFiles(long companyId, long groupId, long userId, File file, long fileTypeId,
        String[] assetTagNames) throws IOException, PortalException {

    String fileName = file.getName();

    if (!fileName.endsWith(".zip")) {
        if (_log.isWarnEnabled()) {
            _log.warn(">>> Unsupported compressed file type. Supports ZIP" + "compressed files only. ");
        }//from  w ww.j  a va2  s. c om

        throw new FileUploaderException("error.unsupported-file-type");
    }

    DataOutputStream outputStream = null;

    try (ZipInputStream inputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)))) {

        ZipEntry fileEntry;
        while ((fileEntry = inputStream.getNextEntry()) != null) {
            boolean isDir = fileEntry.isDirectory();
            boolean isSubDirFile = fileEntry.getName().contains(SLASH);

            if (isDir || isSubDirFile) {
                if (_log.isWarnEnabled()) {
                    _log.warn(">>> Directory found inside the zip file " + "uploaded.");
                }

                continue;
            }

            String fileEntryName = fileEntry.getName();

            String extension = PERIOD + FileUtil.getExtension(fileEntryName);

            File tempFile = null;

            try {
                tempFile = File.createTempFile("tempfile", extension);

                byte[] buffer = new byte[INPUT_BUFFER];

                outputStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tempFile)));

                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.flush();

                String fileDescription = BLANK;
                String changeLog = BLANK;

                uploadFile(companyId, groupId, userId, tempFile, fileDescription, fileEntryName, fileTypeId,
                        changeLog, assetTagNames);
            } finally {
                StreamUtil.cleanUp(outputStream);

                if ((tempFile != null) && tempFile.exists()) {
                    tempFile.delete();
                }
            }
        }
    } catch (FileNotFoundException fnfe) {
        if (_log.isWarnEnabled()) {
            _log.warn(">>> Unable to upload files" + fnfe);
        }
    }
}

From source file:com.fmdp.webform.portlet.WebFormPortlet.java

License:Open Source License

public void saveData(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
    ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);

    String portletId = PortalUtil.getPortletId(actionRequest);

    PortletPreferences preferences = PortletPreferencesFactoryUtil.getPortletSetup(actionRequest, portletId);

    boolean requireCaptcha = GetterUtil.getBoolean(preferences.getValue("requireCaptcha", StringPool.BLANK));
    String successURL = GetterUtil.getString(preferences.getValue("successURL", StringPool.BLANK));
    boolean sendAsEmail = GetterUtil.getBoolean(preferences.getValue("sendAsEmail", StringPool.BLANK));
    boolean sendThanksEmail = GetterUtil.getBoolean(preferences.getValue("sendThanksEmail", StringPool.BLANK));
    boolean saveToDatabase = GetterUtil.getBoolean(preferences.getValue("saveToDatabase", StringPool.BLANK));
    String databaseTableName = GetterUtil
            .getString(preferences.getValue("databaseTableName", StringPool.BLANK));
    boolean saveToFile = GetterUtil.getBoolean(preferences.getValue("saveToFile", StringPool.BLANK));
    boolean uploadToDisk = GetterUtil.getBoolean(preferences.getValue("uploadToDisk", StringPool.BLANK));
    boolean uploadToDM = GetterUtil.getBoolean(preferences.getValue("uploadToDM", StringPool.BLANK));
    long newFolderId = GetterUtil.getLong(preferences.getValue("newFolderId", StringPool.BLANK));
    String fileName = GetterUtil.getString(preferences.getValue("fileName", StringPool.BLANK));
    String uploadDiskDir = GetterUtil.getString(preferences.getValue("uploadDiskDir", StringPool.BLANK));

    if (requireCaptcha) {
        try {//from w  w w  . j a  va2 s.c o  m
            CaptchaUtil.check(actionRequest);
        } catch (CaptchaTextException cte) {
            SessionErrors.add(actionRequest, CaptchaTextException.class.getName());

            return;
        }
    }

    UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);

    Map<String, String> fieldsMap = new LinkedHashMap<String, String>();

    String fileAttachment = "";

    for (int i = 1; true; i++) {
        String fieldLabel = preferences.getValue("fieldLabel" + i, StringPool.BLANK);

        String fieldType = preferences.getValue("fieldType" + i, StringPool.BLANK);

        if (Validator.isNull(fieldLabel)) {
            break;
        }

        if (StringUtil.equalsIgnoreCase(fieldType, "paragraph")) {
            continue;
        }
        if (StringUtil.equalsIgnoreCase(fieldType, "file")) {
            if (_log.isDebugEnabled()) {
                _log.debug("Field name for file: " + fieldLabel);
            }

            File file = uploadRequest.getFile("field" + i);

            String sourceFileName = uploadRequest.getFileName("field" + i);
            if (_log.isDebugEnabled()) {
                _log.debug("File attachment: " + sourceFileName);
            }
            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

            if (Validator.isNotNull(sourceFileName) && !"".equals(sourceFileName)) {

                if (uploadRequest.getSize("field" + i) == 0) {
                    SessionErrors.add(actionRequest, "uploadToDiskError", "Uploaded file size is 0");
                    if (_log.isDebugEnabled()) {
                        _log.debug("Uploaded file size is 0");
                    }
                    return;
                }
                //               List<String> uploadResults = new ArrayList<String>();
                String uploadResult = "";
                if (uploadToDisk) {
                    uploadResult = uploadFile(file, sourceFileName, uploadDiskDir);
                    if (uploadResult.equalsIgnoreCase("File Upload Error")) {
                        SessionErrors.add(actionRequest, "uploadToDiskError", uploadResult);
                        return;
                    }
                    fileAttachment = uploadDiskDir + File.separator + uploadResult;
                    //uploadResults.add(uploadResult);
                    jsonObject.put("fsOriginalName", sourceFileName);
                    jsonObject.put("fsName", uploadResult);
                }
                if (uploadToDM) {
                    uploadResult = "";
                    String contentType = MimeTypesUtil.getContentType(file);
                    Folder folderName = DLAppLocalServiceUtil.getFolder(newFolderId);
                    if (_log.isDebugEnabled()) {
                        _log.debug("DM Folder: " + folderName.getName());
                    }
                    InputStream inputStream = new FileInputStream(file);
                    long repositoryId = folderName.getRepositoryId();
                    try {
                        String selectedFileName = sourceFileName;
                        while (true) {
                            try {
                                DLAppLocalServiceUtil.getFileEntry(themeDisplay.getScopeGroupId(), newFolderId,
                                        selectedFileName);

                                StringBundler sb = new StringBundler(5);

                                sb.append(FileUtil.stripExtension(selectedFileName));
                                sb.append(StringPool.DASH);
                                sb.append(StringUtil.randomString());
                                sb.append(StringPool.PERIOD);
                                sb.append(FileUtil.getExtension(selectedFileName));

                                selectedFileName = sb.toString();
                            } catch (Exception e) {
                                break;
                            }
                        }

                        FileEntry fileEntry = DLAppLocalServiceUtil.addFileEntry(themeDisplay.getUserId(),
                                repositoryId, newFolderId, selectedFileName, //file.getName(), 
                                contentType, selectedFileName, "", "", inputStream, file.length(),
                                serviceContext);
                        if (_log.isDebugEnabled()) {
                            _log.debug("DM file uploade: " + fileEntry.getTitle());
                        }
                        //Map<String, Serializable> workflowContext = new HashMap<String, Serializable>();
                        //workflowContext.put("event",DLSyncConstants.EVENT_UPDATE);
                        //DLFileEntryLocalServiceUtil.updateStatus(themeDisplay.getUserId(), fileEntry.getFileVersion().getFileVersionId(), WorkflowConstants.STATUS_APPROVED, workflowContext, serviceContext);
                        uploadResult = String.valueOf(fileEntry.getFileEntryId());
                        //uploadResults.add(uploadResult);
                        String docUrl = themeDisplay.getPortalURL() + "/c/document_library/get_file?uuid="
                                + fileEntry.getUuid() + "&groupId=" + themeDisplay.getScopeGroupId();
                        jsonObject.put("fe", uploadResult);
                        jsonObject.put("feOriginalName", sourceFileName);
                        jsonObject.put("feName", fileEntry.getTitle());
                        jsonObject.put("feUrl", docUrl);
                    } catch (PortalException pe) {
                        SessionErrors.add(actionRequest, "uploadToDmError");
                        _log.error("The upload to DM failed", pe);
                        return;
                    } catch (Exception e) {
                        _log.error("The upload to DM failed", e);
                        return;
                    }
                }
                jsonObject.put("Status", "With Attachment");
            } else {
                jsonObject.put("Status", "No Attachment");
            }
            fieldsMap.put(fieldLabel, jsonObject.toString());
        } else {
            fieldsMap.put(fieldLabel, uploadRequest.getParameter("field" + i));
        }
    }

    Set<String> validationErrors = null;

    try {
        validationErrors = validate(fieldsMap, preferences);
    } catch (Exception e) {
        SessionErrors.add(actionRequest, "validationScriptError", e.getMessage().trim());

        return;
    }

    User currentUser = PortalUtil.getUser(actionRequest);
    String userEmail = "";
    if (!Validator.isNull(currentUser)) {
        userEmail = currentUser.getEmailAddress();
        if (_log.isDebugEnabled()) {
            _log.debug("User email for the form author: " + userEmail);
        }

        fieldsMap.put("email-from", userEmail);
    } else {
        fieldsMap.put("email-from", "guest");
    }

    DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone(themeDisplay.getTimeZone().getID()));
    Date dateobj = new Date();
    fieldsMap.put("email-sent-on", df.format(dateobj));

    if (validationErrors.isEmpty()) {
        boolean emailSuccess = true;
        boolean databaseSuccess = true;
        boolean fileSuccess = true;
        boolean emailThanksSuccess = true;

        if (sendAsEmail) {
            emailSuccess = WebFormUtil.sendEmail(themeDisplay.getCompanyId(), fieldsMap, preferences,
                    fileAttachment);
        }

        if (sendThanksEmail && !Validator.isNull(currentUser)) {
            emailThanksSuccess = WebFormUtil.sendThanksEmail(themeDisplay.getCompanyId(), fieldsMap,
                    preferences, userEmail);
        }

        if (saveToDatabase) {
            if (Validator.isNull(databaseTableName)) {
                databaseTableName = WebFormUtil.getNewDatabaseTableName(portletId);

                preferences.setValue("databaseTableName", databaseTableName);

                preferences.store();
            }

            databaseSuccess = saveDatabase(themeDisplay.getCompanyId(), fieldsMap, preferences,
                    databaseTableName);
        }

        if (saveToFile) {
            fileSuccess = saveFile(fieldsMap, fileName);
        }

        if (emailSuccess && emailThanksSuccess && databaseSuccess && fileSuccess) {
            if (Validator.isNull(successURL)) {
                SessionMessages.add(actionRequest, "success");
            } else {
                SessionMessages.add(actionRequest,
                        portletId + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_SUCCESS_MESSAGE);
            }
        } else {
            SessionErrors.add(actionRequest, "error");
        }
    } else {
        for (String badField : validationErrors) {
            SessionErrors.add(actionRequest, "error" + badField);
        }
    }

    if (SessionErrors.isEmpty(actionRequest) && Validator.isNotNull(successURL)) {

        actionResponse.sendRedirect(successURL);
    }
}

From source file:com.fmdp.webform.portlet.WebFormPortlet.java

License:Open Source License

public String uploadFile(File file, String sourceFileName, String folder) throws PortletException, IOException {

    //String realPath = getPortletContext().getRealPath("/");
    String fsep = File.separator;

    if (_log.isDebugEnabled()) {
        _log.debug("Folder to upload: " + folder);
    }/*from w  w w  .j  a  va 2 s . co m*/

    try {

        if (_log.isDebugEnabled()) {
            _log.debug("Source file name to upload: " + sourceFileName);
        }

        File newFolder = null;
        newFolder = new File(folder);
        if (!newFolder.exists()) {
            newFolder.mkdir();
        }
        File newfile = null;
        String filename = newFolder.getAbsoluteFile() + fsep + sourceFileName;
        String originalFileName = sourceFileName;
        newfile = new File(filename);
        int j = 0;

        while (newfile.exists()) {
            j++;
            String ext = FileUtil.getExtension(originalFileName);
            filename = newFolder.getAbsoluteFile() + fsep + stripExtension(originalFileName) + "("
                    + Integer.toString(j) + ")." + ext;
            newfile = new File(filename);
        }
        if (_log.isDebugEnabled()) {
            _log.debug("New file name: " + newfile.getName());
            _log.debug("New file path: " + newfile.getPath());
        }

        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(newfile);

        byte[] bytes_ = FileUtil.getBytes(file);
        int i = fis.read(bytes_);

        while (i != -1) {
            fos.write(bytes_, 0, i);
            i = fis.read(bytes_);
        }
        fis.close();
        fos.close();
        Float size = (float) newfile.length();
        if (_log.isDebugEnabled()) {
            _log.debug("file size bytes: " + size);
            _log.debug("file size Mb: " + size / 1048576);
            _log.debug("File created: " + newfile.getName());
        }

        return newfile.getName();

    } catch (FileNotFoundException e) {
        _log.error("File Not Found.");
        e.printStackTrace();
        return "File Upload Error";
    } catch (NullPointerException e) {
        _log.error("File Not Found.");
        e.printStackTrace();
        return "File Upload Error";
    }

    catch (IOException e1) {
        _log.error("Error Reading The File.");
        e1.printStackTrace();
        return "File Upload Error.";
    }

}

From source file:com.liferay.blogs.web.internal.upload.BaseBlogsUploadHandler.java

License:Open Source License

@Override
public void validateFile(String fileName, String contentType, long size) throws PortalException {

    long maxSize = getMaxFileSize();

    if ((maxSize > 0) && (size > maxSize)) {
        throw new EntryImageSizeException();
    }/*from ww  w . ja  va2s.c  om*/

    String extension = FileUtil.getExtension(fileName);

    String[] imageExtensions = PrefsPropsUtil.getStringArray(PropsKeys.BLOGS_IMAGE_EXTENSIONS,
            StringPool.COMMA);

    for (String imageExtension : imageExtensions) {
        if (StringPool.STAR.equals(imageExtension) || imageExtension.equals(StringPool.PERIOD + extension)) {

            return;
        }
    }

    throw new EntryImageNameException("Invalid image for file name " + fileName);
}

From source file:com.liferay.blogs.web.internal.upload.ImageBlogsUploadFileEntryHandler.java

License:Open Source License

private void _validateFile(String fileName, long size) throws PortalException {

    if ((PropsValues.BLOGS_IMAGE_MAX_SIZE > 0) && (size > PropsValues.BLOGS_IMAGE_MAX_SIZE)) {

        throw new EntryImageSizeException();
    }/*from   www  .j  ava 2s  .  c  om*/

    String extension = FileUtil.getExtension(fileName);

    String[] imageExtensions = PrefsPropsUtil.getStringArray(PropsKeys.BLOGS_IMAGE_EXTENSIONS,
            StringPool.COMMA);

    for (String imageExtension : imageExtensions) {
        if (StringPool.STAR.equals(imageExtension) || imageExtension.equals(StringPool.PERIOD + extension)) {

            return;
        }
    }

    throw new EntryImageNameException("Invalid image for file name " + fileName);
}

From source file:com.liferay.compat.hook.webdav.CompatDLWebDAVStorageImpl.java

License:Open Source License

public Status lockResource(WebDAVRequest webDAVRequest, String owner, long timeout) throws WebDAVException {

    Resource resource = getResource(webDAVRequest);

    Lock lock = null;/*from w ww.  ja v a  2  s .  c  o  m*/
    int status = HttpServletResponse.SC_OK;

    try {
        if (resource == null) {
            status = HttpServletResponse.SC_CREATED;

            HttpServletRequest request = webDAVRequest.getHttpServletRequest();

            String[] pathArray = webDAVRequest.getPathArray();

            long companyId = webDAVRequest.getCompanyId();
            long groupId = webDAVRequest.getGroupId();
            long parentFolderId = getParentFolderId(companyId, pathArray);
            String title = WebDAVUtil.getResourceName(pathArray);

            String contentType = GetterUtil.get(request.getHeader(HttpHeaders.CONTENT_TYPE),
                    ContentTypes.APPLICATION_OCTET_STREAM);

            if (contentType.equals(ContentTypes.APPLICATION_OCTET_STREAM)) {
                contentType = MimeTypesUtil.getContentType(request.getInputStream(), title);
            }

            String description = StringPool.BLANK;
            String changeLog = StringPool.BLANK;

            File file = FileUtil.createTempFile(FileUtil.getExtension(title));

            file.createNewFile();

            ServiceContext serviceContext = new ServiceContext();

            serviceContext.setAddGroupPermissions(isAddGroupPermissions(groupId));
            serviceContext.setAddGuestPermissions(true);

            FileEntry fileEntry = DLAppServiceUtil.addFileEntry(groupId, parentFolderId, title, contentType,
                    title, description, changeLog, file, serviceContext);

            resource = toResource(webDAVRequest, fileEntry, false);
        }

        if (isInstanceOfDLFileEntryResourceImpl(super.getResource(webDAVRequest))) {

            FileEntry fileEntry = (FileEntry) resource.getModel();

            ServiceContext serviceContext = new ServiceContext();

            serviceContext.setAttribute(DLUtil.MANUAL_CHECK_IN_REQUIRED,
                    CompatWebDAVThreadLocal.isManualCheckInRequired());

            DLAppServiceUtil.checkOutFileEntry(fileEntry.getFileEntryId(), owner, timeout, serviceContext);

            lock = fileEntry.getLock();
        } else {
            boolean inheritable = false;

            long depth = WebDAVUtil.getDepth(webDAVRequest.getHttpServletRequest());

            if (depth != 0) {
                inheritable = true;
            }

            Folder folder = (Folder) resource.getModel();

            lock = DLAppServiceUtil.lockFolder(folder.getRepositoryId(), folder.getFolderId(), owner,
                    inheritable, timeout);
        }
    } catch (Exception e) {

        // DuplicateLock is 423 not 501

        if (!(e instanceof DuplicateLockException)) {
            throw new WebDAVException(e);
        }

        status = WebDAVUtil.SC_LOCKED;
    }

    return new Status(lock, status);
}

From source file:com.liferay.document.library.internal.util.DLValidatorImpl.java

License:Open Source License

@Override
public void validateSourceFileExtension(String fileExtension, String sourceFileName)
        throws SourceFileNameException {

    String sourceFileExtension = FileUtil.getExtension(sourceFileName);

    if (Validator.isNotNull(sourceFileName) && PropsValues.DL_FILE_EXTENSIONS_STRICT_CHECK
            && !fileExtension.equals(sourceFileExtension)) {

        throw new SourceFileNameException(sourceFileExtension);
    }/*from  w w w  .  j  a  v a  2s.  c  o m*/
}

From source file:com.liferay.document.library.internal.util.DLValidatorImpl.java

License:Open Source License

protected String replaceDLNameBlacklist(String title) {
    String extension = FileUtil.getExtension(title);
    String nameWithoutExtension = FileUtil.stripExtension(title);

    for (String blacklistName : PropsValues.DL_NAME_BLACKLIST) {
        if (StringUtil.equalsIgnoreCase(nameWithoutExtension, blacklistName)) {

            if (Validator.isNull(extension)) {
                return nameWithoutExtension + StringPool.UNDERLINE;
            }/*from w w w . j a va2s.c  o m*/

            return StringBundler.concat(nameWithoutExtension, StringPool.UNDERLINE, StringPool.PERIOD,
                    extension);
        }
    }

    return title;
}

From source file:com.liferay.document.library.repository.cmis.internal.model.CMISFileEntry.java

License:Open Source License

@Override
public String getExtension() {
    return FileUtil.getExtension(getTitle());
}

From source file:com.liferay.document.library.web.asset.DLFileEntryAssetRenderer.java

License:Open Source License

@Override
public String getNewName(String oldName, String token) {
    String extension = FileUtil.getExtension(oldName);

    if (Validator.isNull(extension)) {
        return super.getNewName(oldName, token);
    }/*from   w  w w.  ja v  a 2s.com*/

    StringBundler sb = new StringBundler(5);

    int index = oldName.lastIndexOf(CharPool.PERIOD);

    sb.append(oldName.substring(0, index));

    sb.append(StringPool.SPACE);
    sb.append(token);
    sb.append(StringPool.PERIOD);
    sb.append(extension);

    return sb.toString();
}