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

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

Introduction

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

Prototype

public static String stripExtension(String fileName) 

Source Link

Usage

From source file:com.fmdp.webform.portlet.WebFormPortlet.java

License:Open Source License

public void saveData(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
    ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest);

    String portletId = PortalUtil.getPortletId(actionRequest);

    PortletPreferences preferences = PortletPreferencesFactoryUtil.getPortletSetup(actionRequest, portletId);

    boolean requireCaptcha = GetterUtil.getBoolean(preferences.getValue("requireCaptcha", StringPool.BLANK));
    String successURL = GetterUtil.getString(preferences.getValue("successURL", StringPool.BLANK));
    boolean sendAsEmail = GetterUtil.getBoolean(preferences.getValue("sendAsEmail", StringPool.BLANK));
    boolean sendThanksEmail = GetterUtil.getBoolean(preferences.getValue("sendThanksEmail", StringPool.BLANK));
    boolean saveToDatabase = GetterUtil.getBoolean(preferences.getValue("saveToDatabase", StringPool.BLANK));
    String databaseTableName = GetterUtil
            .getString(preferences.getValue("databaseTableName", StringPool.BLANK));
    boolean saveToFile = GetterUtil.getBoolean(preferences.getValue("saveToFile", StringPool.BLANK));
    boolean uploadToDisk = GetterUtil.getBoolean(preferences.getValue("uploadToDisk", StringPool.BLANK));
    boolean uploadToDM = GetterUtil.getBoolean(preferences.getValue("uploadToDM", StringPool.BLANK));
    long newFolderId = GetterUtil.getLong(preferences.getValue("newFolderId", StringPool.BLANK));
    String fileName = GetterUtil.getString(preferences.getValue("fileName", StringPool.BLANK));
    String uploadDiskDir = GetterUtil.getString(preferences.getValue("uploadDiskDir", StringPool.BLANK));

    if (requireCaptcha) {
        try {/*from   w  w w .  j  a v  a 2 s .  c  o  m*/
            CaptchaUtil.check(actionRequest);
        } catch (CaptchaTextException cte) {
            SessionErrors.add(actionRequest, CaptchaTextException.class.getName());

            return;
        }
    }

    UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);

    Map<String, String> fieldsMap = new LinkedHashMap<String, String>();

    String fileAttachment = "";

    for (int i = 1; true; i++) {
        String fieldLabel = preferences.getValue("fieldLabel" + i, StringPool.BLANK);

        String fieldType = preferences.getValue("fieldType" + i, StringPool.BLANK);

        if (Validator.isNull(fieldLabel)) {
            break;
        }

        if (StringUtil.equalsIgnoreCase(fieldType, "paragraph")) {
            continue;
        }
        if (StringUtil.equalsIgnoreCase(fieldType, "file")) {
            if (_log.isDebugEnabled()) {
                _log.debug("Field name for file: " + fieldLabel);
            }

            File file = uploadRequest.getFile("field" + i);

            String sourceFileName = uploadRequest.getFileName("field" + i);
            if (_log.isDebugEnabled()) {
                _log.debug("File attachment: " + sourceFileName);
            }
            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

            if (Validator.isNotNull(sourceFileName) && !"".equals(sourceFileName)) {

                if (uploadRequest.getSize("field" + i) == 0) {
                    SessionErrors.add(actionRequest, "uploadToDiskError", "Uploaded file size is 0");
                    if (_log.isDebugEnabled()) {
                        _log.debug("Uploaded file size is 0");
                    }
                    return;
                }
                //               List<String> uploadResults = new ArrayList<String>();
                String uploadResult = "";
                if (uploadToDisk) {
                    uploadResult = uploadFile(file, sourceFileName, uploadDiskDir);
                    if (uploadResult.equalsIgnoreCase("File Upload Error")) {
                        SessionErrors.add(actionRequest, "uploadToDiskError", uploadResult);
                        return;
                    }
                    fileAttachment = uploadDiskDir + File.separator + uploadResult;
                    //uploadResults.add(uploadResult);
                    jsonObject.put("fsOriginalName", sourceFileName);
                    jsonObject.put("fsName", uploadResult);
                }
                if (uploadToDM) {
                    uploadResult = "";
                    String contentType = MimeTypesUtil.getContentType(file);
                    Folder folderName = DLAppLocalServiceUtil.getFolder(newFolderId);
                    if (_log.isDebugEnabled()) {
                        _log.debug("DM Folder: " + folderName.getName());
                    }
                    InputStream inputStream = new FileInputStream(file);
                    long repositoryId = folderName.getRepositoryId();
                    try {
                        String selectedFileName = sourceFileName;
                        while (true) {
                            try {
                                DLAppLocalServiceUtil.getFileEntry(themeDisplay.getScopeGroupId(), newFolderId,
                                        selectedFileName);

                                StringBundler sb = new StringBundler(5);

                                sb.append(FileUtil.stripExtension(selectedFileName));
                                sb.append(StringPool.DASH);
                                sb.append(StringUtil.randomString());
                                sb.append(StringPool.PERIOD);
                                sb.append(FileUtil.getExtension(selectedFileName));

                                selectedFileName = sb.toString();
                            } catch (Exception e) {
                                break;
                            }
                        }

                        FileEntry fileEntry = DLAppLocalServiceUtil.addFileEntry(themeDisplay.getUserId(),
                                repositoryId, newFolderId, selectedFileName, //file.getName(), 
                                contentType, selectedFileName, "", "", inputStream, file.length(),
                                serviceContext);
                        if (_log.isDebugEnabled()) {
                            _log.debug("DM file uploade: " + fileEntry.getTitle());
                        }
                        //Map<String, Serializable> workflowContext = new HashMap<String, Serializable>();
                        //workflowContext.put("event",DLSyncConstants.EVENT_UPDATE);
                        //DLFileEntryLocalServiceUtil.updateStatus(themeDisplay.getUserId(), fileEntry.getFileVersion().getFileVersionId(), WorkflowConstants.STATUS_APPROVED, workflowContext, serviceContext);
                        uploadResult = String.valueOf(fileEntry.getFileEntryId());
                        //uploadResults.add(uploadResult);
                        String docUrl = themeDisplay.getPortalURL() + "/c/document_library/get_file?uuid="
                                + fileEntry.getUuid() + "&groupId=" + themeDisplay.getScopeGroupId();
                        jsonObject.put("fe", uploadResult);
                        jsonObject.put("feOriginalName", sourceFileName);
                        jsonObject.put("feName", fileEntry.getTitle());
                        jsonObject.put("feUrl", docUrl);
                    } catch (PortalException pe) {
                        SessionErrors.add(actionRequest, "uploadToDmError");
                        _log.error("The upload to DM failed", pe);
                        return;
                    } catch (Exception e) {
                        _log.error("The upload to DM failed", e);
                        return;
                    }
                }
                jsonObject.put("Status", "With Attachment");
            } else {
                jsonObject.put("Status", "No Attachment");
            }
            fieldsMap.put(fieldLabel, jsonObject.toString());
        } else {
            fieldsMap.put(fieldLabel, uploadRequest.getParameter("field" + i));
        }
    }

    Set<String> validationErrors = null;

    try {
        validationErrors = validate(fieldsMap, preferences);
    } catch (Exception e) {
        SessionErrors.add(actionRequest, "validationScriptError", e.getMessage().trim());

        return;
    }

    User currentUser = PortalUtil.getUser(actionRequest);
    String userEmail = "";
    if (!Validator.isNull(currentUser)) {
        userEmail = currentUser.getEmailAddress();
        if (_log.isDebugEnabled()) {
            _log.debug("User email for the form author: " + userEmail);
        }

        fieldsMap.put("email-from", userEmail);
    } else {
        fieldsMap.put("email-from", "guest");
    }

    DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone(themeDisplay.getTimeZone().getID()));
    Date dateobj = new Date();
    fieldsMap.put("email-sent-on", df.format(dateobj));

    if (validationErrors.isEmpty()) {
        boolean emailSuccess = true;
        boolean databaseSuccess = true;
        boolean fileSuccess = true;
        boolean emailThanksSuccess = true;

        if (sendAsEmail) {
            emailSuccess = WebFormUtil.sendEmail(themeDisplay.getCompanyId(), fieldsMap, preferences,
                    fileAttachment);
        }

        if (sendThanksEmail && !Validator.isNull(currentUser)) {
            emailThanksSuccess = WebFormUtil.sendThanksEmail(themeDisplay.getCompanyId(), fieldsMap,
                    preferences, userEmail);
        }

        if (saveToDatabase) {
            if (Validator.isNull(databaseTableName)) {
                databaseTableName = WebFormUtil.getNewDatabaseTableName(portletId);

                preferences.setValue("databaseTableName", databaseTableName);

                preferences.store();
            }

            databaseSuccess = saveDatabase(themeDisplay.getCompanyId(), fieldsMap, preferences,
                    databaseTableName);
        }

        if (saveToFile) {
            fileSuccess = saveFile(fieldsMap, fileName);
        }

        if (emailSuccess && emailThanksSuccess && databaseSuccess && fileSuccess) {
            if (Validator.isNull(successURL)) {
                SessionMessages.add(actionRequest, "success");
            } else {
                SessionMessages.add(actionRequest,
                        portletId + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_SUCCESS_MESSAGE);
            }
        } else {
            SessionErrors.add(actionRequest, "error");
        }
    } else {
        for (String badField : validationErrors) {
            SessionErrors.add(actionRequest, "error" + badField);
        }
    }

    if (SessionErrors.isEmpty(actionRequest) && Validator.isNotNull(successURL)) {

        actionResponse.sendRedirect(successURL);
    }
}

