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

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

Introduction

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

Prototype

public static File createTempFile(String extension) 

Source Link

Usage

From source file:com.liferay.document.library.web.internal.webdav.DLWebDAVStorageImpl.java

License:Open Source License

@Override
public int moveSimpleResource(WebDAVRequest webDAVRequest, Resource resource, String destination,
        boolean overwrite) throws WebDAVException {

    File file = null;//from   w  ww .  java  2s.com

    try {
        String[] destinationArray = WebDAVUtil.getPathArray(destination, true);

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

        if (!hasLock(fileEntry, webDAVRequest.getLockUuid()) && (fileEntry.getLock() != null)) {

            return WebDAVUtil.SC_LOCKED;
        }

        long companyId = webDAVRequest.getCompanyId();

        long groupId = WebDAVUtil.getGroupId(companyId, destinationArray);
        long newParentFolderId = getParentFolderId(companyId, destinationArray);

        String title = getTitle(destinationArray);
        String description = fileEntry.getDescription();
        String changeLog = StringPool.BLANK;

        ServiceContext serviceContext = new ServiceContext();

        populateServiceContext(serviceContext, fileEntry);

        int status = HttpServletResponse.SC_CREATED;

        if (overwrite) {
            if (deleteResource(groupId, newParentFolderId, title, webDAVRequest.getLockUuid())) {

                status = HttpServletResponse.SC_NO_CONTENT;
            }
        }

        // LPS-5415

        if (webDAVRequest.isMac()) {
            try {
                FileEntry destFileEntry = _dlAppService.getFileEntry(groupId, newParentFolderId, title);

                InputStream is = fileEntry.getContentStream();

                file = FileUtil.createTempFile(is);

                populateServiceContext(serviceContext, destFileEntry);

                _dlAppService.updateFileEntry(destFileEntry.getFileEntryId(), destFileEntry.getTitle(),
                        destFileEntry.getMimeType(), destFileEntry.getTitle(), destFileEntry.getDescription(),
                        changeLog, false, file, serviceContext);

                _dlAppService.deleteFileEntry(fileEntry.getFileEntryId());

                return status;
            } catch (NoSuchFileEntryException nsfee) {
                if (_log.isDebugEnabled()) {
                    _log.debug(nsfee, nsfee);
                }
            }
        }

        populateServiceContext(serviceContext, fileEntry);

        _dlAppService.updateFileEntry(fileEntry.getFileEntryId(), title, fileEntry.getMimeType(), title,
                description, changeLog, false, file, serviceContext);

        if (fileEntry.getFolderId() != newParentFolderId) {
            fileEntry = _dlAppService.moveFileEntry(fileEntry.getFileEntryId(), newParentFolderId,
                    serviceContext);
        }

        return status;
    } catch (PrincipalException pe) {
        if (_log.isDebugEnabled()) {
            _log.debug(pe, pe);
        }

        return HttpServletResponse.SC_FORBIDDEN;
    } catch (DuplicateFileEntryException dfee) {
        if (_log.isDebugEnabled()) {
            _log.debug(dfee, dfee);
        }

        return HttpServletResponse.SC_PRECONDITION_FAILED;
    } catch (DuplicateFolderNameException dfne) {
        if (_log.isDebugEnabled()) {
            _log.debug(dfne, dfne);
        }

        return HttpServletResponse.SC_PRECONDITION_FAILED;
    } catch (LockException le) {
        if (_log.isDebugEnabled()) {
            _log.debug(le, le);
        }

        return WebDAVUtil.SC_LOCKED;
    } catch (Exception e) {
        throw new WebDAVException(e);
    } finally {
        FileUtil.delete(file);
    }
}

From source file:com.liferay.document.library.web.internal.webdav.DLWebDAVStorageImpl.java

License:Open Source License

