List of usage examples for org.apache.commons.lang.time StopWatch start
public void start()
Start the stopwatch.
This method starts a new timing session, clearing any previous values.
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 www.jav a2 s .c o m*/ 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(); 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/* ww w . ja v a 2 s . c o m*/ 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:nl.utwente.bigdata.OutgoingLinks.java
public static void main(String[] args) throws Exception { // Tijd bijhouden StopWatch timer = new StopWatch(); timer.start(); // HashMap van PageRanks initializeren //pageRanks = new HashMap<String, Float>(); Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length < 2) { System.err.println("Usage: pageRank <in> [<in>...] <out>"); System.exit(2);/*from w w w. j av a 2 s . co m*/ } Job job = new Job(conf, "Twitter Reader"); job.setJarByClass(OutgoingLinks.class); job.setMapperClass(OutgoingLinksMapper.class); job.setReducerClass(OutgoingLinksReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); for (int i = 0; i < otherArgs.length - 1; ++i) { FileInputFormat.addInputPath(job, new Path(otherArgs[i])); } FileOutputFormat.setOutputPath(job, new Path(otherArgs[otherArgs.length - 1])); boolean succesful = job.waitForCompletion(true); if (succesful) { timer.stop(); System.out.println("Elapsed " + timer.toString()); //System.exit(0); } else { //System.exit(1); } }
From source file:no.sesat.search.http.filters.SiteJspLoaderFilter.java
private void downloadJsp(final HttpServletRequest request, final String jsp) throws MalformedURLException { final StopWatch stopWatch = new StopWatch(); stopWatch.start(); byte[] golden = new byte[0]; // search skins for the jsp and write it out to "golden" for (Site site = (Site) request.getAttribute(Site.NAME_KEY); 0 == golden.length; site = site.getParent()) { if (null == site) { if (null == config.getServletContext().getResource(jsp)) { throw new ResourceLoadException("Unable to find " + jsp + " in any skin"); }// ww w . j a v a2 s . c om break; } final Site finalSite = site; final BytecodeLoader bcLoader = UrlResourceLoader.newBytecodeLoader(finalSite.getSiteContext(), jsp, null); bcLoader.abut(); golden = bcLoader.getBytecode(); } // if golden now contains data save it to a local (ie local web application) file if (0 < golden.length) { try { final File file = new File(root + jsp); // create the directory structure file.getParentFile().mkdirs(); // check existing file boolean needsUpdating = true; final boolean fileExisted = file.exists(); if (!fileExisted) { file.createNewFile(); } // channel.lock() only synchronises file access between programs, but not between threads inside // the current JVM. The latter results in the OverlappingFileLockException. // At least this is my current understanding of java.nio.channels // It may be that no synchronisation or locking is required at all. A beer to whom answers :-) // So we must provide synchronisation between our own threads, // synchronisation against the file's path (using the JVM's String.intern() functionality) // should work. (I can't imagine this string be used for any other synchronisation purposes). synchronized (file.toString().intern()) { RandomAccessFile fileAccess = null; FileChannel channel = null; try { fileAccess = new RandomAccessFile(file, "rws"); channel = fileAccess.getChannel(); channel.lock(); if (fileExisted) { final byte[] bytes = new byte[(int) channel.size()]; final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); int reads; do { reads = channel.read(byteBuffer); } while (0 < reads); needsUpdating = !Arrays.equals(golden, bytes); } if (needsUpdating) { // download file from skin channel.write(ByteBuffer.wrap(golden), 0); file.deleteOnExit(); } } finally { if (null != channel) { channel.close(); } if (null != fileAccess) { fileAccess.close(); } LOG.debug("resource created as " + config.getServletContext().getResource(jsp)); } } } catch (IOException ex) { LOG.error(ex.getMessage(), ex); } } stopWatch.stop(); LOG.trace("SiteJspLoaderFilter.downloadJsp(..) took " + stopWatch); }
From source file:no.sesat.search.http.filters.SiteLocatorFilter.java
/** Will redirect to correct (search-config) url for resources (css,images, javascript). * * @param request The servlet request we are processing * @param r The servlet response//from w ww . j ava 2 s.co m * @param chain The filter chain we are processing * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ @Override public void doFilter(final ServletRequest request, final ServletResponse r, final FilterChain chain) throws IOException, ServletException { LOG.trace("doFilter(..)"); final StopWatch stopWatch = new StopWatch(); stopWatch.start(); final ServletResponse response = r instanceof HttpServletResponse ? new AccessLogResponse((HttpServletResponse) r) : r; try { if (request instanceof HttpServletRequest) { final HttpServletRequest httpServletRequest = (HttpServletRequest) request; final HttpServletResponse httpServletResponse = (HttpServletResponse) response; if (httpServletRequest.getRequestURI().contains(CONFIGURATION_RESOURCE)) { /* We are looping, looking for a site search which does not exsist */ LOG.info("We are looping, looking for a site search which does not exist"); httpServletResponse.reset(); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } } doBeforeProcessing(request, response); logAccessRequest(request); if (request instanceof HttpServletRequest) { final HttpServletRequest req = (HttpServletRequest) request; final HttpServletResponse res = (HttpServletResponse) response; final Site site = (Site) req.getAttribute(Site.NAME_KEY); final String uri = req.getRequestURI(); final String resource = uri; final String rscDir = resource != null && resource.indexOf('/', 1) >= 0 ? resource.substring(0, resource.indexOf('/', 1) + 1) : null; if (isAccessAllowed(req)) { if (rscDir != null && EXTERNAL_DIRS.contains(rscDir)) { // This URL does not belong to search-portal final String url = FindResource.find(site, resource); if (url != null) { // Cache the client-resource redirects on a short (session-equivilant) period res.setHeader("Cache-Control", "Public"); res.setDateHeader("Expires", System.currentTimeMillis() + 1000 * 60 * 10); // ten minutes // send the redirect to where the resource really resides res.sendRedirect(url); LOG.trace(resource + DEBUG_REDIRECTING_TO + url); } else if (resource.startsWith(PUBLISH_DIR)) { // XXX Why do we avoid sending 404 for publish resources? res.sendError(HttpServletResponse.SC_NOT_FOUND); if (resource.endsWith(".css")) { LOG.info(ERR_NOT_FOUND + resource); } else { LOG.error(ERR_NOT_FOUND + resource); } } } else { doChainFilter(chain, request, response); } } else { // Forbidden client res.sendError(HttpServletResponse.SC_FORBIDDEN); } } else { doChainFilter(chain, request, response); } doAfterProcessing(request, response); } catch (Exception e) { // Don't let anything through without logging it. // Otherwise it ends in a different logfile. LOG.error(ERR_UNCAUGHT_RUNTIME_EXCEPTION); for (Throwable t = e; t != null; t = t.getCause()) { LOG.error(t.getMessage(), t); } throw new ServletException(e); } finally { logAccessResponse(request, response, stopWatch); } }
From source file:no.sesat.search.http.servlet.SearchServlet.java
@Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { logAccessRequest(request);/*w w w .ja v a 2 s .co m*/ LOG.trace("doGet()"); final DataModel datamodel = (DataModel) request.getSession().getAttribute(DataModel.KEY); final ParametersDataObject parametersDO = datamodel.getParameters(); final Site site = datamodel.getSite().getSite(); // BaseContext providing SiteContext and ResourceContext. // We need it casted as a SiteContext for the ResourceContext code to be happy. final SiteContext genericCxt = new SiteContext() { public PropertiesLoader newPropertiesLoader(final SiteContext siteCxt, final String resource, final Properties properties) { return UrlResourceLoader.newPropertiesLoader(siteCxt, resource, properties); } public DocumentLoader newDocumentLoader(final SiteContext siteCxt, final String resource, final DocumentBuilder builder) { return UrlResourceLoader.newDocumentLoader(siteCxt, resource, builder); } public BytecodeLoader newBytecodeLoader(SiteContext context, String className, final String jar) { return UrlResourceLoader.newBytecodeLoader(context, className, jar); } @Override public Site getSite() { return site; } }; final DataModelFactory dmFactory; try { dmFactory = DataModelFactory .instanceOf(ContextWrapper.wrap(DataModelFactory.Context.class, genericCxt)); } catch (SiteKeyedFactoryInstantiationException skfe) { throw new ServletException(skfe); } // DataModel's ControlLevel will be VIEW_CONSTRUCTION (safe setting set by DataModelFilter) // Bring it back to VIEW_CONSTRUCTION. dmFactory.assignControlLevel(datamodel, ControlLevel.REQUEST_CONSTRUCTION); try { final String cParameter = null != parametersDO.getValue(SearchTab.PARAMETER_KEY) ? parametersDO.getValue(SearchTab.PARAMETER_KEY).getString() : null; final SearchTab searchTab = RunningQueryUtility.findSearchTabByKey(datamodel, cParameter, dmFactory, genericCxt); if (null != searchTab) { // this is legacy. shorter to write in templates than $datamodel.page.currentTab request.setAttribute("tab", searchTab); LOG.debug("Character encoding =" + request.getCharacterEncoding()); final StopWatch stopWatch = new StopWatch(); stopWatch.start(); final String ipAddr = null != request.getAttribute(REMOTE_ADDRESS_KEY) ? (String) request.getAttribute(REMOTE_ADDRESS_KEY) : request.getRemoteAddr(); performFactoryReloads(request.getParameter("reload"), genericCxt, ipAddr, datamodel.getSite().getSiteConfiguration()); // If the rss is hidden, require a partnerId. // The security by obscurity has been somewhat improved by the // addition of rssPartnerId as a md5-protected parameter (MD5ProtectedParametersFilter). final StringDataObject layout = parametersDO.getValue("layout"); boolean hiddenRssWithoutPartnerId = null != layout && "rss".equals(layout.getString()) && searchTab.isRssHidden() && null == parametersDO.getValues().get("rssPartnerId"); if (hiddenRssWithoutPartnerId) { response.sendError(HttpServletResponse.SC_NOT_FOUND); } else if (null != layout && "rss".equals(layout.getString()) && "".equals(searchTab.getRssResultName())) { LOG.warn("RSS not supported for requested vertical " + searchTab.toString()); response.sendError(HttpServletResponse.SC_NOT_FOUND); } else { performSearch(request, response, genericCxt, searchTab, stopWatch); getServletContext().getRequestDispatcher("/WEB-INF/jsp/start.jsp").forward(request, response); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } finally { // DataModel's ControlLevel will be REQUEST_CONSTRUCTION or RUNNING_QUERY_HANDLING // Increment it onwards to VIEW_CONSTRUCTION. dmFactory.assignControlLevel(datamodel, ControlLevel.VIEW_CONSTRUCTION); } }
From source file:no.sesat.search.mode.command.AbstractSearchCommand.java
/** Handles the execution process. Will determine whether to call execute() and wrap it with timing info. * @return/*from w ww. j a v a 2 s .c o m*/ */ protected final ResultList<ResultItem> performExecution() { final StopWatch watch = new StopWatch(); watch.start(); final String notNullQuery = null != getTransformedQuery() ? getTransformedQuery().trim() : ""; Integer hitCount = null; try { // we will be executing the command IF there's a valid query or filter, // or if the configuration specifies that we should run anyway. boolean executeQuery = null != datamodel.getQuery() && "*".equals(datamodel.getQuery().getString()); executeQuery |= notNullQuery.length() > 0 || getSearchConfiguration().isRunBlank(); executeQuery |= null != getFilter() && 0 < getFilter().length(); LOG.info("executeQuery==" + executeQuery + " ; query:" + notNullQuery + " ; filter:" + getFilter()); final ResultList<ResultItem> result = executeQuery ? execute() : new BasicResultList<ResultItem>(); if (!executeQuery) { // sent hit count to zero since we have intentionally avoiding searching. result.setHitCount(0); } hitCount = result.getHitCount(); LOG.debug("Hits is " + getSearchConfiguration().getId() + ':' + hitCount); return result; } finally { watch.stop(); LOG.info("Search " + getSearchConfiguration().getId() + " took " + watch); statisticsInfo("<search-command id=\"" + getSearchConfiguration().getId() + "\" name=\"" + getSearchConfiguration().getStatisticalName() + "\" type=\"" + getClass().getSimpleName() + "\">" + (hitCount != null ? "<hits>" + hitCount + "</hits>" : "<failure/>") + "<time>" + watch + "</time>" + "</search-command>"); } }
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(); if (StringUtils.isEmpty(name)) { return null; }/*from w ww .j a va 2 s . c o m*/ 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; }
From source file:nu.mine.kino.jenkins.plugins.projectmanagement.HolidayCalendarAction.java
public Holiday[] getHolidays() { StopWatch watch = new StopWatch(); watch.start(); if (StringUtils.isEmpty(name)) { return new Holiday[0]; }/*from www . j av a 2s. co m*/ try { Project targetProject = getProject(name); return targetProject.getHolidays(); } catch (ProjectException e) { // TODO ?? catch u?bN e.printStackTrace(); } finally { watch.stop(); System.out.printf("getHolidays : [%d] ms\n", watch.getTime()); watch = null; } return null; }
From source file:nu.mine.kino.jenkins.plugins.projectmanagement.ProjectSummaryAction.java
public EVMViewBean getCurrentPVACEV() { if (delegate != null) { return delegate; }/*w ww . jav a2 s .c o m*/ StopWatch watch = new StopWatch(); watch.start(); EVMViewBean ret = this.internalCreateCurrentEVM(); watch.stop(); System.out.printf("EVMViewBean getCurrentPVACEV() (EVM) : [%d] ms\n", watch.getTime()); watch = null; return ret; }