From source file:com.liferay.document.library.internal.util.DLValidatorImpl.java

License:Open Source License

@Override
public boolean isValidName(String name) {
    if (Validator.isNull(name)) {
        return false;
    }/*from  w w w  . j av a2  s .c om*/

    for (String blacklistChar : PropsValues.DL_CHAR_BLACKLIST) {
        if (name.contains(blacklistChar)) {
            return false;
        }
    }

    for (String blacklistLastChar : PropsValues.DL_CHAR_LAST_BLACKLIST) {
        if (blacklistLastChar.startsWith(UnicodeFormatter.UNICODE_PREFIX)) {
            blacklistLastChar = UnicodeFormatter.parseString(blacklistLastChar);
        }

        if (name.endsWith(blacklistLastChar)) {
            return false;
        }
    }

    String nameWithoutExtension = FileUtil.stripExtension(name);

    for (String blacklistName : PropsValues.DL_NAME_BLACKLIST) {
        if (StringUtil.equalsIgnoreCase(nameWithoutExtension, blacklistName)) {

            return false;
        }
    }

    return true;
}

From source file:com.liferay.document.library.internal.util.DLValidatorImpl.java

License:Open Source License

protected String replaceDLNameBlacklist(String title) {
    String extension = FileUtil.getExtension(title);
    String nameWithoutExtension = FileUtil.stripExtension(title);

    for (String blacklistName : PropsValues.DL_NAME_BLACKLIST) {
        if (StringUtil.equalsIgnoreCase(nameWithoutExtension, blacklistName)) {

            if (Validator.isNull(extension)) {
                return nameWithoutExtension + StringPool.UNDERLINE;
            }/*from   w w w  .  j  av a2  s .c o  m*/

            return StringBundler.concat(nameWithoutExtension, StringPool.UNDERLINE, StringPool.PERIOD,
                    extension);
        }
    }

    return title;
}

