Example usage for com.liferay.portal.kernel.xml SAXReaderUtil read

List of usage examples for com.liferay.portal.kernel.xml SAXReaderUtil read

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.xml SAXReaderUtil read.

Prototype

public static Document read(URL url) throws DocumentException 

Source Link

Usage

From source file:com.liferay.calendar.web.upgrade.v1_1_0.test.UpgradePortalPreferencesTest.java

License:Open Source License

protected String getPreference(String preferencesXML, String namespace, String name) throws DocumentException {

    String value = null;/*from   w ww. ja  va  2 s  . co m*/

    Document document = SAXReaderUtil.read(preferencesXML);

    Element rootElement = document.getRootElement();

    Iterator<Element> iterator = rootElement.elementIterator();

    while (iterator.hasNext()) {
        Element preferenceElement = iterator.next();

        String preferenceName = preferenceElement.elementText("name");

        if (preferenceName.equals(namespace + "#" + name)) {
            value = preferenceElement.elementText("value");
        }
    }

    return value;
}

From source file:com.liferay.customsql.CustomSQL.java

License:Open Source License

protected void read(ClassLoader classLoader, String source) throws Exception {

    InputStream is = classLoader.getResourceAsStream(source);

    if (is == null) {
        return;/*from  w w w .j a v a 2 s . c om*/
    }

    if (_log.isDebugEnabled()) {
        _log.debug("Loading " + source);
    }

    Document document = SAXReaderUtil.read(is);

    Element rootElement = document.getRootElement();

    for (Element sqlElement : rootElement.elements("sql")) {
        String file = sqlElement.attributeValue("file");

        if (Validator.isNotNull(file)) {
            read(classLoader, file);
        } else {
            String id = sqlElement.attributeValue("id");
            String content = transform(sqlElement.getText());

            content = replaceIsNull(content);

            _sqlPool.put(id, content);
        }
    }
}

From source file:com.liferay.ddlform.lar.DDLFormPortletDataHandlerImpl.java

License:Open Source License

