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

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

Introduction

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

Prototype

public static void write(String fileName, String s) throws IOException 

Source Link

Usage

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 .  ja v a  2s .  c o m

    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;/*  w  w  w  . j  a  va 2s .c  o  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;/* www.j  a v  a  2 s. c  o m*/

    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.ide.servlet.WebServicesServlet.java

License:Open Source License

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String path = this.getServletContext().getRealPath("/") + "jsonws-js-templates.xml";

    ServletOutputStream out = response.getOutputStream();

    try {//w ww  . j  a  v a 2s .co m
        String xml = getWebServicesXML();

        File file = new File(path);

        if (!file.exists()) {
            file.createNewFile();
        }

        FileUtil.write(file, xml);

        out.println("success:" + path);

        System.out.println("success:" + path);
    } catch (Exception e) {
        out.println("faild:" + path);

        System.out.println("faild:" + path);
    }
}

From source file:com.liferay.journal.exportimport.data.handler.JournalArticleStagedModelDataHandler.java

License:Open Source License

@Override
protected void doImportStagedModel(PortletDataContext portletDataContext, JournalArticle article)
        throws Exception {

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

    long authorId = _journalCreationStrategy.getAuthorUserId(portletDataContext, article);

    if (authorId != JournalCreationStrategy.USE_DEFAULT_USER_ID_STRATEGY) {
        userId = authorId;/*from   w  w w  .j  ava  2 s  .co  m*/
    }

    User user = _userLocalService.getUser(userId);

    Map<Long, Long> folderIds = (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(JournalFolder.class);

    long folderId = MapUtil.getLong(folderIds, article.getFolderId(), article.getFolderId());

    String articleId = article.getArticleId();

    boolean autoArticleId = false;

    if (Validator.isNumber(articleId)
            || (_journalArticleLocalService.fetchArticle(portletDataContext.getScopeGroupId(), articleId,
                    JournalArticleConstants.VERSION_DEFAULT) != null)) {

        autoArticleId = true;
    }

    Map<String, String> articleIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalArticle.class + ".articleId");

    String newArticleId = articleIds.get(articleId);

    if (Validator.isNotNull(newArticleId)) {

        // A sibling of a different version was already assigned a new
        // article id

        articleId = newArticleId;
        autoArticleId = false;
    }

    String content = article.getContent();

    content = _journalArticleExportImportContentProcessor.replaceImportContentReferences(portletDataContext,
            article, content);

    article.setContent(content);

    String newContent = _journalCreationStrategy.getTransformedContent(portletDataContext, article);

    if (newContent != JournalCreationStrategy.ARTICLE_CONTENT_UNCHANGED) {
        article.setContent(newContent);
    }

    Date displayDate = article.getDisplayDate();

    int displayDateMonth = 0;
    int displayDateDay = 0;
    int displayDateYear = 0;
    int displayDateHour = 0;
    int displayDateMinute = 0;

    if (displayDate != null) {
        Calendar displayCal = CalendarFactoryUtil.getCalendar(user.getTimeZone());

        displayCal.setTime(displayDate);

        displayDateMonth = displayCal.get(Calendar.MONTH);
        displayDateDay = displayCal.get(Calendar.DATE);
        displayDateYear = displayCal.get(Calendar.YEAR);
        displayDateHour = displayCal.get(Calendar.HOUR);
        displayDateMinute = displayCal.get(Calendar.MINUTE);

        if (displayCal.get(Calendar.AM_PM) == Calendar.PM) {
            displayDateHour += 12;
        }
    }

    Date expirationDate = article.getExpirationDate();

    int expirationDateMonth = 0;
    int expirationDateDay = 0;
    int expirationDateYear = 0;
    int expirationDateHour = 0;
    int expirationDateMinute = 0;
    boolean neverExpire = true;

    if (expirationDate != null) {
        Calendar expirationCal = CalendarFactoryUtil.getCalendar(user.getTimeZone());

        expirationCal.setTime(expirationDate);

        expirationDateMonth = expirationCal.get(Calendar.MONTH);
        expirationDateDay = expirationCal.get(Calendar.DATE);
        expirationDateYear = expirationCal.get(Calendar.YEAR);
        expirationDateHour = expirationCal.get(Calendar.HOUR);
        expirationDateMinute = expirationCal.get(Calendar.MINUTE);

        neverExpire = false;

        if (expirationCal.get(Calendar.AM_PM) == Calendar.PM) {
            expirationDateHour += 12;
        }
    }

    Date reviewDate = article.getReviewDate();

    int reviewDateMonth = 0;
    int reviewDateDay = 0;
    int reviewDateYear = 0;
    int reviewDateHour = 0;
    int reviewDateMinute = 0;
    boolean neverReview = true;

    if (reviewDate != null) {
        Calendar reviewCal = CalendarFactoryUtil.getCalendar(user.getTimeZone());

        reviewCal.setTime(reviewDate);

        reviewDateMonth = reviewCal.get(Calendar.MONTH);
        reviewDateDay = reviewCal.get(Calendar.DATE);
        reviewDateYear = reviewCal.get(Calendar.YEAR);
        reviewDateHour = reviewCal.get(Calendar.HOUR);
        reviewDateMinute = reviewCal.get(Calendar.MINUTE);

        neverReview = false;

        if (reviewCal.get(Calendar.AM_PM) == Calendar.PM) {
            reviewDateHour += 12;
        }
    }

    Map<String, String> ddmStructureKeys = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(DDMStructure.class + ".ddmStructureKey");

    String parentDDMStructureKey = MapUtil.getString(ddmStructureKeys, article.getDDMStructureKey(),
            article.getDDMStructureKey());

    Map<String, Long> ddmStructureIds = (Map<String, Long>) portletDataContext
            .getNewPrimaryKeysMap(DDMStructure.class);

    long ddmStructureId = 0;

    if (article.getClassNameId() != 0) {
        ddmStructureId = ddmStructureIds.get(article.getClassPK());
    }

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

    String parentDDMTemplateKey = MapUtil.getString(ddmTemplateKeys, article.getDDMTemplateKey(),
            article.getDDMTemplateKey());

    File smallFile = null;

    try {
        Element articleElement = portletDataContext.getImportDataStagedModelElement(article);

        if (article.isSmallImage()) {
            String smallImagePath = articleElement.attributeValue("small-image-path");

            if (Validator.isNotNull(article.getSmallImageURL())) {
                String smallImageURL = _journalArticleExportImportContentProcessor
                        .replaceImportContentReferences(portletDataContext, article,
                                article.getSmallImageURL());

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

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

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

        JournalArticle latestArticle = _journalArticleLocalService
                .fetchLatestArticle(article.getResourcePrimKey());

        if ((latestArticle != null) && (latestArticle.getId() == article.getId())) {

            List<Element> attachmentElements = portletDataContext.getReferenceDataElements(article,
                    DLFileEntry.class, PortletDataContext.REFERENCE_TYPE_WEAK);

            for (Element attachmentElement : attachmentElements) {
                String path = attachmentElement.attributeValue("path");

                FileEntry fileEntry = (FileEntry) portletDataContext.getZipEntryAsObject(path);

                InputStream inputStream = null;

                try {
                    String binPath = attachmentElement.attributeValue("bin-path");

                    if (Validator.isNull(binPath) && portletDataContext.isPerformDirectBinaryImport()) {

                        try {
                            inputStream = FileEntryUtil.getContentStream(fileEntry);
                        } catch (NoSuchFileException nsfe) {
                        }
                    } else {
                        inputStream = portletDataContext.getZipEntryAsInputStream(binPath);
                    }

                    if (inputStream == null) {
                        if (_log.isWarnEnabled()) {
                            _log.warn("Unable to import attachment for file " + "entry "
                                    + fileEntry.getFileEntryId());
                        }

                        continue;
                    }

                    TempFileEntryUtil.addTempFileEntry(portletDataContext.getScopeGroupId(), userId,
                            JournalArticleStagedModelDataHandler.class.getName(), fileEntry.getFileName(),
                            inputStream, fileEntry.getMimeType());
                } finally {
                    StreamUtil.cleanUp(inputStream);
                }
            }
        }

        String articleURL = null;

        boolean addGroupPermissions = _journalCreationStrategy.addGroupPermissions(portletDataContext, article);
        boolean addGuestPermissions = _journalCreationStrategy.addGuestPermissions(portletDataContext, article);

        ServiceContext serviceContext = portletDataContext.createServiceContext(article);

        serviceContext.setAddGroupPermissions(addGroupPermissions);
        serviceContext.setAddGuestPermissions(addGuestPermissions);

        if ((expirationDate != null) && expirationDate.before(new Date())) {
            article.setStatus(WorkflowConstants.STATUS_EXPIRED);
        }

        if ((article.getStatus() != WorkflowConstants.STATUS_APPROVED)
                && (article.getStatus() != WorkflowConstants.STATUS_SCHEDULED)) {

            serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);
        }

        JournalArticle importedArticle = null;

        String articleResourceUuid = articleElement.attributeValue("article-resource-uuid");

        // Used when importing LARs with journal schemas under 1.1.0

        _setLegacyValues(article);

        if (portletDataContext.isDataStrategyMirror()) {
            serviceContext.setUuid(article.getUuid());
            serviceContext.setAttribute("articleResourceUuid", articleResourceUuid);
            serviceContext.setAttribute("urlTitle", article.getUrlTitle());

            boolean preloaded = GetterUtil.getBoolean(articleElement.attributeValue("preloaded"));

            JournalArticle existingArticle = fetchExistingArticle(articleResourceUuid,
                    portletDataContext.getScopeGroupId(), articleId, newArticleId, preloaded);

            JournalArticle existingArticleVersion = null;

            if (existingArticle != null) {
                existingArticleVersion = fetchExistingArticleVersion(article.getUuid(),
                        portletDataContext.getScopeGroupId(), existingArticle.getArticleId(),
                        article.getVersion());
            }

            if ((existingArticle != null) && (existingArticleVersion == null)) {

                autoArticleId = false;
                articleId = existingArticle.getArticleId();
            }

            if (existingArticleVersion == null) {
                importedArticle = _journalArticleLocalService.addArticle(userId,
                        portletDataContext.getScopeGroupId(), folderId, article.getClassNameId(),
                        ddmStructureId, articleId, autoArticleId, article.getVersion(), article.getTitleMap(),
                        article.getDescriptionMap(), article.getContent(), parentDDMStructureKey,
                        parentDDMTemplateKey, article.getLayoutUuid(), displayDateMonth, displayDateDay,
                        displayDateYear, displayDateHour, displayDateMinute, expirationDateMonth,
                        expirationDateDay, expirationDateYear, expirationDateHour, expirationDateMinute,
                        neverExpire, reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour,
                        reviewDateMinute, neverReview, article.isIndexable(), article.isSmallImage(),
                        article.getSmallImageURL(), smallFile, null, articleURL, serviceContext);
            } else {
                importedArticle = _journalArticleLocalService.updateArticle(userId,
                        existingArticle.getGroupId(), folderId, existingArticle.getArticleId(),
                        article.getVersion(), article.getTitleMap(), article.getDescriptionMap(),
                        article.getContent(), parentDDMStructureKey, parentDDMTemplateKey,
                        article.getLayoutUuid(), displayDateMonth, displayDateDay, displayDateYear,
                        displayDateHour, displayDateMinute, expirationDateMonth, expirationDateDay,
                        expirationDateYear, expirationDateHour, expirationDateMinute, neverExpire,
                        reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute,
                        neverReview, article.isIndexable(), article.isSmallImage(), article.getSmallImageURL(),
                        smallFile, null, articleURL, serviceContext);

                String articleUuid = article.getUuid();
                String importedArticleUuid = importedArticle.getUuid();

                if (!articleUuid.equals(importedArticleUuid)) {
                    importedArticle.setUuid(articleUuid);

                    _journalArticleLocalService.updateJournalArticle(importedArticle);
                }
            }
        } else {
            importedArticle = _journalArticleLocalService.addArticle(userId,
                    portletDataContext.getScopeGroupId(), folderId, article.getClassNameId(), ddmStructureId,
                    articleId, autoArticleId, article.getVersion(), article.getTitleMap(),
                    article.getDescriptionMap(), article.getContent(), parentDDMStructureKey,
                    parentDDMTemplateKey, article.getLayoutUuid(), displayDateMonth, displayDateDay,
                    displayDateYear, displayDateHour, displayDateMinute, expirationDateMonth, expirationDateDay,
                    expirationDateYear, expirationDateHour, expirationDateMinute, neverExpire, reviewDateMonth,
                    reviewDateDay, reviewDateYear, reviewDateHour, reviewDateMinute, neverReview,
                    article.isIndexable(), article.isSmallImage(), article.getSmallImageURL(), smallFile, null,
                    articleURL, serviceContext);
        }

        portletDataContext.importClassedModel(article, importedArticle);

        if (Validator.isNull(newArticleId)) {
            articleIds.put(article.getArticleId(), importedArticle.getArticleId());
        }

        Map<Long, Long> articlePrimaryKeys = (Map<Long, Long>) portletDataContext
                .getNewPrimaryKeysMap(JournalArticle.class + ".primaryKey");

        articlePrimaryKeys.put(article.getPrimaryKey(), importedArticle.getPrimaryKey());
    } finally {
        if (smallFile != null) {
            smallFile.delete();
        }
    }
}

From source file:com.liferay.mail.service.impl.AttachmentLocalServiceImpl.java

License:Open Source License

public File getFile(long attachmentId) throws PortalException {
    try {//from   w  ww.  j a  v a  2  s .co m
        File file = FileUtil.createTempFile();

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

        return file;
    } catch (IOException ioe) {
        throw new SystemException(ioe);
    }
}

From source file:com.liferay.mail.util.CyrusHook.java

License:Open Source License

public void addForward(long companyId, long userId, List<Filter> filters, List<String> emailAddresses,
        boolean leaveCopy) {

    try {/*from  ww  w .  j av  a 2s. c om*/
        if (emailAddresses != null) {
            String home = PropsUtil.get(PropsKeys.MAIL_HOOK_CYRUS_HOME);

            File file = new File(home + "/" + userId + ".procmail.forward");

            if ((filters.size() > 0) || (emailAddresses.size() > 0) || (leaveCopy)) {

                StringBundler sb = new StringBundler();

                for (int i = 0; i < filters.size(); i++) {
                    Filter filter = filters.get(i);

                    sb.append(":0\n");
                    sb.append("* ^(From|Cc|To).*");
                    sb.append(filter.getEmailAddress());
                    sb.append("\n");
                    sb.append("| $DELIVER -e -a $USER -m user.$USER.");
                    sb.append(filter.getFolder());
                    sb.append("\n\n");
                }

                if (leaveCopy) {
                    sb.append(":0 c\n");
                    sb.append("| $DELIVER -e -a $USER -m user.$USER\n\n");
                }

                if (emailAddresses.size() > 0) {
                    sb.append(":0\n");
                    sb.append("!");

                    for (String emailAddress : emailAddresses) {
                        sb.append(" ");
                        sb.append(emailAddress);
                    }
                }

                String content = sb.toString();

                while (content.endsWith("\n")) {
                    content = content.substring(0, content.length() - 1);
                }

                FileUtil.write(file, content);
            } else {
                file.delete();
            }
        }
    } catch (Exception e) {
        _log.error(e, e);
    }
}

From source file:com.liferay.mail.util.CyrusHook.java

License:Open Source License

public void addVacationMessage(long companyId, long userId, String emailAddress, String vacationMessage) {

    try {/*from   w  w  w.  j av  a2  s .c o  m*/
        String home = PropsUtil.get(PropsKeys.MAIL_HOOK_CYRUS_HOME);

        // Remove vacation cache

        new File(home + "/" + userId + ".vacation.cache").delete();

        // Update vacation message

        File vacation = new File(home + "/" + userId + ".vacation");

        if (Validator.isNull(vacationMessage)) {
            vacation.delete();
        } else {
            FileUtil.write(vacation, emailAddress + "\n" + vacationMessage);
        }
    } catch (Exception e) {
        _log.error(e, e);
    }
}

From source file:com.liferay.mail.util.CyrusHook.java

License:Open Source License

public void updateBlocked(long companyId, long userId, List<String> blocked) {

    String home = PropsUtil.get(PropsKeys.MAIL_HOOK_CYRUS_HOME);

    File file = new File(home + "/" + userId + ".procmail.blocked");

    if ((blocked == null) || (blocked.size() == 0)) {
        file.delete();//from  w  ww .  j  av  a2 s.  c  om

        return;
    }

    StringBundler sb = new StringBundler(blocked.size() * 9);

    for (int i = 0; i < blocked.size(); i++) {
        String emailAddress = blocked.get(i);

        sb.append("\n");
        sb.append(":0\n");
        sb.append("* ^From.*");
        sb.append(emailAddress);
        sb.append("\n");
        sb.append("{\n");
        sb.append(":0\n");
        sb.append("/dev/null\n");
        sb.append("}\n");
    }

    try {
        FileUtil.write(file, sb.toString());
    } catch (Exception e) {
        _log.error(e, e);
    }
}

From source file:com.liferay.mail.util.SendmailHook.java

License:Open Source License

public void addForward(long companyId, long userId, List<Filter> filters, List<String> emailAddresses,
        boolean leaveCopy) {

    try {/*from   w  w w. j  a  v a  2  s . c  o m*/
        if (emailAddresses != null) {
            String home = PropsUtil.get(PropsKeys.MAIL_HOOK_SENDMAIL_HOME);

            File file = new File(home + "/" + userId + "/.forward");

            if (emailAddresses.size() > 0) {
                StringBundler sb = new StringBundler(emailAddresses.size() * 2);

                for (int i = 0; i < emailAddresses.size(); i++) {
                    String emailAddress = emailAddresses.get(i);

                    sb.append(emailAddress);
                    sb.append("\n");
                }

                FileUtil.write(file, sb.toString());
            } else {
                file.delete();
            }
        }
    } catch (Exception e) {
        _log.error(e, e);
    }
}