From source file:com.liferay.document.library.web.internal.portlet.action.GetFileActionHelper.java

License:Open Source License

protected void getFile(long fileEntryId, long folderId, String name, String title, String version,
        long fileShortcutId, String uuid, long groupId, String targetExtension, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    if (name.startsWith("DLFE-")) {
        name = name.substring(5);/*from  w  w  w.  jav  a 2  s .  com*/
    }

    name = FileUtil.stripExtension(name);

    FileEntry fileEntry = null;

    if (Validator.isNotNull(uuid) && (groupId > 0)) {
        fileEntry = DLAppServiceUtil.getFileEntryByUuidAndGroupId(uuid, groupId);

        folderId = fileEntry.getFolderId();
    }

    if (fileEntryId > 0) {
        fileEntry = DLAppServiceUtil.getFileEntry(fileEntryId);
    } else if (fileShortcutId <= 0) {
        if (Validator.isNotNull(title)) {
            fileEntry = DLAppServiceUtil.getFileEntry(groupId, folderId, title);
        } else if (Validator.isNotNull(name)) {
            DLFileEntry dlFileEntry = DLFileEntryLocalServiceUtil.fetchFileEntryByName(groupId, folderId, name);

            if (dlFileEntry == null) {

                // LPS-30374

                List<DLFileEntry> dlFileEntries = DLFileEntryLocalServiceUtil.getFileEntries(folderId, name);

                if (!dlFileEntries.isEmpty()) {
                    dlFileEntry = dlFileEntries.get(0);
                }
            }

            if (dlFileEntry != null) {
                ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

                PermissionChecker permissionChecker = themeDisplay.getPermissionChecker();

                DLFileEntryPermission.check(permissionChecker, dlFileEntry, ActionKeys.VIEW);

                fileEntry = new LiferayFileEntry(dlFileEntry);
            }
        }
    } else {
        FileShortcut fileShortcut = DLAppServiceUtil.getFileShortcut(fileShortcutId);

        fileEntryId = fileShortcut.getToFileEntryId();

        fileEntry = DLAppServiceUtil.getFileEntry(fileEntryId);
    }

    if (Validator.isNull(version)) {
        if ((fileEntry != null) && Validator.isNotNull(fileEntry.getVersion())) {

            version = fileEntry.getVersion();
        } else {
            throw new NoSuchFileEntryException("{fileEntryId=" + fileEntryId + "}");
        }
    }

    FileVersion fileVersion = fileEntry.getFileVersion(version);

    InputStream is = fileVersion.getContentStream(true);

    String fileName = fileVersion.getTitle();

    String sourceExtension = fileVersion.getExtension();

    if (Validator.isNotNull(sourceExtension) && !fileName.endsWith(StringPool.PERIOD + sourceExtension)) {

        fileName += StringPool.PERIOD + sourceExtension;
    }

    long contentLength = fileVersion.getSize();
    String contentType = fileVersion.getMimeType();

    if (Validator.isNotNull(targetExtension)) {
        String id = DLUtil.getTempFileId(fileEntry.getFileEntryId(), version);

        File convertedFile = DocumentConversionUtil.convert(id, is, sourceExtension, targetExtension);

        if (convertedFile != null) {
            fileName = FileUtil.stripExtension(fileName).concat(StringPool.PERIOD).concat(targetExtension);
            is = new FileInputStream(convertedFile);
            contentLength = convertedFile.length();
            contentType = MimeTypesUtil.getContentType(fileName);
        }
    }

    FlashMagicBytesUtil.Result flashMagicBytesUtilResult = FlashMagicBytesUtil.check(is);

    if (flashMagicBytesUtilResult.isFlash()) {
        fileName = FileUtil.stripExtension(fileName) + ".swf";
    }

    is = flashMagicBytesUtilResult.getInputStream();

    ServletResponseUtil.sendFile(request, response, fileName, is, contentLength, contentType);
}