@Override
public int putResource(WebDAVRequest webDAVRequest) throws WebDAVException {
    File file = null;/*from www  .  j  a  va 2 s  . co m*/

    try {
        HttpServletRequest request = webDAVRequest.getHttpServletRequest();

        String[] pathArray = webDAVRequest.getPathArray();

        long companyId = webDAVRequest.getCompanyId();
        long groupId = webDAVRequest.getGroupId();
        long parentFolderId = getParentFolderId(companyId, pathArray);
        String title = getTitle(pathArray);
        String description = StringPool.BLANK;
        String changeLog = StringPool.BLANK;

        ServiceContext serviceContext = ServiceContextFactory.getInstance(request);

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

        String extension = FileUtil.getExtension(title);

        file = FileUtil.createTempFile(extension);

        FileUtil.write(file, request.getInputStream());

        String contentType = getContentType(request, file, title, extension);

        try {
            FileEntry fileEntry = _dlAppService.getFileEntry(groupId, parentFolderId, title);

            if (!hasLock(fileEntry, webDAVRequest.getLockUuid()) && (fileEntry.getLock() != null)) {

                return WebDAVUtil.SC_LOCKED;
            }

            long fileEntryId = fileEntry.getFileEntryId();

            description = fileEntry.getDescription();

            populateServiceContext(serviceContext, fileEntry);

            serviceContext.setCommand(Constants.UPDATE_WEBDAV);

            _dlAppService.updateFileEntry(fileEntryId, title, contentType, title, description, changeLog, false,
                    file, serviceContext);
        } catch (NoSuchFileEntryException nsfee) {
            if (_log.isDebugEnabled()) {
                _log.debug(nsfee, nsfee);
            }

            serviceContext.setCommand(Constants.ADD_WEBDAV);

            _dlAppService.addFileEntry(groupId, parentFolderId, title, contentType, title, description,
                    changeLog, file, serviceContext);
        }

        if (_log.isInfoEnabled()) {
            _log.info("Added " + StringUtil.merge(pathArray, StringPool.SLASH));
        }

        return HttpServletResponse.SC_CREATED;
    } catch (FileSizeException fse) {
        if (_log.isDebugEnabled()) {
            _log.debug(fse, fse);
        }

        return HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
    } catch (NoSuchFolderException nsfe) {
        if (_log.isDebugEnabled()) {
            _log.debug(nsfe, nsfe);
        }

        return HttpServletResponse.SC_CONFLICT;
    } catch (PrincipalException pe) {
        if (_log.isDebugEnabled()) {
            _log.debug(pe, pe);
        }

        return HttpServletResponse.SC_FORBIDDEN;
    } catch (PortalException pe) {
        if (_log.isWarnEnabled()) {
            _log.warn(pe, pe);
        }

        return HttpServletResponse.SC_CONFLICT;
    } catch (Exception e) {
        throw new WebDAVException(e);
    } finally {
        FileUtil.delete(file);
    }
}

From source file:com.liferay.document.library.web.webdav.DLWebDAVStorageImpl.java

License:Open Source License

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

    Resource resource = getResource(webDAVRequest);

    Lock lock = null;/*from  w w  w.j av  a  2s. 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 = getTitle(pathArray);

            String extension = FileUtil.getExtension(title);

            String contentType = getContentType(request, null, title, extension);

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

            File file = FileUtil.createTempFile(extension);

            file.createNewFile();

            ServiceContext serviceContext = new ServiceContext();

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

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

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

        if (resource instanceof DLFileEntryResourceImpl) {
            FileEntry fileEntry = (FileEntry) resource.getModel();

            ServiceContext serviceContext = new ServiceContext();

            serviceContext.setAttribute(DL.MANUAL_CHECK_IN_REQUIRED, webDAVRequest.isManualCheckInRequired());

            _dlAppService.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 = _dlAppService.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.web.webdav.DLWebDAVStorageImpl.java

License:Open Source License

@Override
public int moveSimpleResource(WebDAVRequest webDAVRequest, Resource resource, String destination,
        boolean overwrite) throws WebDAVException {

    File file = null;/*from w  w w  . j  av a2s. co  m*/

    try {
        String[] destinationArray = WebDAVUtil.getPathArray(destination, true);

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

        if (!hasLock(fileEntry, webDAVRequest.getLockUuid()) && (fileEntry.getLock() != null)) {

            return WebDAVUtil.SC_LOCKED;
        }

        long companyId = webDAVRequest.getCompanyId();

        long groupId = WebDAVUtil.getGroupId(companyId, destinationArray);
        long newParentFolderId = getParentFolderId(companyId, destinationArray);

        String title = getTitle(destinationArray);
        String description = fileEntry.getDescription();
        String changeLog = StringPool.BLANK;

        ServiceContext serviceContext = new ServiceContext();

        populateServiceContext(serviceContext, fileEntry);

        int status = HttpServletResponse.SC_CREATED;

        if (overwrite) {
            if (deleteResource(groupId, newParentFolderId, title, webDAVRequest.getLockUuid())) {

                status = HttpServletResponse.SC_NO_CONTENT;
            }
        }

        // LPS-5415

        if (webDAVRequest.isMac()) {
            try {
                FileEntry destFileEntry = _dlAppService.getFileEntry(groupId, newParentFolderId, title);

                InputStream is = fileEntry.getContentStream();

                file = FileUtil.createTempFile(is);

                _dlAppService.updateFileEntry(destFileEntry.getFileEntryId(), destFileEntry.getTitle(),
                        destFileEntry.getMimeType(), destFileEntry.getTitle(), destFileEntry.getDescription(),
                        changeLog, false, file, serviceContext);

                _dlAppService.deleteFileEntry(fileEntry.getFileEntryId());

                return status;
            } catch (NoSuchFileEntryException nsfee) {
                if (_log.isDebugEnabled()) {
                    _log.debug(nsfee, nsfee);
                }
            }
        }

        _dlAppService.updateFileEntry(fileEntry.getFileEntryId(), title, fileEntry.getMimeType(), title,
                description, changeLog, false, file, serviceContext);

        if (fileEntry.getFolderId() != newParentFolderId) {
            fileEntry = _dlAppService.moveFileEntry(fileEntry.getFileEntryId(), newParentFolderId,
                    serviceContext);
        }

        return status;
    } catch (PrincipalException pe) {
        if (_log.isDebugEnabled()) {
            _log.debug(pe, pe);
        }

        return HttpServletResponse.SC_FORBIDDEN;
    } catch (DuplicateFileEntryException dfee) {
        if (_log.isDebugEnabled()) {
            _log.debug(dfee, dfee);
        }

        return HttpServletResponse.SC_PRECONDITION_FAILED;
    } catch (DuplicateFolderNameException dfne) {
        if (_log.isDebugEnabled()) {
            _log.debug(dfne, dfne);
        }

        return HttpServletResponse.SC_PRECONDITION_FAILED;
    } catch (LockException le) {
        if (_log.isDebugEnabled()) {
            _log.debug(le, le);
        }

        return WebDAVUtil.SC_LOCKED;
    } catch (Exception e) {
        throw new WebDAVException(e);
    } finally {
        FileUtil.delete(file);
    }
}

