com.bemis.portal.fileuploader.service.impl.FileUploaderLocalServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.bemis.portal.fileuploader.service.impl.FileUploaderLocalServiceImpl.java

Source

/**
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package com.bemis.portal.fileuploader.service.impl;

import static com.bemis.portal.fileuploader.constants.FileUploaderConstants.DESTINATION_FOLDER_ID;
import static com.bemis.portal.fileuploader.constants.FileUploaderConstants.INPUT_BUFFER;

import static com.liferay.portal.kernel.util.StringPool.BLANK;
import static com.liferay.portal.kernel.util.StringPool.PERIOD;
import static com.liferay.portal.kernel.util.StringPool.SLASH;

import aQute.bnd.annotation.ProviderType;

import com.bemis.portal.fileuploader.constants.FileUploaderConstants;
import com.bemis.portal.fileuploader.exception.FileUploaderException;
import com.bemis.portal.fileuploader.helper.FileUploadHelper;
import com.bemis.portal.fileuploader.service.base.FileUploaderLocalServiceBaseImpl;

import com.liferay.document.library.kernel.model.DLFileEntry;
import com.liferay.document.library.kernel.service.DLAppLocalService;
import com.liferay.document.library.kernel.service.DLFileEntryLocalService;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.model.User;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.repository.model.FileVersion;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.util.FileUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.MimeTypesUtil;
import com.liferay.portal.kernel.util.StreamUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.spring.extender.service.ServiceReference;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.io.FilenameUtils;

/**
 * @author Prathima Shreenath
 * @see FileUploaderLocalServiceBaseImpl
 * @see com.bemis.portal.fileuploader.service.FileUploaderLocalServiceUtil
 */
@ProviderType
public class FileUploaderLocalServiceImpl extends FileUploaderLocalServiceBaseImpl {

    /**
     * Uploads the file into the destination folder
     * If the file does not exist, adds the file. If exists, updates the existing file
     * Adds tags and categories to documents
     *
     * @param file
     * @param fileDescription
     * @param fileName
     * @param changeLog
     * @param serviceContext
     * @return FileEntry
     * @throws PortalException
     */
    public FileEntry uploadFile(File file, String fileDescription, String fileName, String changeLog,
            ServiceContext serviceContext) throws PortalException {

        if (_log.isDebugEnabled()) {
            _log.debug("Invoking uploadFile....");
        }

        long companyId = serviceContext.getCompanyId();
        long groupId = serviceContext.getScopeGroupId();
        long userId = serviceContext.getUserId();

        // see https://issues.liferay.com/browse/LPS-66607

        User user = userLocalService.getUser(userId);

        // Check permissions

        _fileUploadHelper.checkPermission(companyId, groupId, userId);

        String title = FilenameUtils.removeExtension(fileName);

        long folderId = GetterUtil.getLong(serviceContext.getAttribute(DESTINATION_FOLDER_ID));

        fileName = file.getName();

        String mimeType = MimeTypesUtil.getContentType(fileName);

        boolean majorVersion = true;

        DLFileEntry dlFileEntry = _dlFileEntryLocalService.fetchFileEntry(groupId, folderId, title);

        FileEntry fileEntry = null;

        if (Validator.isNull(dlFileEntry)) {
            fileEntry = addFileEntry(userId, groupId, folderId, fileName, mimeType, title, fileDescription,
                    changeLog, file, serviceContext);
        } else {
            fileEntry = updateFileEntry(userId, dlFileEntry, fileName, mimeType, title, fileDescription, changeLog,
                    majorVersion, file, serviceContext);
        }

        FileVersion fileVersion = fileEntry.getFileVersion();

        long[] assetCategoryIds = _fileUploadHelper.getAssetCategoryIds(groupId, title, serviceContext);

        String[] assetTagNames = serviceContext.getAssetTagNames();

        if (_log.isDebugEnabled()) {
            _log.debug(">>> Updating FileEntry with tags and categories");
        }

        _dlAppLocalService.updateAsset(userId, fileEntry, fileVersion, assetCategoryIds, assetTagNames, null);

        // Post processing uploaded file

        _fileUploadHelper.postProcessUpload(file, fileEntry.getFileEntryId(), serviceContext);

        return fileEntry;
    }