From source file:com.liferay.exportimport.resources.importer.internal.portlet.preferences.JournalPortletPreferencesTranslator.java

License:Open Source License

@Override
public void translate(JSONObject portletPreferencesJSONObject, String key,
        PortletPreferences portletPreferences) throws PortletException {

    String value = portletPreferencesJSONObject.getString(key);

    if (key.equals("articleId")) {
        String articleId = FileUtil.stripExtension(value);

        articleId = StringUtil.toUpperCase(articleId);

        value = StringUtil.replace(articleId, CharPool.SPACE, CharPool.DASH);
    }//from w  w  w . jav a  2 s.  co m

    portletPreferences.setValue(key, value);
}

From source file:com.liferay.exportimport.resources.importer.internal.util.FileSystemImporter.java

License:Open Source License

protected void addApplicationDisplayTemplate(String script, File file, long classNameId)
        throws PortalException {

    String fileName = FileUtil.stripExtension(file.getName());

    String name = getName(fileName);

    DDMTemplate ddmTemplate = ddmTemplateLocalService.fetchTemplate(groupId, classNameId, getKey(fileName));

    if (ddmTemplate != null) {
        if (!developerModeEnabled) {
            if (_log.isInfoEnabled()) {
                _log.info(StringBundler.concat("DDM template with name ", name, " and version ",
                        String.valueOf(version), " already exists"));
            }/*from  w ww  .j a  v a  2s . c o  m*/

            return;
        }

        if (!updateModeEnabled) {
            ddmTemplateLocalService.deleteTemplate(ddmTemplate);
        }
    }

    try {
        if (!updateModeEnabled || (ddmTemplate == null)) {
            ddmTemplateLocalService.addTemplate(userId, groupId, classNameId, 0,
                    portal.getClassNameId(PortletDisplayTemplate.class), getKey(fileName), getMap(name), null,
                    DDMTemplateConstants.TEMPLATE_TYPE_DISPLAY, StringPool.BLANK,
                    getDDMTemplateLanguage(file.getName()), script, true, false, StringPool.BLANK, null,
                    serviceContext);
        } else {
            ddmTemplateLocalService.updateTemplate(userId, ddmTemplate.getTemplateId(),
                    ddmTemplate.getClassPK(), getMap(name), null, DDMTemplateConstants.TEMPLATE_TYPE_DISPLAY,
                    StringPool.BLANK, getDDMTemplateLanguage(file.getName()), script,
                    ddmTemplate.getCacheable(), serviceContext);
        }
    } catch (PortalException pe) {
        if (_log.isWarnEnabled()) {
            _log.warn("Unable to import application display template " + file.getName(), pe);
        }

        throw pe;
    }
}

