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

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

Introduction

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

Prototype

public long getTime() 

Source Link

Document

Get the time on the stopwatch.

This is either the time between the start and the moment this method is called, or the amount of time between start and stop.

Usage

From source file:com.liferay.journal.util.impl.JournalContentImpl.java

@Override
public JournalArticleDisplay getDisplay(JournalArticle article, String ddmTemplateKey, String viewMode,
        String languageId, int page, PortletRequestModel portletRequestModel, ThemeDisplay themeDisplay) {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();//www  .  j av  a2 s. com

    long groupId = article.getGroupId();
    String articleId = article.getArticleId();
    double version = article.getVersion();

    articleId = StringUtil.toUpperCase(GetterUtil.getString(articleId));
    ddmTemplateKey = StringUtil.toUpperCase(GetterUtil.getString(ddmTemplateKey));

    long layoutSetId = 0;
    boolean secure = false;

    if (themeDisplay != null) {
        try {
            if (!JournalArticlePermission.contains(themeDisplay.getPermissionChecker(), article,
                    ActionKeys.VIEW)) {

                return null;
            }
        } catch (Exception e) {
        }

        LayoutSet layoutSet = themeDisplay.getLayoutSet();

        layoutSetId = layoutSet.getLayoutSetId();

        secure = themeDisplay.isSecure();
    }

    if (Validator.isNull(ddmTemplateKey)) {
        ddmTemplateKey = article.getDDMTemplateKey();
    }

    JournalContentKey journalContentKey = new JournalContentKey(groupId, articleId, version, ddmTemplateKey,
            layoutSetId, viewMode, languageId, page, secure);

    JournalArticleDisplay articleDisplay = _portalCache.get(journalContentKey);

    boolean lifecycleRender = false;

    if (portletRequestModel != null) {
        lifecycleRender = RenderRequest.RENDER_PHASE.equals(portletRequestModel.getLifecycle());
    }

    if ((articleDisplay == null) || !lifecycleRender) {
        articleDisplay = getArticleDisplay(article, ddmTemplateKey, viewMode, languageId, page,
                portletRequestModel, themeDisplay);

        if ((articleDisplay != null) && articleDisplay.isCacheable() && lifecycleRender) {

            _portalCache.put(journalContentKey, articleDisplay);
        }
    }

    if (_log.isDebugEnabled()) {
        _log.debug(StringBundler.concat("getDisplay for {", String.valueOf(groupId), ", ", articleId, ", ",
                ddmTemplateKey, ", ", viewMode, ", ", languageId, ", ", String.valueOf(page), "} takes ",
                String.valueOf(stopWatch.getTime()), " ms"));
    }

    return articleDisplay;
}

From source file:io.cloudslang.engine.queue.services.ExecutionQueueServiceImpl.java

