Example usage for org.apache.commons.lang.time StopWatch start

List of usage examples for org.apache.commons.lang.time StopWatch start

Introduction

In this page you can find the example usage for org.apache.commons.lang.time StopWatch start.

Prototype

public void start() 

Source Link

Document

Start the stopwatch.

This method starts a new timing session, clearing any previous values.

Usage

From source file:edu.internet2.middleware.psp.grouper.PspChangeLogConsumer.java

/**
 * Run a full synchronization by executing a {@link BulkSyncRequest}.
 * /*from ww w .  ja v  a2s.com*/
 * @return the response
 */
public synchronized Response fullSync() {

    LOG.info("PSP Consumer '{}' - Starting full sync", name);

    if (fullSyncIsRunning) {
        LOG.info("PSP Consumer '{}' - Full sync is already running, will defer to next scheduled trigger.",
                name);
        return null;
    }

    fullSyncIsRunning = true;

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    // Perform bulk sync request without responses to conserve memory.
    BulkSyncRequest request = new BulkSyncRequest();
    if (omitDiffResponses) {
        request.setReturnDiffResponses(false);
    }
    if (omitSyncResponses) {
        request.setReturnSyncResponses(false);
    }
    BulkSyncResponse response = psp.execute(request);

    stopWatch.stop();

    fullSyncIsRunning = false;

    if (response.getStatus().equals(StatusCode.SUCCESS)) {
        LOG.info("PSP Consumer '{}' - Full sync was successful '{}'", name, PSPUtil.toString(response));
    } else {
        LOG.error("PSP Consumer '{}' - Full sync was not successful '{}'", name, PSPUtil.toString(response));
    }

    LOG.info("PSP Consumer '{}' - Finished full sync. Elapsed time {}", name, stopWatch);

    if (LOG.isDebugEnabled()) {
        for (String stats : PspCLI.getAllCacheStats()) {
            LOG.debug(stats);
        }
    }

    return response;
}

From source file:com.liferay.portal.lar.LayoutExporter.java

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 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);
    }//  w  w w . j av a 2s.co m

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

    Group group = layoutSet.getGroup();

    if (group.isLayoutSetPrototype()) {
        LayoutSetPrototype layoutSetPrototype = LayoutSetPrototypeLocalServiceUtil
                .getLayoutSetPrototype(group.getClassPK());

        String layoutSetPrototypeUuid = layoutSetPrototype.getUuid();

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

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

            File layoutSetPrototypeFile = SitesUtil.exportLayoutSetPrototype(layoutSetPrototype,
                    serviceContext);

            try {
                portletDataContext.addZipEntry(path.concat(".lar"),
                        new FileInputStream(layoutSetPrototypeFile));
                portletDataContext.addZipEntry(path.concat(".xml"), layoutSetPrototype);
            } finally {
                layoutSetPrototypeFile.delete();
            }
        }
    }

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

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

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

From source file:com.sforce.cd.apexUnit.client.testEngine.TestStatusPollerAndResultHandler.java

