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.portlet.documentlibrary.util.AudioProcessorImpl.java

License:Open Source License

private void _generateAudio(FileVersion fileVersion) throws Exception {
    String tempFileId = DLUtil.getTempFileId(fileVersion.getFileEntryId(), fileVersion.getVersion());

    File audioTempFile = _getAudioTempFile(tempFileId, fileVersion.getExtension());
    File previewTempFile = getPreviewTempFile(tempFileId);

    try {/*from   w w  w  .j av a 2 s  .com*/
        if (!PrefsPropsUtil.getBoolean(PropsKeys.XUGGLER_ENABLED, PropsValues.XUGGLER_ENABLED)
                || _hasAudio(fileVersion)) {

            return;
        }

        if (_isGeneratePreview(fileVersion)) {
            File file = null;

            if (fileVersion instanceof LiferayFileVersion) {
                try {
                    LiferayFileVersion liferayFileVersion = (LiferayFileVersion) fileVersion;

                    file = liferayFileVersion.getFile(false);
                } catch (UnsupportedOperationException uoe) {
                }
            }

            if (file == null) {
                InputStream inputStream = fileVersion.getContentStream(false);

                FileUtil.write(audioTempFile, inputStream);

                file = audioTempFile;
            }

            try {
                _generateAudioXuggler(fileVersion, file, previewTempFile);
            } catch (Exception e) {
                _log.error(e, e);
            }
        }
    } catch (NoSuchFileEntryException nsfee) {
    } finally {
        _fileVersionIds.remove(fileVersion.getFileVersionId());

        FileUtil.delete(audioTempFile);
        FileUtil.delete(previewTempFile);
    }
}

From source file:com.liferay.portlet.documentlibrary.util.VideoProcessorImpl.java

License:Open Source License

private void _generateVideo(FileVersion fileVersion) throws Exception {
    String tempFileId = DLUtil.getTempFileId(fileVersion.getFileEntryId(), fileVersion.getVersion());

    File videoTempFile = _getVideoTempFile(tempFileId, fileVersion.getExtension());

    File[] previewTempFiles = new File[_PREVIEW_TYPES.length];

    for (int i = 0; i < _PREVIEW_TYPES.length; i++) {
        previewTempFiles[i] = getPreviewTempFile(tempFileId, _PREVIEW_TYPES[i]);
    }//from   w w  w .j  a va  2 s  .co m

    try {
        if (!PrefsPropsUtil.getBoolean(PropsKeys.XUGGLER_ENABLED, PropsValues.XUGGLER_ENABLED)
                || _hasVideo(fileVersion)) {

            return;
        }

        File file = null;

        if (_isGeneratePreview(fileVersion) || _isGenerateThumbnail(fileVersion)) {

            if (fileVersion instanceof LiferayFileVersion) {
                try {
                    LiferayFileVersion liferayFileVersion = (LiferayFileVersion) fileVersion;

                    file = liferayFileVersion.getFile(false);
                } catch (UnsupportedOperationException uoe) {
                }
            }

            if (file == null) {
                InputStream inputStream = fileVersion.getContentStream(false);

                FileUtil.write(videoTempFile, inputStream);

                file = videoTempFile;
            }
        }

        if (_isGeneratePreview(fileVersion)) {
            try {
                _generateVideoXuggler(fileVersion, file, previewTempFiles,
                        PropsValues.DL_FILE_ENTRY_PREVIEW_VIDEO_HEIGHT,
                        PropsValues.DL_FILE_ENTRY_PREVIEW_VIDEO_WIDTH);
            } catch (Exception e) {
                _log.error(e, e);
            }
        }

        if (_isGenerateThumbnail(fileVersion)) {
            try {
                _generateThumbnailXuggler(fileVersion, file, PropsValues.DL_FILE_ENTRY_PREVIEW_VIDEO_HEIGHT,
                        PropsValues.DL_FILE_ENTRY_PREVIEW_VIDEO_WIDTH);
            } catch (Exception e) {
                _log.error(e, e);
            }
        }
    } catch (NoSuchFileEntryException nsfee) {
    } finally {
        _fileVersionIds.remove(fileVersion.getFileVersionId());

        for (int i = 0; i < previewTempFiles.length; i++) {
            FileUtil.delete(previewTempFiles[i]);
        }

        FileUtil.delete(videoTempFile);
    }
}