@Override
protected PortletPreferences doImportData(PortletDataContext portletDataContext, String portletId,
        PortletPreferences portletPreferences, String data) throws Exception {

    portletDataContext.importPermissions("com.liferay.portlet.dynamicdatalist",
            portletDataContext.getSourceGroupId(), portletDataContext.getScopeGroupId());

    if (Validator.isNull(data)) {
        return null;
    }/*from   w  ww . j  a va 2 s . co  m*/

    Document document = SAXReaderUtil.read(data);

    Element rootElement = document.getRootElement();

    Element recordSetElement = rootElement.element("record-set");

    if (recordSetElement != null) {
        DDLPortletDataHandler ddlPortletDataHandler = DDLPortletDataHandlerUtil.getDDLPortletDataHandler();

        ddlPortletDataHandler.importRecordSet(portletDataContext, recordSetElement);
    }

    Map<Long, Long> templateIds = (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(DDMTemplate.class);

    long importedFormDDMTemplateId = GetterUtil.getLong(portletPreferences.getValue("formDDMTemplateId", null));

    long formDDMTemplateId = MapUtil.getLong(templateIds, importedFormDDMTemplateId, importedFormDDMTemplateId);

    portletPreferences.setValue("formDDMTemplateId", String.valueOf(formDDMTemplateId));

    long importedRecordSetId = GetterUtil.getLong(portletPreferences.getValue("recordSetId", null));

    Map<Long, Long> recordSetIds = (Map<Long, Long>) portletDataContext
            .getNewPrimaryKeysMap(DDLRecordSet.class);

    long recordSetId = MapUtil.getLong(recordSetIds, importedRecordSetId, importedRecordSetId);

    portletPreferences.setValue("recordSetId", String.valueOf(recordSetId));

    return portletPreferences;
}

From source file:com.liferay.dynamic.data.mapping.internal.upgrade.v1_0_0.UpgradeDynamicDataMappingTest.java

License:Open Source License

@Test
public void testToXMLWithoutLocalizedData() throws Exception {
    Map<String, String> expandoValuesMap = new HashMap<>();

    expandoValuesMap.put("Text", createLocalizationXML(new String[] { "Joe Bloggs" }));

    String fieldsDisplay = "Text_INSTANCE_hcxo";

    expandoValuesMap.put("_fieldsDisplay", createLocalizationXML(new String[] { fieldsDisplay }));

    String xml = _upgradeDynamicDataMapping.toXML(expandoValuesMap);

    Document document = SAXReaderUtil.read(xml);

    Map<String, Map<String, List<String>>> dataMap = toDataMap(document);

    Map<String, List<String>> actualTextData = dataMap.get("Text");

    assertEquals(ListUtil.toList(new String[] { "Joe Bloggs" }), actualTextData.get("en_US"));

    Map<String, List<String>> actualFieldsDisplayData = dataMap.get("_fieldsDisplay");

    assertEquals(ListUtil.toList(new String[] { fieldsDisplay }), actualFieldsDisplayData.get("en_US"));
}

From source file:com.liferay.dynamic.data.mapping.internal.upgrade.v1_0_0.UpgradeDynamicDataMappingTest.java

License:Open Source License

@Test
public void testToXMLWithRepeatableAndLocalizedData() throws Exception {
    Map<String, String> expandoValuesMap = new HashMap<>();

    expandoValuesMap.put("Text",
            createLocalizationXML(new String[] { "A", "B", "C" }, new String[] { "D", "E", "F" }));

    String fieldsDisplay = "Text_INSTANCE_hcxo,Text_INSTANCE_vfqd,Text_INSTANCE_ycey";

    expandoValuesMap.put("_fieldsDisplay", createLocalizationXML(new String[] { fieldsDisplay }));

    String xml = _upgradeDynamicDataMapping.toXML(expandoValuesMap);

    Document document = SAXReaderUtil.read(xml);

    Map<String, Map<String, List<String>>> dataMap = toDataMap(document);

    Map<String, List<String>> actualTextData = dataMap.get("Text");

    assertEquals(ListUtil.toList(new String[] { "A", "B", "C" }), actualTextData.get("en_US"));

    assertEquals(ListUtil.toList(new String[] { "D", "E", "F" }), actualTextData.get("pt_BR"));

    Map<String, List<String>> actualFieldsDisplayData = dataMap.get("_fieldsDisplay");

    assertEquals(ListUtil.toList(new String[] { fieldsDisplay }), actualFieldsDisplayData.get("en_US"));
}

From source file:com.liferay.dynamic.data.mapping.model.impl.DDMTemplateImpl.java

License:Open Source License

@Override
public String getDefaultLanguageId() {
    Document document = null;//from   ww  w . j av a  2  s. c o  m

    try {
        document = SAXReaderUtil.read(getName());

        if (document != null) {
            Element rootElement = document.getRootElement();

            return rootElement.attributeValue("default-locale");
        }
    } catch (Exception e) {
    }

    Locale locale = LocaleUtil.getSiteDefault();

    return locale.toString();
}

From source file:com.liferay.exportimport.controller.LayoutImportController.java

License:Open Source License

protected void doImportFile(PortletDataContext portletDataContext, long userId) throws Exception {

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

    Group group = _groupLocalService.getGroup(portletDataContext.getGroupId());

    String layoutsImportMode = MapUtil.getString(parameterMap, PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID);
    boolean permissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);

    if (group.isLayoutSetPrototype()) {
        parameterMap.put(PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_LINK_ENABLED,
                new String[] { Boolean.FALSE.toString() });
    }//w ww.  jav  a  2  s. c  o m

    if (_log.isDebugEnabled()) {
        _log.debug("Import permissions " + permissions);
    }

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    LayoutCache layoutCache = new LayoutCache();

    long companyId = portletDataContext.getCompanyId();

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
        serviceContext = new ServiceContext();
    }

    serviceContext.setCompanyId(companyId);
    serviceContext.setSignedIn(false);
    serviceContext.setUserId(userId);

    ServiceContextThreadLocal.pushServiceContext(serviceContext);

    // LAR validation

    validateFile(companyId, portletDataContext.getGroupId(), parameterMap, portletDataContext.getZipReader());

    // Source and target group id

    Map<Long, Long> groupIds = (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Group.class);

    groupIds.put(portletDataContext.getSourceGroupId(), portletDataContext.getGroupId());

    // Manifest

    ManifestSummary manifestSummary = _exportImportHelper.getManifestSummary(portletDataContext);

    portletDataContext.setManifestSummary(manifestSummary);

    // Layout and layout set prototype

    Element rootElement = portletDataContext.getImportDataRootElement();

    Element headerElement = rootElement.element("header");

    String layoutSetPrototypeUuid = headerElement.attributeValue("layout-set-prototype-uuid");

    String larType = headerElement.attributeValue("type");

    portletDataContext.setType(larType);

    if (group.isLayoutPrototype() && larType.equals("layout-prototype")) {
        parameterMap.put(PortletDataHandlerKeys.DELETE_MISSING_LAYOUTS,
                new String[] { Boolean.FALSE.toString() });

        LayoutPrototype layoutPrototype = _layoutPrototypeLocalService.getLayoutPrototype(group.getClassPK());

        String layoutPrototypeUuid = GetterUtil.getString(headerElement.attributeValue("type-uuid"));

        LayoutPrototype existingLayoutPrototype = null;

        if (Validator.isNotNull(layoutPrototypeUuid)) {
            try {
                existingLayoutPrototype = _layoutPrototypeLocalService
                        .getLayoutPrototypeByUuidAndCompanyId(layoutPrototypeUuid, companyId);
            } catch (NoSuchLayoutPrototypeException nslpe) {

                // LPS-52675

                if (_log.isDebugEnabled()) {
                    _log.debug(nslpe, nslpe);
                }
            }
        }

        if (existingLayoutPrototype == null) {
            List<Layout> layouts = _layoutLocalService
                    .getLayoutsByLayoutPrototypeUuid(layoutPrototype.getUuid());

            layoutPrototype.setUuid(layoutPrototypeUuid);

            _layoutPrototypeLocalService.updateLayoutPrototype(layoutPrototype);

            for (Layout layout : layouts) {
                layout.setLayoutPrototypeUuid(layoutPrototypeUuid);

                _layoutLocalService.updateLayout(layout);
            }
        }
    } else if (group.isLayoutSetPrototype() && larType.equals("layout-set-prototype")) {

        parameterMap.put(PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_SETTINGS,
                new String[] { Boolean.TRUE.toString() });

        LayoutSetPrototype layoutSetPrototype = _layoutSetPrototypeLocalService
                .getLayoutSetPrototype(group.getClassPK());

        String importedLayoutSetPrototypeUuid = GetterUtil.getString(headerElement.attributeValue("type-uuid"));

        LayoutSetPrototype existingLayoutSetPrototype = null;

        if (Validator.isNotNull(importedLayoutSetPrototypeUuid)) {
            try {
                existingLayoutSetPrototype = _layoutSetPrototypeLocalService
                        .getLayoutSetPrototypeByUuidAndCompanyId(importedLayoutSetPrototypeUuid, companyId);
            } catch (NoSuchLayoutSetPrototypeException nslspe) {

                // LPS-52675

                if (_log.isDebugEnabled()) {
                    _log.debug(nslspe, nslspe);
                }
            }
        }

        if (existingLayoutSetPrototype == null) {
            List<LayoutSet> layoutSets = _layoutSetLocalService
                    .getLayoutSetsByLayoutSetPrototypeUuid(layoutSetPrototype.getUuid());

            layoutSetPrototype.setUuid(importedLayoutSetPrototypeUuid);

            _layoutSetPrototypeLocalService.updateLayoutSetPrototype(layoutSetPrototype);

            for (LayoutSet curLayoutSet : layoutSets) {
                curLayoutSet.setLayoutSetPrototypeUuid(importedLayoutSetPrototypeUuid);

                _layoutSetLocalService.updateLayoutSet(curLayoutSet);
            }
        }
    } else if (larType.equals("layout-set-prototype")) {
        parameterMap.put(PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_SETTINGS,
                new String[] { Boolean.TRUE.toString() });

        layoutSetPrototypeUuid = GetterUtil.getString(headerElement.attributeValue("type-uuid"));
    }

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
        portletDataContext.setLayoutSetPrototypeUuid(layoutSetPrototypeUuid);
    }

    List<Element> portletElements = fetchPortletElements(rootElement);

    if (permissions) {
        for (Element portletElement : portletElements) {
            String portletPath = portletElement.attributeValue("path");

            Document portletDocument = SAXReaderUtil.read(portletDataContext.getZipEntryAsString(portletPath));

            _permissionImporter.checkRoles(layoutCache, companyId, portletDataContext.getGroupId(), userId,
                    portletDocument.getRootElement());
        }

        _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

    if (!layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

        _portletImportController.readExpandoTables(portletDataContext);
    }

    _portletImportController.readLocks(portletDataContext);

    // Import the group

    Element groupsElement = portletDataContext.getImportDataGroupElement(StagedGroup.class);

    for (Element groupElement : groupsElement.elements()) {
        StagedModelDataHandlerUtil.importStagedModel(portletDataContext, groupElement);
    }

    // Asset links

    _portletImportController.importAssetLinks(portletDataContext);

    // Site

    _groupLocalService.updateSite(portletDataContext.getGroupId(), true);

    if (_log.isInfoEnabled()) {
        _log.info("Importing layouts takes " + stopWatch.getTime() + " ms");
    }

    ZipReader zipReader = portletDataContext.getZipReader();

    zipReader.close();
}

