Example usage for com.liferay.portal.kernel.zip ZipReader getEntryAsString

List of usage examples for com.liferay.portal.kernel.zip ZipReader getEntryAsString

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.zip ZipReader getEntryAsString.

Prototype

public String getEntryAsString(String name);

Source Link

Usage

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/*  w ww .j  a v a  2  s  .co 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.PortletImportController.java

License:Open Source License

protected void validateFile(long companyId, long groupId, String portletId, ZipReader zipReader)
        throws Exception {

    // XML/*from   w w  w  . j  a v a  2s .  co 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);
    }

    // Build compatibility

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

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

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

        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");

    if (!larType.equals("portlet")) {
        throw new LARTypeException(larType, new String[] { "portlet" });
    }

    // Portlet compatibility

    String rootPortletId = headerElement.attributeValue("root-portlet-id");

    String expectedRootPortletId = PortletIdCodec.decodePortletName(portletId);

    if (!expectedRootPortletId.equals(rootPortletId)) {
        throw new PortletIdException(expectedRootPortletId);
    }

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

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

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

    // Available locales

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

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

                LocaleException le = new LocaleException(LocaleException.TYPE_EXPORT_IMPORT);

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

                throw le;
            }
        }
    }
}

From source file:com.liferay.knowledgebase.admin.importer.KBArticleImporter.java

License:Open Source License

protected void processKBArticleFiles(long userId, long groupId, long parentKBFolderId, ZipReader zipReader,
        Map<String, String> metadata, ServiceContext serviceContext) throws KBArticleImportException {

    Map<String, List<String>> folderNameFileEntryNamesMap = getFolderNameFileEntryNamesMap(zipReader);

    Set<String> folderNames = folderNameFileEntryNamesMap.keySet();

    for (String folderName : folderNames) {
        List<String> fileEntryNames = folderNameFileEntryNamesMap.get(folderName);

        String sectionIntroFileEntryName = null;

        List<String> sectionFileEntryNames = new ArrayList<String>();

        for (String fileEntryName : fileEntryNames) {
            if (fileEntryName.endsWith(PortletPropsValues.MARKDOWN_IMPORTER_ARTICLE_INTRO)) {

                sectionIntroFileEntryName = fileEntryName;
            } else {
                sectionFileEntryNames.add(fileEntryName);
            }//  www. j  a  v  a  2  s .  com
        }

        long parentResourceClassNameId = PortalUtil.getClassNameId(KBFolderConstants.getClassName());
        long parentResourcePrimaryKey = parentKBFolderId;

        long sectionResourceClassNameId = parentResourceClassNameId;
        long sectionResourcePrimaryKey = parentResourcePrimaryKey;

        if (Validator.isNotNull(sectionIntroFileEntryName)) {
            KBArticle sectionIntroKBArticle = addKBArticleMarkdown(userId, groupId, parentKBFolderId,
                    sectionResourceClassNameId, sectionResourcePrimaryKey,
                    zipReader.getEntryAsString(sectionIntroFileEntryName), sectionIntroFileEntryName, zipReader,
                    metadata, serviceContext);

            sectionResourceClassNameId = PortalUtil.getClassNameId(KBArticleConstants.getClassName());
            sectionResourcePrimaryKey = sectionIntroKBArticle.getResourcePrimKey();
        }

        for (String sectionFileEntryName : sectionFileEntryNames) {
            String sectionMarkdown = zipReader.getEntryAsString(sectionFileEntryName);

            if (Validator.isNull(sectionMarkdown)) {
                if (_log.isWarnEnabled()) {
                    _log.warn("Missing Markdown in file entry " + sectionFileEntryName);
                }
            }

            addKBArticleMarkdown(userId, groupId, parentKBFolderId, sectionResourceClassNameId,
                    sectionResourcePrimaryKey, sectionMarkdown, sectionFileEntryName, zipReader, metadata,
                    serviceContext);
        }
    }
}

From source file:com.liferay.layout.set.prototype.exportimport.data.handler.test.LayoutSetPrototypeStagedModelDataHandlerTest.java

License:Open Source License

protected Layout importLayoutFromLAR(StagedModel stagedModel) throws DocumentException, IOException {

    LayoutSetPrototype layoutSetPrototype = (LayoutSetPrototype) stagedModel;

    String fileName = layoutSetPrototype.getLayoutSetPrototypeId() + ".lar";

    String modelPath = ExportImportPathUtil.getModelPath(stagedModel, fileName);

    try (InputStream inputStream = portletDataContext.getZipEntryAsInputStream(modelPath)) {

        ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(inputStream);

        Document document = UnsecureSAXReaderUtil.read(zipReader.getEntryAsString("manifest.xml"));

        Element rootElement = document.getRootElement();

        Element layoutElement = rootElement.element("Layout");

        List<Element> elements = layoutElement.elements();

        List<Layout> importedLayouts = new ArrayList<>(elements.size());

        for (Element element : elements) {
            String layoutPrototypeUuid = element.attributeValue("layout-prototype-uuid");

            if (Validator.isNotNull(layoutPrototypeUuid)) {
                String path = element.attributeValue("path");

                Layout layout = (Layout) portletDataContext.fromXML(zipReader.getEntryAsString(path));

                importedLayouts.add(layout);
            }/*from  www.  ja va2  s  .  c  o  m*/
        }

        Assert.assertEquals(importedLayouts.toString(), 1, importedLayouts.size());

        return importedLayouts.get(0);
    } finally {
        zipReader.close();
    }
}

From source file:com.liferay.samplelar.plugin.LARPlugin.java

License:Open Source License

@Override
public PortletPreferences importData(PortletDataContext context, String portletId,
        PortletPreferences preferences, String data) throws PortletDataException {

    Map parameterMap = context.getParameterMap();

    boolean importData = MapUtil.getBoolean(parameterMap, "import-sample-lar-portlet-data",
            _enableImport.getDefaultState());

    if (_log.isDebugEnabled()) {
        if (importData) {
            _log.debug("Importing data is enabled");
        } else {/*from ww  w .j  a va 2 s.  c o m*/
            _log.debug("Importing data is disabled");
        }
    }

    if (!importData) {
        return null;
    }

    try {
        long importDate = System.currentTimeMillis();

        preferences.setValue("last-import-date", String.valueOf(importDate));

        if (_log.isInfoEnabled()) {
            _log.info("Importing data " + data);
        }

        ZipReader zipReader = context.getZipReader();

        if (zipReader != null) {
            _log.info("From README file:\n\n" + zipReader.getEntryAsString(portletId + "/README.txt"));
        }

        return preferences;
    } catch (Exception e) {
        throw new PortletDataException(e);
    }
}