@Override
@Transactional/*from  www.  j  a v a 2  s .  c om*/
public void enqueue(List<ExecutionMessage> messages) {
    if (CollectionUtils.isEmpty(messages))
        return;

    if (logger.isDebugEnabled())
        logger.debug("Enqueue " + messages.size() + " messages");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    // assign worker for messages with pending status
    messages = executionAssignerService.assignWorkers(messages);
    if (logger.isDebugEnabled())
        logger.debug("Messages were assigned successfully");

    final List<ExecutionMessage> stateMessages = new ArrayList<>(messages.size());

    // first fill the execution state id for new insert
    for (ExecutionMessage msg : messages) {
        if (msg.getExecStateId() == ExecutionMessage.EMPTY_EXEC_STATE_ID) {
            long execStateId = executionQueueRepository.generateExecStateId();
            msg.setExecStateId(execStateId);
            stateMessages.add(msg);
        } else if (msg.getPayload() != null && msg.getStatus() == ExecStatus.IN_PROGRESS) {
            stateMessages.add(msg);
        }
    }

    if (CollectionUtils.isNotEmpty(listeners)) {
        stopWatch.split();
        for (QueueListener listener : listeners) {
            listener.prePersist(messages);
        }
        if (logger.isDebugEnabled())
            logger.debug("Listeners done in " + (stopWatch.getSplitTime()) + " ms");
    }

    stopWatch.split();
    if (stateMessages.size() > 0)
        executionQueueRepository.insertExecutionStates(stateMessages);

    long msgVersion = versionService.getCurrentVersion(VersionService.MSG_RECOVERY_VERSION_COUNTER_NAME);
    executionQueueRepository.insertExecutionQueue(messages, msgVersion);
    if (logger.isDebugEnabled())
        logger.debug("Persistency done in " + (stopWatch.getSplitTime()) + " ms");

    if (CollectionUtils.isNotEmpty(listeners)) {
        stopWatch.split();
        List<ExecutionMessage> failedMessages = filter(messages, ExecStatus.FAILED);
        List<ExecutionMessage> terminatedMessages = filter(messages, ExecStatus.TERMINATED);
        for (QueueListener listener : listeners) {
            listener.onEnqueue(messages, messages.size());
            if (failedMessages.size() > 0)
                listener.onFailed(failedMessages);
            if (terminatedMessages.size() > 0)
                listener.onTerminated(terminatedMessages);
        }
        if (logger.isDebugEnabled())
            logger.debug("Listeners done in " + (stopWatch.getSplitTime()) + " ms");
    }
    if (logger.isDebugEnabled())
        logger.debug("Enqueue done in " + (stopWatch.getTime()) + " ms");
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java

protected long runWithTimeout(MutationTestRunnable r) {
    long[] preIds = threadMxBean.getAllThreadIds();
    FutureTask<Object> future = new FutureTask<Object>(Executors.callable(r));
    Thread thread = new Thread(future);
    thread.setDaemon(true);/*from w w w . jav  a2s  .co  m*/
    logger.debug("Start  test: ");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    thread.start();
    String exceptionMessage = null;
    Throwable capturedThrowable = null;
    try {
        future.get(timeout, TimeUnit.SECONDS);
        logger.debug("Second timeout");
    } catch (InterruptedException e) {
        capturedThrowable = e;
    } catch (ExecutionException e) {
        capturedThrowable = e;
    } catch (TimeoutException e) {
        exceptionMessage = JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE + "Mutation causes test timeout";
        capturedThrowable = e;
    } catch (Throwable t) {
        capturedThrowable = t;
    } finally {
        if (capturedThrowable != null) {
            if (exceptionMessage == null) {
                exceptionMessage = "Exception caught during test execution.";
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            capturedThrowable.printStackTrace(new PrintStream(out));
            logger.debug(
                    "Setting test failed. Message: " + exceptionMessage + " Exception " + capturedThrowable);
            r.setFailed(exceptionMessage, capturedThrowable);
        }
    }
    if (!future.isDone()) {
        r.setFailed(JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE
                + "Mutated Thread is still running after timeout.", null);
        switchOfMutation(future);
    }
    stopWatch.stop();
    if (!checkAllFinished(preIds)) {
        if (configuration.useThreadStop()) {
            stopThreads(preIds);
        } else {
            shutDown(r, stopWatch);
        }
    }
    logger.debug("End timed test, it took " + stopWatch.getTime() + " ms");
    return stopWatch.getTime();
}

From source file:net.nan21.dnet.core.web.controller.data.AbstractAsgnController.java

/**
 * Default handler for find action./*from  w  ww .  ja  va  2 s.c  o m*/
 * 
 * @param resourceName
 * @param dataformat
 * @param dataString
 * @param paramString
 * @param resultStart
 * @param resultSize
 * @param orderByCol
 * @param orderBySense
 * @return
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.POST, params = Constants.REQUEST_PARAM_ACTION + "="
        + Constants.ASGN_ACTION_QUERY_LEFT)
@ResponseBody
public String findLeft(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_ASGN_OBJECT_ID, required = true) String objectId,
        @RequestParam(value = Constants.REQUEST_PARAM_ASGN_SELECTION_ID, required = true) String selectionId,
        @RequestParam(value = Constants.REQUEST_PARAM_FILTER, required = false, defaultValue = "{}") String dataString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        @RequestParam(value = Constants.REQUEST_PARAM_START, required = false, defaultValue = "0") int resultStart,
        @RequestParam(value = Constants.REQUEST_PARAM_SIZE, required = false, defaultValue = "500") int resultSize,
        @RequestParam(value = Constants.REQUEST_PARAM_SORT, required = false, defaultValue = "") String orderByCol,
        @RequestParam(value = Constants.REQUEST_PARAM_SENSE, required = false, defaultValue = "") String orderBySense,
        @RequestParam(value = Constants.REQUEST_PARAM_ORDERBY, required = false, defaultValue = "") String orderBy,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {

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

        if (logger.isInfoEnabled()) {
            logger.info("Processing request: {}.{} -> action = {} ",
                    new String[] { resourceName, dataFormat, Constants.ASGN_ACTION_QUERY_LEFT });
        }

        if (logger.isDebugEnabled()) {
            logger.debug("  --> request-filter: objectId={}, selectionId={} data={}",
                    new String[] { objectId, selectionId, dataString });
            logger.debug("  --> request-params: {} ", new String[] { paramString });
            logger.debug("  --> request-orderBy: sort={}, sense={}, orderBy={}",
                    new String[] { orderByCol, orderBySense, orderBy });
            logger.debug("  --> request-result-range: {} ",
                    new String[] { resultStart + "", (resultStart + resultSize) + "" });
        }

        this.prepareRequest(request, response);

        this.authorizeAsgnAction(resourceName, "find");

        IAsgnService<M, F, P> service = this.findAsgnService(this.serviceNameFromResourceName(resourceName));
        IDsMarshaller<M, F, P> marshaller = service.createMarshaller(dataFormat);

        IQueryBuilder<M, F, P> builder = service.createQueryBuilder().addFetchLimit(resultStart, resultSize);

        if (orderBy != null && !orderBy.equals("")) {
            List<SortToken> sortTokens = marshaller.readListFromString(orderBy, SortToken.class);
            builder.addSortInfo(sortTokens);
        } else {
            builder.addSortInfo(orderByCol, orderBySense);
        }

        F filter = marshaller.readFilterFromString(dataString);
        P params = marshaller.readParamsFromString(paramString);

        List<M> list = service.findLeft(selectionId, filter, params, builder);
        long totalCount = service.countLeft(selectionId, filter, params, builder);

        IActionResultFind result = this.packfindResult(list, params, totalCount);
        stopWatch.stop();
        result.setExecutionTime(stopWatch.getTime());

        return marshaller.writeResultToString(result);
    } catch (Exception e) {
        return this.handleException(e, response);
    } finally {
        this.finishRequest();
    }

}