From source file:com.liferay.exportimport.controller.LayoutImportController.java

License:Open Source License

protected void validateFile(long companyId, long groupId, Map<String, String[]> parameterMap,
        ZipReader zipReader) throws Exception {

    // XML//  www . ja  v a 2 s . c  o  m

    String xml = zipReader.getEntryAsString("/manifest.xml");

    if (xml == null) {
        throw new LARFileException(LARFileException.TYPE_MISSING_MANIFEST);
    }

    Element rootElement = null;

    try {
        Document document = SAXReaderUtil.read(xml);

        rootElement = document.getRootElement();
    } catch (Exception e) {
        throw new LARFileException(LARFileException.TYPE_INVALID_MANIFEST, e);
    }

    // Bundle compatibility

    Element headerElement = rootElement.element("header");

    int importBuildNumber = GetterUtil.getInteger(headerElement.attributeValue("build-number"));

    if (importBuildNumber < ReleaseInfo.RELEASE_7_0_0_BUILD_NUMBER) {
        int buildNumber = ReleaseInfo.getBuildNumber();

        if (buildNumber != importBuildNumber) {
            throw new LayoutImportException(LayoutImportException.TYPE_WRONG_BUILD_NUMBER,
                    new Object[] { importBuildNumber, buildNumber });
        }
    } else {
        BiPredicate<Version, Version> majorVersionBiPredicate = (currentVersion, importVersion) -> Objects
                .equals(currentVersion.getMajor(), importVersion.getMajor());

        BiPredicate<Version, Version> minorVersionBiPredicate = (currentVersion, importVersion) -> {
            int currentMinorVersion = GetterUtil.getInteger(currentVersion.getMinor(), -1);
            int importedMinorVersion = GetterUtil.getInteger(importVersion.getMinor(), -1);

            if (((currentMinorVersion == -1) && (importedMinorVersion == -1))
                    || (currentMinorVersion < importedMinorVersion)) {

                return false;
            }

            return true;
        };

        BiPredicate<Version, Version> manifestVersionBiPredicate = (currentVersion, importVersion) -> {
            BiPredicate<Version, Version> versionBiPredicate = majorVersionBiPredicate
                    .and(minorVersionBiPredicate);

            return versionBiPredicate.test(currentVersion, importVersion);
        };

        String importSchemaVersion = GetterUtil.getString(headerElement.attributeValue("schema-version"),
                "1.0.0");

        if (!manifestVersionBiPredicate.test(
                Version.getInstance(ExportImportConstants.EXPORT_IMPORT_SCHEMA_VERSION),
                Version.getInstance(importSchemaVersion))) {

            throw new LayoutImportException(LayoutImportException.TYPE_WRONG_LAR_SCHEMA_VERSION,
                    new Object[] { importSchemaVersion, ExportImportConstants.EXPORT_IMPORT_SCHEMA_VERSION });
        }
    }

    // Type

    String larType = headerElement.attributeValue("type");

    String[] expectedLARTypes = { "layout-prototype", "layout-set", "layout-set-prototype" };

    Stream<String> stream = Stream.of(expectedLARTypes);

    if (stream.noneMatch(lt -> lt.equals(larType))) {
        throw new LARTypeException(larType, expectedLARTypes);
    }

    Group group = _groupLocalService.fetchGroup(groupId);

    String layoutsImportMode = MapUtil.getString(parameterMap, PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE);

    if (larType.equals("layout-prototype") && !group.isLayoutPrototype()
            && !layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

        throw new LARTypeException(LARTypeException.TYPE_LAYOUT_PROTOTYPE);
    }

    if (larType.equals("layout-set")) {
        if (group.isLayoutPrototype() || group.isLayoutSetPrototype()) {
            throw new LARTypeException(LARTypeException.TYPE_LAYOUT_SET);
        }

        long sourceCompanyGroupId = GetterUtil.getLong(headerElement.attributeValue("company-group-id"));
        long sourceGroupId = GetterUtil.getLong(headerElement.attributeValue("group-id"));

        boolean companySourceGroup = false;

        if (sourceCompanyGroupId == sourceGroupId) {
            companySourceGroup = true;
        }

        if (group.isCompany() ^ companySourceGroup) {
            throw new LARTypeException(LARTypeException.TYPE_COMPANY_GROUP);
        }
    }

    if (larType.equals("layout-set-prototype") && !group.isLayoutSetPrototype()
            && !layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

        throw new LARTypeException(LARTypeException.TYPE_LAYOUT_SET_PROTOTYPE);
    }

    // Portlets compatibility

    List<Element> portletElements = fetchPortletElements(rootElement);

    for (Element portletElement : portletElements) {
        String portletId = GetterUtil.getString(portletElement.attributeValue("portlet-id"));

        if (Validator.isNull(portletId)) {
            continue;
        }

        String schemaVersion = GetterUtil.getString(portletElement.attributeValue("schema-version"));

        PortletDataHandler portletDataHandler = _portletDataHandlerProvider.provide(companyId, portletId);

        if (portletDataHandler == null) {
            continue;
        }

        if (!portletDataHandler.validateSchemaVersion(schemaVersion)) {
            throw new LayoutImportException(LayoutImportException.TYPE_WRONG_PORTLET_SCHEMA_VERSION,
                    new Object[] { schemaVersion, portletId, portletDataHandler.getSchemaVersion() });
        }
    }

    // Available locales

    List<Locale> sourceAvailableLocales = Arrays.asList(
            LocaleUtil.fromLanguageIds(StringUtil.split(headerElement.attributeValue("available-locales"))));

    for (Locale sourceAvailableLocale : sourceAvailableLocales) {
        if (!LanguageUtil.isAvailableLocale(groupId, sourceAvailableLocale)) {

            LocaleException le = new LocaleException(LocaleException.TYPE_EXPORT_IMPORT);

            le.setSourceAvailableLocales(sourceAvailableLocales);
            le.setTargetAvailableLocales(LanguageUtil.getAvailableLocales(groupId));

            throw le;
        }
    }

    // Layout prototypes validity

    Element layoutsElement = rootElement.element(Layout.class.getSimpleName());

    validateLayoutPrototypes(companyId, headerElement, layoutsElement);
}