From source file:com.liferay.dynamic.data.mapping.service.impl.DDMTemplateLocalServiceImpl.java

License:Open Source License

protected File getSmallImageFile(DDMTemplate template) {
    File smallImageFile = null;/*from www.j  ava 2  s  . com*/

    if (template.isSmallImage() && Validator.isNull(template.getSmallImageURL())) {

        Image smallImage = imageLocalService.fetchImage(template.getSmallImageId());

        if (smallImage != null) {
            smallImageFile = FileUtil.createTempFile(smallImage.getType());

            try {
                FileUtil.write(smallImageFile, smallImage.getTextObj());
            } catch (IOException ioe) {
                _log.error(ioe, ioe);
            }
        }
    }

    return smallImageFile;
}

From source file:com.liferay.dynamic.data.mapping.web.internal.exportimport.data.handler.DDMTemplateStagedModelDataHandler.java

License:Open Source License

@Override
protected void doImportStagedModel(PortletDataContext portletDataContext, DDMTemplate template)
        throws Exception {

    long userId = portletDataContext.getUserId(template.getUserUuid());

    long classPK = template.getClassPK();

    if (classPK > 0) {
        Map<Long, Long> structureIds = (Map<Long, Long>) portletDataContext
                .getNewPrimaryKeysMap(DDMStructure.class);

        classPK = MapUtil.getLong(structureIds, classPK, classPK);
    }/*from  www.j  av  a2 s  .  c o  m*/

    Element element = portletDataContext.getImportDataStagedModelElement(template);

    File smallFile = null;

    try {
        if (template.isSmallImage()) {
            String smallImagePath = element.attributeValue("small-image-path");

            if (Validator.isNotNull(template.getSmallImageURL())) {
                String smallImageURL = _ddmTemplateExportImportContentProcessor.replaceImportContentReferences(
                        portletDataContext, template, template.getSmallImageURL());

                template.setSmallImageURL(smallImageURL);
            } else if (Validator.isNotNull(smallImagePath)) {
                byte[] bytes = portletDataContext.getZipEntryAsByteArray(smallImagePath);

                if (bytes != null) {
                    smallFile = FileUtil.createTempFile(template.getSmallImageType());

                    FileUtil.write(smallFile, bytes);
                }
            }
        }

        String script = _ddmTemplateExportImportContentProcessor
                .replaceImportContentReferences(portletDataContext, template, template.getScript());

        template.setScript(script);

        long resourceClassNameId = 0L;

        if (template.getResourceClassNameId() > 0) {
            String resourceClassName = element.attributeValue("resource-class-name");

            if (Validator.isNotNull(resourceClassName)) {
                resourceClassNameId = _portal.getClassNameId(resourceClassName);
            }
        }

        ServiceContext serviceContext = portletDataContext.createServiceContext(template);

        DDMTemplate importedTemplate = null;

        if (portletDataContext.isDataStrategyMirror()) {
            boolean preloaded = GetterUtil.getBoolean(element.attributeValue("preloaded"));

            DDMTemplate existingTemplate = fetchExistingTemplate(template.getUuid(),
                    portletDataContext.getScopeGroupId(), template.getClassNameId(), template.getTemplateKey(),
                    preloaded);

            if (existingTemplate == null) {
                serviceContext.setUuid(template.getUuid());

                // Force a new template key if a template with the same key
                // already exists

                existingTemplate = _ddmTemplateLocalService.fetchTemplate(portletDataContext.getScopeGroupId(),
                        template.getClassNameId(), template.getTemplateKey());

                if (existingTemplate != null) {
                    template.setTemplateKey(null);
                }

                importedTemplate = _ddmTemplateLocalService.addTemplate(userId,
                        portletDataContext.getScopeGroupId(), template.getClassNameId(), classPK,
                        resourceClassNameId, template.getTemplateKey(), template.getNameMap(),
                        template.getDescriptionMap(), template.getType(), template.getMode(),
                        template.getLanguage(), template.getScript(), template.isCacheable(),
                        template.isSmallImage(), template.getSmallImageURL(), smallFile, serviceContext);
            } else {
                importedTemplate = _ddmTemplateLocalService.updateTemplate(userId,
                        existingTemplate.getTemplateId(), classPK, template.getNameMap(),
                        template.getDescriptionMap(), template.getType(), template.getMode(),
                        template.getLanguage(), template.getScript(), template.isCacheable(),
                        template.isSmallImage(), template.getSmallImageURL(), smallFile, serviceContext);
            }
        } else {
            importedTemplate = _ddmTemplateLocalService.addTemplate(userId,
                    portletDataContext.getScopeGroupId(), template.getClassNameId(), classPK,
                    resourceClassNameId, null, template.getNameMap(), template.getDescriptionMap(),
                    template.getType(), template.getMode(), template.getLanguage(), template.getScript(),
                    template.isCacheable(), template.isSmallImage(), template.getSmallImageURL(), smallFile,
                    serviceContext);
        }

        portletDataContext.importClassedModel(template, importedTemplate);

        Map<String, String> ddmTemplateKeys = (Map<String, String>) portletDataContext
                .getNewPrimaryKeysMap(DDMTemplate.class + ".ddmTemplateKey");

        ddmTemplateKeys.put(template.getTemplateKey(), importedTemplate.getTemplateKey());
    } finally {
        if (smallFile != null) {
            smallFile.delete();
        }
    }
}