From source file:net.nan21.dnet.core.web.controller.data.AbstractAsgnController.java

/**
 * Default handler for find action.//w w w .  j  ava 2  s.  c om
 * 
 * @param resourceName
 * @param dataformat
 * @param dataString
 * @param paramString
 * @param resultStart
 * @param resultSize
 * @param orderByCol
 * @param orderBySense
 * @return
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.POST, params = Constants.REQUEST_PARAM_ACTION + "="
        + Constants.ASGN_ACTION_QUERY_RIGHT)
@ResponseBody
public String findRight(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_ASGN_OBJECT_ID, required = true) String objectId,
        @RequestParam(value = Constants.REQUEST_PARAM_ASGN_SELECTION_ID, required = true) String selectionId,
        @RequestParam(value = Constants.REQUEST_PARAM_FILTER, required = false, defaultValue = "{}") String dataString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        @RequestParam(value = Constants.REQUEST_PARAM_START, required = false, defaultValue = "0") int resultStart,
        @RequestParam(value = Constants.REQUEST_PARAM_SIZE, required = false, defaultValue = "500") int resultSize,
        @RequestParam(value = Constants.REQUEST_PARAM_SORT, required = false, defaultValue = "") String orderByCol,
        @RequestParam(value = Constants.REQUEST_PARAM_SENSE, required = false, defaultValue = "") String orderBySense,
        @RequestParam(value = Constants.REQUEST_PARAM_ORDERBY, required = false, defaultValue = "") String orderBy,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {

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

        if (logger.isInfoEnabled()) {
            logger.info("Processing request: {}.{} -> action = {} ",
                    new String[] { resourceName, dataFormat, Constants.ASGN_ACTION_QUERY_RIGHT });
        }

        if (logger.isDebugEnabled()) {
            logger.debug("  --> request-filter: objectId={}, selectionId={} data={}",
                    new String[] { objectId, selectionId, dataString });
            logger.debug("  --> request-params: {} ", new String[] { paramString });
            logger.debug("  --> request-orderBy: sort={}, sense={}, orderBy={}",
                    new String[] { orderByCol, orderBySense, orderBy });
            logger.debug("  --> request-result-range: {} ",
                    new String[] { resultStart + "", (resultStart + resultSize) + "" });
        }

        this.prepareRequest(request, response);

        this.authorizeAsgnAction(resourceName, "find");

        IAsgnService<M, F, P> service = this.findAsgnService(this.serviceNameFromResourceName(resourceName));

        IDsMarshaller<M, F, P> marshaller = service.createMarshaller(dataFormat);

        IQueryBuilder<M, F, P> builder = service.createQueryBuilder().addFetchLimit(resultStart, resultSize);

        if (orderBy != null && !orderBy.equals("")) {
            List<SortToken> sortTokens = marshaller.readListFromString(orderBy, SortToken.class);
            builder.addSortInfo(sortTokens);
        } else {
            builder.addSortInfo(orderByCol, orderBySense);
        }

        F filter = marshaller.readFilterFromString(dataString);
        P params = marshaller.readParamsFromString(paramString);

        List<M> list = service.findRight(selectionId, filter, params, builder);
        long totalCount = service.countRight(selectionId, filter, params, builder);

        IActionResultFind result = this.packfindResult(list, params, totalCount);
        stopWatch.stop();
        result.setExecutionTime(stopWatch.getTime());

        return marshaller.writeResultToString(result);
    } catch (Exception e) {
        return this.handleException(e, response);
    } finally {
        this.finishRequest();
    }
}

From source file:net.nan21.dnet.core.web.controller.data.AbstractDsReadController.java

/**
 * Default handler for find action./*  w w  w  . ja  v  a  2  s . c o m*/
 * 
 * @param resourceName
 * @param dataformat
 * @param dataString
 * @param paramString
 * @param resultStart
 * @param resultSize
 * @param orderByCol
 * @param orderBySense
 * @param orderBy
 * @return
 * @throws Exception
 */