From source file:com.liferay.portlet.documentlibrary.webdav.DLWebDAVStorageImpl.java

License:Open Source License

@Override
public int putResource(WebDAVRequest webDavRequest) throws WebDAVException {
    File file = null;//w  w w . j av a2 s. com

    try {
        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 description = StringPool.BLANK;
        String changeLog = StringPool.BLANK;

        ServiceContext serviceContext = ServiceContextFactory.getInstance(request);

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

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

        String extension = FileUtil.getExtension(title);

        file = FileUtil.createTempFile(extension);

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

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

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

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

                return WebDAVUtil.SC_LOCKED;
            }

            long fileEntryId = fileEntry.getFileEntryId();

            description = fileEntry.getDescription();

            String[] assetTagNames = AssetTagLocalServiceUtil.getTagNames(FileEntry.class.getName(),
                    fileEntry.getFileEntryId());

            serviceContext.setAssetTagNames(assetTagNames);

            DLAppServiceUtil.updateFileEntry(fileEntryId, title, contentType, title, description, changeLog,
                    false, file, serviceContext);
        } catch (NoSuchFileEntryException nsfee) {
            if (file.length() == 0) {
                serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);
            }

            DLAppServiceUtil.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 (PrincipalException pe) {
        return HttpServletResponse.SC_FORBIDDEN;
    } catch (NoSuchFolderException nsfe) {
        return HttpServletResponse.SC_CONFLICT;
    } 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.portlet.journal.lar.JournalPortletDataHandlerImpl.java

License:Open Source License

