Example usage for com.liferay.portal.kernel.zip ZipWriter getFile

List of usage examples for com.liferay.portal.kernel.zip ZipWriter getFile

Introduction

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

Prototype

public File getFile();

Source Link

Usage

From source file:com.liferay.configuration.admin.web.internal.portlet.action.ExportConfigurationMVCResourceCommand.java

License:Open Source License

protected void exportAll(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

    String languageId = themeDisplay.getLanguageId();

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    Map<String, ConfigurationModel> configurationModels = _configurationModelRetriever
            .getConfigurationModels(themeDisplay.getLanguageId());

    for (ConfigurationModel configurationModel : configurationModels.values()) {

        if (configurationModel.isFactory()) {
            String curFactoryPid = configurationModel.getFactoryPid();

            List<ConfigurationModel> factoryInstances = _configurationModelRetriever
                    .getFactoryInstances(configurationModel);

            for (ConfigurationModel factoryInstance : factoryInstances) {
                String curPid = factoryInstance.getID();

                String curFileName = getFileName(curFactoryPid, curPid);

                zipWriter.addEntry(curFileName, ConfigurationExporter
                        .getPropertiesAsBytes(getProperties(languageId, curFactoryPid, curPid)));
            }//ww w  .  ja  va2  s.c  om
        } else if (configurationModel.hasConfiguration()) {
            String curPid = configurationModel.getID();

            String curFileName = getFileName(null, curPid);

            zipWriter.addEntry(curFileName,
                    ConfigurationExporter.getPropertiesAsBytes(getProperties(languageId, curPid, curPid)));
        }
    }

    String fileName = "liferay-system-settings.zip";

    PortletResponseUtil.sendFile(resourceRequest, resourceResponse, fileName,
            new FileInputStream(zipWriter.getFile()), ContentTypes.APPLICATION_ZIP);
}

From source file:com.liferay.configuration.admin.web.internal.portlet.action.ExportConfigurationMVCResourceCommand.java

License:Open Source License

protected void exportFactoryPid(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

    String languageId = themeDisplay.getLanguageId();

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    String factoryPid = ParamUtil.getString(resourceRequest, "factoryPid");

    Map<String, ConfigurationModel> configurationModels = _configurationModelRetriever
            .getConfigurationModels(themeDisplay.getLanguageId());

    ConfigurationModel factoryConfigurationModel = configurationModels.get(factoryPid);

    List<ConfigurationModel> factoryInstances = _configurationModelRetriever
            .getFactoryInstances(factoryConfigurationModel);

    for (ConfigurationModel factoryInstance : factoryInstances) {
        String curPid = factoryInstance.getID();

        String curFileName = getFileName(factoryPid, curPid);

        zipWriter.addEntry(curFileName,/*from w  ww  .  j  a  v a2s .  c o  m*/
                ConfigurationExporter.getPropertiesAsBytes(getProperties(languageId, factoryPid, curPid)));
    }

    String fileName = "liferay-system-settings-" + factoryConfigurationModel.getFactoryPid() + ".zip";

    PortletResponseUtil.sendFile(resourceRequest, resourceResponse, fileName,
            new FileInputStream(zipWriter.getFile()), ContentTypes.APPLICATION_ZIP);
}

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

License:Open Source License