@RequestMapping(params = Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_QUERY)
@ResponseBody
public String find(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_FILTER, required = false, defaultValue = "{}") String filterString,
        @RequestParam(value = Constants.REQUEST_PARAM_ADVANCED_FILTER, required = false, defaultValue = "") String filterRulesString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        @RequestParam(value = Constants.REQUEST_PARAM_START, required = false, defaultValue = DEFAULT_RESULT_START) int resultStart,
        @RequestParam(value = Constants.REQUEST_PARAM_SIZE, required = false, defaultValue = DEFAULT_RESULT_SIZE) int resultSize,
        @RequestParam(value = Constants.REQUEST_PARAM_SORT, required = false, defaultValue = "") String orderByCol,
        @RequestParam(value = Constants.REQUEST_PARAM_SENSE, required = false, defaultValue = "") String orderBySense,
        @RequestParam(value = Constants.REQUEST_PARAM_ORDERBY, required = false, defaultValue = "") String orderBy,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {

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

        if (logger.isInfoEnabled()) {
            logger.info("Processing request: {}.{} -> action = {} ",
                    new String[] { resourceName, dataFormat, Constants.DS_ACTION_QUERY });
        }

        if (logger.isDebugEnabled()) {
            logger.debug("  --> request-filter: {} ", new String[] { filterString });
            logger.debug("  --> request-params: {} ", new String[] { paramString });
            logger.debug("  --> request-orderBy: sort={}, sense={}, orderBy={}",
                    new String[] { orderByCol, orderBySense, orderBy });
            logger.debug("  --> request-result-range: {} ",
                    new String[] { resultStart + "", (resultStart + resultSize) + "" });
        }
        this.prepareRequest(request, response);

        this.authorizeDsAction(resourceName, Constants.DS_ACTION_QUERY, null);

        IDsService<M, F, P> service = this.findDsService(resourceName);
        IDsMarshaller<M, F, P> marshaller = service.createMarshaller(IDsMarshaller.JSON);

        F filter = marshaller.readFilterFromString(filterString);
        P params = marshaller.readParamsFromString(paramString);

        IQueryBuilder<M, F, P> builder = service.createQueryBuilder().addFetchLimit(resultStart, resultSize)
                .addFilter(filter).addParams(params);

        if (orderBy != null && !orderBy.equals("")) {
            List<SortToken> sortTokens = marshaller.readListFromString(orderBy, SortToken.class);
            builder.addSortInfo(sortTokens);
        } else {
            builder.addSortInfo(orderByCol, orderBySense);
        }

        if (filterRulesString != null && !filterRulesString.equals("")) {
            List<FilterRule> filterRules = marshaller.readListFromString(filterRulesString, FilterRule.class);
            builder.addFilterRules(filterRules);
        }

        List<M> list = service.find(builder);
        long totalCount = service.count(builder);

        IActionResultFind result = this.packfindResult(list, params, totalCount);
        stopWatch.stop();
        result.setExecutionTime(stopWatch.getTime());

        String out = null;

        if (dataFormat.equals(IDsMarshaller.XML)) {
            IDsMarshaller<M, F, P> resultMarshaller = service.createMarshaller(dataFormat);
            out = resultMarshaller.writeResultToString(result);
            response.setContentType("text/xml; charset=UTF-8");
        } else {
            out = marshaller.writeResultToString(result);
            response.setContentType("text/plain; charset=UTF-8");
        }

        return out;
    } catch (Exception e) {
        return this.handleException(e, response);
    } finally {
        this.finishRequest();
    }

}