public static void importArticle(PortletDataContext portletDataContext, Element articleElement)
        throws Exception {

    String path = articleElement.attributeValue("path");

    if (!portletDataContext.isPathNotProcessed(path)) {
        return;//from  www  .j  ava 2s . c  om
    }

    JournalArticle article = (JournalArticle) portletDataContext.getZipEntryAsObject(path);

    prepareLanguagesForImport(article);

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

    JournalCreationStrategy creationStrategy = JournalCreationStrategyFactory.getInstance();

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

    if (authorId != JournalCreationStrategy.USE_DEFAULT_USER_ID_STRATEGY) {
        userId = authorId;
    }

    User user = UserLocalServiceUtil.getUser(userId);

    String articleId = article.getArticleId();
    boolean autoArticleId = false;

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

    String newArticleId = articleIds.get(articleId);

    // ======= Start of change ============
    if (Validator.isNotNull(newArticleId)) {

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

        articleId = newArticleId;
    }
    // =======end of change================

    String content = article.getContent();

    content = importDLFileEntries(portletDataContext, articleElement, content);

    Group group = GroupLocalServiceUtil.getGroup(portletDataContext.getScopeGroupId());

    content = StringUtil.replace(content, "@data_handler_group_friendly_url@", group.getFriendlyURL());

    content = importLinksToLayout(portletDataContext, content);

    article.setContent(content);

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

    if (!StringUtils.equals(JournalCreationStrategy.ARTICLE_CONTENT_UNCHANGED, newContent)) {
        article.setContent(newContent);
    }

    Map<String, String> structureIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalStructure.class);

    String parentStructureId = MapUtil.getString(structureIds, article.getStructureId(),
            article.getStructureId());

    Map<String, String> templateIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalTemplate.class);

    String parentTemplateId = MapUtil.getString(templateIds, article.getTemplateId(), article.getTemplateId());

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

    long structurePrimaryKey = 0;

    if (Validator.isNotNull(article.getStructureId())) {
        String structureUuid = articleElement.attributeValue("structure-uuid");

        JournalStructure existingStructure = JournalStructureUtil.fetchByUUID_G(structureUuid,
                portletDataContext.getScopeGroupId());

        if (existingStructure == null) {
            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

            long companyGroupId = companyGroup.getGroupId();

            existingStructure = JournalStructureUtil.fetchByUUID_G(structureUuid, companyGroupId);
        }

        if (existingStructure == null) {
            String newStructureId = structureIds.get(article.getStructureId());

            if (Validator.isNotNull(newStructureId)) {
                existingStructure = JournalStructureUtil.fetchByG_S(portletDataContext.getScopeGroupId(),
                        String.valueOf(newStructureId));
            }

            if (existingStructure == null) {
                if (_log.isWarnEnabled()) {
                    StringBundler sb = new StringBundler();

                    sb.append("Structure ");
                    sb.append(article.getStructureId());
                    sb.append(" is missing for article ");
                    sb.append(article.getArticleId());
                    sb.append(", skipping this article.");

                    _log.warn(sb.toString());
                }

                return;
            }
        }

        structurePrimaryKey = existingStructure.getPrimaryKey();

        parentStructureId = existingStructure.getStructureId();
    }

    if (Validator.isNotNull(article.getTemplateId())) {
        String templateUuid = articleElement.attributeValue("template-uuid");

        JournalTemplate existingTemplate = JournalTemplateUtil.fetchByUUID_G(templateUuid,
                portletDataContext.getScopeGroupId());

        if (existingTemplate == null) {
            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

            long companyGroupId = companyGroup.getGroupId();

            existingTemplate = JournalTemplateUtil.fetchByUUID_G(templateUuid, companyGroupId);
        }

        if (existingTemplate == null) {
            String newTemplateId = templateIds.get(article.getTemplateId());

            if (Validator.isNotNull(newTemplateId)) {
                existingTemplate = JournalTemplateUtil.fetchByG_T(portletDataContext.getScopeGroupId(),
                        newTemplateId);
            }

            if (existingTemplate == null) {
                if (_log.isWarnEnabled()) {
                    StringBundler sb = new StringBundler();

                    sb.append("Template ");
                    sb.append(article.getTemplateId());
                    sb.append(" is missing for article ");
                    sb.append(article.getArticleId());
                    sb.append(", skipping this article.");

                    _log.warn(sb.toString());
                }

                return;
            }
        }

        parentTemplateId = existingTemplate.getTemplateId();
    }

    File smallFile = null;

    String smallImagePath = articleElement.attributeValue("small-image-path");

    if (article.isSmallImage() && Validator.isNotNull(smallImagePath)) {
        byte[] bytes = portletDataContext.getZipEntryAsByteArray(smallImagePath);

        smallFile = FileUtil.createTempFile(article.getSmallImageType());

        FileUtil.write(smallFile, bytes);
    }

    Map<String, byte[]> images = new HashMap<String, byte[]>();

    String imagePath = articleElement.attributeValue("image-path");

    if (portletDataContext.getBooleanParameter(_NAMESPACE, "images") && Validator.isNotNull(imagePath)) {

        List<String> imageFiles = portletDataContext.getZipFolderEntries(imagePath);

        for (String imageFile : imageFiles) {
            String fileName = imageFile;

            if (fileName.contains(StringPool.SLASH)) {
                fileName = fileName.substring(fileName.lastIndexOf(CharPool.SLASH) + 1);
            }

            if (fileName.endsWith(".xml")) {
                continue;
            }

            int pos = fileName.lastIndexOf(CharPool.PERIOD);

            if (pos != -1) {
                fileName = fileName.substring(0, pos);
            }

            images.put(fileName, portletDataContext.getZipEntryAsByteArray(imageFile));
        }
    }

    String articleURL = null;

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

    ServiceContext serviceContext = portletDataContext.createServiceContext(articleElement, article,
            _NAMESPACE);

    serviceContext.setAddGroupPermissions(addGroupPermissions);
    serviceContext.setAddGuestPermissions(addGuestPermissions);
    serviceContext.setAttribute("imported", Boolean.TRUE.toString());

    if (article.getStatus() != WorkflowConstants.STATUS_APPROVED) {
        serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);
    }

    JournalArticle importedArticle = null;

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

    if (portletDataContext.isDataStrategyMirror()) {
        JournalArticleResource articleResource = JournalArticleResourceUtil.fetchByUUID_G(articleResourceUuid,
                portletDataContext.getScopeGroupId());

        if (articleResource == null) {
            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

            long companyGroupId = companyGroup.getGroupId();

            articleResource = JournalArticleResourceUtil.fetchByUUID_G(articleResourceUuid, companyGroupId);
        }
        //Modification start
        if (articleResource == null) {
            articleResource = JournalArticleResourceUtil.fetchByG_A(portletDataContext.getScopeGroupId(),
                    articleId);
        }
        //Modification end
        serviceContext.setUuid(articleResourceUuid);

        JournalArticle existingArticle = null;

        if (articleResource != null) {
            try {
                existingArticle = JournalArticleLocalServiceUtil.getLatestArticle(
                        articleResource.getResourcePrimKey(), WorkflowConstants.STATUS_ANY, false);
            } catch (NoSuchArticleException nsae) {
            }
        }

        if (existingArticle == null) {
            existingArticle = JournalArticleUtil.fetchByG_A_V(portletDataContext.getScopeGroupId(),
                    newArticleId, article.getVersion());
        }

        if (existingArticle == null) {
            importedArticle = JournalArticleLocalServiceUtil.addArticle(userId,
                    portletDataContext.getScopeGroupId(), article.getClassNameId(), structurePrimaryKey,
                    articleId, autoArticleId, article.getVersion(), article.getTitleMap(),
                    article.getDescriptionMap(), article.getContent(), article.getType(), parentStructureId,
                    parentTemplateId, 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,
                    images, articleURL, serviceContext);
        } else {
            importedArticle = JournalArticleLocalServiceUtil.updateArticle(userId, existingArticle.getGroupId(),
                    existingArticle.getArticleId(), existingArticle.getVersion(), article.getTitleMap(),
                    article.getDescriptionMap(), article.getContent(), article.getType(), parentStructureId,
                    parentTemplateId, 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,
                    images, articleURL, serviceContext);
        }
    } else {
        importedArticle = JournalArticleLocalServiceUtil.addArticle(userId,
                portletDataContext.getScopeGroupId(), article.getClassNameId(), structurePrimaryKey, articleId,
                autoArticleId, article.getVersion(), article.getTitleMap(), article.getDescriptionMap(),
                article.getContent(), article.getType(), parentStructureId, parentTemplateId,
                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, images, articleURL,
                serviceContext);
    }

    if (smallFile != null) {
        smallFile.delete();
    }

    portletDataContext.importClassedModel(article, importedArticle, _NAMESPACE);

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

    Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

    if (importedArticle.getGroupId() == companyGroup.getGroupId()) {
        portletDataContext.addCompanyReference(JournalArticle.class, articleId);
    }

    if (!articleId.equals(importedArticle.getArticleId())) {
        if (_log.isWarnEnabled()) {
            _log.warn("An article with the ID " + articleId + " already " + "exists. The new generated ID is "
                    + importedArticle.getArticleId());
        }
    }
}