    /**
     * Uploads the file into the destination folder
     * If the file does not exist, adds the file. If exists, updates the existing file
     * Adds tags and categories to documents
     *
     * @param companyId
     * @param groupId
     * @param userId
     * @param file
     * @param fileDescription
     * @param title
     * @param folderId
     * @param changeLog
     * @param assetTagNames
     * @return FileEntry
     * @throws PortalException
     */
    public FileEntry uploadFile(long companyId, long groupId, long userId, File file, String fileDescription,
            String title, long folderId, String changeLog, String[] assetTagNames) throws PortalException {

        ServiceContext serviceContext = new ServiceContext();

        serviceContext.setCompanyId(companyId);
        serviceContext.setScopeGroupId(groupId);
        serviceContext.setUserId(userId);
        serviceContext.setAssetTagNames(assetTagNames);
        serviceContext.setAttribute(FileUploaderConstants.DESTINATION_FOLDER_ID, folderId);

        return uploadFile(file, fileDescription, title, changeLog, serviceContext);
    }

    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. ");
            }

            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);
            }
        }
    }

    protected FileEntry addFileEntry(long userId, long groupId, long folderId, String sourceFileName,
            String mimeType, String title, String fileDescription, String changeLog, File inputFile,
            ServiceContext serviceContext) throws PortalException {

        long repositoryId = groupId;

        if (_log.isDebugEnabled()) {
            _log.debug(">>> File does not exist. Adding File Entry for : " + title);
        }

        if (Validator.isBlank(fileDescription)) {
            fileDescription = title;
        }

        FileEntry fileEntry = _dlAppLocalService.addFileEntry(userId, repositoryId, folderId, sourceFileName,
                mimeType, title, fileDescription, changeLog, inputFile, serviceContext);

        if (_log.isWarnEnabled()) {
            _log.warn(String.format(">>> File with name '%s' added successfully with id : '%s'", title,
                    fileEntry.getFileEntryId()));
        }

        return fileEntry;
    }

    protected FileEntry updateFileEntry(long userId, DLFileEntry dlFileEntry, String sourceFileName,
            String mimeType, String title, String fileDescription, String changeLog, boolean majorVersion,
            File file, ServiceContext serviceContext) throws PortalException {

        long dlFileEntryId = dlFileEntry.getFileEntryId();

        if (_log.isDebugEnabled()) {
            _log.debug(">>> File already exists, updating fileEntry with id :" + dlFileEntryId);
        }

        if (Validator.isBlank(changeLog)) {
            long currentFileSize = file.length();

            if (currentFileSize != dlFileEntry.getSize()) {
                changeLog = FileUploaderConstants.DEFAULT_CHANGE_LOG;
            }
        }

        FileEntry fileEntry = _dlAppLocalService.updateFileEntry(userId, dlFileEntryId, sourceFileName, mimeType,
                title, fileDescription, changeLog, majorVersion, file, serviceContext);

        if (_log.isWarnEnabled()) {
            _log.warn(String.format(
                    ">>> File with name '%s' updated with change : '%s'" + "successfully with id : '%s'", title,
                    changeLog, fileEntry.getFileEntryId()));
        }

        return fileEntry;
    }

    private static final Log _log = LogFactoryUtil.getLog(FileUploaderLocalServiceImpl.class);

    @ServiceReference(type = DLAppLocalService.class)
    private DLAppLocalService _dlAppLocalService;

    @ServiceReference(type = DLFileEntryLocalService.class)
    private DLFileEntryLocalService _dlFileEntryLocalService;

    @ServiceReference(type = FileUploadHelper.class)
    private FileUploadHelper _fileUploadHelper;

}