From source file:com.liferay.portal.security.permission.AdvancedPermissionChecker.java

public boolean hasPermission(long groupId, String name, String primKey, String actionId) {

    StopWatch stopWatch = null;

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

        stopWatch.start();//from  www .ja  v a 2s.c o m
    }

    Group group = null;

    // If the current group is a staging group, check the live group. If the
    // current group is a scope group for a layout, check the original
    // group.

    try {
        if (groupId > 0) {
            group = GroupLocalServiceUtil.getGroup(groupId);

            if (group.isUser() && (group.getClassPK() == getUserId())) {
                group = GroupLocalServiceUtil.getGroup(getCompanyId(), GroupConstants.USER_PERSONAL_SITE);

                groupId = group.getGroupId();
            }

            if (group.isLayout()) {
                Layout layout = LayoutLocalServiceUtil.getLayout(group.getClassPK());

                groupId = layout.getGroupId();

                group = GroupLocalServiceUtil.getGroup(groupId);
            }

            if (group.isStagingGroup()) {
                if (primKey.equals(String.valueOf(groupId))) {
                    primKey = String.valueOf(group.getLiveGroupId());
                }

                groupId = group.getLiveGroupId();
                group = group.getLiveGroup();
            }
        }
    } catch (Exception e) {
        _log.error(e, e);
    }

    Boolean value = PermissionCacheUtil.getPermission(user.getUserId(), signedIn, checkGuest, groupId, name,
            primKey, actionId);

    if (value == null) {
        try {
            value = Boolean.valueOf(hasPermissionImpl(groupId, name, primKey, actionId));

            if (_log.isDebugEnabled()) {
                _log.debug("Checking permission for " + groupId + " " + name + " " + primKey + " " + actionId
                        + " takes " + stopWatch.getTime() + " ms");
            }
        } finally {
            if (value == null) {
                value = Boolean.FALSE;
            }

            PermissionCacheUtil.putPermission(user.getUserId(), signedIn, checkGuest, groupId, name, primKey,
                    actionId, value);
        }
    }

    return value.booleanValue();
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