public boolean waitForTestsToComplete(String parentJobId, PartnerConnection conn) {
    String soql = QueryConstructor.getTestExecutionStatus(parentJobId);
    // String soql =
    // QueryConstructor.getTestExecutionStatusAndTransactionTime(parentJobId);

    QueryResult queryResult;/*from  w  ww  . j  av a 2 s  .  c o m*/
    boolean testsCompleted = false;

    try {
        LOG.debug(soql);
        int index = 0;
        queryResult = conn.query(soql);

        if (queryResult.getDone()) {
            SObject[] sObjects = queryResult.getRecords();

            if (sObjects != null) {
                String status = "";
                int totalTests = sObjects.length;
                totalTestClasses = totalTests;
                int remainingTests = totalTests;
                LOG.info("Total test classes to execute: " + totalTestClasses);
                String testId = "";
                String testName = "";
                String id = "";
                StopWatch stopWatch = new StopWatch();
                long startTime = 0;
                long endTime = 0;
                for (SObject sobject : sObjects) {
                    sobject.setType("ApexTestQueueItem");
                    status = sobject.getField("Status").toString();
                    testId = sobject.getField("ApexClassId").toString();
                    id = sobject.getField("Id").toString();
                    LOG.debug("ID for ApexTestQueueItem: " + id);
                    testName = ApexClassFetcherUtils.apexClassMap.get(testId);
                    LOG.info("Now executing the test class: " + testName + " ("
                            + CommandLineArguments.getOrgUrl() + "/" + testId + " ) " + "Status : " + status);
                    stopWatch.reset();
                    stopWatch.start();
                    startTime = stopWatch.getTime();
                    LOG.debug("Start time: " + startTime);

                    while (status.equals("Processing") || status.equals("Queued") || status.equals("Preparing")
                            || !status.equals("Completed")) {

                        // break out of the loop if the test failed
                        if (status.equals("Failed")) {
                            LOG.info("Test class failure for : " + testName + " ("
                                    + CommandLineArguments.getOrgUrl() + "/" + testId + " ) ");
                            break;
                        } else if (status.equals("Aborted")) {
                            LOG.info("Test : " + testName + " (" + CommandLineArguments.getOrgUrl() + "/"
                                    + testId + " ) has been aborted.");
                            totalTestClassesAborted++;
                            break;
                        }
                        // Abort the long running tests based on user
                        // input(default: 10 minutes)
                        // stopWatch.getTime() will be in milliseconds,
                        // hence divide by 1000 to convert to seconds
                        // maxTestExecTimeThreshold will be in minutes,
                        // hence multiply by 60 to convert to seconds

                        if (CommandLineArguments.getMaxTestExecTimeThreshold() != null
                                && stopWatch.getTime()
                                        / 1000.0 > CommandLineArguments.getMaxTestExecTimeThreshold() * 60
                                && status.equals("Processing")) {
                            LOG.info("Oops! This test is a long running test. "
                                    + CommandLineArguments.getMaxTestExecTimeThreshold()
                                    + " minutes elapsed; aborting the test: " + testName);

                            // create new sobject for updating the record
                            SObject newSObject = new SObject();
                            newSObject.setType("ApexTestQueueItem");
                            newSObject.setField("Id", id);
                            // abort the test using DML, set status to
                            // "Aborted"
                            newSObject.setField("Status", "Aborted");
                            totalTestClassesAborted++;
                            // logging the status and id fields to compare
                            // them for pre and post update call

                            try {
                                // TODO : up to 10 records can be updated at
                                // a time by update() call.
                                // add the logic to leverage this feature.
                                // Currently only one record is being
                                // updated(aborted)

                                // Challenge: By the time we wait for 10
                                // records that needs to be aborted, the
                                // 'to-be-aborted' test might continue to
                                // run and might get completed

                                // update() call- analogous to UPDATE
                                // Statement in SQL
                                SaveResult[] saveResults = conn.update(new SObject[] { newSObject });

                                LOG.debug("Stop time: " + stopWatch.getTime());
                                stopWatch.stop();

                                for (int i = 0; i < saveResults.length; i++) {
                                    if (saveResults[i].isSuccess()) {
                                        LOG.debug("The record " + saveResults[i].getId()
                                                + " was updated successfully");
                                        LOG.info("Aborted test case: " + testName
                                                + " since the test took more time than the threshold execution time of "
                                                + CommandLineArguments.getMaxTestExecTimeThreshold() + " mins");
                                    } else {
                                        // There were errors during the
                                        // update call, so loop through and
                                        // print them out

                                        StringBuffer errorMsg = new StringBuffer();
                                        errorMsg.append("Record " + saveResults[i].getId() + " failed to save");
                                        for (int j = 0; j < saveResults[i].getErrors().length; j++) {
                                            com.sforce.soap.partner.Error err = saveResults[i].getErrors()[j];
                                            errorMsg.append("error code: " + err.getStatusCode().toString());
                                            errorMsg.append("error message: " + err.getMessage());
                                        }
                                        ApexUnitUtils.shutDownWithErrMsg(errorMsg.toString());
                                    }
                                }
                                LOG.debug("After update--" + newSObject.getField("Status").toString());
                                break;
                            } catch (ConnectionException e) {
                                ApexUnitUtils.shutDownWithDebugLog(e,
                                        ConnectionHandler.logConnectionException(e, conn, soql));
                            }

                        }

                        LOG.debug("Status of the test class: " + testName + " ("
                                + CommandLineArguments.getOrgUrl() + "/" + testId + " ) " + " is : " + status);

                        while (stopWatch.getTime() % 1000 != 0) {
                            // wait, till 1 second elapses
                        }
                        LOG.debug("Firing polling query at " + stopWatch.getTime());
                        queryResult = conn.query(soql);
                        sObjects = queryResult.getRecords();
                        status = sObjects[index].getField("Status").toString();
                    }
                    endTime = stopWatch.getTime();
                    // get and log extended status for the test
                    if (sObjects[index] != null && sObjects[index].getField("ExtendedStatus") != null) {
                        String extendedStatus = sObjects[index].getField("ExtendedStatus").toString();
                        LOG.info("Test status for " + testName + ":" + extendedStatus);
                    }
                    LOG.info("Completed executing the test class: " + testName + ". Time taken by the test: "
                            + endTime / 1000 / 60 + " minutes," + (endTime / 1000) % 60 + " seconds");
                    index++;
                    remainingTests = totalTests - index;
                    LOG.info("Total tests executed " + index + " , Remaining tests " + remainingTests);
                    if (remainingTests == 0) {
                        testsCompleted = true;
                    }
                }
            }
        }
    } catch (ConnectionException e) {
        ApexUnitUtils.shutDownWithDebugLog(e, ConnectionHandler.logConnectionException(e, conn, soql));
    }
    return testsCompleted;

}