From source file:com.liferay.exportimport.internal.background.task.LayoutImportBackgroundTaskExecutor.java

License:Open Source License

@Override
public BackgroundTaskResult execute(BackgroundTask backgroundTask) throws Exception {

    ExportImportConfiguration exportImportConfiguration = getExportImportConfiguration(backgroundTask);

    List<FileEntry> attachmentsFileEntries = backgroundTask.getAttachmentsFileEntries();

    File file = null;/*from w  w  w . j  a  va2 s .  c  om*/

    for (FileEntry attachmentsFileEntry : attachmentsFileEntries) {
        try {
            file = FileUtil.createTempFile("lar");

            FileUtil.write(file, attachmentsFileEntry.getContentStream());

            TransactionInvokerUtil.invoke(transactionConfig,
                    new LayoutImportCallable(exportImportConfiguration, file));
        } catch (IOException ioe) {
            StringBundler sb = new StringBundler(3);

            sb.append("Unable to process LAR file while executing ");
            sb.append("LayoutImportBackgroundTaskExecutor: ");

            if (!Objects.isNull(attachmentsFileEntry)
                    && Validator.isNotNull(attachmentsFileEntry.getFileName())) {

                sb.append(attachmentsFileEntry.getFileName());
            } else {
                sb.append("unknown file name");
            }

            throw new SystemException(sb.toString(), ioe);
        } catch (Throwable t) {
            if (_log.isDebugEnabled()) {
                _log.debug(t, t);
            } else if (_log.isWarnEnabled()) {
                _log.warn("Unable to import layouts: " + t.getMessage());
            }

            throw new SystemException(t);
        } finally {
            FileUtil.delete(file);
        }
    }

    return BackgroundTaskResult.SUCCESS;
}

From source file:com.liferay.exportimport.internal.background.task.PortletImportBackgroundTaskExecutor.java

License:Open Source License

