@GET
  @Transactional
  @Path("/user/{userName}/accountBalance")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getAccountBalance(
      @PathParam("apiVersion") String apiVersion,
      @PathParam("userName") String userName,
      @DefaultValue("true") @QueryParam("cache") boolean cache)
      throws JsonProcessingException {
    StopWatch watch = new StopWatch();
    watch.start();

    EntityManager em = emf.createEntityManager();
    if (log.isDebugEnabled()) {
      log.trace("Time to execute getTree Service : {}ms", watch.getTime());
    }
    //		if (!accountValidator.validateAccount(accountId)) {
    //			return
    // Response.status(Response.Status.UNAUTHORIZED).entity(accountValidator.getResponse(accountId)).build();
    //		}
    long accNo = 746353;
    // BossUserRepository userRepo = new BossUserRepository();
    double accountBalance = userRepo.account(accNo);

    watch.stop();
    if (log.isDebugEnabled()) {
      log.trace("Time to execute ACCOUNTDETAILS for a USER : {}ms", watch.getTime());
    }
    return Response.status(Response.Status.OK).entity(accountBalance).build();
  }
  public static MultiVariatePieceWiseLinearFunction createSenseSleepFunctionVerbose(
      ScenarioProperties scenario, List<SensorProperties> sensorProperties) {

    NCube domain = createDomain(sensorProperties, scenario);

    // max(0, min(x1 + l1, x2 + l2) - max(x1, x2))

    MultiVariatePieceWiseLinearFunction zero =
        MultiVariatePieceWiseLinearFunctionUtilities.createZeroFunction(domain);

    double l = scenario.getScheduleIntervalLength();

    StopWatch watch = new StopWatch();

    watch.start();
    MultiVariatePieceWiseLinearFunction maxStart = createMaxStartFunction(domain);
    watch.stop();
    System.out.println(
        "Created maxStart in "
            + watch.getTime()
            + ". Simplices "
            + maxStart.getPartitioning().getSimplices().size());

    watch.reset();
    watch.start();
    MultiVariatePieceWiseLinearFunction minEnd = createMinEndFunction(domain, sensorProperties);
    watch.stop();
    System.out.println(
        "Created minEnd in "
            + watch.getTime()
            + ". Simplices "
            + minEnd.getPartitioning().getSimplices().size());

    watch.reset();
    watch.start();
    MultiVariatePieceWiseLinearFunction minMinusMax = minEnd.subtract(maxStart);
    watch.stop();
    System.out.println(
        "Created minMinusMax in "
            + watch.getTime()
            + ". Simplices "
            + minMinusMax.getPartitioning().getSimplices().size());

    watch.reset();
    watch.start();
    MultiVariatePieceWiseLinearFunction overlap = minMinusMax.max(zero);
    System.out.println(
        "Created overlap in "
            + watch.getTime()
            + ". Simplices "
            + overlap.getPartitioning().getSimplices().size());

    MultiVariatePieceWiseLinearFunction result = overlap.subtract(l).multiply(-1.0);

    System.out.println("Simplices " + result.getPartitioning().getSimplices().size());

    return result;
  }
  @Override
  protected Client createClient(Settings.Builder builder) {
    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    if (_log.isDebugEnabled()) {
      _log.debug(
          "Starting embedded Elasticsearch cluster " + elasticsearchConfiguration.clusterName());
    }

    NodeBuilder nodeBuilder = NodeBuilder.nodeBuilder();

    nodeBuilder.settings(builder);

    _node = nodeBuilder.node();

    _node.start();

    Client client = _node.client();

    if (_log.isDebugEnabled()) {
      stopWatch.stop();

      _log.debug(
          "Finished starting "
              + elasticsearchConfiguration.clusterName()
              + " in "
              + stopWatch.getTime()
              + " ms");
    }

    return client;
  }
  protected void testOutgoingConnection() throws MailException {
    StopWatch stopWatch = null;

    if (_log.isDebugEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    try {
      Transport transport = getTransport();

      transport.isConnected();

      transport.close();
    } catch (Exception e) {
      throw new MailException(MailException.ACCOUNT_OUTGOING_CONNECTION_FAILED, e);
    } finally {
      if (_log.isDebugEnabled()) {
        stopWatch.stop();

        _log.debug("Testing outgoing connection completed in " + stopWatch.getTime() + " ms");
      }
    }
  }
Exemple #5
0
 /**
  * 测试哨兵模式
  *
  * <p>one master(one sentinel) - one slave
  */
 @Test
 public void testSentinel() {
   // 哨兵初始化
   HostAndPort sentinelAddr = new HostAndPort("192.168.1.201", 26379);
   Set<String> sentinels = new HashSet<String>();
   sentinels.add(sentinelAddr.toString());
   JedisSentinelPool sentinelPool =
       new JedisSentinelPool("mymaster", sentinels, new GenericObjectPoolConfig());
   // 线程初始化
   StopWatch stopWatch = new StopWatch();
   stopWatch.start();
   AtomicInteger calcCount = new AtomicInteger(0);
   AtomicInteger failCount = new AtomicInteger(0);
   for (int t = 0; t < TIMES; t++) {
     ThreadPool threadPool = new ThreadPool(THREADS);
     SentinelThread sentinelThread = new SentinelThread(sentinelPool, calcCount, failCount);
     threadPool.executeThread(sentinelThread);
     try {
       TimeUnit.SECONDS.sleep(SECONDS);
     } catch (InterruptedException e) {
       Thread.currentThread().interrupt();
       System.err.println("error !!!");
     }
   }
   sentinelPool.close();
   stopWatch.stop();
   // 打印结果
   System.out.println(
       String.format(
           "redis sentinel work finish, times:%d(milliseconds), fails:%d",
           stopWatch.getTime(), failCount.get()));
 }
Exemple #6
0
  public void testLotsOfLoanRequests() throws Exception {
    final MuleClient client = new MuleClient();
    Customer c = new Customer("Ross Mason", 1234);
    CustomerQuoteRequest[] requests = new CustomerQuoteRequest[3];
    requests[0] = new CustomerQuoteRequest(c, 100000, 48);
    requests[1] = new CustomerQuoteRequest(c, 1000, 12);
    requests[2] = new CustomerQuoteRequest(c, 10, 24);

    final StopWatch stopWatch = new StopWatch();

    final int numRequests = getNumberOfRequests() + getWarmUpMessages();
    int i = 0;

    int numberOfThreads = 1;

    CountDownLatch latch = new CountDownLatch(numberOfThreads);
    ExceptionHolder exceptionHolder = new ExceptionHolder();
    try {
      for (int x = 0; x < numberOfThreads; x++) {
        Thread thread =
            new Thread(new ClientReceiver(latch, numRequests / numberOfThreads, exceptionHolder));
        thread.start();
      }

      for (i = 0; i < numRequests; i++) {
        if (i == getWarmUpMessages()) {
          stopWatch.start();
        }
        client.dispatch("CustomerRequests", requests[i % 3], null);
      }
    } finally {
      latch.await();
      stopWatch.stop();
      System.out.println("Total running time was: " + stopWatch.getTime() + "ms");
      System.out.println("Requests processed was: " + i);
      int mps = (int) (numRequests / ((double) stopWatch.getTime() / (double) 1000));
      System.out.println("Msg/sec: " + mps + " (warm up msgs = " + getWarmUpMessages() + ")");
      if (exceptionHolder.isExceptionThrown()) {
        exceptionHolder.print();
        fail("Exceptions thrown during async processing");
      }
    }
  }
  private void _generateImagesGS(FileVersion fileVersion, File file) throws Exception {

    if (_isGeneratePreview(fileVersion)) {
      StopWatch stopWatch = new StopWatch();

      stopWatch.start();

      _generateImagesGS(fileVersion, file, false);

      if (_log.isInfoEnabled()) {
        int previewFileCount = getPreviewFileCount(fileVersion);

        _log.info(
            "Ghostscript generated "
                + previewFileCount
                + " preview pages for "
                + fileVersion.getTitle()
                + " in "
                + stopWatch.getTime()
                + " ms");
      }
    }

    if (_isGenerateThumbnail(fileVersion)) {
      StopWatch stopWatch = new StopWatch();

      stopWatch.start();

      _generateImagesGS(fileVersion, file, true);

      if (_log.isInfoEnabled()) {
        _log.info(
            "Ghostscript generated a thumbnail for "
                + fileVersion.getTitle()
                + " in "
                + stopWatch.getTime()
                + " ms");
      }
    }
  }
 @SyncThread(level = 1000)
 private void createVm(
     VmInstanceInventory vm, String rootDiskUuid, List<String> nws, List<String> disks)
     throws ApiSenderException {
   StopWatch watch = new StopWatch();
   watch.start();
   try {
     api.createVmByFullConfig(vm, rootDiskUuid, nws, disks);
   } finally {
     watch.stop();
     timeCost.add(watch.getTime());
     latch.countDown();
   }
 }
  @GET
  @Path("/")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getTree(
      @PathParam("apiVersion") String apiVersion,
      @DefaultValue("true") @QueryParam("cache") boolean cache)
      throws JsonProcessingException {
    StopWatch watch = new StopWatch();
    watch.start();

    if (log.isDebugEnabled()) {
      log.trace("Time to execute getTree Service : {}ms", watch.getTime());
    }
    return Response.status(Response.Status.OK).build();
  }
  /** @param orgIn */
  private void publishUpdateErrataCacheEvent(Org orgIn) {
    StopWatch sw = new StopWatch();
    if (log.isDebugEnabled()) {
      log.debug("Updating errata cache");
      sw.start();
    }

    UpdateErrataCacheEvent uece = new UpdateErrataCacheEvent(UpdateErrataCacheEvent.TYPE_ORG);
    uece.setOrgId(orgIn.getId());
    MessageQueue.publish(uece);

    if (log.isDebugEnabled()) {
      sw.stop();
      log.debug("Finished Updating errata cache. Took [" + sw.getTime() + "]");
    }
  }
  @Override
  protected Client createClient(Settings.Builder builder) {
    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    if (_log.isWarnEnabled()) {
      StringBundler sb = new StringBundler(6);

      sb.append("Liferay is configured to use embedded Elasticsearch ");
      sb.append("as its search engine. Do NOT use embedded ");
      sb.append("Elasticsearch in production. Embedded Elasticsearch ");
      sb.append("is useful for development and demonstration purposes. ");
      sb.append("Remote Elasticsearch connections can be configured in ");
      sb.append("the Control Panel.");

      _log.warn(sb);
    }

    if (_log.isDebugEnabled()) {
      _log.debug(
          "Starting embedded Elasticsearch cluster " + elasticsearchConfiguration.clusterName());
    }

    NodeBuilder nodeBuilder = NodeBuilder.nodeBuilder();

    nodeBuilder.settings(builder);

    _node = nodeBuilder.node();

    _node.start();

    Client client = _node.client();

    if (_log.isDebugEnabled()) {
      stopWatch.stop();

      _log.debug(
          "Finished starting "
              + elasticsearchConfiguration.clusterName()
              + " in "
              + stopWatch.getTime()
              + " ms");
    }

    return client;
  }
  @Test
  public void rdfsEntailQuery() throws EngineException, MalformedURLException, IOException {

    Graph gRes = Graph.create(false);
    QueryProcessDQP exec = QueryProcessDQP.create(gRes);
    exec.addRemote(new URL("http://localhost:" + port + "/kgram/sparql"), WSImplem.REST);

    StopWatch sw = new StopWatch();
    sw.start();
    Mappings res = exec.query(sparqlEntailQueryPerson);

    System.out.println("--------");
    System.out.println("Results in " + sw.getTime() + "ms");
    System.out.println(res);

    assertEquals(17, res.size());
  }
  @Test
  public void localEntailments() throws EngineException {
    Graph localGraph = Graph.create(true);
    Load ld = Load.create(localGraph);
    ld.load(humanData.getAbsolutePath());
    ld.load(humanOnt.getAbsolutePath());

    QueryProcess exec = QueryProcess.create(localGraph);
    StopWatch sw = new StopWatch();
    sw.start();
    Mappings res = exec.query(sparqlEntailQueryPerson);

    System.out.println("--------");
    System.out.println("Results in " + sw.getTime() + "ms");
    System.out.println(res);

    assertEquals(17, res.size());
  }
  protected void logHasUserPermissions(
      long userId, long resourceId, String actionId, StopWatch stopWatch, int block) {

    if (!_log.isDebugEnabled()) {
      return;
    }

    _log.debug(
        "Checking user permissions block "
            + block
            + " for "
            + userId
            + " "
            + resourceId
            + " "
            + actionId
            + " takes "
            + stopWatch.getTime()
            + " ms");
  }
  public MetadataSegment fetchMetadataOld(String type, String[] levels) throws RetsReplyException {
    // Always need system to get version and date
    MSystem system = findSystemFromHibernate();

    MetadataFinder finder = (MetadataFinder) sMetadataFinders.get(type);
    if (finder != null) {
      StopWatch stopWatch = new StopWatch();
      LOG.debug("Using finder for type: " + type);
      stopWatch.start();
      List metadata = finder.findMetadata(levels, mSessions);
      stopWatch.stop();
      LOG.debug("End finder: " + stopWatch.getTime());
      return new MetadataSegment(metadata, levels, system.getVersionString(), system.getDate());
    } else {
      LOG.warn(
          "Recieved query for unknown metadataResults type: "
              + type
              + ", level="
              + StringUtils.join(levels, ":"));
      throw new RetsReplyException(ReplyCode.INVALID_TYPE, type);
    }
  }
  protected void reindex(Indexer indexer) throws Exception {
    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    if (_log.isInfoEnabled()) {
      _log.info("Reindexing with " + indexer.getClass() + " started");
    }

    indexer.reindex(new String[] {String.valueOf(_companyId)});

    _usedSearchEngineIds.add(indexer.getSearchEngineId());

    if (_log.isInfoEnabled()) {
      _log.info(
          "Reindexing with "
              + indexer.getClass()
              + " completed in "
              + (stopWatch.getTime() / Time.SECOND)
              + " seconds");
    }
  }
  @Override
  public void loadIndex(long companyId, InputStream inputStream) throws IOException {

    if (!isLoadIndexFromClusterEnabled()) {
      return;
    }

    IndexAccessor indexAccessor = _indexAccessors.get(companyId);

    if (indexAccessor == null) {
      if (_log.isInfoEnabled()) {
        _log.info(
            "Skip loading Lucene index files for company "
                + companyId
                + " in favor of lazy loading");
      }

      return;
    }

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    if (_log.isInfoEnabled()) {
      _log.info("Start loading Lucene index files for company " + companyId);
    }

    indexAccessor.loadIndex(inputStream);

    if (_log.isInfoEnabled()) {
      _log.info(
          "Finished loading index files for company "
              + companyId
              + " in "
              + stopWatch.getTime()
              + " ms");
    }
  }
  public static void main(String[] args) {
    try {
      StopWatch stopWatch = new StopWatch();

      stopWatch.start();

      InitUtil.initWithSpring();

      upgrade();
      verify();

      System.out.println(
          "\nSuccessfully completed upgrade process in "
              + (stopWatch.getTime() / Time.SECOND)
              + " seconds.");

      System.exit(0);
    } catch (Exception e) {
      e.printStackTrace();

      System.exit(1);
    }
  }
  protected void testIncomingConnection() throws MailException {
    StopWatch stopWatch = null;

    if (_log.isDebugEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    try {
      Store store = getStore(false);

      store.close();
    } catch (Exception e) {
      throw new MailException(MailException.ACCOUNT_INCOMING_CONNECTION_FAILED, e);
    } finally {
      if (_log.isDebugEnabled()) {
        stopWatch.stop();

        _log.debug("Testing incoming connection completed in " + stopWatch.getTime() + " ms");
      }
    }
  }
  protected File doExport(PortletDataContext portletDataContext) throws Exception {

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

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

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

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

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

      throw new LayoutImportException("Layout type " + layout.getType() + " is not valid");
    }

    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(
                PortalUtil.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", "portlet");
    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());

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

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

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

    exportPortlet(
        portletDataContext,
        layout,
        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);

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

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

    ExportImportHelperUtil.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(ioe);
    }

    ZipWriter zipWriter = portletDataContext.getZipWriter();

    return zipWriter.getFile();
  }
 @Override
 public Observable<Long> getElapsed() {
   return Observable.just(stopWatch.getTime() / 1000L);
 }
  protected File doExportPortletInfoAsFile(
      long plid,
      long groupId,
      String portletId,
      Map<String, String[]> parameterMap,
      Date startDate,
      Date endDate)
      throws Exception {

    boolean exportCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean exportPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean exportPortletArchivedSetups =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);

    boolean exportPortletData = false;

    if (parameterMap.containsKey(
        PortletDataHandlerKeys.PORTLET_DATA + "_" + PortletConstants.getRootPortletId(portletId))) {

      exportPortletData =
          MapUtil.getBoolean(
              parameterMap,
              PortletDataHandlerKeys.PORTLET_DATA
                  + "_"
                  + PortletConstants.getRootPortletId(portletId));
    } else {
      exportPortletData = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
    }

    boolean exportPortletDataAll =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA_ALL);
    boolean exportPortletSetup =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_SETUP);
    boolean exportPortletUserPreferences =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
    boolean exportUserPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.USER_PERMISSIONS);

    if (_log.isDebugEnabled()) {
      _log.debug("Export categories " + exportCategories);
      _log.debug("Export permissions " + exportPermissions);
      _log.debug("Export portlet archived setups " + exportPortletArchivedSetups);
      _log.debug("Export portlet data " + exportPortletData);
      _log.debug("Export all portlet data " + exportPortletDataAll);
      _log.debug("Export portlet setup " + exportPortletSetup);
      _log.debug("Export portlet user preferences " + exportPortletUserPreferences);
      _log.debug("Export user permissions " + exportUserPermissions);
    }

    if (exportPortletDataAll) {
      exportPortletData = true;
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    Layout layout = LayoutLocalServiceUtil.getLayout(plid);

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

      throw new LayoutImportException("Layout type " + layout.getType() + " is not valid");
    }

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

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    long scopeGroupId = groupId;

    javax.portlet.PortletPreferences jxPreferences =
        PortletPreferencesFactoryUtil.getLayoutPortletSetup(layout, portletId);

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

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

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

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

    PortletDataContext portletDataContext =
        new PortletDataContextImpl(
            layout.getCompanyId(),
            scopeGroupId,
            parameterMap,
            new HashSet<String>(),
            startDate,
            endDate,
            zipWriter);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    portletDataContext.setPlid(plid);
    portletDataContext.setOldPlid(plid);
    portletDataContext.setScopeType(scopeType);
    portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

    Document document = SAXReaderUtil.createDocument();

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

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

    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", "portlet");
    headerElement.addAttribute("group-id", String.valueOf(scopeGroupId));
    headerElement.addAttribute("private-layout", String.valueOf(layout.isPrivateLayout()));
    headerElement.addAttribute("root-portlet-id", PortletConstants.getRootPortletId(portletId));

    exportPortlet(
        portletDataContext,
        layoutCache,
        portletId,
        layout,
        rootElement,
        defaultUserId,
        exportPermissions,
        exportPortletArchivedSetups,
        exportPortletData,
        exportPortletSetup,
        exportPortletUserPreferences,
        exportUserPermissions);

    if (exportCategories) {
      exportAssetCategories(portletDataContext);
    }

    exportAssetLinks(portletDataContext);
    exportAssetTags(portletDataContext);
    exportComments(portletDataContext);
    exportExpandoTables(portletDataContext);
    exportLocks(portletDataContext);

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

    exportRatingsEntries(portletDataContext, rootElement);

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

    try {
      portletDataContext.addZipEntry("/manifest.xml", document.formattedString());
    } catch (IOException ioe) {
      throw new SystemException(ioe);
    }

    return zipWriter.getFile();
  }
  protected File doExport(PortletDataContext portletDataContext, long[] layoutIds)
      throws Exception {

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

    boolean ignoreLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean layoutSetPrototypeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_SETTINGS);
    boolean layoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);
    boolean logo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean permissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);

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

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

    long companyId = layoutSet.getCompanyId();
    long defaultUserId = _userLocalService.getDefaultUserId(companyId);

    ServiceContext serviceContext = ServiceContextThreadLocal.popServiceContext();

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

    serviceContext.setCompanyId(companyId);
    serviceContext.setSignedIn(false);
    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("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 = layoutSet.getGroup();

    String type = "layout-set";

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

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

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

      layoutIds =
          ExportImportHelperUtil.getAllLayoutIds(
              portletDataContext.getGroupId(), portletDataContext.isPrivateLayout());
    } else if (group.isLayoutSetPrototype()) {
      type = "layout-set-prototype";

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

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

    headerElement.addAttribute("type", type);

    LayoutSetBranch layoutSetBranch =
        _layoutSetBranchLocalService.fetchLayoutSetBranch(layoutSetBranchId);

    if (logo) {
      Image image = null;

      if (layoutSetBranch != null) {
        image = _imageLocalService.getImage(layoutSetBranch.getLogoId());
      } else {
        image = _imageLocalService.getImage(layoutSet.getLogoId());
      }

      if ((image != null) && (image.getTextObj() != null)) {
        String logoPath = ExportImportPathUtil.getRootPath(portletDataContext);

        logoPath += "/logo";

        headerElement.addAttribute("logo-path", logoPath);

        portletDataContext.addZipEntry(logoPath, image.getTextObj());
      }
    }

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    if (layoutSetPrototypeSettings && Validator.isNotNull(layoutSetPrototypeUuid)) {

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

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

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

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

    if (layoutSetBranch != null) {
      _themeExporter.exportTheme(portletDataContext, layoutSetBranch);
    } else {
      _themeExporter.exportTheme(portletDataContext, layoutSet);
    }

    if (layoutSetSettings) {
      Element settingsElement = headerElement.addElement("settings");

      if (layoutSetBranch != null) {
        settingsElement.addCDATA(layoutSetBranch.getSettings());
      } else {
        settingsElement.addCDATA(layoutSet.getSettings());
      }
    }

    Map<String, Object[]> portletIds = new LinkedHashMap<>();

    List<Layout> layouts =
        _layoutLocalService.getLayouts(
            portletDataContext.getGroupId(), portletDataContext.isPrivateLayout());

    if (group.isStagingGroup()) {
      group = group.getLiveGroup();
    }

    // Collect data portlets

    for (Portlet portlet : ExportImportHelperUtil.getDataSiteLevelPortlets(companyId)) {

      String portletId = portlet.getRootPortletId();

      if (ExportImportThreadLocal.isStagingInProcess() && !group.isStagedPortlet(portletId)) {

        continue;
      }

      // Calculate the amount of exported data

      if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
        PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance();

        portletDataHandler.prepareManifestSummary(portletDataContext);
      }

      // Add portlet ID to exportable portlets list

      portletIds.put(
          PortletPermissionUtil.getPrimaryKey(0, portletId),
          new Object[] {
            portletId,
            LayoutConstants.DEFAULT_PLID,
            portletDataContext.getGroupId(),
            StringPool.BLANK,
            StringPool.BLANK
          });

      if (!portlet.isScopeable()) {
        continue;
      }

      // Scoped data

      for (Layout layout : layouts) {
        if (!ArrayUtil.contains(layoutIds, layout.getLayoutId())
            || !layout.isTypePortlet()
            || !layout.hasScopeGroup()) {

          continue;
        }

        Group scopeGroup = layout.getScopeGroup();

        portletIds.put(
            PortletPermissionUtil.getPrimaryKey(layout.getPlid(), portlet.getPortletId()),
            new Object[] {
              portlet.getPortletId(),
              layout.getPlid(),
              scopeGroup.getGroupId(),
              StringPool.BLANK,
              layout.getUuid()
            });
      }
    }

    // Collect layout portlets

    for (Layout layout : layouts) {
      getLayoutPortlets(portletDataContext, layoutIds, portletIds, layout);
    }

    if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
      ManifestSummary manifestSummary = portletDataContext.getManifestSummary();

      PortletDataHandlerStatusMessageSenderUtil.sendStatusMessage(
          "layout", ArrayUtil.toStringArray(portletIds.keySet()), manifestSummary);

      manifestSummary.resetCounters();
    }

    // Export actual data

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

    // Force to always have a layout group element

    portletDataContext.getExportDataGroupElement(Layout.class);

    for (Layout layout : layouts) {
      exportLayout(portletDataContext, layoutIds, layout);
    }

    Element portletsElement = rootElement.addElement("portlets");

    Element servicesElement = rootElement.addElement("services");

    long previousScopeGroupId = portletDataContext.getScopeGroupId();

    for (Map.Entry<String, Object[]> portletIdsEntry : portletIds.entrySet()) {

      Object[] portletObjects = portletIdsEntry.getValue();

      String portletId = null;
      long plid = LayoutConstants.DEFAULT_PLID;
      long scopeGroupId = 0;
      String scopeType = StringPool.BLANK;
      String scopeLayoutUuid = null;

      if (portletObjects.length == 4) {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[3];
      } else {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeType = (String) portletIdsEntry.getValue()[3];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[4];
      }

      Layout layout = _layoutLocalService.fetchLayout(plid);

      if (layout == null) {
        layout = new LayoutImpl();

        layout.setCompanyId(companyId);
        layout.setGroupId(portletDataContext.getGroupId());
      }

      portletDataContext.setPlid(plid);
      portletDataContext.setOldPlid(plid);
      portletDataContext.setPortletId(portletId);
      portletDataContext.setScopeGroupId(scopeGroupId);
      portletDataContext.setScopeType(scopeType);
      portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

      Map<String, Boolean> exportPortletControlsMap =
          ExportImportHelperUtil.getExportPortletControlsMap(
              companyId, portletId, parameterMap, type);

      try {
        _exportImportLifecycleManager.fireExportImportLifecycleEvent(
            EVENT_PORTLET_EXPORT_STARTED,
            getProcessFlag(),
            PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext));

        _portletExportController.exportPortlet(
            portletDataContext,
            layout,
            portletsElement,
            permissions,
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_USER_PREFERENCES));
        _portletExportController.exportService(
            portletDataContext,
            servicesElement,
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP));

        _exportImportLifecycleManager.fireExportImportLifecycleEvent(
            EVENT_PORTLET_EXPORT_SUCCEEDED,
            getProcessFlag(),
            PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext));
      } catch (Throwable t) {
        _exportImportLifecycleManager.fireExportImportLifecycleEvent(
            EVENT_PORTLET_EXPORT_FAILED,
            getProcessFlag(),
            PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext),
            t);

        throw t;
      }
    }

    portletDataContext.setScopeGroupId(previousScopeGroupId);

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

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

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

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

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

    boolean updateLastPublishDate =
        MapUtil.getBoolean(
            portletDataContext.getParameterMap(), PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE);

    if (ExportImportThreadLocal.isStagingInProcess() && updateLastPublishDate) {

      ExportImportProcessCallbackRegistryUtil.registerCallback(
          new UpdateLayoutSetLastPublishDateCallable(
              portletDataContext.getDateRange(),
              portletDataContext.getGroupId(),
              portletDataContext.isPrivateLayout()));
    }

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

    ZipWriter zipWriter = portletDataContext.getZipWriter();

    return zipWriter.getFile();
  }