From source file:com.liferay.exportimport.controller.PortletExportController.java

License:Open Source License

protected void exportPortletPreference(PortletDataContext portletDataContext, long ownerId, int ownerType,
        boolean defaultUser, PortletPreferences portletPreferences, String portletId, long plid,
        Element parentElement) throws Exception {

    String preferencesXML = portletPreferences.getPreferences();

    if (Validator.isNull(preferencesXML)) {
        preferencesXML = PortletConstants.DEFAULT_PREFERENCES;
    }/*from w w w  . j ava2s  . c o m*/

    javax.portlet.PortletPreferences jxPortletPreferences = PortletPreferencesFactoryUtil
            .fromDefaultXML(preferencesXML);

    Portlet portlet = _portletLocalService.getPortletById(portletDataContext.getCompanyId(), portletId);

    Element portletPreferencesElement = parentElement.addElement("portlet-preferences");

    if ((portlet != null) && (portlet.getPortletDataHandlerInstance() != null)) {

        Element exportDataRootElement = portletDataContext.getExportDataRootElement();

        try {
            portletDataContext.clearScopedPrimaryKeys();

            Element preferenceDataElement = portletPreferencesElement.addElement("preference-data");

            portletDataContext.setExportDataRootElement(preferenceDataElement);

            ExportImportPortletPreferencesProcessor exportImportPortletPreferencesProcessor = ExportImportPortletPreferencesProcessorRegistryUtil
                    .getExportImportPortletPreferencesProcessor(portlet.getRootPortletId());

            if (exportImportPortletPreferencesProcessor != null) {
                List<Capability> exportCapabilities = exportImportPortletPreferencesProcessor
                        .getExportCapabilities();

                if (ListUtil.isNotEmpty(exportCapabilities)) {
                    for (Capability exportCapability : exportCapabilities) {
                        exportCapability.process(portletDataContext, jxPortletPreferences);
                    }
                }

                exportImportPortletPreferencesProcessor.processExportPortletPreferences(portletDataContext,
                        jxPortletPreferences);
            } else {
                PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance();

                jxPortletPreferences = portletDataHandler.processExportPortletPreferences(portletDataContext,
                        portletId, jxPortletPreferences);
            }
        } finally {
            portletDataContext.setExportDataRootElement(exportDataRootElement);
        }
    }

    Document document = SAXReaderUtil.read(PortletPreferencesFactoryUtil.toXML(jxPortletPreferences));

    Element rootElement = document.getRootElement();

    rootElement.addAttribute("owner-id", String.valueOf(ownerId));
    rootElement.addAttribute("owner-type", String.valueOf(ownerType));
    rootElement.addAttribute("default-user", String.valueOf(defaultUser));
    rootElement.addAttribute("plid", String.valueOf(plid));
    rootElement.addAttribute("portlet-id", portletId);

    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) {
        PortletItem portletItem = _portletItemLocalService.getPortletItem(ownerId);

        rootElement.addAttribute("archive-user-uuid", portletItem.getUserUuid());
        rootElement.addAttribute("archive-name", portletItem.getName());
    } else if (ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) {
        User user = _userLocalService.fetchUserById(ownerId);

        if (user == null) {
            return;
        }

        rootElement.addAttribute("user-uuid", user.getUserUuid());
    }

    List<Node> nodes = document
            .selectNodes("/portlet-preferences/preference[name/text() = " + "'last-publish-date']");

    for (Node node : nodes) {
        node.detach();
    }

    String path = ExportImportPathUtil.getPortletPreferencesPath(portletDataContext, portletId, ownerId,
            ownerType, plid);

    portletPreferencesElement.addAttribute("path", path);

    portletDataContext.addZipEntry(path, document.formattedString(StringPool.TAB, false, false));
}