protected void downloadFileEntries(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

    long folderId = ParamUtil.getLong(resourceRequest, "folderId");

    File file = null;/*w w w  .  ja  va2  s. c  o m*/
    InputStream inputStream = null;

    try {
        List<FileEntry> fileEntries = ActionUtil.getFileEntries(resourceRequest);

        List<FileShortcut> fileShortcuts = ActionUtil.getFileShortcuts(resourceRequest);

        List<Folder> folders = ActionUtil.getFolders(resourceRequest);

        if (fileEntries.isEmpty() && fileShortcuts.isEmpty() && folders.isEmpty()) {

            return;
        } else if ((fileEntries.size() == 1) && fileShortcuts.isEmpty() && folders.isEmpty()) {

            FileEntry fileEntry = fileEntries.get(0);

            PortletResponseUtil.sendFile(resourceRequest, resourceResponse, fileEntry.getFileName(),
                    fileEntry.getContentStream(), 0, fileEntry.getMimeType(),
                    HttpHeaders.CONTENT_DISPOSITION_ATTACHMENT);
        } else if ((fileShortcuts.size() == 1) && fileEntries.isEmpty() && folders.isEmpty()) {

            FileShortcut fileShortcut = fileShortcuts.get(0);

            FileEntry fileEntry = _dlAppService.getFileEntry(fileShortcut.getToFileEntryId());

            PortletResponseUtil.sendFile(resourceRequest, resourceResponse, fileEntry.getFileName(),
                    fileEntry.getContentStream(), 0, fileEntry.getMimeType(),
                    HttpHeaders.CONTENT_DISPOSITION_ATTACHMENT);
        } else {
            String zipFileName = getZipFileName(folderId, themeDisplay);

            ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

            for (FileEntry fileEntry : fileEntries) {
                zipFileEntry(fileEntry, StringPool.SLASH, zipWriter);
            }

            for (FileShortcut fileShortcut : fileShortcuts) {
                FileEntry fileEntry = _dlAppService.getFileEntry(fileShortcut.getToFileEntryId());

                zipFileEntry(fileEntry, StringPool.SLASH, zipWriter);
            }

            for (Folder folder : folders) {
                zipFolder(folder.getRepositoryId(), folder.getFolderId(),
                        StringPool.SLASH.concat(folder.getName()), zipWriter);
            }

            file = zipWriter.getFile();

            inputStream = new FileInputStream(file);

            PortletResponseUtil.sendFile(resourceRequest, resourceResponse, zipFileName, inputStream,
                    ContentTypes.APPLICATION_ZIP);
        }
    } finally {
        StreamUtil.cleanUp(inputStream);

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

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

License:Open Source License

protected void downloadFolder(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

    long repositoryId = ParamUtil.getLong(resourceRequest, "repositoryId");
    long folderId = ParamUtil.getLong(resourceRequest, "folderId");

    File file = null;//from   w  ww .  j a  va  2 s. co m
    InputStream inputStream = null;

    try {
        String zipFileName = getZipFileName(folderId, themeDisplay);

        ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

        zipFolder(repositoryId, folderId, StringPool.SLASH, zipWriter);

        file = zipWriter.getFile();

        inputStream = new FileInputStream(file);

        PortletResponseUtil.sendFile(resourceRequest, resourceResponse, zipFileName, inputStream,
                ContentTypes.APPLICATION_ZIP);
    } finally {
        StreamUtil.cleanUp(inputStream);

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

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

License:Open Source License

protected File doExport(PortletDataContext portletDataContext) throws Exception {

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

    boolean ignoreLastPublishDate = MapUtil.getBoolean(parameterMap,
            PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean permissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);

    if (_log.isDebugEnabled()) {
        _log.debug("Export permissions " + permissions);
    }/*w w  w  .  j av  a2 s.  co m*/

    long companyId = portletDataContext.getCompanyId();

    long defaultUserId = _userLocalService.getDefaultUserId(companyId);

    ServiceContext serviceContext = ServiceContextThreadLocal.popServiceContext();

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

    serviceContext.setCompanyId(companyId);
    serviceContext.setSignedIn(true);

    if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
        BackgroundTask backgroundTask = _backgroundTaskLocalService
                .getBackgroundTask(BackgroundTaskThreadLocal.getBackgroundTaskId());

        serviceContext.setUserId(backgroundTask.getUserId());
    } else {
        serviceContext.setUserId(defaultUserId);
    }

    serviceContext.setAttribute("exporting", Boolean.TRUE);

    long layoutSetBranchId = MapUtil.getLong(parameterMap, "layoutSetBranchId");

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    ServiceContextThreadLocal.pushServiceContext(serviceContext);

    if (ignoreLastPublishDate) {
        portletDataContext.setEndDate(null);
        portletDataContext.setStartDate(null);
    }

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    portletDataContext.setExportDataRootElement(rootElement);

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

    headerElement.addAttribute("available-locales",
            StringUtil.merge(LanguageUtil.getAvailableLocales(portletDataContext.getScopeGroupId())));

    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));

    headerElement.addAttribute("schema-version", ExportImportConstants.EXPORT_IMPORT_SCHEMA_VERSION);

    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
        headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
        headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("company-id", String.valueOf(portletDataContext.getCompanyId()));
    headerElement.addAttribute("company-group-id", String.valueOf(portletDataContext.getCompanyGroupId()));
    headerElement.addAttribute("group-id", String.valueOf(portletDataContext.getGroupId()));
    headerElement.addAttribute("user-personal-site-group-id",
            String.valueOf(portletDataContext.getUserPersonalSiteGroupId()));
    headerElement.addAttribute("private-layout", String.valueOf(portletDataContext.isPrivateLayout()));

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

    String type = "layout-set";

    if (group.isLayoutPrototype()) {
        type = "layout-prototype";

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

        headerElement.addAttribute("type-uuid", layoutPrototype.getUuid());
    } else if (group.isLayoutSetPrototype()) {
        type = "layout-set-prototype";

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

        headerElement.addAttribute("type-uuid", layoutSetPrototype.getUuid());
    }

    headerElement.addAttribute("type", type);
    portletDataContext.setType(type);

    Element missingReferencesElement = rootElement.addElement("missing-references");

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

    rootElement.addElement("site-portlets");
    rootElement.addElement("site-services");

    // Export the group

    LayoutSet layoutSet = _layoutSetLocalService.getLayoutSet(portletDataContext.getGroupId(),
            portletDataContext.isPrivateLayout());

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    boolean layoutSetPrototypeSettings = MapUtil.getBoolean(portletDataContext.getParameterMap(),
            PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_SETTINGS);

    if (!group.isStaged() && Validator.isNotNull(layoutSetPrototypeUuid) && layoutSetPrototypeSettings) {

        LayoutSetPrototype layoutSetPrototype = _layoutSetPrototypeLocalService
                .getLayoutSetPrototypeByUuidAndCompanyId(layoutSetPrototypeUuid, companyId);

        headerElement.addAttribute("layout-set-prototype-uuid", layoutSetPrototypeUuid);

        headerElement.addAttribute("layout-set-prototype-name",
                layoutSetPrototype.getName(LocaleUtil.getDefault()));
    }

    StagedGroup stagedGroup = ModelAdapterUtil.adapt(group, Group.class, StagedGroup.class);

    StagedModelDataHandlerUtil.exportStagedModel(portletDataContext, stagedGroup);

    // Export other models

    _portletExportController.exportAssetLinks(portletDataContext);
    _portletExportController.exportExpandoTables(portletDataContext);
    _portletExportController.exportLocks(portletDataContext);

    portletDataContext.addDeletionSystemEventStagedModelTypes(new StagedModelType(StagedAssetLink.class));

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

    if (permissions) {
        _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    _exportImportHelper.writeManifestSummary(document, portletDataContext.getManifestSummary());

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

    portletDataContext.addZipEntry("/manifest.xml", document.formattedString());

    ZipWriter zipWriter = portletDataContext.getZipWriter();

    return zipWriter.getFile();
}

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

License:Open Source License

protected File doExport(PortletDataContext portletDataContext) throws Exception {

    boolean exportPermissions = MapUtil.getBoolean(portletDataContext.getParameterMap(),
            PortletDataHandlerKeys.PERMISSIONS);

    if (_log.isDebugEnabled()) {
        _log.debug("Export permissions " + exportPermissions);
    }//  w  w  w  . j  a  va2s . c  o m

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    Layout layout = _layoutLocalService.getLayout(portletDataContext.getPlid());

    if (!layout.isTypeControlPanel() && !layout.isTypePanel() && !layout.isTypePortlet()) {

        StringBundler sb = new StringBundler(4);

        sb.append("Unable to export layout ");
        sb.append(layout.getPlid());
        sb.append(" because it has an invalid type: ");
        sb.append(layout.getType());

        throw new LayoutImportException(sb.toString());
    }

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

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

        serviceContext.setCompanyId(layout.getCompanyId());
        serviceContext.setSignedIn(false);

        long defaultUserId = _userLocalService.getDefaultUserId(layout.getCompanyId());

        serviceContext.setUserId(defaultUserId);

        ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    long layoutSetBranchId = MapUtil.getLong(portletDataContext.getParameterMap(), "layoutSetBranchId");

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    long scopeGroupId = portletDataContext.getGroupId();

    javax.portlet.PortletPreferences jxPortletPreferences = PortletPreferencesFactoryUtil
            .getLayoutPortletSetup(layout, portletDataContext.getPortletId());

    String scopeType = GetterUtil.getString(jxPortletPreferences.getValue("lfrScopeType", null));
    String scopeLayoutUuid = GetterUtil.getString(jxPortletPreferences.getValue("lfrScopeLayoutUuid", null));

    if (Validator.isNotNull(scopeType)) {
        Group scopeGroup = null;

        if (scopeType.equals("company")) {
            scopeGroup = _groupLocalService.getCompanyGroup(layout.getCompanyId());
        } else if (Validator.isNotNull(scopeLayoutUuid)) {
            scopeGroup = layout.getScopeGroup();
        }

        if (scopeGroup != null) {
            scopeGroupId = scopeGroup.getGroupId();
        }
    }

    portletDataContext.setScopeType(scopeType);
    portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    portletDataContext.setExportDataRootElement(rootElement);

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

    headerElement.addAttribute("available-locales", StringUtil.merge(
            LanguageUtil.getAvailableLocales(_portal.getSiteGroupId(portletDataContext.getScopeGroupId()))));
    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));
    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
        headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
        headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("type", portletDataContext.getType());
    headerElement.addAttribute("company-id", String.valueOf(portletDataContext.getCompanyId()));
    headerElement.addAttribute("company-group-id", String.valueOf(portletDataContext.getCompanyGroupId()));
    headerElement.addAttribute("group-id", String.valueOf(scopeGroupId));
    headerElement.addAttribute("user-personal-site-group-id",
            String.valueOf(portletDataContext.getUserPersonalSiteGroupId()));
    headerElement.addAttribute("private-layout", String.valueOf(layout.isPrivateLayout()));
    headerElement.addAttribute("root-portlet-id", portletDataContext.getRootPortletId());
    headerElement.addAttribute("schema-version", ExportImportConstants.EXPORT_IMPORT_SCHEMA_VERSION);

    Element missingReferencesElement = rootElement.addElement("missing-references");

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

    Map<String, Boolean> exportPortletControlsMap = _exportImportHelper.getExportPortletControlsMap(
            layout.getCompanyId(), portletDataContext.getPortletId(), portletDataContext.getParameterMap());

    exportPortlet(portletDataContext, layout.getPlid(), rootElement, exportPermissions,
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_USER_PREFERENCES));
    exportService(portletDataContext, rootElement,
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP));

    exportAssetLinks(portletDataContext);
    exportExpandoTables(portletDataContext);
    exportLocks(portletDataContext);

    portletDataContext.addDeletionSystemEventStagedModelTypes(new StagedModelType(StagedAssetLink.class));

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

    if (exportPermissions) {
        _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    _exportImportHelper.writeManifestSummary(document, portletDataContext.getManifestSummary());

    if (_log.isInfoEnabled()) {
        _log.info("Exporting portlet took " + stopWatch.getTime() + " ms");
    }

    try {
        portletDataContext.addZipEntry("/manifest.xml", document.formattedString());
    } catch (IOException ioe) {
        throw new SystemException("Unable to create the export LAR manifest file for portlet "
                + portletDataContext.getPortletId(), ioe);
    }

    ZipWriter zipWriter = portletDataContext.getZipWriter();

    return zipWriter.getFile();
}