public void storeEnvelopes(long folderId, Folder jxFolder, Message[] jxMessages) throws PortalException {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();/*  w ww  . j  a va  2  s  .  co m*/

    try {
        FetchProfile fetchProfile = new FetchProfile();

        fetchProfile.add(UIDFolder.FetchProfileItem.ENVELOPE);
        fetchProfile.add(UIDFolder.FetchProfileItem.FLAGS);
        fetchProfile.add(UIDFolder.FetchProfileItem.UID);

        jxFolder.fetch(jxMessages, fetchProfile);

        for (Message jxMessage : jxMessages) {
            String sender = InternetAddressUtil.toString(jxMessage.getFrom());
            String to = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.TO));
            String cc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.CC));
            String bcc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.BCC));
            Date sentDate = jxMessage.getSentDate();
            String subject = jxMessage.getSubject();
            String flags = getFlags(jxMessage);
            long remoteMessageId = getUID(jxFolder, jxMessage);
            String contentType = jxMessage.getContentType();

            try {
                MessageLocalServiceUtil.getMessage(folderId, remoteMessageId);
            } catch (NoSuchMessageException nsme) {
                MessageLocalServiceUtil.addMessage(_user.getUserId(), folderId, sender, to, cc, bcc, sentDate,
                        subject, StringPool.BLANK, flags, remoteMessageId, contentType);
            }
        }

        com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.getFolder(folderId);

        FolderLocalServiceUtil.updateFolder(folderId, folder.getFullName(), folder.getDisplayName(),
                jxFolder.getMessageCount());
    } catch (MessagingException me) {
        throw new MailException(me);
    }

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

        _log.debug("Downloaded " + jxMessages.length + " messages from folder " + jxFolder.getFullName()
                + " completed in " + stopWatch.getTime() + " ms");
    }
}

From source file:com.liferay.portlet.InvokerPortletImpl.java

public void render(RenderRequest renderRequest, RenderResponse renderResponse)
        throws IOException, PortletException {

    PortletException portletException = (PortletException) renderRequest
            .getAttribute(_portletId + PortletException.class.getName());

    if (portletException != null) {
        throw portletException;
    }/*ww w .j  a  v a 2  s.  c om*/

    StopWatch stopWatch = null;

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

        stopWatch.start();
    }

    String remoteUser = renderRequest.getRemoteUser();

    if ((remoteUser == null) || (_expCache == null) || (_expCache.intValue() == 0)) {

        invokeRender(renderRequest, renderResponse);
    } else {
        RenderResponseImpl renderResponseImpl = (RenderResponseImpl) renderResponse;

        StringServletResponse stringResponse = (StringServletResponse) renderResponseImpl
                .getHttpServletResponse();

        PortletSession portletSession = renderRequest.getPortletSession();

        long now = System.currentTimeMillis();

        Layout layout = (Layout) renderRequest.getAttribute(WebKeys.LAYOUT);

        Map<String, InvokerPortletResponse> sessionResponses = getResponses(portletSession);

        String sessionResponseId = encodeResponseKey(layout.getPlid(), _portletId,
                LanguageUtil.getLanguageId(renderRequest));

        InvokerPortletResponse response = sessionResponses.get(sessionResponseId);

        if (response == null) {
            String title = invokeRender(renderRequest, renderResponse);

            response = new InvokerPortletResponse(title, stringResponse.getString(),
                    now + Time.SECOND * _expCache.intValue());

            sessionResponses.put(sessionResponseId, response);
        } else if ((response.getTime() < now) && (_expCache.intValue() > 0)) {
            String title = invokeRender(renderRequest, renderResponse);

            response.setTitle(title);
            response.setContent(stringResponse.getString());
            response.setTime(now + Time.SECOND * _expCache.intValue());
        } else {
            renderResponseImpl.setTitle(response.getTitle());
            stringResponse.getWriter().print(response.getContent());
        }
    }

    Map<String, String[]> properties = ((RenderResponseImpl) renderResponse).getProperties();

    if (properties.containsKey("clear-request-parameters")) {
        Map<String, String[]> renderParameters = ((RenderRequestImpl) renderRequest).getRenderParameters();

        renderParameters.clear();
    }

    if (_log.isDebugEnabled()) {
        _log.debug("render for " + _portletId + " takes " + stopWatch.getTime() + " ms");
    }
}

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