From source file:com.liferay.exportimport.controller.PortletExportController.java

License:Open Source License

protected void exportServicePortletPreference(PortletDataContext portletDataContext, long ownerId,
        int ownerType, PortletPreferences portletPreferences, String serviceName, Element parentElement)
        throws Exception {

    String preferencesXML = portletPreferences.getPreferences();

    if (Validator.isNull(preferencesXML)) {
        preferencesXML = PortletConstants.DEFAULT_PREFERENCES;
    }/* w ww  .java 2  s  . c o  m*/

    javax.portlet.PortletPreferences jxPortletPreferences = PortletPreferencesFactoryUtil
            .fromDefaultXML(preferencesXML);

    Document document = SAXReaderUtil.read(PortletPreferencesFactoryUtil.toXML(jxPortletPreferences));

    Element rootElement = document.getRootElement();

    rootElement.addAttribute("owner-id", String.valueOf(ownerId));
    rootElement.addAttribute("owner-type", String.valueOf(ownerType));
    rootElement.addAttribute("default-user", String.valueOf(false));
    rootElement.addAttribute("service-name", serviceName);

    if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) {
        PortletItem portletItem = _portletItemLocalService.getPortletItem(ownerId);

        rootElement.addAttribute("archive-user-uuid", portletItem.getUserUuid());
        rootElement.addAttribute("archive-name", portletItem.getName());
    } else if (ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) {
        User user = _userLocalService.fetchUserById(ownerId);

        if (user == null) {
            return;
        }

        rootElement.addAttribute("user-uuid", user.getUserUuid());
    }

    List<Node> nodes = document
            .selectNodes("/portlet-preferences/preference[name/text() = " + "'last-publish-date']");

    for (Node node : nodes) {
        node.detach();
    }

    Element serviceElement = parentElement.addElement("service");

    String path = ExportImportPathUtil.getServicePortletPreferencesPath(portletDataContext, serviceName,
            ownerId, ownerType);

    serviceElement.addAttribute("path", path);

    serviceElement.addAttribute("service-name", serviceName);

    portletDataContext.addZipEntry(path, document.formattedString());
}