List of usage examples for org.apache.commons.lang.time StopWatch getTime
public long getTime()
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.
From source file:net.nan21.dnet.core.web.controller.data.AbstractDsRpcController.java
/** * Default handler for remote procedure call on a single value-object. * /* ww w . j a v a2 s . c o m*/ * @param resourceName * @param dataformat * @param dataString * @param paramString * @return * @throws Exception */ @RequestMapping(params = { Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_RPC, Constants.DS_ACTION_RPC + "Type=data" }) @ResponseBody public String rpcData(@PathVariable String resourceName, @PathVariable String dataFormat, @RequestParam(value = Constants.REQUEST_PARAM_SERVICE_NAME_PARAM, required = true) String rpcName, @RequestParam(value = Constants.REQUEST_PARAM_DATA, required = false, defaultValue = "{}") String dataString, @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString, HttpServletRequest request, HttpServletResponse response) throws Exception { try { StopWatch stopWatch = new StopWatch(); stopWatch.start(); if (logger.isInfoEnabled()) { logger.info("Processing request: {}.{} -> action = {}-data / {}", new String[] { resourceName, dataFormat, Constants.DS_ACTION_RPC, rpcName }); } if (logger.isDebugEnabled()) { logger.debug(" --> request-data: {} ", new String[] { dataString }); logger.debug(" --> request-params: {} ", new String[] { paramString }); } this.prepareRequest(request, response); this.authorizeDsAction(resourceName, Constants.DS_ACTION_RPC, rpcName); if (dataFormat.equals("stream")) { IDsService<M, F, P> service = this.findDsService(resourceName); IDsMarshaller<M, F, P> marshaller = service.createMarshaller("json"); M data = marshaller.readDataFromString(dataString); P params = marshaller.readParamsFromString(paramString); InputStream s = service.rpcDataStream(rpcName, data, params); this.sendFile(s, response.getOutputStream()); return ""; } else { IDsService<M, F, P> service = this.findDsService(resourceName); IDsMarshaller<M, F, P> marshaller = service.createMarshaller(dataFormat); M data = marshaller.readDataFromString(dataString); P params = marshaller.readParamsFromString(paramString); service.rpcData(rpcName, data, params); IActionResultRpcData result = this.packRpcDataResult(data, params); stopWatch.stop(); result.setExecutionTime(stopWatch.getTime()); return marshaller.writeResultToString(result); } } catch (Exception e) { return this.handleException(e, response); } finally { this.finishRequest(); } }
From source file:com.liferay.portal.events.ServicePreActionExt.java
public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException { StopWatch stopWatch = null; if (_log.isDebugEnabled()) { stopWatch = new StopWatch(); stopWatch.start();//from ww w.j av a2 s . c o m } try { servicePre(request, response); } catch (Exception e) { throw new ActionException(e); } if (_log.isDebugEnabled()) { _log.debug("Running takes " + stopWatch.getTime() + " ms"); } }
From source file:net.nan21.dnet.core.web.controller.data.AbstractDsRpcController.java
/** * Default handler for remote procedure call on a list of value-objects. * Contributed by Jan Fockaert//from ww w. j a v a2s. co m * * @param resourceName * @param dataFormat * @param rpcName * @param dataString * @param paramString * @param request * @param response * @return * @throws Exception */ @RequestMapping(params = { Constants.REQUEST_PARAM_ACTION + "=" + Constants.DS_ACTION_RPC, Constants.DS_ACTION_RPC + "Type=dataList" }) @ResponseBody public String rpcDataList(@PathVariable String resourceName, @PathVariable String dataFormat, @RequestParam(value = Constants.REQUEST_PARAM_SERVICE_NAME_PARAM, required = true) String rpcName, @RequestParam(value = Constants.REQUEST_PARAM_DATA, required = false, defaultValue = "{}") String dataString, @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString, HttpServletRequest request, HttpServletResponse response) throws Exception { try { StopWatch stopWatch = new StopWatch(); stopWatch.start(); if (logger.isInfoEnabled()) { logger.info("Processing request: {}.{} -> action = {}-dataList / {}", new String[] { resourceName, dataFormat, Constants.DS_ACTION_RPC, rpcName }); } if (logger.isDebugEnabled()) { logger.debug(" --> request-dataList: {} ", new String[] { dataString }); logger.debug(" --> request-params: {} ", new String[] { paramString }); } this.prepareRequest(request, response); this.authorizeDsAction(resourceName, Constants.DS_ACTION_RPC, rpcName); if (dataFormat.equals("stream")) { IDsService<M, F, P> service = this.findDsService(resourceName); IDsMarshaller<M, F, P> marshaller = service.createMarshaller("json"); List<M> list = marshaller.readListFromString(dataString); P params = marshaller.readParamsFromString(paramString); InputStream s = service.rpcDataStream(rpcName, list, params); this.sendFile(s, response.getOutputStream()); return ""; } else { IDsService<M, F, P> service = this.findDsService(resourceName); IDsMarshaller<M, F, P> marshaller = service.createMarshaller(dataFormat); List<M> list = marshaller.readListFromString(dataString); P params = marshaller.readParamsFromString(paramString); service.rpcData(rpcName, list, params); IActionResultSave result = this.packRpcDataListResult(list, params); stopWatch.stop(); result.setExecutionTime(stopWatch.getTime()); return marshaller.writeResultToString(result); } } catch (Exception e) { return this.handleException(e, response); } finally { this.finishRequest(); } }
From source file:de.griffel.confluence.plugins.plantuml.PlantUmlMacro.java
protected final String executeInternal(Map<String, String> params, final String body, final RenderContext renderContext) throws MacroException, IOException, UnauthorizedDownloadResourceException, DownloadResourceNotFoundException { final StopWatch stopWatch = new StopWatch(); stopWatch.start();//from w w w . j av a 2s.c om final PlantUmlMacroParams macroParams = new PlantUmlMacroParams(params); if (!(renderContext instanceof PageContext)) { throw new MacroException("This macro can only be used in Confluence pages. (ctx=" + renderContext.getClass().getName() + ")"); } final PageContext pageContext = (PageContext) renderContext; final UmlSourceLocator umlSourceLocator = new UmlSourceLocatorConfluence(pageContext); final PreprocessingContext preprocessingContext = new MyPreprocessingContext(pageContext); final DiagramType diagramType = macroParams.getDiagramType(); final boolean dropShadow = macroParams.getDropShadow(); final boolean separation = macroParams.getSeparation(); final PlantUmlConfiguration configuration = configurationManager.load(); final UmlSourceBuilder builder = new UmlSourceBuilder(diagramType, dropShadow, separation, configuration) .append(new StringReader(body)); final PlantUmlPreprocessor preprocessor = new PlantUmlPreprocessor(builder.build(), umlSourceLocator, preprocessingContext); final String umlBlock = preprocessor.toUmlBlock(); final String result = render(umlBlock, pageContext, macroParams, preprocessor); stopWatch.stop(); logger.info(String.format("Rendering %s diagram on page %s:%s took %d ms.", diagramType, pageContext.getSpaceKey(), pageContext.getPageTitle(), stopWatch.getTime())); return result; }
From source file:com.liferay.portal.search.elasticsearch.ElasticsearchIndexSearcher.java
@Override public Hits search(SearchContext searchContext, Query query) { StopWatch stopWatch = new StopWatch(); stopWatch.start();//w ww . j a va2 s . c o m ElasticsearchConnectionManager elasticsearchConnectionManager = ElasticsearchConnectionManager .getInstance(); Client client = elasticsearchConnectionManager.getClient(); SearchRequestBuilder searchRequestBuilder = client .prepareSearch(String.valueOf(searchContext.getCompanyId())); addFacets(searchRequestBuilder, searchContext); addHighlights(searchRequestBuilder, query.getQueryConfig()); addPagination(searchRequestBuilder, searchContext.getStart(), searchContext.getEnd()); addSelectedFields(searchRequestBuilder, query.getQueryConfig()); addSort(searchRequestBuilder, searchContext.getSorts()); QueryBuilder queryBuilder = QueryBuilders.queryString(query.toString()); searchRequestBuilder.setQuery(queryBuilder); searchRequestBuilder.setTypes(DocumentTypes.LIFERAY); SearchRequest searchRequest = searchRequestBuilder.request(); ActionFuture<SearchResponse> future = client.search(searchRequest); SearchResponse searchResponse = future.actionGet(); updateFacetCollectors(searchContext, searchResponse); Hits hits = processSearchHits(searchResponse.getHits(), query.getQueryConfig()); hits.setQuery(query); TimeValue timeValue = searchResponse.getTook(); hits.setSearchTime((float) timeValue.getSecondsFrac()); hits.setStart(stopWatch.getStartTime()); if (_log.isInfoEnabled()) { stopWatch.stop(); _log.info("Searching " + queryBuilder.toString() + " took " + stopWatch.getTime() + " ms with the search engine using " + hits.getSearchTime() + " s"); } return hits; }
From source file:com.liferay.portal.util.InitUtil.java
public static synchronized void init() { if (_initialized) { return;// w ww. ja v a 2s . co m } StopWatch stopWatch = null; if (_PRINT_TIME) { stopWatch = new StopWatch(); stopWatch.start(); } // Set the default locale used by Liferay. This locale is no longer set // at the VM level. See LEP-2584. String userLanguage = SystemProperties.get("user.language"); String userCountry = SystemProperties.get("user.country"); String userVariant = SystemProperties.get("user.variant"); LocaleUtil.setDefault(userLanguage, userCountry, userVariant); // Set the default time zone used by Liferay. This time zone is no // longer set at the VM level. See LEP-2584. String userTimeZone = SystemProperties.get("user.timezone"); TimeZoneUtil.setDefault(userTimeZone); // Shared class loader try { Thread currentThread = Thread.currentThread(); PortalClassLoaderUtil.setClassLoader(currentThread.getContextClassLoader()); } catch (Exception e) { e.printStackTrace(); } // Log4J if (GetterUtil.getBoolean(SystemProperties.get("log4j.configure.on.startup"), true)) { ClassLoader classLoader = InitUtil.class.getClassLoader(); Log4JUtil.configureLog4J(classLoader.getResource("META-INF/portal-log4j.xml")); try { Log _log = LogFactoryUtil.getLog(InitUtil.class); String configName = "META-INF/portal-log4j-ext.xml"; Enumeration<URL> configs = classLoader.getResources(configName); if (_log.isDebugEnabled() && !configs.hasMoreElements()) { _log.debug("No " + configName + " has been found"); } while (configs.hasMoreElements()) { URL config = configs.nextElement(); Log4JUtil.configureLog4J(config); } } catch (Exception e) { e.printStackTrace(); } } // Shared log try { LogFactoryUtil.setLogFactory(new Log4jLogFactoryImpl()); } catch (Exception e) { e.printStackTrace(); } // Cache registry CacheRegistryUtil.setCacheRegistry(new CacheRegistryImpl()); // Configuration factory ConfigurationFactoryUtil.setConfigurationFactory(new ConfigurationFactoryImpl()); // Data source factory DataSourceFactoryUtil.setDataSourceFactory(new DataSourceFactoryImpl()); // DB factory DBFactoryUtil.setDBFactory(new DBFactoryImpl()); // Java properties JavaProps.isJDK5(); // ROME XmlReader.setDefaultEncoding(StringPool.UTF8); if (_PRINT_TIME) { System.out.println("InitAction takes " + stopWatch.getTime() + " ms"); } _initialized = true; }
From source file:eagle.service.generic.GenericEntityServiceResource.java
/** * * Delete by entity lists//from w ww . j a v a 2 s .com * * Use "POST /entities/delete" instead of "DELETE /entities" to walk around jersey DELETE issue for request with body * * @param inputStream * @param serviceName * @return */ @POST @Path(DELETE_ENTITIES_PATH) @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public GenericServiceAPIResponseEntity deleteEntities(InputStream inputStream, @QueryParam("serviceName") String serviceName, @QueryParam("byId") Boolean deleteById) { GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<String>(); DataStorage dataStorage = null; Map<String, Object> meta = new HashMap<String, Object>(); if (deleteById == null) deleteById = false; StopWatch stopWatch = new StopWatch(); try { stopWatch.start(); dataStorage = DataStorageManager.getDataStorageByEagleConfig(); DeleteStatement statement = new DeleteStatement(serviceName); if (deleteById) { LOG.info("Deleting " + serviceName + " by ids"); List<String> deleteIds = unmarshalAsStringlist(inputStream); statement.setIds(deleteIds); } else { LOG.info("Deleting " + serviceName + " by entities"); EntityDefinition entityDefinition = EntityDefinitionManager.getEntityByServiceName(serviceName); if (entityDefinition == null) { throw new IllegalArgumentException( "Entity definition of service " + serviceName + " not found"); } List<? extends TaggedLogAPIEntity> entities = unmarshalEntitiesByServie(inputStream, entityDefinition); statement.setEntities(entities); } ModifyResult<String> result = statement.execute(dataStorage); if (result.isSuccess()) { List<String> keys = result.getIdentifiers(); if (keys != null) { response.setObj(keys, String.class); meta.put(TOTAL_RESULTS, keys.size()); } else { meta.put(TOTAL_RESULTS, 0); } meta.put(ELAPSEDMS, stopWatch.getTime()); response.setMeta(meta); response.setSuccess(true); } } catch (Exception e) { LOG.error(e.getMessage(), e); response.setException(e); } finally { stopWatch.stop(); } return response; }
From source file:com.liferay.portal.events.ServicePreAction.java
@Override public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException { StopWatch stopWatch = null; if (_log.isDebugEnabled()) { stopWatch = new StopWatch(); stopWatch.start();// w ww . j a v a 2 s.c om } try { servicePre(request, response); } catch (Exception e) { throw new ActionException(e); } if (_log.isDebugEnabled()) { _log.debug("Running takes " + stopWatch.getTime() + " ms"); } }
From source file:eagle.storage.jdbc.entity.impl.JdbcEntityWriterImpl.java
@Override public List<String> write(List<E> entities) throws Exception { List<String> keys = new ArrayList<String>(); if (LOG.isDebugEnabled()) LOG.debug("Writing " + entities.size() + " entities"); StopWatch stopWatch = new StopWatch(); stopWatch.start();//from w ww . java 2s.co m Connection connection = ConnectionManagerFactory.getInstance().getConnection(); // set auto commit false and commit by hands for 3x~5x better performance connection.setAutoCommit(false); try { TorqueStatementPeerImpl<E> peer = connectionManager .getStatementExecutor(this.jdbcEntityDefinition.getJdbcTableName()); for (E entity : entities) { entity.setEncodedRowkey(peer.getPrimaryKeyBuilder().build(entity)); ColumnValues columnValues = JdbcEntitySerDeserHelper.buildColumnValues(entity, this.jdbcEntityDefinition); // TODO: implement batch insert for better performance ObjectKey key = peer.delegate().doInsert(columnValues, connection); try { if (key != null) { keys.add((String) key.getValue()); } else { keys.add(entity.getEncodedRowkey()); } } catch (ClassCastException ex) { throw new RuntimeException( "Key is not in type of String (VARCHAR) , but JdbcType (java.sql.Types): " + key.getJdbcType() + ", value: " + key.getValue(), ex); } } // Why not commit in finally: give up all if any single entity throws exception to make sure consistency guarantee if (LOG.isDebugEnabled()) { LOG.debug("Committing writing"); } connection.commit(); } catch (Exception ex) { LOG.error("Failed to write records, rolling back", ex); connection.rollback(); throw ex; } finally { stopWatch.stop(); if (LOG.isDebugEnabled()) LOG.debug("Closing connection"); connection.close(); } LOG.info(String.format("Wrote %s records in %s ms (table: %s)", keys.size(), stopWatch.getTime(), this.jdbcEntityDefinition.getJdbcTableName())); return keys; }
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 . ja va2 s . co 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; }