@Override
public void exportUser(long userId, long userGroupId, UserOperation userOperation) throws Exception {

    User user = _userLocalService.getUser(userId);

    long companyId = user.getCompanyId();

    StopWatch stopWatch = new StopWatch();

    if (_log.isDebugEnabled()) {
        stopWatch.start();//from   ww w . j a va 2  s.  c  o m

        _log.debug(StringBundler.concat("Exporting user ", String.valueOf(user), " in user group ",
                String.valueOf(userGroupId)));
    }

    if (!_ldapSettings.isExportEnabled(companyId) || !_ldapSettings.isExportGroupEnabled(companyId)) {

        return;
    }

    long ldapServerId = _portalLDAP.getLdapServerId(companyId, user.getScreenName(), user.getEmailAddress());

    LdapContext ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

    if (ldapContext == null) {
        return;
    }

    UserGroup userGroup = _userGroupLocalService.getUserGroup(userGroupId);

    Properties groupMappings = _ldapSettings.getGroupMappings(ldapServerId, companyId);
    Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);

    Binding binding = _portalLDAP.getGroup(ldapServerId, companyId, userGroup.getName());

    if (binding == null) {
        if (userOperation == UserOperation.ADD) {
            addGroup(ldapServerId, ldapContext, userGroup, user, groupMappings, userMappings);
        } else {
            if (_log.isWarnEnabled()) {
                _log.warn("Unable to get or add LDAP bindings for user group " + userGroup.getName());
            }
        }

        return;
    }

    try {
        Name name = new CompositeName();

        name.add(binding.getNameInNamespace());

        Modifications modifications = _portalToLDAPConverter.getLDAPGroupModifications(ldapServerId, userGroup,
                user, groupMappings, userMappings, userOperation);

        ModificationItem[] modificationItems = modifications.getItems();

        ldapContext.modifyAttributes(name, modificationItems);
    } catch (SchemaViolationException sve) {
        if (_log.isInfoEnabled()) {
            _log.info("Unable to update LDAP bindings for user group " + userGroup.getName(), sve);
        }

        String fullGroupDN = binding.getNameInNamespace();

        Attributes attributes = _portalLDAP.getGroupAttributes(ldapServerId, companyId, ldapContext,
                fullGroupDN, true);

        Attribute groupMembers = attributes.get(groupMappings.getProperty(GroupConverterKeys.USER));

        if ((groupMembers != null) && (groupMembers.size() == 1)) {
            ldapContext.unbind(fullGroupDN);
        }
    } finally {
        if (ldapContext != null) {
            ldapContext.close();
        }

        if (_log.isDebugEnabled()) {
            _log.debug(StringBundler.concat("Finished exporting user ", String.valueOf(user), " in user group ",
                    String.valueOf(userGroupId), " in ", String.valueOf(stopWatch.getTime()), "ms"));
        }
    }
}