From source file:com.liferay.exportimport.resources.importer.internal.util.FileSystemImporter.java

License:Open Source License

protected void addDDLStructures(String dirName) throws Exception {
    File dir = new File(_resourcesDir, dirName);

    if (!dir.isDirectory() || !dir.canRead()) {
        return;//from w ww .jav  a  2  s  . c  om
    }

    File[] files = listFiles(dir);

    for (File file : files) {
        String fileName = FileUtil.stripExtension(file.getName());

        addDDMStructures(fileName, getInputStream(file));
    }
}

From source file:com.liferay.exportimport.resources.importer.internal.util.FileSystemImporter.java

License:Open Source License

protected void addDDMStructures(String fileName, InputStream inputStream) throws Exception {

    fileName = FileUtil.stripExtension(fileName);

    String name = getName(fileName);

    DDMStructure ddmStructure = ddmStructureLocalService.fetchStructure(groupId,
            portal.getClassNameId(DDLRecordSet.class), getKey(fileName));

    if (ddmStructure != null) {
        if (!developerModeEnabled) {
            if (_log.isInfoEnabled()) {
                _log.info(StringBundler.concat("DDM structure with name ", name, " and version ",
                        String.valueOf(version), " already exists"));
            }/* www.jav a  2 s .  c  o  m*/

            return;
        }

        if (!updateModeEnabled) {
            ddmStructureLocalService.deleteDDMStructure(ddmStructure);
        }
    }

    try {
        String definition = StringUtil.read(inputStream);

        ddmxml.validateXML(definition);

        DDMForm ddmForm = ddmFormXSDDeserializer.deserialize(definition);

        DDMFormLayout ddmFormLayout = DDMUtil.getDefaultDDMFormLayout(ddmForm);

        if (!updateModeEnabled || (ddmStructure == null)) {
            ddmStructure = ddmStructureLocalService.addStructure(userId, groupId,
                    DDMStructureConstants.DEFAULT_PARENT_STRUCTURE_ID,
                    portal.getClassNameId(DDLRecordSet.class), getKey(fileName), getMap(name), null, ddmForm,
                    ddmFormLayout, StorageType.JSON.toString(), DDMStructureConstants.TYPE_DEFAULT,
                    serviceContext);
        } else {
            ddmStructure = ddmStructureLocalService.updateStructure(userId, ddmStructure.getStructureId(),
                    DDMStructureConstants.DEFAULT_PARENT_STRUCTURE_ID, getMap(name), null, ddmForm,
                    ddmFormLayout, serviceContext);
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn("Unable to import DDM structure " + fileName, e);
        }

        throw e;
    }

    addDDLDisplayTemplates(ddmStructure.getStructureKey(), _DDL_STRUCTURE_DISPLAY_TEMPLATE_DIR_NAME, fileName);

    addDDLFormTemplates(ddmStructure.getStructureKey(), _DDL_STRUCTURE_FORM_TEMPLATE_DIR_NAME, fileName);
}

From source file:com.liferay.exportimport.resources.importer.internal.util.FileSystemImporter.java

License:Open Source License