@Override
public BackgroundTaskResult execute(BackgroundTask backgroundTask) throws Exception {

    ExportImportConfiguration exportImportConfiguration = getExportImportConfiguration(backgroundTask);

    List<FileEntry> attachmentsFileEntries = backgroundTask.getAttachmentsFileEntries();

    File file = null;/*from   w  w w.  ja  v  a 2  s . co  m*/

    for (FileEntry attachmentsFileEntry : attachmentsFileEntries) {
        try {
            file = FileUtil.createTempFile("lar");

            FileUtil.write(file, attachmentsFileEntry.getContentStream());

            TransactionInvokerUtil.invoke(transactionConfig,
                    new PortletImportCallable(exportImportConfiguration, file));
        } catch (Throwable t) {
            if (_log.isDebugEnabled()) {
                _log.debug(t, t);
            } else if (_log.isWarnEnabled()) {
                _log.warn("Unable to import portlet: " + t.getMessage());
            }

            throw new SystemException(t);
        } finally {
            FileUtil.delete(file);
        }
    }

    return BackgroundTaskResult.SUCCESS;
}

From source file:com.liferay.exportimport.lar.ExportImportHelperImpl.java

License:Open Source License

@Override
public ManifestSummary getManifestSummary(long userId, long groupId, Map<String, String[]> parameterMap,
        FileEntry fileEntry) throws Exception {

    File file = FileUtil.createTempFile("lar");

    ZipReader zipReader = null;//w  ww .  j  av a 2s  .c om

    ManifestSummary manifestSummary = null;

    try (InputStream inputStream = _dlFileEntryLocalService.getFileAsStream(fileEntry.getFileEntryId(),
            fileEntry.getVersion(), false)) {

        FileUtil.write(file, inputStream);

        Group group = _groupLocalService.getGroup(groupId);
        String userIdStrategy = MapUtil.getString(parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);

        zipReader = ZipReaderFactoryUtil.getZipReader(file);

        PortletDataContext portletDataContext = _portletDataContextFactory.createImportPortletDataContext(
                group.getCompanyId(), groupId, parameterMap, getUserIdStrategy(userId, userIdStrategy),
                zipReader);

        manifestSummary = getManifestSummary(portletDataContext);
    } finally {
        if (zipReader != null) {
            zipReader.close();
        }

        FileUtil.delete(file);
    }

    return manifestSummary;
}

From source file:com.liferay.image.uploader.web.internal.portlet.action.UploadImageMVCActionCommand.java

License:Open Source License

protected FileEntry saveTempImageFileEntry(ActionRequest actionRequest) throws Exception {

    try {//from  w w w  . j  av a2 s. co m
        FileEntry tempFileEntry = UploadImageUtil.getTempImageFileEntry(actionRequest);

        try (InputStream tempImageStream = tempFileEntry.getContentStream()) {

            ImageBag imageBag = ImageToolUtil.read(tempImageStream);

            RenderedImage renderedImage = imageBag.getRenderedImage();

            String cropRegionJSON = ParamUtil.getString(actionRequest, "cropRegion");

            if (Validator.isNotNull(cropRegionJSON)) {
                JSONObject jsonObject = JSONFactoryUtil.createJSONObject(cropRegionJSON);

                int height = jsonObject.getInt("height");
                int width = jsonObject.getInt("width");
                int x = jsonObject.getInt("x");
                int y = jsonObject.getInt("y");

                if ((x == 0) && (y == 0) && (renderedImage.getHeight() == height)
                        && (renderedImage.getWidth() == width)) {

                    return tempFileEntry;
                }

                if ((height + y) > renderedImage.getHeight()) {
                    height = renderedImage.getHeight() - y;
                }

                if ((width + x) > renderedImage.getWidth()) {
                    width = renderedImage.getWidth() - x;
                }

                renderedImage = ImageToolUtil.crop(renderedImage, height, width, x, y);
            }

            byte[] bytes = ImageToolUtil.getBytes(renderedImage, imageBag.getType());

            ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

            File file = FileUtil.createTempFile(bytes);

            try {
                TempFileEntryUtil.deleteTempFileEntry(themeDisplay.getScopeGroupId(), themeDisplay.getUserId(),
                        UploadImageUtil.getTempImageFolderName(), getTempImageFileName(actionRequest));
            } catch (Exception e) {
            }

            return TempFileEntryUtil.addTempFileEntry(themeDisplay.getScopeGroupId(), themeDisplay.getUserId(),
                    UploadImageUtil.getTempImageFolderName(), getTempImageFileName(actionRequest), file,
                    tempFileEntry.getMimeType());
        }
    } catch (NoSuchFileEntryException nsfee) {
        throw new UploadException(nsfee);
    } catch (NoSuchRepositoryException nsre) {
        throw new UploadException(nsre);
    }
}