From source file:com.liferay.portal.lar.PortletExporter.java

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 {//from  w  w  w .ja v a2s . com
        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();
}

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

protected File doExport(PortletDataContext portletDataContext) throws Exception {

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

    if (_log.isDebugEnabled()) {
        _log.debug("Export permissions " + exportPermissions);
    }//from www. j a va 2  s .com

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

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

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

        StringBundler sb = new StringBundler(4);

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

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

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

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

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

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

        serviceContext.setUserId(defaultUserId);

        ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

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

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    long scopeGroupId = portletDataContext.getGroupId();

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

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

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

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

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

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

    Document document = SAXReaderUtil.createDocument();

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

    portletDataContext.setExportDataRootElement(rootElement);

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

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

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

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

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

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

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

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

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

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

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

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

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

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

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

    ZipWriter zipWriter = portletDataContext.getZipWriter();

    return zipWriter.getFile();
}

From source file:com.liferay.portal.lar.PlaytechLayoutExporter.java

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);
    }//from ww w  .  j  a va  2 s .c  o m

    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("available-locales", StringUtil.merge(LanguageUtil.getAvailableLocales()));
    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.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 = 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<>();

    List<Layout> layouts = null;

    if ((layoutIds == null) || (layoutIds.length == 0)) {
        String scope = MapUtil.getString(parameterMap, "scope");
        if ("no-pages".equals(scope) || "selected-pages".equals(scope)) {
            layouts = Arrays.asList();
        } else {
            layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout);
        }
    } else {
        layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout, layoutIds);
    }

    List<Portlet> portlets = getAlwaysExportablePortlets(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();
        _log.debug("Exporting portlet " + portletId);

        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 layoutsElement = rootElement.addElement("layouts");

    long processedItems = 0;

    StagingProgressUpdaterThreadLocal.getMonitor().getComponent(PublishProcessProgressMonitor.COMPONENT_LAYOUTS)
            .setItemsCount(layouts.size());

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

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

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

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

    for (Layout layout : layouts) {
        StagingProgressUpdaterThreadLocal.getMonitor()
                .getComponent(PublishProcessProgressMonitor.COMPONENT_LAYOUTS)
                .setItemsProcessed(processedItems++);

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

    StagingProgressUpdaterThreadLocal.getMonitor()
            .getComponent(PublishProcessProgressMonitor.COMPONENT_PORTLETS).setItemsCount(portletIds.size());

    processedItems = 0;
    for (Map.Entry<String, Object[]> portletIdsEntry : portletIds.entrySet()) {
        StagingProgressUpdaterThreadLocal.getMonitor()
                .getComponent(PublishProcessProgressMonitor.COMPONENT_PORTLETS)
                .setItemsProcessed(processedItems++);

        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, portletDataContext,
                parameterMap);

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

    portletDataContext.setScopeGroupId(previousScopeGroupId);

    if (exportCategories || group.isCompany()) {
        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);
        }
    }
}

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

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);
    }//from   w  ww.j  ava2s  . co m

    // 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 = _exportImportHelper.getManifestSummary(portletDataContext);

    if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
        _portletDataHandlerStatusMessageSender.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("Unable to parse XML document for portlet "
                + portletDataContext.getPortletId() + " during import", de);
    }

    LayoutCache layoutCache = new LayoutCache();

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

        _permissionImporter.readPortletDataPermissions(portletDataContext);
    }

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

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

        readExpandoTables(portletDataContext);
    }

    readLocks(portletDataContext);

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

    Map<String, Boolean> importPortletControlsMap = _exportImportHelper.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("Unable to parse XML service information for portlet "
                    + portletDataContext.getPortletId() + " during import", de);
        } catch (PortalException pe) {
            throw new PortletDataException(
                    "Unable to import service preferences for portlet " + portletDataContext.getPortletId(),
                    pe);
        }
    }

    ZipReader zipReader = portletDataContext.getZipReader();

    zipReader.close();
}