From source file:com.liferay.portlet.journal.lar.JournalPortletDataHandlerImpl.java

License:Open Source License

public static void importTemplate(PortletDataContext portletDataContext, Element templateElement)
        throws Exception {

    String path = templateElement.attributeValue("path");

    if (!portletDataContext.isPathNotProcessed(path)) {
        return;/*from w  w  w .ja v a 2  s  .c o m*/
    }

    JournalTemplate template = (JournalTemplate) portletDataContext.getZipEntryAsObject(path);

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

    JournalCreationStrategy creationStrategy = JournalCreationStrategyFactory.getInstance();

    long authorId = creationStrategy.getAuthorUserId(portletDataContext, template);

    if (authorId != JournalCreationStrategy.USE_DEFAULT_USER_ID_STRATEGY) {
        userId = authorId;
    }

    String templateId = template.getTemplateId();
    boolean autoTemplateId = false;

    if (Validator.isNumber(templateId)
            || (JournalTemplateUtil.fetchByG_T(portletDataContext.getScopeGroupId(), templateId) != null)) {

        autoTemplateId = true;
    }

    Map<String, String> structureIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalStructure.class + ".structureId");

    String parentStructureId = MapUtil.getString(structureIds, template.getStructureId(),
            template.getStructureId());

    String xsl = template.getXsl();

    xsl = importDLFileEntries(portletDataContext, templateElement, xsl);

    Group group = GroupLocalServiceUtil.getGroup(portletDataContext.getScopeGroupId());

    xsl = StringUtil.replace(xsl, "@data_handler_group_friendly_url@", group.getFriendlyURL());

    template.setXsl(xsl);

    boolean formatXsl = false;

    boolean addGroupPermissions = creationStrategy.addGroupPermissions(portletDataContext, template);
    boolean addGuestPermissions = creationStrategy.addGuestPermissions(portletDataContext, template);

    ServiceContext serviceContext = portletDataContext.createServiceContext(templateElement, template,
            _NAMESPACE);

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

    File smallFile = null;

    String smallImagePath = templateElement.attributeValue("small-image-path");

    if (template.isSmallImage() && Validator.isNotNull(smallImagePath)) {
        if (smallImagePath.endsWith(StringPool.PERIOD)) {
            smallImagePath += template.getSmallImageType();
        }

        byte[] bytes = portletDataContext.getZipEntryAsByteArray(smallImagePath);

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

            FileUtil.write(smallFile, bytes);
        }
    }

    JournalTemplate importedTemplate = null;

    if (portletDataContext.isDataStrategyMirror()) {
        JournalTemplate existingTemplate = JournalTemplateUtil.fetchByUUID_G(template.getUuid(),
                portletDataContext.getScopeGroupId());

        if (existingTemplate == null) {
            Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

            long companyGroupId = companyGroup.getGroupId();

            existingTemplate = JournalTemplateUtil.fetchByUUID_G(template.getUuid(), companyGroupId);
        }

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

            importedTemplate = JournalTemplateLocalServiceUtil.addTemplate(userId,
                    portletDataContext.getScopeGroupId(), templateId, autoTemplateId, parentStructureId,
                    template.getNameMap(), template.getDescriptionMap(), template.getXsl(), formatXsl,
                    template.getLangType(), template.getCacheable(), template.isSmallImage(),
                    template.getSmallImageURL(), smallFile, serviceContext);
        } else {
            String structureId = existingTemplate.getStructureId();

            if (Validator.isNull(structureId) && Validator.isNotNull(template.getStructureId())) {

                JournalStructure structure = JournalStructureUtil.fetchByG_S(template.getGroupId(),
                        template.getStructureId());

                if (structure == null) {
                    structureId = template.getStructureId();
                } else {
                    JournalStructure existingStructure = JournalStructureUtil.findByUUID_G(structure.getUuid(),
                            portletDataContext.getScopeGroupId());

                    structureId = existingStructure.getStructureId();
                }
            }

            importedTemplate = JournalTemplateLocalServiceUtil.updateTemplate(existingTemplate.getGroupId(),
                    existingTemplate.getTemplateId(), structureId, template.getNameMap(),
                    template.getDescriptionMap(), template.getXsl(), formatXsl, template.getLangType(),
                    template.getCacheable(), template.isSmallImage(), template.getSmallImageURL(), smallFile,
                    serviceContext);
        }
    } else {
        importedTemplate = JournalTemplateLocalServiceUtil.addTemplate(userId,
                portletDataContext.getScopeGroupId(), templateId, autoTemplateId, parentStructureId,
                template.getNameMap(), template.getDescriptionMap(), template.getXsl(), formatXsl,
                template.getLangType(), template.getCacheable(), template.isSmallImage(),
                template.getSmallImageURL(), smallFile, serviceContext);
    }

    if (smallFile != null) {
        smallFile.delete();
    }

    portletDataContext.importClassedModel(template, importedTemplate, _NAMESPACE);

    Map<String, String> templateIds = (Map<String, String>) portletDataContext
            .getNewPrimaryKeysMap(JournalTemplate.class + ".templateId");

    templateIds.put(template.getTemplateId(), importedTemplate.getTemplateId());

    if (!templateId.equals(importedTemplate.getTemplateId())) {
        if (_log.isWarnEnabled()) {
            _log.warn("A template with the ID " + templateId + " already " + "exists. The new generated ID is "
                    + importedTemplate.getTemplateId());
        }
    }
}