From source file:com.liferay.exportimport.test.ExportImportHelperUtilTest.java

License:Open Source License

@Test
public void testValidateMissingReferences() throws Exception {
    String xml = replaceParameters(getContent("missing_references.txt"), getFileEntry());

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    zipWriter.addEntry("/manifest.xml", xml);

    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(zipWriter.getFile());

    PortletDataContext portletDataContextImport = PortletDataContextFactoryUtil.createImportPortletDataContext(
            _liveGroup.getCompanyId(), _liveGroup.getGroupId(), new HashMap<String, String[]>(),
            new TestUserIdStrategy(), zipReader);

    MissingReferences missingReferences = ExportImportHelperUtil
            .validateMissingReferences(portletDataContextImport);

    Map<String, MissingReference> dependencyMissingReferences = missingReferences
            .getDependencyMissingReferences();

    Map<String, MissingReference> weakMissingReferences = missingReferences.getWeakMissingReferences();

    Assert.assertEquals(dependencyMissingReferences.toString(), 2, dependencyMissingReferences.size());
    Assert.assertEquals(weakMissingReferences.toString(), 1, weakMissingReferences.size());

    FileUtil.delete(zipWriter.getFile());

    zipReader.close();//  ww  w  .j  a v  a  2s  .  c  o m
}