protected void addDDMStructures(String parentDDMStructureKey, String fileName, InputStream inputStream)
        throws Exception {

    String language = getDDMStructureLanguage(fileName);

    fileName = FileUtil.stripExtension(fileName);

    String name = getName(fileName);

    DDMStructure ddmStructure = ddmStructureLocalService.fetchStructure(groupId,
            portal.getClassNameId(JournalArticle.class), getKey(fileName));

    if (ddmStructure != null) {
        if (!developerModeEnabled) {
            if (_log.isInfoEnabled()) {
                _log.info(StringBundler.concat("DDM structure with name ", name, " and version ",
                        String.valueOf(version), " already exists"));
            }/* w w w. j a v a2  s.  c o m*/

            return;
        }

        if (!updateModeEnabled) {
            ddmStructureLocalService.deleteDDMStructure(ddmStructure);
        }
    }

    String content = StringUtil.read(inputStream);

    DDMForm ddmForm = null;

    if (language.equals(TemplateConstants.LANG_TYPE_XML)) {
        if (isJournalStructureXSD(content)) {
            content = journalConverter.getDDMXSD(content);
        }

        ddmxml.validateXML(content);

        ddmForm = ddmFormXSDDeserializer.deserialize(content);
    } else {
        ddmForm = ddmFormJSONDeserializer.deserialize(content);
    }

    DDMFormLayout ddmFormLayout = DDMUtil.getDefaultDDMFormLayout(ddmForm);

    setServiceContext(fileName);

    try {
        if (!updateModeEnabled || (ddmStructure == null)) {
            ddmStructure = ddmStructureLocalService.addStructure(userId, groupId, parentDDMStructureKey,
                    portal.getClassNameId(JournalArticle.class), getKey(fileName), getMap(name), null, ddmForm,
                    ddmFormLayout, JournalServiceConfigurationValues.JOURNAL_ARTICLE_STORAGE_TYPE,
                    DDMStructureConstants.TYPE_DEFAULT, serviceContext);
        } else {
            DDMStructure parentStructure = ddmStructureLocalService.fetchStructure(groupId,
                    portal.getClassNameId(JournalArticle.class), parentDDMStructureKey);

            long parentDDMStructureId = DDMStructureConstants.DEFAULT_PARENT_STRUCTURE_ID;

            if (parentStructure != null) {
                parentDDMStructureId = parentStructure.getStructureId();
            }

            ddmStructure = ddmStructureLocalService.updateStructure(userId, ddmStructure.getStructureId(),
                    parentDDMStructureId, getMap(name), null, ddmForm, ddmFormLayout, serviceContext);
        }
    } catch (PortalException pe) {
        if (_log.isWarnEnabled()) {
            _log.warn("Unable to import DDM structure " + fileName, pe);
        }

        throw pe;
    }

    _ddmStructureKeys.add(ddmStructure.getStructureKey());

    addDDMTemplates(ddmStructure.getStructureKey(), _JOURNAL_DDM_TEMPLATES_DIR_NAME + fileName);

    if (Validator.isNull(parentDDMStructureKey)) {
        addDDMStructures(ddmStructure.getStructureKey(), _JOURNAL_DDM_STRUCTURES_DIR_NAME + fileName);
    }
}

From source file:com.liferay.exportimport.resources.importer.internal.util.FileSystemImporter.java

License:Open Source License

protected void addDDMTemplate(long templateGroupId, long ddmStructureId, String fileName, String language,
        String script, String type, String mode) throws Exception {

    fileName = FileUtil.getShortFileName(fileName);

    fileName = FileUtil.stripExtension(fileName);

    String name = getName(fileName);

    DDMTemplate ddmTemplate = ddmTemplateLocalService.fetchTemplate(groupId,
            portal.getClassNameId(DDMStructure.class), getKey(fileName));

    if (ddmTemplate != null) {
        if (!developerModeEnabled) {
            if (_log.isInfoEnabled()) {
                _log.info(StringBundler.concat("DDM template with name ", name, " and version ",
                        String.valueOf(version), " already exists"));
            }//from  w  w w .j  av  a2 s.  co m

            return;
        }

        if (!updateModeEnabled) {
            ddmTemplateLocalService.deleteTemplate(ddmTemplate);
        }
    }

    try {
        if (!updateModeEnabled || (ddmTemplate == null)) {
            ddmTemplateLocalService.addTemplate(userId, templateGroupId,
                    portal.getClassNameId(DDMStructure.class), ddmStructureId,
                    portal.getClassNameId(JournalArticle.class), getKey(fileName), getMap(name), null, type,
                    mode, language, script, true, false, StringPool.BLANK, null, serviceContext);
        } else {
            ddmTemplateLocalService.updateTemplate(userId, ddmTemplate.getTemplateId(),
                    portal.getClassNameId(DDMStructure.class), getMap(name), null,
                    DDMTemplateConstants.TEMPLATE_TYPE_DISPLAY, null, language, script,
                    ddmTemplate.getCacheable(), serviceContext);
        }
    } catch (PortalException pe) {
        if (_log.isWarnEnabled()) {
            _log.warn("Unable to import DDM template " + fileName, pe);
        }

        throw pe;
    }
}