List of usage examples for org.apache.commons.lang.time StopWatch StopWatch
public StopWatch()
Constructor.
From source file:com.cedarsoft.serialization.test.performance.XmlParserPerformance.java
private void runBenchmark(@Nonnull Runnable runnable, final int count) { //Warmup/*from w w w . j ava2 s. c o m*/ runnable.run(); runnable.run(); runnable.run(); List<Long> times = new ArrayList<Long>(); for (int i = 0; i < count; i++) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); runnable.run(); stopWatch.stop(); times.add(stopWatch.getTime()); } System.out.println("-----------------------"); for (Long time : times) { System.out.println("--> " + time + " ms"); } System.out.println("-----------------------"); }
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 ww w. ja va2s . 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; }
From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java
protected void importUsers(LDAPImportContext ldapImportContext, long userGroupId, Attribute usersLdapAttribute) throws Exception { StopWatch stopWatch = new StopWatch(); if (_log.isDebugEnabled()) { stopWatch.start();/* w w w. j a va 2 s .c o m*/ int size = usersLdapAttribute.size(); _log.debug(StringBundler.concat("Importing ", String.valueOf(size), " users from LDAP server ", String.valueOf(ldapImportContext.getLdapServerId()), " to company ", String.valueOf(ldapImportContext.getCompanyId()))); } Set<Long> newUserIds = new LinkedHashSet<>(usersLdapAttribute.size()); for (int i = 0; i < usersLdapAttribute.size(); i++) { String fullUserDN = (String) usersLdapAttribute.get(i); Long userId = ldapImportContext.getImportedUserId(fullUserDN); if (userId != null) { newUserIds.add(userId); } else { Attributes userAttributes = null; try { userAttributes = _portalLDAP.getUserAttributes(ldapImportContext.getLdapServerId(), ldapImportContext.getCompanyId(), ldapImportContext.getLdapContext(), fullUserDN); } catch (NameNotFoundException nnfe) { _log.error("LDAP user not found with fullUserDN " + fullUserDN, nnfe); continue; } try { User user = importUser(ldapImportContext, fullUserDN, userAttributes, null); if (user != null) { if (_log.isDebugEnabled()) { _log.debug(StringBundler.concat("Adding user ", String.valueOf(user), " to user group ", String.valueOf(userGroupId))); } newUserIds.add(user.getUserId()); } } catch (GroupFriendlyURLException gfurle) { int type = gfurle.getType(); if (type == GroupFriendlyURLException.DUPLICATE) { _log.error("Unable to import user " + userAttributes + " because of a duplicate group friendly URL", gfurle); } else { _log.error("Unable to import user " + userAttributes, gfurle); } } catch (Exception e) { _log.error("Unable to load user " + userAttributes, e); } } } Set<Long> deletedUserIds = new LinkedHashSet<>(); List<User> userGroupUsers = _userLocalService.getUserGroupUsers(userGroupId); for (User user : userGroupUsers) { if ((ldapImportContext.getLdapServerId() == user.getLdapServerId()) && !newUserIds.contains(user.getUserId())) { if (_log.isDebugEnabled()) { _log.debug(StringBundler.concat("Removing user ", String.valueOf(user), " from user group ", String.valueOf(userGroupId))); } deletedUserIds.add(user.getUserId()); } } _userLocalService.addUserGroupUsers(userGroupId, ArrayUtil.toLongArray(newUserIds)); _userLocalService.deleteUserGroupUsers(userGroupId, ArrayUtil.toLongArray(deletedUserIds)); }
From source file:com.liferay.portal.events.ServicePreAction.java
@Override public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException { StopWatch stopWatch = null;/* w w w. j ava 2s . c o m*/ if (_log.isDebugEnabled()) { stopWatch = new StopWatch(); stopWatch.start(); } try { servicePre(request, response); } catch (Exception e) { throw new ActionException(e); } if (_log.isDebugEnabled()) { _log.debug("Running takes " + stopWatch.getTime() + " ms"); } }
From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java
protected User updateUser(LDAPImportContext ldapImportContext, LDAPUser ldapUser, User user, String password, String modifyTimestamp, boolean isNew) throws Exception { StopWatch stopWatch = new StopWatch(); long companyId = ldapImportContext.getCompanyId(); long ldapServerId = ldapImportContext.getLdapServerId(); if (_log.isDebugEnabled()) { stopWatch.start();//from w w w . j a v a2s . c om if (isNew) { _log.debug(StringBundler.concat("Updating new user ", String.valueOf(user), " from LDAP server ", String.valueOf(ldapServerId), " to company ", String.valueOf(companyId))); } else { _log.debug( StringBundler.concat("Updating existing user ", String.valueOf(user), " from LDAP server ", String.valueOf(ldapServerId), " to company ", String.valueOf(companyId))); } } Date modifiedDate = null; LDAPImportConfiguration ldapImportConfiguration = _ldapImportConfigurationProvider .getConfiguration(companyId); boolean passwordReset = ldapUser.isPasswordReset(); if (_ldapSettings.isExportEnabled(companyId)) { passwordReset = user.isPasswordReset(); } try { if (Validator.isNotNull(modifyTimestamp)) { modifiedDate = LDAPUtil.parseDate(modifyTimestamp); if (modifiedDate.equals(user.getModifiedDate())) { if (ldapUser.isUpdatePassword() || !ldapImportConfiguration.importUserPasswordEnabled()) { updateUserPassword(ldapImportConfiguration, user.getUserId(), user.getScreenName(), password, passwordReset); } if (_log.isDebugEnabled()) { _log.debug(StringBundler.concat("User ", user.getEmailAddress(), " is already synchronized, but updated ", "password to avoid a blank value")); } return user; } } else if (!isNew) { if (_log.isInfoEnabled()) { _log.info("Skipping user " + user.getEmailAddress() + " because the LDAP entry was never modified"); } return user; } } catch (ParseException pe) { if (_log.isDebugEnabled()) { _log.debug("Unable to parse LDAP modify timestamp " + modifyTimestamp, pe); } } LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider .getConfiguration(companyId, ldapServerId); String[] userIgnoreAttributes = ldapServerConfiguration.userIgnoreAttributes(); Set<String> ldapUserIgnoreAttributes = new HashSet<>(Arrays.asList(userIgnoreAttributes)); if (Validator.isNull(ldapUser.getScreenName()) || ldapUser.isAutoScreenName()) { ldapUser.setScreenName(user.getScreenName()); } if (ldapUser.isUpdatePassword() || !ldapImportConfiguration.importUserPasswordEnabled()) { password = updateUserPassword(ldapImportConfiguration, user.getUserId(), ldapUser.getScreenName(), password, passwordReset); } Contact ldapContact = ldapUser.getContact(); updateLDAPUser(ldapUser.getUser(), ldapContact, user, ldapImportContext.getUserMappings(), ldapImportContext.getContactMappings(), ldapUserIgnoreAttributes); Calendar birthdayCal = CalendarFactoryUtil.getCalendar(); birthdayCal.setTime(ldapContact.getBirthday()); int birthdayMonth = birthdayCal.get(Calendar.MONTH); int birthdayDay = birthdayCal.get(Calendar.DAY_OF_MONTH); int birthdayYear = birthdayCal.get(Calendar.YEAR); user = _userLocalService.updateUser(user.getUserId(), password, StringPool.BLANK, StringPool.BLANK, passwordReset, ldapUser.getReminderQueryQuestion(), ldapUser.getReminderQueryAnswer(), ldapUser.getScreenName(), ldapUser.getEmailAddress(), ldapUser.getFacebookId(), ldapUser.getOpenId(), ldapUser.isUpdatePortrait(), ldapUser.getPortraitBytes(), ldapUser.getLanguageId(), ldapUser.getTimeZoneId(), ldapUser.getGreeting(), ldapUser.getComments(), ldapUser.getFirstName(), ldapUser.getMiddleName(), ldapUser.getLastName(), ldapUser.getPrefixId(), ldapUser.getSuffixId(), ldapUser.isMale(), birthdayMonth, birthdayDay, birthdayYear, ldapUser.getSmsSn(), ldapUser.getFacebookSn(), ldapUser.getJabberSn(), ldapUser.getSkypeSn(), ldapUser.getTwitterSn(), ldapUser.getJobTitle(), ldapUser.getGroupIds(), ldapUser.getOrganizationIds(), ldapUser.getRoleIds(), ldapUser.getUserGroupRoles(), ldapUser.getUserGroupIds(), ldapUser.getServiceContext()); ServiceContext serviceContext = new ServiceContext(); if (modifiedDate != null) { serviceContext.setModifiedDate(modifiedDate); } user = _userLocalService.updateStatus(user.getUserId(), ldapUser.getStatus(), serviceContext); if (_log.isDebugEnabled()) { _log.debug(StringBundler.concat("Finished update for user ", String.valueOf(user), " in ", String.valueOf(stopWatch.getTime()), "ms")); } return user; }
From source file:com.ecyrd.jspwiki.WikiEngine.java
/** * Converts raw page data to HTML./*from w w w . ja va 2s . c o m*/ * * @param pagedata Raw page data to convert to HTML * @param context The WikiContext in which the page is to be rendered * @return Rendered page text */ public String textToHTML(WikiContext context, String pagedata) { String result = ""; boolean runFilters = "true".equals(m_variableManager.getValue(context, PROP_RUNFILTERS, "true")); StopWatch sw = new StopWatch(); sw.start(); try { if (runFilters) pagedata = m_filterManager.doPreTranslateFiltering(context, pagedata); result = m_renderingManager.getHTML(context, pagedata); if (runFilters) result = m_filterManager.doPostTranslateFiltering(context, result); } catch (FilterException e) { // FIXME: Don't yet know what to do } sw.stop(); if (log.isDebugEnabled()) log.debug("Page " + context.getRealPage().getName() + " rendered, took " + sw); return result; }
From source file:com.ecyrd.jspwiki.WikiEngine.java
/** * Helper method for doing the HTML translation. * * @param context The WikiContext in which to do the conversion * @param pagedata The data to render//from www. j a v a 2 s . c o m * @param localLinkHook Is called whenever a wiki link is found * @param extLinkHook Is called whenever an external link is found * @param parseAccessRules Parse the access rules if we encounter them * @param justParse Just parses the pagedata, does not actually render. In this case, * this methods an empty string. * @return HTML-rendered page text. */ private String textToHTML(WikiContext context, String pagedata, StringTransmutator localLinkHook, StringTransmutator extLinkHook, StringTransmutator attLinkHook, boolean parseAccessRules, boolean justParse) { String result = ""; if (pagedata == null) { log.error("NULL pagedata to textToHTML()"); return null; } boolean runFilters = "true".equals(m_variableManager.getValue(context, PROP_RUNFILTERS, "true")); try { StopWatch sw = new StopWatch(); sw.start(); if (runFilters && m_filterManager != null) pagedata = m_filterManager.doPreTranslateFiltering(context, pagedata); MarkupParser mp = m_renderingManager.getParser(context, pagedata); mp.addLocalLinkHook(localLinkHook); mp.addExternalLinkHook(extLinkHook); mp.addAttachmentLinkHook(attLinkHook); if (!parseAccessRules) mp.disableAccessRules(); WikiDocument doc = mp.parse(); // // In some cases it's better just to parse, not to render // if (!justParse) { result = m_renderingManager.getHTML(context, doc); if (runFilters && m_filterManager != null) result = m_filterManager.doPostTranslateFiltering(context, result); } sw.stop(); if (log.isDebugEnabled()) log.debug("Page " + context.getRealPage().getName() + " rendered, took " + sw); } catch (IOException e) { log.error("Failed to scan page data: ", e); } catch (FilterException e) { // FIXME: Don't yet know what to do } return result; }
From source file:com.redhat.rhn.frontend.xmlrpc.channel.software.ChannelSoftwareHandler.java
/** * Private helper method to create a new UpdateErrataCacheEvent and publish it to the * MessageQueue./*from w w w .j a v a2 s .c om*/ * @param orgIn The org we're updating. */ 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() + "]"); } }
From source file:net.sourceforge.squirrel_sql.plugins.sqlscript.table_script.CreateFileOfCurrentSQLCommand.java
/** * Do the work.//from w w w . j a v a2 s . co m * @param owner */ private void doCreateFileOfCurrentSQL(JFrame owner) { try { ISQLConnection unmanagedConnection = null; try { unmanagedConnection = createUnmanagedConnection(); // TODO maybe, we should use a SQLExecutorTask for taking advantage of some ExecutionListeners like the parameter replacement. But how to get the right Listeners? if (unmanagedConnection != null) { stmt = createStatementForStreamingResults(unmanagedConnection.getConnection()); } else { stmt = createStatementForStreamingResults(getSession().getSQLConnection().getConnection()); } ProgressAbortFactoryCallback progressFactory = new ProgressAbortFactoryCallback() { @Override public ProgressAbortCallback create() { createProgressAbortDialog(); return progressDialog; } }; StopWatch stopWatch = new StopWatch(); stopWatch.start(); DialectType dialectType = DialectFactory.getDialectType(getSession().getMetaData()); resultSetExportCommand = new ResultSetExportCommand(stmt, currentSQL, dialectType, progressFactory); resultSetExportCommand.execute(owner); stopWatch.stop(); if (isAborted()) { return; } else if (resultSetExportCommand.getWrittenRows() >= 0) { NumberFormat nf = NumberFormat.getIntegerInstance(); String rows = nf.format(resultSetExportCommand.getWrittenRows()); File targetFile = resultSetExportCommand.getTargetFile(); String seconds = nf.format(stopWatch.getTime() / 1000); String msg = s_stringMgr.getString("CreateFileOfCurrentSQLCommand.progress.sucessMessage", rows, targetFile, seconds); getSession().showMessage(msg); } } finally { SQLUtilities.closeStatement(stmt); if (unmanagedConnection != null) { unmanagedConnection.close(); } } } catch (Exception e) { if (e.getCause() != null) { getSession().showErrorMessage(e.getCause()); } getSession().showErrorMessage(e.getMessage()); } finally { SwingUtilities.invokeLater(new Runnable() { public void run() { hideProgressMonitor(); } }); } }
From source file:net.ymate.module.webproxy.WebProxy.java
@SuppressWarnings("unchecked") public void transmission(HttpServletRequest request, HttpServletResponse response, String url, Type.HttpMethod method) throws Exception { StopWatch _consumeTime = null;/*from ww w . j av a2 s .co m*/ long _threadId = 0; if (_LOG.isDebugEnabled()) { _consumeTime = new StopWatch(); _consumeTime.start(); _threadId = Thread.currentThread().getId(); _LOG.debug("-------------------------------------------------"); _LOG.debug("--> [" + _threadId + "] URL: " + url); } // HttpURLConnection _conn = null; try { if (__moduleCfg.isUseProxy()) { _conn = (HttpURLConnection) new URL(url).openConnection(__moduleCfg.getProxy()); } else { _conn = (HttpURLConnection) new URL(url).openConnection(); } _conn.setUseCaches(__moduleCfg.isUseCaches()); _conn.setInstanceFollowRedirects(__moduleCfg.isInstanceFollowRedirects()); // boolean _postFlag = Type.HttpMethod.POST.equals(method); boolean _multipartFlag = _postFlag && StringUtils.contains(request.getContentType(), "multipart/"); if (_postFlag) { _conn.setDoOutput(true); _conn.setDoInput(true); _conn.setRequestMethod(method.name()); } if (__moduleCfg.getConnectTimeout() > 0) { _conn.setConnectTimeout(__moduleCfg.getConnectTimeout()); } if (__moduleCfg.getReadTimeout() > 0) { _conn.setReadTimeout(__moduleCfg.getReadTimeout()); } // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Method: " + method.name()); _LOG.debug("--> [" + _threadId + "] Request Headers: "); } // Enumeration _header = request.getHeaderNames(); while (_header.hasMoreElements()) { String _name = (String) _header.nextElement(); String _value = request.getHeader(_name); boolean _flag = false; if (_postFlag && StringUtils.equalsIgnoreCase(_name, "content-type") || __moduleCfg.isTransferHeaderEnabled() && (!__moduleCfg.getTransferHeaderBlackList().isEmpty() && !__moduleCfg.getTransferHeaderBlackList().contains(_name) || !__moduleCfg.getTransferHeaderWhiteList().isEmpty() && __moduleCfg.getTransferHeaderWhiteList().contains(_name))) { _conn.setRequestProperty(_name, _value); _flag = true; } // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _name + ": " + _value); } } _conn.connect(); // if (_postFlag) { DataOutputStream _output = new DataOutputStream(_conn.getOutputStream()); try { if (_multipartFlag) { if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Multipart: TRUE"); } IOUtils.copyLarge(request.getInputStream(), _output); } else { String _charset = request.getCharacterEncoding(); String _queryStr = ParamUtils.buildQueryParamStr(request.getParameterMap(), true, _charset); IOUtils.write(_queryStr, _output, _charset); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Request Parameters: "); Map<String, String> _paramsMap = ParamUtils.parseQueryParamStr(_queryStr, true, _charset); for (Map.Entry<String, String> _param : _paramsMap.entrySet()) { _LOG.debug("--> [" + _threadId + "] \t - " + _param.getKey() + ": " + _param.getValue()); } } } _output.flush(); } finally { IOUtils.closeQuietly(_output); } } // int _code = _conn.getResponseCode(); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Code: " + _code); _LOG.debug("--> [" + _threadId + "] Response Headers: "); } // Map<String, List<String>> _headers = _conn.getHeaderFields(); for (Map.Entry<String, List<String>> _entry : _headers.entrySet()) { if (_entry.getKey() != null) { boolean _flag = false; String _values = StringUtils.join(_entry.getValue(), ","); if (StringUtils.equalsIgnoreCase(_entry.getKey(), "content-type") || __moduleCfg.isTransferHeaderEnabled() && !__moduleCfg.getResponseHeaderWhileList().isEmpty() && __moduleCfg.getResponseHeaderWhileList().contains(_entry.getKey())) { response.setHeader(_entry.getKey(), _values); _flag = true; } if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] \t " + (_flag ? " - " : " > ") + _entry.getKey() + ": " + _values); } } } if (HttpURLConnection.HTTP_BAD_REQUEST <= _conn.getResponseCode()) { response.sendError(_code); } else { if (HttpURLConnection.HTTP_OK == _code) { InputStream _inputStream = _conn.getInputStream(); if (_inputStream != null) { if (!_multipartFlag) { byte[] _content = IOUtils.toByteArray(_inputStream); IOUtils.write(_content, response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody( _conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding())); } } else { IOUtils.copyLarge(_conn.getInputStream(), response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: MultipartBody"); } } } else if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: NULL"); } response.flushBuffer(); } else { InputStream _inputStream = _conn.getInputStream(); if (_inputStream != null) { byte[] _content = IOUtils.toByteArray(_inputStream); IOUtils.write(_content, response.getOutputStream()); // if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: " + __doParseContentBody(_conn, _content, WebMVC.get().getModuleCfg().getDefaultCharsetEncoding())); } } else if (_LOG.isDebugEnabled()) { _LOG.debug("--> [" + _threadId + "] Response Content: NULL"); } response.setStatus(_code); response.flushBuffer(); } } } catch (Throwable e) { _LOG.warn("An exception occurred while processing request mapping '" + url + "': ", RuntimeUtils.unwrapThrow(e)); } finally { IOUtils.close(_conn); // if (_LOG.isDebugEnabled()) { if (_consumeTime != null) { _consumeTime.stop(); _LOG.debug("--> [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms"); } _LOG.debug("-------------------------------------------------"); } } }