From source file:com.liferay.sync.internal.servlet.SyncDownloadServlet.java

License:Open Source License

protected void sendZipFile(HttpServletResponse response, long userId, JSONArray zipFileIdsJSONArray)
        throws Exception {

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    JSONObject errorsJSONObject = JSONFactoryUtil.createJSONObject();

    for (int i = 0; i < zipFileIdsJSONArray.length(); i++) {
        JSONObject zipObjectJSONObject = zipFileIdsJSONArray.getJSONObject(i);

        long groupId = zipObjectJSONObject.getLong("groupId");
        String zipFileId = zipObjectJSONObject.getString("zipFileId");

        Group group = _groupLocalService.fetchGroup(groupId);

        if ((group == null) || !_syncUtil.isSyncEnabled(group)) {
            processException(zipFileId, SyncSiteUnavailableException.class.getName(), errorsJSONObject);

            continue;
        }/* w w  w .j  a  va2s.co  m*/

        try (InputStream inputStream = _getZipFileInputStream(zipObjectJSONObject, userId, groupId)) {

            zipWriter.addEntry(zipFileId, inputStream);
        } catch (Exception e) {
            Class<?> clazz = e.getClass();

            processException(zipFileId, clazz.getName(), errorsJSONObject);
        }
    }

    zipWriter.addEntry("errors.json", errorsJSONObject.toString());

    File file = zipWriter.getFile();

    ServletResponseUtil.write(response, new FileInputStream(file), file.length());
}

From source file:com.liferay.sync.internal.servlet.SyncDownloadServlet.java

License:Open Source License

protected void sendZipFolder(HttpServletResponse response, long userId, long repositoryId, long folderId)
        throws Exception {

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    addZipFolderEntry(userId, repositoryId, folderId, StringPool.BLANK, zipWriter);

    File file = zipWriter.getFile();

    ServletResponseUtil.write(response, new FileInputStream(file), file.length());
}

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

License:Open Source License

public java.io.InputStream getInputStream() throws IOException {
    if (!_deployedAppFolder.exists() || !_deployedAppFolder.isDirectory()) {
        return null;
    }//from   w  ww . j  a v  a  2s . c  o  m

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    try {
        writeJarPaths(_deployedAppFolder, _deployedAppFolder.toURI(), zipWriter);
    } finally {
        //_deployedAppFolder.delete();
    }

    zipWriter.getFile();

    return new FileInputStream(zipWriter.getFile());
}