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:eagle.service.generic.ListQueryResource.java
/** * <b>TODO</b> remove the legacy deprecated implementation of listQueryWithoutCoprocessor * * @see #listQuery(String, String, String, int, String, boolean, boolean, long, int, boolean, int, String,Boolean) * * @param query/*from w ww.j a v a2 s . co m*/ * @param startTime * @param endTime * @param pageSize * @param startRowkey * @param treeAgg * @param timeSeries * @param intervalmin * @return */ @GET @Path("/legacy") @Produces({ MediaType.APPLICATION_JSON }) @Deprecated public ListQueryAPIResponseEntity listQueryWithoutCoprocessor(@QueryParam("query") String query, @QueryParam("startTime") String startTime, @QueryParam("endTime") String endTime, @QueryParam("pageSize") int pageSize, @QueryParam("startRowkey") String startRowkey, @QueryParam("treeAgg") boolean treeAgg, @QueryParam("timeSeries") boolean timeSeries, @QueryParam("intervalmin") long intervalmin, @QueryParam("top") int top, @QueryParam("filterIfMissing") boolean filterIfMissing, @QueryParam("parallel") int parallel, @QueryParam("metricName") String metricName, @QueryParam("verbose") Boolean verbose) { StopWatch watch = new StopWatch(); watch.start(); ListQueryAPIResponseEntity result = new ListQueryAPIResponseEntity(); try { validateQueryParameters(startRowkey, pageSize); ListQueryCompiler comp = new ListQueryCompiler(query, filterIfMissing); String serviceName = comp.serviceName(); SearchCondition condition = new SearchCondition(); condition.setFilter(comp.filter()); condition.setQueryExpression(comp.getQueryExpression()); if (comp.sortOptions() == null && top > 0) { LOG.warn( "Parameter \"top\" is only used for sort query! Ignore top parameter this time since it's not a sort query"); } // TODO: For now we don't support one query to query multiple partitions. In future // if partition is defined for the entity, internally We need to spawn multiple // queries and send one query for each search condition for each partition final List<String[]> partitionValues = comp.getQueryPartitionValues(); if (partitionValues != null) { condition.setPartitionValues(Arrays.asList(partitionValues.get(0))); } EntityDefinition ed = EntityDefinitionManager.getEntityByServiceName(serviceName); if (ed.isTimeSeries()) { // TODO check timestamp exists for timeseries or topology data condition.setStartTime(startTime); condition.setEndTime(endTime); } condition.setOutputVerbose(verbose == null || verbose); condition.setOutputAlias(comp.getOutputAlias()); condition.setOutputAll(comp.isOutputAll()); condition.setStartRowkey(startRowkey); condition.setPageSize(pageSize); List<String> outputFields = comp.outputFields(); if (outputFields == null) outputFields = new ArrayList<String>(); /** * TODO ugly logic, waiting for refactoring */ if (!comp.hasAgg() && !serviceName.equals(GenericMetricEntity.GENERIC_METRIC_SERVICE)) { // pure list query // List<String> outputFields = comp.outputFields(); Set<String> filterFields = comp.getFilterFields(); if (filterFields != null) outputFields.addAll(filterFields); condition.setOutputFields(outputFields); if (condition.isOutputAll()) { LOG.info("Output: ALL"); } else { LOG.info("Output: " + StringUtils.join(condition.getOutputFields(), ", ")); } GenericEntityBatchReader reader = new GenericEntityBatchReader(serviceName, condition); List<? extends TaggedLogAPIEntity> entityList = reader.read(); result.setObj(entityList); result.setTotalResults(entityList.size()); result.setSuccess(true); result.setLastTimestamp(reader.getLastTimestamp()); result.setFirstTimestamp(reader.getFirstTimestamp()); } else if (!comp.hasAgg() && serviceName.equals(GenericMetricEntity.GENERIC_METRIC_SERVICE)) { // validate metric name if (metricName == null || metricName.isEmpty()) { throw new IllegalArgumentException("metricName should not be empty for metric list query"); } // List<String> outputFields = comp.outputFields(); Set<String> filterFields = comp.getFilterFields(); if (filterFields != null) outputFields.addAll(filterFields); condition.setOutputFields(outputFields); if (condition.isOutputAll()) { LOG.info("Output: ALL"); } else { LOG.info("Output: " + StringUtils.join(condition.getOutputFields(), ", ")); } GenericMetricEntityBatchReader reader = new GenericMetricEntityBatchReader(metricName, condition); List<? extends TaggedLogAPIEntity> entityList = reader.read(); result.setObj(entityList); result.setTotalResults(entityList.size()); result.setSuccess(true); result.setLastTimestamp(reader.getLastTimestamp()); result.setFirstTimestamp(reader.getFirstTimestamp()); } else if (!treeAgg && !timeSeries && parallel <= 0) { // non time-series based aggregate query, not hierarchical List<String> groupbyFields = comp.groupbyFields(); List<String> aggregateFields = comp.aggregateFields(); Set<String> filterFields = comp.getFilterFields(); // List<String> outputFields = new ArrayList<String>(); if (groupbyFields != null) outputFields.addAll(groupbyFields); if (filterFields != null) outputFields.addAll(filterFields); outputFields.addAll(aggregateFields); if (GenericMetricEntity.GENERIC_METRIC_SERVICE.equals(serviceName) && !outputFields.contains(GenericMetricEntity.VALUE_FIELD)) { outputFields.add(GenericMetricEntity.VALUE_FIELD); } FlatAggregator agg = new FlatAggregator(groupbyFields, comp.aggregateFunctionTypes(), comp.aggregateFields()); StreamReader reader = null; if (ed.getMetricDefinition() == null) { reader = new GenericEntityStreamReader(serviceName, condition); } else { // metric aggregation need metric reader reader = new GenericMetricEntityDecompactionStreamReader(metricName, condition); } condition.setOutputFields(outputFields); if (condition.isOutputAll()) { LOG.info("Output: ALL"); } else { LOG.info("Output: " + StringUtils.join(condition.getOutputFields(), ", ")); } reader.register(agg); reader.readAsStream(); ArrayList<Map.Entry<List<String>, List<Double>>> obj = new ArrayList<Map.Entry<List<String>, List<Double>>>(); obj.addAll(agg.result().entrySet()); if (comp.sortOptions() == null) { result.setObj(obj); } else { // has sort options result.setObj(PostFlatAggregateSort.sort(agg.result(), comp.sortOptions(), top)); } result.setTotalResults(0); result.setSuccess(true); result.setLastTimestamp(reader.getLastTimestamp()); result.setFirstTimestamp(reader.getFirstTimestamp()); } else if (!treeAgg && !timeSeries && parallel > 0) { // TODO ugly branch, let us refactor List<String> groupbyFields = comp.groupbyFields(); List<String> aggregateFields = comp.aggregateFields(); Set<String> filterFields = comp.getFilterFields(); // List<String> outputFields = new ArrayList<String>(); if (groupbyFields != null) outputFields.addAll(groupbyFields); if (filterFields != null) outputFields.addAll(filterFields); outputFields.addAll(aggregateFields); if (GenericMetricEntity.GENERIC_METRIC_SERVICE.equals(serviceName) && !outputFields.contains(GenericMetricEntity.VALUE_FIELD)) { outputFields.add(GenericMetricEntity.VALUE_FIELD); } condition.setOutputFields(outputFields); if (condition.isOutputAll()) { LOG.info("Output: ALL"); } else { LOG.info("Output: " + StringUtils.join(condition.getOutputFields(), ", ")); } FlatAggregator agg = new FlatAggregator(groupbyFields, comp.aggregateFunctionTypes(), comp.aggregateFields()); EntityCreationListener listener = EntityCreationListenerFactory .synchronizedEntityCreationListener(agg); StreamReader reader = new GenericEntityStreamReaderMT(serviceName, condition, parallel); reader.register(listener); reader.readAsStream(); ArrayList<Map.Entry<List<String>, List<Double>>> obj = new ArrayList<Map.Entry<List<String>, List<Double>>>(); obj.addAll(agg.result().entrySet()); if (comp.sortOptions() == null) { result.setObj(obj); } else { // has sort options result.setObj(PostFlatAggregateSort.sort(agg.result(), comp.sortOptions(), top)); } result.setTotalResults(0); result.setSuccess(true); result.setLastTimestamp(reader.getLastTimestamp()); result.setFirstTimestamp(reader.getFirstTimestamp()); } else if (!treeAgg && timeSeries) { // time-series based aggregate query, not hierarchical List<String> groupbyFields = comp.groupbyFields(); List<String> sortFields = comp.sortFields(); List<String> aggregateFields = comp.aggregateFields(); Set<String> filterFields = comp.getFilterFields(); // List<String> outputFields = new ArrayList<String>(); if (groupbyFields != null) outputFields.addAll(groupbyFields); if (filterFields != null) outputFields.addAll(filterFields); if (sortFields != null) outputFields.addAll(sortFields); outputFields.addAll(aggregateFields); if (GenericMetricEntity.GENERIC_METRIC_SERVICE.equals(serviceName) && !outputFields.contains(GenericMetricEntity.VALUE_FIELD)) { outputFields.add(GenericMetricEntity.VALUE_FIELD); } StreamReader reader = null; if (ed.getMetricDefinition() == null) { if (parallel <= 0) { // TODO ugly quick win reader = new GenericEntityStreamReader(serviceName, condition); } else { reader = new GenericEntityStreamReaderMT(serviceName, condition, parallel); } } else { // metric aggregation need metric reader reader = new GenericMetricEntityDecompactionStreamReader(metricName, condition); if (!outputFields.contains(GenericMetricEntity.VALUE_FIELD)) { outputFields.add(GenericMetricEntity.VALUE_FIELD); } } condition.setOutputFields(outputFields); if (condition.isOutputAll()) { LOG.info("Output: ALL"); } else { LOG.info("Output: " + StringUtils.join(condition.getOutputFields(), ", ")); } TimeSeriesAggregator tsAgg = new TimeSeriesAggregator(groupbyFields, comp.aggregateFunctionTypes(), aggregateFields, DateTimeUtil.humanDateToDate(condition.getStartTime()).getTime(), DateTimeUtil.humanDateToDate(condition.getEndTime()).getTime(), intervalmin * 60 * 1000); if (parallel <= 0) { reader.register(tsAgg); } else { EntityCreationListener listener = EntityCreationListenerFactory .synchronizedEntityCreationListener(tsAgg); reader.register(listener); } // for sorting FlatAggregator sortAgg = null; if (comp.sortOptions() != null) { sortAgg = new FlatAggregator(groupbyFields, comp.sortFunctions(), comp.sortFields()); if (parallel <= 0) { reader.register(sortAgg); } else { EntityCreationListener listener = EntityCreationListenerFactory .synchronizedEntityCreationListener(sortAgg); reader.register(listener); } } reader.readAsStream(); ArrayList<Map.Entry<List<String>, List<double[]>>> obj = new ArrayList<Map.Entry<List<String>, List<double[]>>>(); obj.addAll(tsAgg.getMetric().entrySet()); if (comp.sortOptions() == null) { result.setObj(obj); } else { // has sort options result.setObj(TimeSeriesPostFlatAggregateSort.sort(sortAgg.result(), tsAgg.getMetric(), comp.sortOptions(), top)); } result.setTotalResults(0); result.setSuccess(true); result.setLastTimestamp(reader.getLastTimestamp()); result.setFirstTimestamp(reader.getFirstTimestamp()); } else { // use hierarchical aggregate mode List<String> groupbyFields = comp.groupbyFields(); List<String> aggregateFields = comp.aggregateFields(); Set<String> filterFields = comp.getFilterFields(); // List<String> outputFields = new ArrayList<String>(); if (groupbyFields != null) outputFields.addAll(groupbyFields); if (filterFields != null) outputFields.addAll(filterFields); outputFields.addAll(aggregateFields); if (GenericMetricEntity.GENERIC_METRIC_SERVICE.equals(serviceName) && !outputFields.contains(GenericMetricEntity.VALUE_FIELD)) { outputFields.add(GenericMetricEntity.VALUE_FIELD); } condition.setOutputFields(outputFields); if (condition.isOutputAll()) { LOG.info("Output: ALL"); } else { LOG.info("Output: " + StringUtils.join(condition.getOutputFields(), ", ")); } GenericEntityStreamReader reader = new GenericEntityStreamReader(serviceName, condition); HierarchicalAggregator agg = new HierarchicalAggregator(groupbyFields, comp.aggregateFunctionTypes(), comp.aggregateFields()); reader.register(agg); reader.readAsStream(); if (comp.sortOptions() == null) { result.setObj(agg.result()); } else { // has sort options result.setObj(PostHierarchicalAggregateSort.sort(agg.result(), comp.sortOptions())); } result.setTotalResults(0); result.setSuccess(true); result.setLastTimestamp(reader.getLastTimestamp()); result.setFirstTimestamp(reader.getFirstTimestamp()); } } catch (Exception ex) { LOG.error("Fail executing list query: " + query, ex); result.setException(EagleExceptionWrapper.wrap(ex)); result.setSuccess(false); return result; } finally { watch.stop(); result.setElapsedms(watch.getTime()); } LOG.info("Query done " + watch.getTime() + " ms"); return result; }
From source file:net.sourceforge.squirrel_sql.plugins.sqlscript.table_script.CreateFileOfCurrentSQLCommand.java
/** * Do the work.//from ww w . jav a2 s . c om * @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; long _threadId = 0; if (_LOG.isDebugEnabled()) { _consumeTime = new StopWatch(); _consumeTime.start();/*from w w w .j av a 2 s . c om*/ _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("-------------------------------------------------"); } } }
From source file:net.ymate.platform.base.YMP.java
/** * ??//from w ww.j a v a 2 s . co m */ public static void initialize() { if (!IS_INITED) { System.out.println(I18N.formatMessage(__LSTRING_FILE, null, null, "ymp.base.platform_version_show", VERSION, BUILD_DATE)); // Properties _configs = new Properties(); InputStream _in = null; if (RuntimeUtils.isWindows()) { _in = YMP.class.getClassLoader().getResourceAsStream("ymp-conf_WIN.properties"); } else if (RuntimeUtils.isUnixOrLinux()) { _in = YMP.class.getClassLoader().getResourceAsStream("ymp-conf_UNIX.properties"); } if (_in == null) { _in = YMP.class.getClassLoader().getResourceAsStream("ymp-conf.properties"); } if (_in != null) { try { _configs.load(_in); IS_DEV_MODEL = new BlurObject(_configs.getProperty("ymp.dev_model")).toBooleanValue(); __MODULE_LOADER = (IModuleLoader) Class .forName(_configs.getProperty("ymp.module_loader_impl_class")).newInstance(); } catch (Exception e) { __MODULE_LOADER = new DefaultModuleLoader(); } } else { System.err.println(I18N.formatMessage(__LSTRING_FILE, null, null, "ymp.base.error_load_conf_file")); } StopWatch _stopWatch = new StopWatch(); _stopWatch.start(); try { __MODULE_LOADER.initialize(_configs); IS_INITED = true; } catch (Throwable e) { e.printStackTrace(System.err); } finally { _stopWatch.stop(); if (IS_INITED) { System.out.println(I18N.formatMessage(__LSTRING_FILE, null, null, "ymp.base.platform_init_successed", _stopWatch.getTime())); } else { System.err.println( I18N.formatMessage(__LSTRING_FILE, null, null, "ymp.base.platform_init_failed")); } } } }
From source file:net.ymate.platform.core.YMP.java
/** * ?YMP// w w w . j av a2 s . c om * * @return ?YMP? * @throws Exception ? */ public YMP init() throws Exception { if (!__inited) { // _LOG.info("\n__ ____ __ ____ ____ \n" + "\\ \\ / / \\/ | _ \\ __ _|___ \\ \n" + " \\ V /| |\\/| | |_) | \\ \\ / / __) |\n" + " | | | | | | __/ \\ V / / __/ \n" + " |_| |_| |_|_| \\_/ |_____| Website: http://www.ymate.net/"); // StopWatch _watch = new StopWatch(); _watch.start(); // _LOG.info("Initializing ymate-platform-core-" + VERSION + " - debug:" + __config.isDevelopMode()); // ?I18N I18N.initialize(__config.getDefaultLocale(), __config.getI18NEventHandlerClass()); // ???? __events = Events.create(new DefaultEventConfig(__config.getEventConfigs())); __events.registerEvent(ApplicationEvent.class); __events.registerEvent(ModuleEvent.class); // __beanFactory = new DefaultBeanFactory(); __beanFactory.setLoader(new DefaultBeanLoader(__config.getExcudedFiles())); __beanFactory.registerHandler(Bean.class); // ?? __modules = new HashMap<Class<? extends IModule>, IModule>(); // ? __moduleFactory = new BeanFactory(this); __moduleFactory.setLoader(new DefaultBeanLoader(__config.getExcudedFiles())); __moduleFactory.registerHandler(Module.class, new ModuleHandler(this)); __moduleFactory.registerHandler(Proxy.class, new ProxyHandler(this)); __moduleFactory.registerHandler(EventRegister.class, new EventRegisterHandler(this)); // ?? __registerScanPackages(__moduleFactory); __registerScanPackages(__beanFactory); // ?? __proxyFactory = new DefaultProxyFactory(this).registerProxy(new InterceptProxy()); // ? __moduleFactory.init(); for (IModule _module : __modules.values()) { if (!_module.isInited()) { _module.init(this); // ???? __events.fireEvent(Events.MODE.NORMAL, new ModuleEvent(_module, ModuleEvent.EVENT.MODULE_INITED)); } } // ? __beanFactory.init(); // ?? __beanFactory.initProxy(__proxyFactory); // IoC? __beanFactory.initIoC(); // __inited = true; // _watch.stop(); _LOG.info("Initialization completed, Total time: " + _watch.getTime() + "ms"); // ??? __events.fireEvent(Events.MODE.NORMAL, new ApplicationEvent(this, ApplicationEvent.EVENT.APPLICATION_INITED)); } return this; }
From source file:net.ymate.platform.persistence.jdbc.base.AbstractOperator.java
public void execute() throws Exception { if (!this.executed) { StopWatch _time = new StopWatch(); _time.start();/* w w w. j a v a 2s .c o m*/ int _effectCounts = 0; try { _effectCounts = __doExecute(); // ????? this.executed = true; } finally { _time.stop(); this.expenseTime = _time.getTime(); // if (this.connectionHolder.getDataSourceCfgMeta().isShowSQL()) { _LOG.info(ExpressionUtils.bind("[${sql}]${param}[${count}][${time}]") .set("sql", StringUtils.defaultIfBlank(this.sql, "@NULL")) .set("param", __doSerializeParameters()).set("count", _effectCounts + "") .set("time", this.expenseTime + "ms").getResult()); } } } }
From source file:net.ymate.platform.persistence.jdbc.operator.AbstractOperator.java
public void execute() throws OperatorException { if (!this.__isExecuted) { if (StringUtils.isBlank(this.__sql)) { throw new OperatorException( I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.jdbc.sql_null")); } else {/*from ww w . j av a2s . c om*/ try { StopWatch _time = new StopWatch(); _time.start(); int _recordSize = this.__execute(); _time.stop(); this.setExpenseTime(_time.getTime()); if (JDBC.isShowSQL) { _LOG.info(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.jdbc.show_sql", this.getSql(), __parametersToString(), _recordSize, this.getExpenseTime())); } } catch (SQLException e) { throw new OperatorException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.jdbc.sql_exception", this.getSql(), __parametersToString()), RuntimeUtils.unwrapThrow(e)); } finally { this.__isExecuted = true; } } } }
From source file:net.ymate.platform.webmvc.WebMVC.java
public void processRequest(IRequestContext context, ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws Exception { StopWatch _consumeTime = null; long _threadId = Thread.currentThread().getId(); try {/*from ww w . ja v a 2s. com*/ if (__owner.getConfig().isDevelopMode()) { _consumeTime = new StopWatch(); _consumeTime.start(); } _LOG.debug("--> [" + _threadId + "] Process request start: " + context.getHttpMethod() + ":" + context.getRequestMapping()); // RequestMeta _meta = __mappingParser.doParse(context); if (_meta != null) { // _LOG.debug("--- [" + _threadId + "] Request mode: controller"); // ???? if (_meta.allowHttpMethod(context.getHttpMethod())) { // ? Map<String, String> _allowMap = _meta.getAllowHeaders(); for (Map.Entry<String, String> _entry : _allowMap.entrySet()) { String _value = WebContext.getRequest().getHeader(_entry.getKey()); if (StringUtils.trimToEmpty(_entry.getValue()).equals("*")) { if (StringUtils.isBlank(_value)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); // _LOG.debug("--- [" + _threadId + "] Check request allowed: NO"); return; } } else { if (_value == null || !_value.equalsIgnoreCase(_entry.getValue())) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); // _LOG.debug("--- [" + _threadId + "] Check request allowed: NO"); return; } } } // ?? _allowMap = _meta.getAllowParams(); for (Map.Entry<String, String> _entry : _allowMap.entrySet()) { if (StringUtils.trimToEmpty(_entry.getValue()).equals("*")) { if (!WebContext.getRequest().getParameterMap().containsKey(_entry.getKey())) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); // _LOG.debug("--- [" + _threadId + "] Check request allowed: NO"); return; } } else { String _value = WebContext.getRequest().getParameter(_entry.getKey()); if (_value == null || !_value.equalsIgnoreCase(_entry.getValue())) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); // _LOG.debug("--- [" + _threadId + "] Check request allowed: NO"); return; } } } // ??? if (context.getHttpMethod().equals(Type.HttpMethod.POST) && _meta.getMethod().isAnnotationPresent(FileUpload.class)) { if (!(request instanceof IMultipartRequestWrapper)) { // ????? request = new MultipartRequestWrapper(this, request); } // _LOG.debug("--- [" + _threadId + "] Include file upload: YES"); } WebContext.getContext().addAttribute(Type.Context.HTTP_REQUEST, request); // IWebCacheProcessor _cacheProcessor = __doGetWebCacheProcessor(_meta.getResponseCache()); IView _view = null; // ?? if (_cacheProcessor != null) { // ? if (_cacheProcessor.processResponseCache(this, _meta.getResponseCache(), context, null)) { // ?, _view = View.nullView(); // _LOG.debug("--- [" + _threadId + "] Load data from the cache: YES"); } } if (_view == null) { _view = RequestExecutor.bind(this, _meta).execute(); if (_view != null) { if (_cacheProcessor != null) { try { // ? if (_cacheProcessor.processResponseCache(this, _meta.getResponseCache(), context, _view)) { _view = View.nullView(); // _LOG.debug("--- [" + _threadId + "] Results data cached: YES"); } } catch (Exception e) { // ????, _LOG.warn(e.getMessage(), RuntimeUtils.unwrapThrow(e)); } } _view.render(); } else { HttpStatusView.NOT_FOUND.render(); } } else { _view.render(); } } else { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } } else if (__moduleCfg.isConventionMode()) { boolean _isAllowConvention = true; if (!__moduleCfg.getConventionViewNotAllowPaths().isEmpty()) { for (String _vPath : __moduleCfg.getConventionViewNotAllowPaths()) { if (context.getRequestMapping().startsWith(_vPath)) { _isAllowConvention = false; break; } } } if (_isAllowConvention && !__moduleCfg.getConventionViewAllowPaths().isEmpty()) { _isAllowConvention = false; for (String _vPath : __moduleCfg.getConventionViewAllowPaths()) { if (context.getRequestMapping().startsWith(_vPath)) { _isAllowConvention = true; break; } } } if (_isAllowConvention) { // _LOG.debug("--- [" + _threadId + "] Request mode: convention"); // IView _view = null; ResponseCache _responseCache = null; if (__interceptorRuleProcessor != null) { // ?Convention PairObject<IView, ResponseCache> _result = __interceptorRuleProcessor.processRequest(this, context); _view = _result.getKey(); _responseCache = _result.getValue(); } // ?? IWebCacheProcessor _cacheProcessor = __doGetWebCacheProcessor(_responseCache); // ?? if (_cacheProcessor != null) { // ? if (_cacheProcessor.processResponseCache(this, _responseCache, context, null)) { // ?, _view = View.nullView(); // _LOG.debug("--- [" + _threadId + "] Load data from the cache: YES"); } } if (_view == null) { // ?Convention?URL?? String _requestMapping = context.getRequestMapping(); String[] _urlParamArr = getModuleCfg().isConventionUrlrewriteMode() ? StringUtils.split(_requestMapping, '_') : new String[] { _requestMapping }; if (_urlParamArr != null && _urlParamArr.length > 1) { _requestMapping = _urlParamArr[0]; List<String> _urlParams = Arrays.asList(_urlParamArr).subList(1, _urlParamArr.length); WebContext.getRequest().setAttribute("UrlParams", _urlParams); // _LOG.debug("--- [" + _threadId + "] With parameters : " + _urlParams); } // if (__moduleCfg.getErrorProcessor() != null) { _view = __moduleCfg.getErrorProcessor().onConvention(this, context); } if (_view == null) { // ???URL String[] _fileTypes = { ".html", ".jsp", ".ftl", ".vm" }; for (String _fileType : _fileTypes) { File _targetFile = new File(__moduleCfg.getAbstractBaseViewPath(), _requestMapping + _fileType); if (_targetFile.exists()) { if (".html".equals(_fileType)) { _view = HtmlView.bind(this, _requestMapping.substring(1)); // _LOG.debug("--- [" + _threadId + "] Rendering template file : " + _requestMapping + _fileType); break; } else if (".jsp".equals(_fileType)) { _view = JspView.bind(this, _requestMapping.substring(1)); // _LOG.debug("--- [" + _threadId + "] Rendering template file : " + _requestMapping + _fileType); break; } else if (".ftl".equals(_fileType)) { _view = FreemarkerView.bind(this, _requestMapping.substring(1)); // _LOG.debug("--- [" + _threadId + "] Rendering template file : " + _requestMapping + _fileType); break; } else if (".vm".equals(_fileType)) { _view = VelocityView.bind(this, _requestMapping.substring(1)); // _LOG.debug("--- [" + _threadId + "] Rendering template file : " + _requestMapping + _fileType); } } } } // if (_view != null && _cacheProcessor != null) { try { if (_cacheProcessor.processResponseCache(this, _responseCache, context, _view)) { _view = View.nullView(); // _LOG.debug("--- [" + _threadId + "] Results data cached: YES"); } } catch (Exception e) { // ????, _LOG.warn(e.getMessage(), RuntimeUtils.unwrapThrow(e)); } } } if (_view != null) { _view.render(); } else { HttpStatusView.NOT_FOUND.render(); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } finally { if (_consumeTime != null && __owner.getConfig().isDevelopMode()) { _consumeTime.stop(); _LOG.debug("--- [" + _threadId + "] Total execution time: " + _consumeTime.getTime() + "ms"); } _LOG.debug("<-- [" + _threadId + "] Process request completed: " + context.getHttpMethod() + ":" + context.getRequestMapping()); } }
From source file:nl.strohalm.cyclos.services.stats.tests.TestDatabaseForStats.java
public static void main(final String[] args) throws Exception { final StopWatch sw = new StopWatch(); sw.start();/*w w w . ja v a2s.com*/ APPLICATION_CONTEXT = new CustomApplicationContext(FILES, TestDatabaseForStats.class); System.out.printf("Total startup time: %.3f\n", sw.getTime() / 1000D); final TransactionTemplate template = bean("transactionTemplate"); template.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(final TransactionStatus status) { try { TestDatabaseForStats.doInTransaction(); } catch (final ValidationException e) { System.out.println("Validation failed."); final Collection<ValidationError> generalErrors = e.getGeneralErrors(); if (generalErrors != null && !generalErrors.isEmpty()) { System.out.println("General errors:"); for (final ValidationError error : generalErrors) { System.out.println(error.getKey()); } } final Map<String, Collection<ValidationError>> errorsByProperty = e.getErrorsByProperty(); if (errorsByProperty != null && !errorsByProperty.isEmpty()) { for (final Map.Entry<String, Collection<ValidationError>> entry : errorsByProperty .entrySet()) { final String name = entry.getKey(); final Collection<ValidationError> errors = entry.getValue(); if (errors != null && !errors.isEmpty()) { System.out.println("Property errors for '" + name + "':"); for (final ValidationError error : errors) { System.out.println(error.getKey()); } } } } } catch (final Exception e) { status.setRollbackOnly(); e.printStackTrace(); } } }); updateGroupChangeLog(groupChanges); System.out.println("FINISHED"); System.exit(0); }
From source file:nu.mine.kino.jenkins.plugins.projectmanagement.HolidayCalendarAction.java
public synchronized Project getProject(String name) throws ProjectException { StopWatch watch = new StopWatch(); watch.start();//from w ww. j ava2s. com if (StringUtils.isEmpty(name)) { return null; } if (map.containsKey(name)) { Project project = map.get(name); return project; } File target = new File(owner.getRootDir(), name); if (!target.exists()) { return null; } Project targetProject = new JSONProjectCreator(target).createProject(); watch.stop(); System.out.printf("%s -> Project : [%d] ms\n", name, watch.getTime()); watch = null; map.put(name, targetProject); return targetProject; }