Exemple #24
0
  public static synchronized void init() {
    if (_initialized) {
      return;
    }

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    // Set the default locale used by Liferay. This locale is no longer set
    // at the VM level. See LEP-2584.

    String userLanguage = SystemProperties.get("user.language");
    String userCountry = SystemProperties.get("user.country");
    String userVariant = SystemProperties.get("user.variant");

    LocaleUtil.setDefault(userLanguage, userCountry, userVariant);

    // Set the default time zone used by Liferay. This time zone is no
    // longer set at the VM level. See LEP-2584.

    String userTimeZone = SystemProperties.get("user.timezone");

    TimeZoneUtil.setDefault(userTimeZone);

    // Shared class loader

    try {
      PortalClassLoaderUtil.setClassLoader(ClassLoaderUtil.getContextClassLoader());
    } catch (Exception e) {
      e.printStackTrace();
    }

    // Properties

    com.liferay.portal.kernel.util.PropsUtil.setProps(new PropsImpl());

    // Log4J

    if (GetterUtil.getBoolean(SystemProperties.get("log4j.configure.on.startup"), true)) {

      ClassLoader classLoader = InitUtil.class.getClassLoader();

      Log4JUtil.configureLog4J(classLoader);
    }

    // Shared log

    try {
      LogFactoryUtil.setLogFactory(new Log4jLogFactoryImpl());
    } catch (Exception e) {
      e.printStackTrace();
    }

    // Log sanitizer

    SanitizerLogWrapper.init();

    // Java properties

    JavaDetector.isJDK5();

    // Security manager

    SecurityManagerUtil.init();

    if (SecurityManagerUtil.ENABLED) {
      com.liferay.portal.kernel.util.PropsUtil.setProps(
          DoPrivilegedUtil.wrap(com.liferay.portal.kernel.util.PropsUtil.getProps()));

      LogFactoryUtil.setLogFactory(DoPrivilegedUtil.wrap(LogFactoryUtil.getLogFactory()));
    }

    // Cache registry

    CacheRegistryUtil.setCacheRegistry(DoPrivilegedUtil.wrap(new CacheRegistryImpl()));

    // Configuration factory

    ConfigurationFactoryUtil.setConfigurationFactory(
        DoPrivilegedUtil.wrap(new ConfigurationFactoryImpl()));

    // Data source factory

    DataSourceFactoryUtil.setDataSourceFactory(DoPrivilegedUtil.wrap(new DataSourceFactoryImpl()));

    // DB factory

    DBFactoryUtil.setDBFactory(DoPrivilegedUtil.wrap(new DBFactoryImpl()));

    // ROME

    XmlReader.setDefaultEncoding(StringPool.UTF8);

    if (_PRINT_TIME) {
      System.out.println("InitAction takes " + stopWatch.getTime() + " ms");
    }

    _initialized = true;
  }
  protected void doImportLayouts(
      long userId,
      long groupId,
      boolean privateLayout,
      Map<String, String[]> parameterMap,
      File file)
      throws Exception {

    boolean deleteMissingLayouts =
        MapUtil.getBoolean(
            parameterMap,
            PortletDataHandlerKeys.DELETE_MISSING_LAYOUTS,
            Boolean.TRUE.booleanValue());
    boolean deletePortletData =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.DELETE_PORTLET_DATA);
    boolean importCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean importPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean importPublicLayoutPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PUBLIC_LAYOUT_PERMISSIONS);
    boolean importUserPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.USER_PERMISSIONS);
    boolean importPortletData =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
    boolean importPortletSetup =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_SETUP);
    boolean importPortletArchivedSetups =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);
    boolean importPortletUserPreferences =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
    boolean importTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME);
    boolean importThemeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE);
    boolean importLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean importLayoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);

    boolean layoutSetPrototypeLinkEnabled =
        MapUtil.getBoolean(
            parameterMap, PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_LINK_ENABLED, true);

    Group group = GroupLocalServiceUtil.getGroup(groupId);

    if (group.isLayoutSetPrototype()) {
      layoutSetPrototypeLinkEnabled = false;
    }

    boolean publishToRemote =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PUBLISH_TO_REMOTE);
    String layoutsImportMode =
        MapUtil.getString(
            parameterMap,
            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID);
    String portletsMergeMode =
        MapUtil.getString(
            parameterMap,
            PortletDataHandlerKeys.PORTLETS_MERGE_MODE,
            PortletDataHandlerKeys.PORTLETS_MERGE_MODE_REPLACE);
    String userIdStrategy =
        MapUtil.getString(parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);

    if (_log.isDebugEnabled()) {
      _log.debug("Delete portlet data " + deletePortletData);
      _log.debug("Import categories " + importCategories);
      _log.debug("Import permissions " + importPermissions);
      _log.debug("Import user permissions " + importUserPermissions);
      _log.debug("Import portlet data " + importPortletData);
      _log.debug("Import portlet setup " + importPortletSetup);
      _log.debug("Import portlet archived setups " + importPortletArchivedSetups);
      _log.debug("Import portlet user preferences " + importPortletUserPreferences);
      _log.debug("Import theme " + importTheme);
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

    long companyId = layoutSet.getCompanyId();

    User user = UserUtil.findByPrimaryKey(userId);

    UserIdStrategy strategy = _portletImporter.getUserIdStrategy(user, userIdStrategy);

    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file);

    PortletDataContext portletDataContext =
        new PortletDataContextImpl(
            companyId, groupId, parameterMap, new HashSet<String>(), strategy, zipReader);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    portletDataContext.setPrivateLayout(privateLayout);

    // Zip

    Element rootElement = null;
    InputStream themeZip = null;

    // Manifest

    String xml = portletDataContext.getZipEntryAsString("/manifest.xml");

    if (xml == null) {
      throw new LARFileException("manifest.xml not found in the LAR");
    }

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

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

    // Build compatibility

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

    int buildNumber = ReleaseInfo.getBuildNumber();

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

    if (buildNumber != importBuildNumber) {
      throw new LayoutImportException(
          "LAR build number "
              + importBuildNumber
              + " does not match "
              + "portal build number "
              + buildNumber);
    }

    // Type compatibility

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

    if (!larType.equals("layout-set") && !larType.equals("layout-set-prototype")) {

      throw new LARTypeException("Invalid type of LAR file (" + larType + ")");
    }

    // Group id

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

    portletDataContext.setSourceGroupId(sourceGroupId);

    // Layout set prototype

    if (group.isLayoutSetPrototype() && larType.equals("layout-set-prototype")) {

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

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

      LayoutSetPrototype existingLayoutSetPrototype = null;

      if (Validator.isNotNull(layoutSetPrototypeUuid)) {
        try {
          existingLayoutSetPrototype =
              LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid(
                  layoutSetPrototypeUuid);
        } catch (NoSuchLayoutSetPrototypeException nslspe) {
        }
      }

      if (existingLayoutSetPrototype == null) {
        layoutSetPrototype.setUuid(layoutSetPrototypeUuid);

        LayoutSetPrototypeLocalServiceUtil.updateLayoutSetPrototype(layoutSetPrototype);
      }
    }

    Element layoutsElement = rootElement.element("layouts");

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

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
      if (layoutSetPrototypeLinkEnabled) {
        if (publishToRemote) {
          importLayoutSetPrototype(
              portletDataContext, user, layoutSetPrototypeUuid, serviceContext);
        }
      }

      layoutSet.setLayoutSetPrototypeUuid(layoutSetPrototypeUuid);
      layoutSet.setLayoutSetPrototypeLinkEnabled(layoutSetPrototypeLinkEnabled);

      LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet);
    }

    // Look and feel

    if (importTheme) {
      themeZip = portletDataContext.getZipEntryAsInputStream("theme.zip");
    }

    // Look and feel

    String themeId = layoutSet.getThemeId();
    String colorSchemeId = layoutSet.getColorSchemeId();

    if (importThemeSettings) {
      Attribute themeIdAttribute = headerElement.attribute("theme-id");

      if (themeIdAttribute != null) {
        themeId = themeIdAttribute.getValue();
      }

      Attribute colorSchemeIdAttribute = headerElement.attribute("color-scheme-id");

      if (colorSchemeIdAttribute != null) {
        colorSchemeId = colorSchemeIdAttribute.getValue();
      }
    }

    if (importLogo) {
      String logoPath = headerElement.attributeValue("logo-path");

      byte[] iconBytes = portletDataContext.getZipEntryAsByteArray(logoPath);

      if ((iconBytes != null) && (iconBytes.length > 0)) {
        File logo = FileUtil.createTempFile(iconBytes);

        LayoutSetLocalServiceUtil.updateLogo(groupId, privateLayout, true, logo);
      } else {
        LayoutSetLocalServiceUtil.updateLogo(groupId, privateLayout, false, (File) null);
      }
    }

    if (importLayoutSetSettings) {
      String settings = GetterUtil.getString(headerElement.elementText("settings"));

      LayoutSetLocalServiceUtil.updateSettings(groupId, privateLayout, settings);
    }

    String css = GetterUtil.getString(headerElement.elementText("css"));

    if (themeZip != null) {
      String importThemeId = importTheme(layoutSet, themeZip);

      if (importThemeId != null) {
        themeId = importThemeId;
        colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId();
      }

      if (_log.isDebugEnabled()) {
        _log.debug("Importing theme takes " + stopWatch.getTime() + " ms");
      }
    }

    boolean wapTheme = false;

    LayoutSetLocalServiceUtil.updateLookAndFeel(
        groupId, privateLayout, themeId, colorSchemeId, css, wapTheme);

    // Read asset categories, asset tags, comments, locks, permissions, and
    // ratings entries to make them available to the data handlers through
    // the context

    if (importPermissions) {
      _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

    if (importCategories) {
      _portletImporter.readAssetCategories(portletDataContext);
    }

    _portletImporter.readAssetTags(portletDataContext);
    _portletImporter.readComments(portletDataContext);
    _portletImporter.readExpandoTables(portletDataContext);
    _portletImporter.readLocks(portletDataContext);
    _portletImporter.readRatingsEntries(portletDataContext);

    // Layouts

    List<Layout> previousLayouts = LayoutUtil.findByG_P(groupId, privateLayout);

    // Remove layouts that were deleted from the layout set prototype

    if (Validator.isNotNull(layoutSetPrototypeUuid) && layoutSetPrototypeLinkEnabled) {

      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid(layoutSetPrototypeUuid);

      Group layoutSetPrototypeGroup = layoutSetPrototype.getGroup();

      for (Layout layout : previousLayouts) {
        String sourcePrototypeLayoutUuid = layout.getSourcePrototypeLayoutUuid();

        if (Validator.isNull(layout.getSourcePrototypeLayoutUuid())) {
          continue;
        }

        Layout sourcePrototypeLayout =
            LayoutUtil.fetchByUUID_G(
                sourcePrototypeLayoutUuid, layoutSetPrototypeGroup.getGroupId());

        if (sourcePrototypeLayout == null) {
          LayoutLocalServiceUtil.deleteLayout(layout, false, serviceContext);
        }
      }
    }

    List<Layout> newLayouts = new ArrayList<Layout>();

    Set<Long> newLayoutIds = new HashSet<Long>();

    Map<Long, Layout> newLayoutsMap =
        (Map<Long, Layout>) portletDataContext.getNewPrimaryKeysMap(Layout.class);

    List<Element> layoutElements = layoutsElement.elements("layout");

    if (_log.isDebugEnabled()) {
      if (layoutElements.size() > 0) {
        _log.debug("Importing layouts");
      }
    }

    for (Element layoutElement : layoutElements) {
      importLayout(
          portletDataContext,
          user,
          layoutCache,
          previousLayouts,
          newLayouts,
          newLayoutsMap,
          newLayoutIds,
          portletsMergeMode,
          themeId,
          colorSchemeId,
          layoutsImportMode,
          privateLayout,
          importPermissions,
          importPublicLayoutPermissions,
          importUserPermissions,
          importThemeSettings,
          rootElement,
          layoutElement);
    }

    Element portletsElement = rootElement.element("portlets");

    List<Element> portletElements = portletsElement.elements("portlet");

    // Delete portlet data

    if (deletePortletData) {
      if (_log.isDebugEnabled()) {
        if (portletElements.size() > 0) {
          _log.debug("Deleting portlet data");
        }
      }

      for (Element portletElement : portletElements) {
        String portletId = portletElement.attributeValue("portlet-id");
        long layoutId = GetterUtil.getLong(portletElement.attributeValue("layout-id"));
        long plid = newLayoutsMap.get(layoutId).getPlid();

        portletDataContext.setPlid(plid);

        _portletImporter.deletePortletData(portletDataContext, portletId, plid);
      }
    }

    // Import portlets

    if (_log.isDebugEnabled()) {
      if (portletElements.size() > 0) {
        _log.debug("Importing portlets");
      }
    }

    for (Element portletElement : portletElements) {
      String portletPath = portletElement.attributeValue("path");
      String portletId = portletElement.attributeValue("portlet-id");
      long layoutId = GetterUtil.getLong(portletElement.attributeValue("layout-id"));
      long plid = newLayoutsMap.get(layoutId).getPlid();
      long oldPlid = GetterUtil.getLong(portletElement.attributeValue("old-plid"));

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

      if (!portlet.isActive() || portlet.isUndeployedPortlet()) {
        continue;
      }

      Layout layout = null;

      try {
        layout = LayoutUtil.findByPrimaryKey(plid);
      } catch (NoSuchLayoutException nsle) {
        continue;
      }

      portletDataContext.setPlid(plid);
      portletDataContext.setOldPlid(oldPlid);

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

      portletElement = portletDocument.getRootElement();

      // The order of the import is important. You must always import
      // the portlet preferences first, then the portlet data, then
      // the portlet permissions. The import of the portlet data
      // assumes that portlet preferences already exist.

      _portletImporter.setPortletScope(portletDataContext, portletElement);

      try {

        // Portlet preferences

        _portletImporter.importPortletPreferences(
            portletDataContext,
            layoutSet.getCompanyId(),
            layout.getGroupId(),
            layout,
            null,
            portletElement,
            importPortletSetup,
            importPortletArchivedSetups,
            importPortletUserPreferences,
            false);

        // Portlet data

        Element portletDataElement = portletElement.element("portlet-data");

        if (importPortletData && (portletDataElement != null)) {
          _portletImporter.importPortletData(
              portletDataContext, portletId, plid, portletDataElement);
        }
      } finally {
        _portletImporter.resetPortletScope(portletDataContext, layout.getGroupId());
      }

      // Portlet permissions

      if (importPermissions) {
        _permissionImporter.importPortletPermissions(
            layoutCache,
            companyId,
            groupId,
            userId,
            layout,
            portletElement,
            portletId,
            importUserPermissions);
      }

      // Archived setups

      _portletImporter.importPortletPreferences(
          portletDataContext,
          layoutSet.getCompanyId(),
          groupId,
          null,
          null,
          portletElement,
          importPortletSetup,
          importPortletArchivedSetups,
          importPortletUserPreferences,
          false);
    }

    if (importPermissions) {
      if ((userId > 0)
          && ((PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5)
              || (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6))) {

        Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

        indexer.reindex(userId);
      }
    }

    // Asset links

    _portletImporter.readAssetLinks(portletDataContext);

    // Delete missing layouts

    if (deleteMissingLayouts) {
      deleteMissingLayouts(groupId, privateLayout, newLayoutIds, previousLayouts, serviceContext);
    }

    // Page count

    LayoutSetLocalServiceUtil.updatePageCount(groupId, privateLayout);

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

    // Site

    GroupLocalServiceUtil.updateSite(groupId, true);

    // Web content layout type

    for (Layout layout : newLayouts) {
      UnicodeProperties typeSettingsProperties = layout.getTypeSettingsProperties();

      String articleId = typeSettingsProperties.getProperty("article-id");

      if (Validator.isNotNull(articleId)) {
        Map<String, String> articleIds =
            (Map<String, String>)
                portletDataContext.getNewPrimaryKeysMap(JournalArticle.class + ".articleId");

        typeSettingsProperties.setProperty(
            "article-id", MapUtil.getString(articleIds, articleId, articleId));

        LayoutUtil.update(layout, false);
      }
    }

    zipReader.close();
  }
  protected void doReIndex(int delay) {
    if (SearchEngineUtil.isIndexReadOnly()) {
      return;
    }

    if (_log.isInfoEnabled()) {
      _log.info("Reindexing Lucene started");
    }

    if (delay < 0) {
      delay = 0;
    }

    try {
      if (delay > 0) {
        Thread.sleep(Time.SECOND * delay);
      }
    } catch (InterruptedException ie) {
    }

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    try {
      SearchEngineUtil.removeCompany(_companyId);

      SearchEngineUtil.initialize(_companyId);

      List<Portlet> portlets = PortletLocalServiceUtil.getPortlets(_companyId);

      portlets = ListUtil.sort(portlets, new PortletLuceneComparator());

      for (Portlet portlet : portlets) {
        if (!portlet.isActive()) {
          continue;
        }

        List<Indexer> indexers = portlet.getIndexerInstances();

        if (indexers == null) {
          continue;
        }

        Set<String> searchEngineIds = new HashSet<>();

        for (Indexer indexer : indexers) {
          String searchEngineId = indexer.getSearchEngineId();

          if (searchEngineIds.add(searchEngineId)) {
            SearchEngineUtil.deletePortletDocuments(
                searchEngineId, _companyId, portlet.getPortletId(), true);
          }

          reindex(indexer);
        }
      }

      if (_log.isInfoEnabled()) {
        _log.info(
            "Reindexing Lucene completed in " + (stopWatch.getTime() / Time.SECOND) + " seconds");
      }
    } catch (Exception e) {
      _log.error("Error encountered while reindexing", e);

      if (_log.isInfoEnabled()) {
        _log.info("Reindexing Lucene failed");
      }
    }

    _finished = true;
  }
  public void importPortletInfo(
      long userId,
      long plid,
      long groupId,
      String portletId,
      Map<String, String[]> parameterMap,
      File file)
      throws Exception {

    boolean deletePortletData =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.DELETE_PORTLET_DATA);
    boolean importPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean importUserPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean importPortletData =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
    boolean importPortletArchivedSetups =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);
    boolean importPortletSetup =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_SETUP);
    boolean importPortletUserPreferences =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
    String userIdStrategyString =
        MapUtil.getString(parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    Layout layout = LayoutLocalServiceUtil.getLayout(plid);

    User user = UserUtil.findByPrimaryKey(userId);

    UserIdStrategy userIdStrategy = getUserIdStrategy(user, userIdStrategyString);

    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file);

    PortletDataContext portletDataContext =
        new PortletDataContextImpl(
            layout.getCompanyId(),
            groupId,
            parameterMap,
            new HashSet<String>(),
            userIdStrategy,
            zipReader);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    portletDataContext.setPlid(plid);
    portletDataContext.setPrivateLayout(layout.isPrivateLayout());

    // Manifest

    String xml = portletDataContext.getZipEntryAsString("/manifest.xml");

    Element rootElement = null;

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

      rootElement = document.getRootElement();
    } catch (Exception e) {
      throw new LARFileException("Unable to read /manifest.xml");
    }

    // Build compatibility

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

    int buildNumber = ReleaseInfo.getBuildNumber();

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

    if (buildNumber != importBuildNumber) {
      throw new LayoutImportException(
          "LAR build number "
              + importBuildNumber
              + " does not match "
              + "portal build number "
              + buildNumber);
    }

    // Type compatibility

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

    if (!type.equals("portlet")) {
      throw new LARTypeException("Invalid type of LAR file (" + type + ")");
    }

    // Portlet compatibility

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

    if (!PortletConstants.getRootPortletId(portletId).equals(rootPortletId)) {

      throw new PortletIdException("Invalid portlet id " + rootPortletId);
    }

    // Import group id

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

    portletDataContext.setSourceGroupId(sourceGroupId);

    // Read asset categories, asset tags, comments, locks, and ratings
    // entries to make them available to the data handlers through the
    // context

    if (importPermissions) {
      _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

    readAssetCategories(portletDataContext);
    readAssetTags(portletDataContext);
    readComments(portletDataContext);
    readExpandoTables(portletDataContext);
    readLocks(portletDataContext);
    readRatingsEntries(portletDataContext);

    // Delete portlet data

    if (_log.isDebugEnabled()) {
      _log.debug("Deleting portlet data");
    }

    if (deletePortletData) {
      deletePortletData(portletDataContext, portletId, plid);
    }

    Element portletElement = null;

    try {
      portletElement = rootElement.element("portlet");

      Document portletDocument =
          SAXReaderUtil.read(
              portletDataContext.getZipEntryAsString(portletElement.attributeValue("path")));

      portletElement = portletDocument.getRootElement();
    } catch (DocumentException de) {
      throw new SystemException(de);
    }

    setPortletScope(portletDataContext, portletElement);

    try {

      // Portlet preferences

      importPortletPreferences(
          portletDataContext,
          layout.getCompanyId(),
          groupId,
          layout,
          portletId,
          portletElement,
          importPortletSetup,
          importPortletArchivedSetups,
          importPortletUserPreferences,
          true);

      // Portlet data

      Element portletDataElement = portletElement.element("portlet-data");

      if (importPortletData && (portletDataElement != null)) {
        if (_log.isDebugEnabled()) {
          _log.debug("Importing portlet data");
        }

        importPortletData(portletDataContext, portletId, plid, portletDataElement);
      }
    } finally {
      resetPortletScope(portletDataContext, groupId);
    }

    // Portlet permissions

    if (importPermissions) {
      if (_log.isDebugEnabled()) {
        _log.debug("Importing portlet permissions");
      }

      LayoutCache layoutCache = new LayoutCache();

      _permissionImporter.importPortletPermissions(
          layoutCache,
          layout.getCompanyId(),
          groupId,
          userId,
          layout,
          portletElement,
          portletId,
          importUserPermissions);
    }

    // Asset links

    if (_log.isDebugEnabled()) {
      _log.debug("Importing asset links");
    }

    readAssetLinks(portletDataContext);

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

    zipReader.close();
  }
  protected File doExportLayoutsAsFile(
      long groupId,
      boolean privateLayout,
      long[] layoutIds,
      Map<String, String[]> parameterMap,
      Date startDate,
      Date endDate)
      throws Exception {

    boolean exportCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean exportIgnoreLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean exportPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean exportPortletDataAll =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA_ALL);
    boolean exportTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME);
    boolean exportThemeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE);
    boolean exportLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean exportLayoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);
    boolean updateLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE);

    if (_log.isDebugEnabled()) {
      _log.debug("Export permissions " + exportPermissions);
      _log.debug("Export theme " + exportTheme);
    }

    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

    long companyId = layoutSet.getCompanyId();
    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

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

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

      ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

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

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

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    long lastPublishDate = System.currentTimeMillis();

    if (endDate != null) {
      lastPublishDate = endDate.getTime();
    }

    if (exportIgnoreLastPublishDate) {
      endDate = null;
      startDate = null;
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    PortletDataContext portletDataContext =
        PortletDataContextFactoryUtil.createExportPortletDataContext(
            companyId, groupId, parameterMap, startDate, endDate, zipWriter);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    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("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(groupId));
    headerElement.addAttribute(
        "user-personal-site-group-id",
        String.valueOf(portletDataContext.getUserPersonalSiteGroupId()));
    headerElement.addAttribute("private-layout", String.valueOf(privateLayout));

    Group group = layoutSet.getGroup();

    String type = "layout-set";

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

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

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

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

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

    headerElement.addAttribute("type", type);

    if (exportTheme || exportThemeSettings) {
      headerElement.addAttribute("theme-id", layoutSet.getThemeId());
      headerElement.addAttribute("color-scheme-id", layoutSet.getColorSchemeId());
    }

    if (exportLogo) {
      Image image = ImageLocalServiceUtil.getImage(layoutSet.getLogoId());

      if ((image != null) && (image.getTextObj() != null)) {
        String logoPath = ExportImportPathUtil.getRootPath(portletDataContext);

        logoPath += "/logo";

        headerElement.addAttribute("logo-path", logoPath);

        portletDataContext.addZipEntry(logoPath, image.getTextObj());
      }
    }

    if (exportLayoutSetSettings) {
      Element settingsElement = headerElement.addElement("settings");

      settingsElement.addCDATA(layoutSet.getSettings());
    }

    Element cssElement = headerElement.addElement("css");

    cssElement.addCDATA(layoutSet.getCss());

    Map<String, Object[]> portletIds = new LinkedHashMap<String, Object[]>();

    List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout);

    List<Portlet> portlets = getDataSiteLevelPortlets(companyId);

    long plid = LayoutConstants.DEFAULT_PLID;

    if (!layouts.isEmpty()) {
      Layout firstLayout = layouts.get(0);

      plid = firstLayout.getPlid();
    }

    if (group.isStagingGroup()) {
      group = group.getLiveGroup();
    }

    for (Portlet portlet : portlets) {
      String portletId = portlet.getRootPortletId();

      if (!group.isStagedPortlet(portletId)) {
        continue;
      }

      String key = PortletPermissionUtil.getPrimaryKey(0, portletId);

      if (portletIds.get(key) == null) {
        portletIds.put(
            key, new Object[] {portletId, plid, groupId, StringPool.BLANK, StringPool.BLANK});
      }
    }

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

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

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

    Element layoutsElement = portletDataContext.getExportDataGroupElement(Layout.class);

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuidAndCompanyId(
              layoutSetPrototypeUuid, companyId);

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

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

    for (Layout layout : layouts) {
      exportLayout(portletDataContext, portlets, layoutIds, portletIds, layout);
    }

    long previousScopeGroupId = portletDataContext.getScopeGroupId();

    Element portletsElement = rootElement.addElement("portlets");

    for (Map.Entry<String, Object[]> portletIdsEntry : portletIds.entrySet()) {

      Object[] portletObjects = portletIdsEntry.getValue();

      String portletId = null;
      plid = LayoutConstants.DEFAULT_PLID;
      long scopeGroupId = 0;
      String scopeType = StringPool.BLANK;
      String scopeLayoutUuid = null;

      if (portletObjects.length == 4) {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[3];
      } else {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeType = (String) portletIdsEntry.getValue()[3];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[4];
      }

      Layout layout = LayoutLocalServiceUtil.fetchLayout(plid);

      if (layout == null) {
        if (!group.isCompany() && (plid <= LayoutConstants.DEFAULT_PLID)) {

          continue;
        }

        if (_log.isWarnEnabled()) {
          _log.warn("Assuming global scope because no layout was found");
        }

        layout = new LayoutImpl();

        layout.setGroupId(groupId);
        layout.setCompanyId(companyId);
      }

      portletDataContext.setPlid(plid);
      portletDataContext.setOldPlid(plid);
      portletDataContext.setScopeGroupId(scopeGroupId);
      portletDataContext.setScopeType(scopeType);
      portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

      boolean[] exportPortletControls =
          getExportPortletControls(companyId, portletId, parameterMap, type);

      _portletExporter.exportPortlet(
          portletDataContext,
          layoutCache,
          portletId,
          layout,
          portletsElement,
          defaultUserId,
          exportPermissions,
          exportPortletControls[0],
          exportPortletControls[1],
          exportPortletControls[2],
          exportPortletControls[3]);
    }

    portletDataContext.setScopeGroupId(previousScopeGroupId);

    exportAssetCategories(
        portletDataContext, exportPortletDataAll, exportCategories, group.isCompany());

    _portletExporter.exportAssetLinks(portletDataContext);
    _portletExporter.exportAssetTags(portletDataContext);
    _portletExporter.exportComments(portletDataContext);
    _portletExporter.exportExpandoTables(portletDataContext);
    _portletExporter.exportLocks(portletDataContext);

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

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

    _portletExporter.exportRatingsEntries(portletDataContext, rootElement);

    if (exportTheme && !portletDataContext.isPerformDirectBinaryImport()) {
      exportTheme(layoutSet, zipWriter);
    }

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

    if (_log.isInfoEnabled()) {
      if (stopWatch != null) {
        _log.info("Exporting layouts takes " + stopWatch.getTime() + " ms");
      } else {
        _log.info("Exporting layouts is finished");
      }
    }

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

    try {
      return zipWriter.getFile();
    } finally {
      if (updateLastPublishDate) {
        updateLastPublishDate(layoutSet, lastPublishDate);
      }
    }
  }
  protected void doImportPortletInfo(PortletDataContext portletDataContext, long userId)
      throws Exception {

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

    boolean importPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

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

      serviceContext.setCompanyId(portletDataContext.getCompanyId());
      serviceContext.setSignedIn(false);
      serviceContext.setUserId(userId);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    // LAR validation

    validateFile(
        portletDataContext.getCompanyId(),
        portletDataContext.getGroupId(),
        portletDataContext.getPortletId(),
        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 = ExportImportHelperUtil.getManifestSummary(portletDataContext);

    if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
      PortletDataHandlerStatusMessageSenderUtil.sendStatusMessage(
          "portlet", portletDataContext.getPortletId(), manifestSummary);
    }

    portletDataContext.setManifestSummary(manifestSummary);

    // Read expando tables, locks and permissions to make them
    // available to the data handlers through the portlet data context

    Element rootElement = portletDataContext.getImportDataRootElement();

    Element portletElement = null;

    try {
      portletElement = rootElement.element("portlet");

      Document portletDocument =
          SAXReaderUtil.read(
              portletDataContext.getZipEntryAsString(portletElement.attributeValue("path")));

      portletElement = portletDocument.getRootElement();
    } catch (DocumentException de) {
      throw new SystemException(de);
    }

    LayoutCache layoutCache = new LayoutCache();

    if (importPermissions) {
      _permissionImporter.checkRoles(
          layoutCache,
          portletDataContext.getCompanyId(),
          portletDataContext.getGroupId(),
          userId,
          portletElement);

      _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

    readExpandoTables(portletDataContext);
    readLocks(portletDataContext);

    Element portletDataElement = portletElement.element("portlet-data");

    Map<String, Boolean> importPortletControlsMap =
        ExportImportHelperUtil.getImportPortletControlsMap(
            portletDataContext.getCompanyId(),
            portletDataContext.getPortletId(),
            parameterMap,
            portletDataElement,
            manifestSummary);

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

    try {

      // Portlet preferences

      importPortletPreferences(
          portletDataContext,
          layout.getCompanyId(),
          portletDataContext.getGroupId(),
          layout,
          portletElement,
          true,
          importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
          importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
          importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
          importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_USER_PREFERENCES));

      // Portlet data

      if (importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA)) {

        if (_log.isDebugEnabled()) {
          _log.debug("Importing portlet data");
        }

        importPortletData(portletDataContext, portletDataElement);
      }
    } finally {
      resetPortletScope(portletDataContext, portletDataContext.getGroupId());
    }

    // Portlet permissions

    if (importPermissions) {
      if (_log.isDebugEnabled()) {
        _log.debug("Importing portlet permissions");
      }

      _permissionImporter.importPortletPermissions(
          layoutCache,
          portletDataContext.getCompanyId(),
          portletDataContext.getGroupId(),
          userId,
          layout,
          portletElement,
          portletDataContext.getPortletId());

      if (userId > 0) {
        Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);

        User user = _userLocalService.fetchUser(userId);

        indexer.reindex(user);
      }
    }

    // Asset links

    if (_log.isDebugEnabled()) {
      _log.debug("Importing asset links");
    }

    importAssetLinks(portletDataContext);

    // Deletion system events

    _deletionSystemEventImporter.importDeletionSystemEvents(portletDataContext);

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

    // Service portlet preferences

    boolean importPortletSetup = importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP);

    if (importPortletSetup) {
      try {
        List<Element> serviceElements = rootElement.elements("service");

        for (Element serviceElement : serviceElements) {
          Document serviceDocument =
              SAXReaderUtil.read(
                  portletDataContext.getZipEntryAsString(serviceElement.attributeValue("path")));

          importServicePortletPreferences(portletDataContext, serviceDocument.getRootElement());
        }
      } catch (DocumentException de) {
        throw new SystemException(de);
      }
    }

    ZipReader zipReader = portletDataContext.getZipReader();

    zipReader.close();
  }
  protected File doExportLayoutsAsFile(
      long groupId,
      boolean privateLayout,
      long[] layoutIds,
      Map<String, String[]> parameterMap,
      Date startDate,
      Date endDate)
      throws Exception {

    boolean exportCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean exportIgnoreLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean exportPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean exportUserPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.USER_PERMISSIONS);
    boolean exportPortletArchivedSetups =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);
    boolean exportPortletUserPreferences =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
    boolean exportTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME);
    boolean exportThemeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE);
    boolean exportLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean exportLayoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);
    boolean publishToRemote =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PUBLISH_TO_REMOTE);
    boolean updateLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE);

    if (_log.isDebugEnabled()) {
      _log.debug("Export categories " + exportCategories);
      _log.debug("Export permissions " + exportPermissions);
      _log.debug("Export user permissions " + exportUserPermissions);
      _log.debug("Export portlet archived setups " + exportPortletArchivedSetups);
      _log.debug("Export portlet user preferences " + exportPortletUserPreferences);
      _log.debug("Export theme " + exportTheme);
    }

    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

    long companyId = layoutSet.getCompanyId();
    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

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

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

      ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

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

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

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    long lastPublishDate = System.currentTimeMillis();

    if (endDate != null) {
      lastPublishDate = endDate.getTime();
    }

    if (exportIgnoreLastPublishDate) {
      endDate = null;
      startDate = null;
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    PortletDataContext portletDataContext =
        new PortletDataContextImpl(
            companyId, groupId, parameterMap, new HashSet<String>(), startDate, endDate, zipWriter);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    Document document = SAXReaderUtil.createDocument();

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

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

    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("group-id", String.valueOf(groupId));
    headerElement.addAttribute("private-layout", String.valueOf(privateLayout));

    Group group = layoutSet.getGroup();

    String type = "layout-set";

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

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

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

    headerElement.addAttribute("type", type);

    if (exportTheme || exportThemeSettings) {
      headerElement.addAttribute("theme-id", layoutSet.getThemeId());
      headerElement.addAttribute("color-scheme-id", layoutSet.getColorSchemeId());
    }

    if (exportLogo) {
      Image image = ImageLocalServiceUtil.getImage(layoutSet.getLogoId());

      if (image != null) {
        String logoPath = getLayoutSetLogoPath(portletDataContext);

        headerElement.addAttribute("logo-path", logoPath);

        portletDataContext.addZipEntry(logoPath, image.getTextObj());
      }
    }

    if (exportLayoutSetSettings) {
      Element settingsElement = headerElement.addElement("settings");

      settingsElement.addCDATA(layoutSet.getSettings());
    }

    Element cssElement = headerElement.addElement("css");

    cssElement.addCDATA(layoutSet.getCss());

    Portlet layoutConfigurationPortlet =
        PortletLocalServiceUtil.getPortletById(
            portletDataContext.getCompanyId(), PortletKeys.LAYOUT_CONFIGURATION);

    Map<String, Object[]> portletIds = new LinkedHashMap<String, Object[]>();

    List<Layout> layouts = null;

    if ((layoutIds == null) || (layoutIds.length == 0)) {
      layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout);
    } else {
      layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout, layoutIds);
    }

    List<Portlet> portlets = getAlwaysExportablePortlets(companyId);

    if (!layouts.isEmpty()) {
      Layout firstLayout = layouts.get(0);

      if (group.isStagingGroup()) {
        group = group.getLiveGroup();
      }

      for (Portlet portlet : portlets) {
        String portletId = portlet.getRootPortletId();

        if (!group.isStagedPortlet(portletId)) {
          continue;
        }

        String key = PortletPermissionUtil.getPrimaryKey(0, portletId);

        if (portletIds.get(key) == null) {
          portletIds.put(
              key,
              new Object[] {
                portletId, firstLayout.getPlid(), groupId, StringPool.BLANK, StringPool.BLANK
              });
        }
      }
    }

    Element layoutsElement = rootElement.addElement("layouts");

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid(layoutSetPrototypeUuid);

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

      if (publishToRemote) {
        String path = getLayoutSetPrototype(portletDataContext, layoutSetPrototypeUuid);

        File layoutSetPrototypeFile = null;

        InputStream inputStream = null;

        try {
          layoutSetPrototypeFile =
              SitesUtil.exportLayoutSetPrototype(layoutSetPrototype, serviceContext);

          inputStream = new FileInputStream(layoutSetPrototypeFile);

          portletDataContext.addZipEntry(path.concat(".lar"), inputStream);
          portletDataContext.addZipEntry(path.concat(".xml"), layoutSetPrototype);
        } finally {
          StreamUtil.cleanUp(inputStream);

          FileUtil.delete(layoutSetPrototypeFile);
        }
      }
    }

    for (Layout layout : layouts) {
      exportLayout(
          portletDataContext,
          layoutConfigurationPortlet,
          layoutCache,
          portlets,
          portletIds,
          exportPermissions,
          exportUserPermissions,
          layout,
          layoutsElement);
    }

    if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM < 5) {
      Element rolesElement = rootElement.addElement("roles");

      if (exportPermissions) {
        _permissionExporter.exportLayoutRoles(layoutCache, companyId, groupId, rolesElement);
      }
    }

    long previousScopeGroupId = portletDataContext.getScopeGroupId();

    Element portletsElement = rootElement.addElement("portlets");

    for (Map.Entry<String, Object[]> portletIdsEntry : portletIds.entrySet()) {

      Object[] portletObjects = portletIdsEntry.getValue();

      String portletId = null;
      long plid = 0;
      long scopeGroupId = 0;
      String scopeType = StringPool.BLANK;
      String scopeLayoutUuid = null;

      if (portletObjects.length == 4) {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[3];
      } else {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeType = (String) portletIdsEntry.getValue()[3];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[4];
      }

      Layout layout = LayoutLocalServiceUtil.getLayout(plid);

      portletDataContext.setPlid(layout.getPlid());
      portletDataContext.setOldPlid(layout.getPlid());
      portletDataContext.setScopeGroupId(scopeGroupId);
      portletDataContext.setScopeType(scopeType);
      portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

      boolean[] exportPortletControls =
          getExportPortletControls(companyId, portletId, portletDataContext, parameterMap);

      _portletExporter.exportPortlet(
          portletDataContext,
          layoutCache,
          portletId,
          layout,
          portletsElement,
          defaultUserId,
          exportPermissions,
          exportPortletArchivedSetups,
          exportPortletControls[0],
          exportPortletControls[1],
          exportPortletUserPreferences,
          exportUserPermissions);
    }

    portletDataContext.setScopeGroupId(previousScopeGroupId);

    if (exportCategories) {
      exportAssetCategories(portletDataContext);
    }

    _portletExporter.exportAssetLinks(portletDataContext);
    _portletExporter.exportAssetTags(portletDataContext);
    _portletExporter.exportComments(portletDataContext);
    _portletExporter.exportExpandoTables(portletDataContext);
    _portletExporter.exportLocks(portletDataContext);

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

    _portletExporter.exportRatingsEntries(portletDataContext, rootElement);

    if (exportTheme && !portletDataContext.isPerformDirectBinaryImport()) {
      exportTheme(layoutSet, zipWriter);
    }

    if (_log.isInfoEnabled()) {
      if (stopWatch != null) {
        _log.info("Exporting layouts takes " + stopWatch.getTime() + " ms");
      } else {
        _log.info("Exporting layouts is finished");
      }
    }

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

    try {
      return zipWriter.getFile();
    } finally {
      if (updateLastPublishDate) {
        updateLastPublishDate(layoutSet, lastPublishDate);
      }
    }
  }