From source file:eionet.meta.service.VocabularyServiceImpl.java

/**
 * {@inheritDoc}//from w  w w .  j av a  2 s  .  co m
 */
@Override
@Transactional(rollbackFor = ServiceException.class)
public int checkOutVocabularyFolder(int vocabularyFolderId, String userName) throws ServiceException {
    if (StringUtils.isBlank(userName)) {
        throw new IllegalArgumentException("User name must not be blank!");
    }

    try {
        StopWatch timer = new StopWatch();
        timer.start();
        VocabularyFolder vocabularyFolder = vocabularyFolderDAO.getVocabularyFolder(vocabularyFolderId);

        if (vocabularyFolder.isWorkingCopy()) {
            throw new ServiceException("Cannot check out a working copy!");
        }

        if (StringUtils.isNotBlank(vocabularyFolder.getWorkingUser())) {
            throw new ServiceException("Cannot check out an already checked-out vocabulary folder!");
        }

        // Update existing working user
        vocabularyFolder.setWorkingUser(userName);
        vocabularyFolderDAO.updateVocabularyFolder(vocabularyFolder);

        // Make new copy of vocabulary folder
        vocabularyFolder.setCheckedOutCopyId(vocabularyFolderId);
        vocabularyFolder.setWorkingCopy(true);
        int newVocabularyFolderId = vocabularyFolderDAO.createVocabularyFolder(vocabularyFolder);

        // Copy simple attributes.
        attributeDAO.copySimpleAttributes(vocabularyFolderId,
                DElemAttribute.ParentType.VOCABULARY_FOLDER.toString(), newVocabularyFolderId);

        // Copy the vocabulary concepts under new vocabulary folder (except of site code type)
        if (!vocabularyFolder.isSiteCodeType()) {
            vocabularyConceptDAO.copyVocabularyConcepts(vocabularyFolderId, newVocabularyFolderId);

            dataElementDAO.checkoutVocabularyConceptDataElementValues(newVocabularyFolderId);
            // dataElementDAO.updateRelatedConceptIds(newVocabularyFolderId);
        }

        // Copy data element relations
        dataElementDAO.copyVocabularyDataElements(vocabularyFolderId, newVocabularyFolderId);

        timer.stop();
        LOGGER.debug("Check-out lasted: " + timer.toString());
        return newVocabularyFolderId;
    } catch (Exception e) {
        throw new ServiceException("Failed to check-out vocabulary folder: " + e.getMessage(), e);
    }
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java

protected User addUser(long companyId, LDAPUser ldapUser, String password) throws Exception {

    StopWatch stopWatch = new StopWatch();

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

        _log.debug(StringBundler.concat("Adding LDAP user ", String.valueOf(ldapUser), " to company ",
                String.valueOf(companyId)));
    }/*from ww  w  .j av  a2  s.co  m*/

    boolean autoPassword = ldapUser.isAutoPassword();

    LDAPImportConfiguration ldapImportConfiguration = _ldapImportConfigurationProvider
            .getConfiguration(companyId);

    if (!ldapImportConfiguration.importUserPasswordEnabled()) {
        autoPassword = ldapImportConfiguration.importUserPasswordAutogenerated();

        if (!autoPassword) {
            String defaultPassword = ldapImportConfiguration.importUserPasswordDefault();

            if (StringUtil.equalsIgnoreCase(defaultPassword, _USER_PASSWORD_SCREEN_NAME)) {

                defaultPassword = ldapUser.getScreenName();
            }

            password = defaultPassword;
        }
    }

    Calendar birthdayCal = CalendarFactoryUtil.getCalendar();

    birthdayCal.setTime(ldapUser.getBirthday());

    int birthdayMonth = birthdayCal.get(Calendar.MONTH);
    int birthdayDay = birthdayCal.get(Calendar.DAY_OF_MONTH);
    int birthdayYear = birthdayCal.get(Calendar.YEAR);

    User user = _userLocalService.addUser(ldapUser.getCreatorUserId(), companyId, autoPassword, password,
            password, ldapUser.isAutoScreenName(), ldapUser.getScreenName(), ldapUser.getEmailAddress(), 0,
            StringPool.BLANK, ldapUser.getLocale(), ldapUser.getFirstName(), ldapUser.getMiddleName(),
            ldapUser.getLastName(), 0, 0, ldapUser.isMale(), birthdayMonth, birthdayDay, birthdayYear,
            StringPool.BLANK, ldapUser.getGroupIds(), ldapUser.getOrganizationIds(), ldapUser.getRoleIds(),
            ldapUser.getUserGroupIds(), ldapUser.isSendEmail(), ldapUser.getServiceContext());

    if (ldapUser.isUpdatePortrait()) {
        byte[] portraitBytes = ldapUser.getPortraitBytes();

        if (ArrayUtil.isNotEmpty(portraitBytes)) {
            user = _userLocalService.updatePortrait(user.getUserId(), portraitBytes);
        }
    }

    if (_log.isDebugEnabled()) {
        _log.debug(StringBundler.concat("Finished adding LDAP user ", String.valueOf(ldapUser), " as user ",
                String.valueOf(user), " in ", String.valueOf(stopWatch.getTime()), "ms"));
    }

    return user;
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java

protected UserGroup importUserGroup(long companyId, Attributes groupAttributes, Properties groupMappings)
        throws Exception {

    groupAttributes = _attributesTransformer.transformGroup(groupAttributes);

    LDAPGroup ldapGroup = _ldapToPortalConverter.importLDAPGroup(companyId, groupAttributes, groupMappings);

    UserGroup userGroup = null;//from   w  ww .  j  a va2 s .  c o m

    try {
        userGroup = _userGroupLocalService.getUserGroup(companyId, ldapGroup.getGroupName());

        if (!Objects.equals(userGroup.getDescription(), ldapGroup.getDescription())) {

            _userGroupLocalService.updateUserGroup(companyId, userGroup.getUserGroupId(),
                    ldapGroup.getGroupName(), ldapGroup.getDescription(), null);
        }
    } catch (NoSuchUserGroupException nsuge) {

        // LPS-52675

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

        StopWatch stopWatch = new StopWatch();

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

            _log.debug("Adding LDAP group " + ldapGroup);
        }

        long defaultUserId = _userLocalService.getDefaultUserId(companyId);

        UserGroupImportTransactionThreadLocal.setOriginatesFromImport(true);

        try {
            userGroup = _userGroupLocalService.addUserGroup(defaultUserId, companyId, ldapGroup.getGroupName(),
                    ldapGroup.getDescription(), null);

            if (_log.isDebugEnabled()) {
                _log.debug(StringBundler.concat("Finished adding LDAP group ", String.valueOf(ldapGroup),
                        " as user group ", String.valueOf(userGroup), " in ",
                        String.valueOf(stopWatch.getTime()), "ms"));
            }
        } catch (Exception e) {
            if (_log.isWarnEnabled()) {
                _log.warn("Unable to create user group " + ldapGroup.getGroupName());
            }

            if (_log.isDebugEnabled()) {
                _log.debug(e, e);
            }
        } finally {
            UserGroupImportTransactionThreadLocal.setOriginatesFromImport(false);
        }
    }

    addRole(companyId, ldapGroup, userGroup);

    return userGroup;
}