From source file:com.liferay.rtl.servlet.filters.dynamiccss.DynamicCSSFilter.java

License:Open Source License

protected Object getDynamicContent(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws Exception {

    String requestURI = request.getRequestURI();

    String requestPath = requestURI;

    String contextPath = request.getContextPath();

    if (!contextPath.equals(StringPool.SLASH)) {
        requestPath = requestPath.substring(contextPath.length());
    }//from ww  w . j a  v  a 2 s.c  om

    URL resourceURL = _servletContext.getResource(requestPath);

    if (resourceURL == null) {
        return null;
    }

    URLConnection urlConnection = resourceURL.openConnection();

    String cacheCommonFileName = getCacheFileName(request);

    File cacheContentTypeFile = new File(_tempDir, cacheCommonFileName + "_E_CONTENT_TYPE");
    File cacheDataFile = new File(_tempDir, cacheCommonFileName + "_E_DATA");

    if (cacheDataFile.exists() && (cacheDataFile.lastModified() >= urlConnection.getLastModified())) {

        if (cacheContentTypeFile.exists()) {
            String contentType = FileUtil.read(cacheContentTypeFile);

            response.setContentType(contentType);
        }

        return cacheDataFile;
    }

    String dynamicContent = null;

    String content = null;

    try {
        if (requestPath.endsWith(_CSS_EXTENSION)) {
            if (_log.isInfoEnabled()) {
                _log.info("Parsing SASS on CSS " + requestPath);
            }

            content = StringUtil.read(urlConnection.getInputStream());

            dynamicContent = DynamicCSSUtil.parseSass(_servletContext, request, requestPath, content);

            response.setContentType(ContentTypes.TEXT_CSS);

            FileUtil.write(cacheContentTypeFile, ContentTypes.TEXT_CSS);
        } else if (requestPath.endsWith(_JSP_EXTENSION)) {
            if (_log.isInfoEnabled()) {
                _log.info("Parsing SASS on JSP or servlet " + requestPath);
            }

            BufferCacheServletResponse bufferCacheServletResponse = new BufferCacheServletResponse(response);

            processFilter(DynamicCSSFilter.class, request, bufferCacheServletResponse, filterChain);

            bufferCacheServletResponse.finishResponse();

            content = bufferCacheServletResponse.getString();

            dynamicContent = DynamicCSSUtil.parseSass(_servletContext, request, requestPath, content);

            FileUtil.write(cacheContentTypeFile, bufferCacheServletResponse.getContentType());
        } else {
            return null;
        }
    } catch (Exception e) {
        _log.error("Unable to parse SASS on CSS " + requestPath, e);

        if (_log.isDebugEnabled()) {
            _log.debug(content);
        }

        response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
    }

    if (dynamicContent != null) {
        FileUtil.write(cacheDataFile, dynamicContent);
    } else {
        dynamicContent = content;
    }

    return dynamicContent;
}

From source file:com.liferay.testhook.hook.events.StartupAction.java

License:Open Source License

@Override
public void run(String[] ids) throws ActionException {
    try {/*  ww  w  . j a  va  2 s  .c  o  m*/
        FileUtil.write(TestHookUtil.getStartupActionFile(), StringPool.BLANK);
    } catch (Exception e) {
        throw new ActionException(e);
    }
}

From source file:com.liferay.util.xml.XMLMergerRunner.java

License:Open Source License

public void mergeAndSave(File masterFile, File slaveFile, File mergedFile) throws ClassNotFoundException,
        DocumentException, IllegalAccessException, InstantiationException, IOException {

    String xml1 = FileUtil.read(masterFile);
    String xml2 = FileUtil.read(slaveFile);

    String mergedXml = _merge(xml1, xml2);

    FileUtil.write(mergedFile, mergedXml);
}

From source file:com.liferay.web.extender.internal.webbundle.WebBundleProcessor.java

License:Open Source License

protected void processLiferayPortletXML(String webContextpath) throws IOException {

    File liferayPortletXMLFile = new File(_deployedAppFolder, "WEB-INF/liferay-portlet.xml");

    if (!liferayPortletXMLFile.exists()) {
        return;/*from   www  .j  a va 2s  .  c  o  m*/
    }

    String content = FileUtil.read(liferayPortletXMLFile);

    Document liferayPortletXMLDoc = null;

    try {
        liferayPortletXMLDoc = SAXReaderUtil.read(content);
    } catch (DocumentException de) {
        throw new IOException(de);
    }

    Element rootEl = liferayPortletXMLDoc.getRootElement();

    List<Element> portletElements = rootEl.elements("portlet");

    for (Element portletElement : portletElements) {
        Element previousChild = portletElement.element("virtual-path");

        if (previousChild == null) {
            previousChild = portletElement.element("icon");
        }

        if (previousChild == null) {
            previousChild = portletElement.element("portlet-name");
        }

        Element strutsPathElement = portletElement.element("struts-path");

        if (strutsPathElement == null) {
            List<Node> children = portletElement.content();

            int pos = children.indexOf(previousChild);

            strutsPathElement = SAXReaderUtil.createElement("struts-path");

            strutsPathElement.setText("osgi".concat(webContextpath));

            children.add(pos + 1, strutsPathElement);
        } else {
            String strutsPath = strutsPathElement.getTextTrim();

            if (!strutsPath.startsWith(StringPool.SLASH)) {
                strutsPath = StringPool.SLASH.concat(strutsPath);
            }

            strutsPath = "osgi".concat(webContextpath).concat(strutsPath);

            strutsPathElement.setText(strutsPath);
        }
    }

    content = DDMXMLUtil.formatXML(liferayPortletXMLDoc);

    FileUtil.write(liferayPortletXMLFile, content);
}

From source file:com.liferay.web.extender.internal.webbundle.WebBundleProcessor.java

License:Open Source License

protected void processPortletXML(String webContextpath) throws IOException {
    File portletXMLFile = new File(_deployedAppFolder, "WEB-INF/" + Portal.PORTLET_XML_FILE_NAME_STANDARD);

    if (!portletXMLFile.exists()) {
        return;/*from w  ww  .  jav a 2s. co m*/
    }

    String content = FileUtil.read(portletXMLFile);

    Document document = null;

    try {
        document = SAXReaderUtil.read(content);
    } catch (DocumentException de) {
        throw new IOException(de);
    }

    Element rootElement = document.getRootElement();

    List<Element> portletElements = rootElement.elements("portlet");

    for (Element portletElement : portletElements) {
        String portletName = portletElement.elementText("portlet-name");

        String invokerPortletName = "osgi".concat(webContextpath).concat(StringPool.SLASH).concat(portletName);

        XPath xPath = SAXReaderUtil.createXPath(_INVOKER_PORTLET_NAME_XPATH);

        Element invokerPortletNameEl = (Element) xPath.selectSingleNode(portletElement);

        if (invokerPortletNameEl == null) {
            Element portletClassElement = portletElement.element("portlet-class");

            List<Node> children = portletElement.content();

            int pos = children.indexOf(portletClassElement);

            QName qName = rootElement.getQName();

            Element initParamElement = SAXReaderUtil
                    .createElement(SAXReaderUtil.createQName("init-param", qName.getNamespace()));

            initParamElement.addElement("name").setText("com.liferay.portal.invokerPortletName");
            initParamElement.addElement("value").setText(invokerPortletName);

            children.add(pos + 1, initParamElement);
        } else {
            Element valueElement = invokerPortletNameEl.element("value");

            invokerPortletName = valueElement.getTextTrim();

            if (!invokerPortletName.startsWith(StringPool.SLASH)) {
                invokerPortletName = StringPool.SLASH.concat(invokerPortletName);
            }

            invokerPortletName = "osgi".concat(webContextpath).concat(invokerPortletName);

            valueElement.setText(invokerPortletName);
        }
    }

    content = DDMXMLUtil.formatXML(document);

    FileUtil.write(portletXMLFile, content);
}