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.portlet.documentlibrary.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  a va 2  s .  c o 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 sourceFileName = WebDAVUtil.getResourceName(destinationArray);
        String title = WebDAVUtil.getResourceName(destinationArray);
        String description = fileEntry.getDescription();
        String changeLog = StringPool.BLANK;

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

        ServiceContext serviceContext = new ServiceContext();

        serviceContext.setAssetTagNames(assetTagNames);

        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 = DLAppServiceUtil.getFileEntry(groupId, newParentFolderId, title);

                InputStream is = fileEntry.getContentStream();

                file = FileUtil.createTempFile(is);

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

                DLAppServiceUtil.deleteFileEntry(fileEntry.getFileEntryId());

                return status;
            } catch (NoSuchFileEntryException nsfee) {
            }
        }

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

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

        return status;
    } catch (PrincipalException pe) {
        return HttpServletResponse.SC_FORBIDDEN;
    } catch (DuplicateFileException dfe) {
        return HttpServletResponse.SC_PRECONDITION_FAILED;
    } catch (DuplicateFolderNameException dfne) {
        return HttpServletResponse.SC_PRECONDITION_FAILED;
    } catch (LockException le) {
        return WebDAVUtil.SC_LOCKED;
    } catch (Exception e) {
        throw new WebDAVException(e);
    } finally {
        FileUtil.delete(file);
    }
}

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;/*from   www .j av  a 2s. 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 = 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  2  s.  co m*/
    }

    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 .j av a 2 s  .co  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.web.extender.internal.webbundle.WebBundleURLConnection.java

License:Open Source License

@Override
public InputStream getInputStream() throws IOException {
    URL url = getURL();//from  w w  w  .  j a  v  a  2  s  .  c  o  m

    String path = url.getPath();
    String queryString = url.getQuery();

    Map<String, String[]> parameterMap = HttpUtil.getParameterMap(queryString);

    if (!parameterMap.containsKey(OSGiConstants.WEB_CONTEXTPATH)) {
        throw new IllegalArgumentException(OSGiConstants.WEB_CONTEXTPATH + " parameter is required");
    }

    URL innerURL = new URL(path);

    File tempFile = FileUtil.createTempFile("war");

    StreamUtil.transfer(innerURL.openStream(), new FileOutputStream(tempFile));

    try {
        WebBundleProcessor webBundleProcessor = new WebBundleProcessor(tempFile, parameterMap);

        webBundleProcessor.process();

        return webBundleProcessor.getInputStream();
    } finally {
        tempFile.delete();
    }
}

From source file:com.liferay.wiki.service.impl.WikiPageLocalServiceImpl.java

License:Open Source License

@Override
public List<FileEntry> addPageAttachments(long userId, long nodeId, String title,
        List<ObjectValuePair<String, InputStream>> inputStreamOVPs) throws PortalException {

    List<FileEntry> fileEntries = new ArrayList<>();

    if (inputStreamOVPs.isEmpty()) {
        return Collections.emptyList();
    }//  ww w.  j  a  v a 2 s  .co m

    for (int i = 0; i < inputStreamOVPs.size(); i++) {
        ObjectValuePair<String, InputStream> inputStreamOVP = inputStreamOVPs.get(i);

        String fileName = inputStreamOVP.getKey();
        InputStream inputStream = inputStreamOVP.getValue();

        File file = null;

        try {
            file = FileUtil.createTempFile(inputStream);

            String mimeType = MimeTypesUtil.getContentType(file, fileName);

            FileEntry fileEntry = addPageAttachment(userId, nodeId, title, fileName, file, mimeType);

            fileEntries.add(fileEntry);
        } catch (IOException ioe) {
            throw new SystemException("Unable to write temporary file", ioe);
        } finally {
            FileUtil.delete(file);
        }
    }

    return fileEntries;
}

From source file:com.liferay.wiki.util.test.WikiTestUtil.java

License:Open Source License

public static File addWikiAttachment(long userId, long nodeId, String title, String fileName, Class<?> clazz)
        throws Exception {

    byte[] fileBytes = FileUtil.getBytes(clazz, "dependencies/OSX_Test.docx");

    File file = null;/*w  w w  .  j  a  va  2  s.  c om*/

    if (ArrayUtil.isNotEmpty(fileBytes)) {
        file = FileUtil.createTempFile(fileBytes);
    }

    String mimeType = MimeTypesUtil.getExtensionContentType("docx");

    WikiPageLocalServiceUtil.addPageAttachment(userId, nodeId, title, fileName, file, mimeType);

    return file;
}

From source file:vn.com.ecopharma.emp.service.impl.DocumentLocalServiceImpl.java

License:Open Source License

public FileEntry uploadFile(PortletRequest request, InputStream is, String fileName, String folderName,
        boolean isAutoCreateFolder, ServiceContext serviceContext) {
    try {/*from ww w . j av a  2 s.  com*/
        File file = FileUtil.createTempFile(is);
        DLFolder folder = DLFolderLocalServiceUtil.fetchFolder(serviceContext.getScopeGroupId(), 0, folderName);
        if (folder == null) {
            if (!isAutoCreateFolder) {
                LOGGER.info("Folder not found");
                return null;
            }
            folder = createFolder(folderName, StringUtils.EMPTY, 0, serviceContext);
            LOGGER.info("Folder " + folder.getName() + " was created.");
        }

        // PortletRequest pRequest = (PortletRequest) LiferayFacesContext
        // .getCurrentInstance().getExternalContext().getRequest();

        // check if a file with same name has already existed
        if (DLFileEntryLocalServiceUtil.fetchFileEntryByName(serviceContext.getScopeGroupId(),
                folder.getFolderId(), fileName) != null) {
            fileName = fileName + System.currentTimeMillis();
        }
        final DLFileEntry dlFileEntry = uploadFile(request, file, fileName, StringUtils.EMPTY,
                StringUtils.EMPTY, folder.getFolderId(), serviceContext);
        file.delete();

        final FileEntry fe = getUploadFileEntry(dlFileEntry);

        // get file version & generate preview

        ImageProcessorUtil.generateImages(fe.getLatestFileVersion(), fe.getLatestFileVersion());

        /*
         * String fileURL = DLUtil .getPreviewURL(fe, fe.getFileVersion(),
         * (ThemeDisplay) pRequest .getAttribute(WebKeys.THEME_DISPLAY), "",
         * false, true); System.out.println(fileURL);
         */
        return fe;
    } catch (IOException e) {
        LOGGER.info(e);
    } catch (SystemException e) {
        LOGGER.info(e);
    } catch (PortalException e) {
        LOGGER.info(e);
    } catch (Exception e) {
        LOGGER.info(e);
    }
    return null;
}