List of usage examples for org.apache.commons.lang.time StopWatch StopWatch
public StopWatch()
Constructor.
From source file:org.beangle.model.persist.hibernate.HibernateEntityContext.java
public void initFrom(SessionFactory sessionFactory) { if (null != sessionFactory && entityTypes.isEmpty()) { StopWatch watch = new StopWatch(); watch.start();/* ww w . j a va 2 s . c o m*/ Map<String, ClassMetadata> classMetadatas = sessionFactory.getAllClassMetadata(); for (Iterator<ClassMetadata> iter = classMetadatas.values().iterator(); iter.hasNext();) { ClassMetadata cm = (ClassMetadata) iter.next(); buildEntityType(sessionFactory, cm.getEntityName()); } logger.info("Find {} entities,{} collections from hibernate in {} ms", new Object[] { entityTypes.size(), collectionTypes.size(), watch.getTime() }); if (logger.isDebugEnabled()) { loggerTypeInfo(); } collectionTypes.clear(); } }
From source file:org.beangle.security.core.session.category.SessioninfoCleaner.java
@Override public void run() { StopWatch watch = new StopWatch(); watch.start();// ww w. j a va2s. c o m logger.debug("clean up expired or over maxOnlineTime session start ..."); Calendar calendar = Calendar.getInstance(); @SuppressWarnings("unchecked") OqlBuilder<Sessioninfo> builder = OqlBuilder.from(registry.getSessioninfoBuilder().getSessioninfoClass(), "info"); builder.where("info.serverName=:server and info.lastAccessAt<:givenTime", registry.getController().getServerName(), DateUtils.rollMinutes(calendar.getTime(), -expiredTime)); List<Sessioninfo> activities = entityDao.search(builder); int removed = 0; for (Sessioninfo activity : activities) { registry.remove(activity.getId()); removed++; } if (removed > 0 || watch.getTime() > 50) { logger.info("removed {} expired sessions in {} ms", removed, watch.getTime()); } registry.getController().stat(); }
From source file:org.beangle.spring.bind.AutoConfigProcessor.java
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { StopWatch watch = new StopWatch(); watch.start();/*from w ww . j a v a2 s . c o m*/ bindRegistry = new DefinitionBindRegistry(registry); register(registry); autowire(); logger.debug("Auto register and wire bean [{}]", newBeanDefinitions.keySet()); logger.info("Auto register and wire {} beans using {} mills", newBeanDefinitions.size(), watch.getTime()); newBeanDefinitions.clear(); bindRegistry = null; }
From source file:org.beangle.web.io.SplitStreamDownloader.java
@Override public void download(HttpServletRequest request, HttpServletResponse response, InputStream input, String name, String display) {/*from w w w .ja v a 2 s .co m*/ String attach = getAttachName(name, display); response.reset(); addContent(request, response, attach); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("connection", "Keep-Alive"); int length = 0; long start = 0L; long begin = 0L; long stop = 0L; StopWatch watch = new StopWatch(); watch.start(); try { length = input.available(); stop = length - 1; response.setContentLength(length); String rangestr = request.getHeader("Range"); if (null != rangestr) { String[] readlength = StringUtils.substringAfter(rangestr, "bytes=").split("-"); start = Long.parseLong(readlength[0]); if (readlength.length > 1 && StringUtils.isNotEmpty(readlength[1])) { stop = Long.parseLong(readlength[1]); } if (start != 0) { response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); String crange = "bytes " + start + "-" + stop + "/" + length; response.setHeader("Content-Range", crange); } } OutputStream output = response.getOutputStream(); input.skip(start); begin = start; int size = 4 * 1024; byte[] buffer = new byte[size]; for (int step = maxStep(start, stop, size); step > 0; step = maxStep(start, stop, size)) { int readed = input.read(buffer, 0, step); if (readed == -1) break; output.write(buffer, 0, readed); start += readed; } } catch (IOException e) { } catch (Exception e) { logger.warn("download file error " + attach, e); } finally { IOUtils.closeQuietly(input); if (logger.isDebugEnabled()) { String percent = null; if (length == 0) { percent = "100%"; } else { percent = ((int) (((start - begin) * 1.0 / length) * 10000)) / 100.0f + "%"; } long time = watch.getTime(); int rate = 0; if (start - begin > 0) { rate = (int) (((start - begin) * 1.0 / time * 1000) / 1024); } logger.debug("{}({}-{}/{}) download {}[{}] in {} ms with {} KB/s", array(attach, begin, stop, length, start - begin, percent, time, rate)); } } }
From source file:org.bml.util.elasticconsumer.ElasticConsumer.java
/** * Offer an object to be processed to the processing queue. * * @param theObject The object to be processed. * @param theTimeout The max wait time for successful offer. * @param theTimeUnit The TimeUnit the argument theTimeout is in. * @return boolean true on success false otherwise * @throws java.lang.InterruptedException if this thread is interrupted * while attempting the offer.//from w w w .ja va 2s.c om * @throws IllegalArgumentException If theObject is null, theTimeout is less * than 1, or theTimeUnit is null. */ public boolean offer(final D theObject, final long theTimeout, final TimeUnit theTimeUnit) throws InterruptedException, IllegalArgumentException { if (theObject == null) { throw new IllegalArgumentException("Can not offer a null object."); } if (theTimeout < 1) { throw new IllegalArgumentException("Can not offer an object with a timeout less than 1."); } if (theTimeUnit == null) { throw new IllegalArgumentException("Can not offer an object with a null TimeUnit."); } if (log.isDebugEnabled()) { StopWatch watch = new StopWatch(); watch.start(); boolean result = doOffer(theObject, theTimeout, theTimeUnit); watch.stop(); log.debug(getLogPrefix() + " DEBUG: OFFER result=" + result + " timeout=" + theTimeout + " time unit " + theTimeUnit + " actual time in mills=" + watch.getTime()); return result; } return doOffer(theObject, theTimeout, theTimeUnit); }
From source file:org.bml.util.errorconsumer.ParseErrorWorkerThread.java
/** * Creates a new BlockingQueueWorkerThread. * * @param queueIn The BlockingQueue<T> for worker threads to poll. * @param timeout The worker threads poll timeout. * @param unit The worker threads poll timeout TimeUnit. * @param waitOnEmptyQueueInMills The worker threads sleep time on an empty * queue.// w w w . j a va 2 s . c om */ public ParseErrorWorkerThread(final BlockingQueue<ParseError> queueIn, final long timeout, final TimeUnit unit, final long waitOnEmptyQueueInMills) { super(queueIn, timeout, unit, waitOnEmptyQueueInMills); timer = new StopWatch(); timer.start(); }
From source file:org.bml.util.errorconsumer.ParseErrorWorkerThread.java
/** * TOOD: Add a temp ordered list to store ParseError objects as they are * taken from the queue and log if any rows are rejected by the DB server * TODO: abstract out the handleDBEntry base logic and use <T> for entry and * a static method for marshaling into a Prepared Statement (Consider adding * the marshal method to a TABLE definition object). *//* w w w . j a v a 2 s. com*/ public void handleDBEntry() { Connection myConnection = null; PreparedStatement myPreparedStatement = null; Connection myPageViewConnection = null; int batchExecutionResults[] = null; List<ParseError> theBatchTrackingList = new LinkedList<ParseError>(); //DeviceType aDeviceType = null; //DeviceClass aDeviceClass = null; //Change to reusable map Map<String, String> tmpMap = null; //Change to StringBuilder //String tmpString = null; //theBatchTrackingList = new ArrayList<PageViewData>(dataQueue.size()); boolean dbErrror = false; try { ParseError aParseError = null; try { aParseError = errorQueue.remove(); theBatchTrackingList.add(aParseError); } catch (NoSuchElementException e) { LOG.info("There are no ParseError Objects to push into the DB"); return; } StopWatch connectionAge = new StopWatch(); connectionAge.start(); setWorkerState(WORKER_STATE.ACQUIRING_CONNECTION); myConnection = DBUtil.getDefaultDataSource().getConnection(); setWorkerState(WORKER_STATE.CONFIGURING_CONNECTION); myConnection.clearWarnings(); myConnection.setAutoCommit(false); setWorkerState(WORKER_STATE.PREPARING_SQL); myPreparedStatement = myConnection.prepareStatement(ParseErrorTable.PREPARED_INSERT_SQL); setWorkerState(WORKER_STATE.BATCHING); while ((connectionAge.getTime() / 1000) <= 20) { ParseErrorTable.populatePreparedStatement(myPreparedStatement, aParseError.toParamMap(), Boolean.FALSE); myPreparedStatement.addBatch(); try { aParseError = errorQueue.remove(); theBatchTrackingList.add(aParseError); } catch (NoSuchElementException e) { break; } } this.setWorkerState(WORKER_STATE.EXECUTING_BATCH); batchExecutionResults = myPreparedStatement.executeBatch(); myConnection.commit(); this.setWorkerState(WORKER_STATE.VERIFYING_BATCH); if (batchExecutionResults.length != theBatchTrackingList.size()) { } } catch (SQLException sqle) { if (LOG.isFatalEnabled()) { LOG.fatal( "SQLException caught. The ErrorConsumer is unable to push data to a database. ParseErrors will be dumped to /tmp/error_consumer/", sqle); } } catch (Exception e) { if (LOG.isFatalEnabled()) { LOG.fatal( "Exception caught. The ErrorConsumer is unable to push data to a database. Errors will be dumped to /tmp/error_consumer/", e); } } finally { DbUtils.closeQuietly(myPreparedStatement); DbUtils.closeQuietly(myConnection); } }
From source file:org.bml.util.geo.util.geolite.GISControler.java
/** *///from w w w .j ava 2 s . co m private static void initGISFromDB() { try { ComboPooledDataSource myComboPooledDataSource = DBUtil.getDefaultDataSource(); StopWatch myStopWatch = new StopWatch(); myStopWatch.start(); ipBlocks = GeoLiteCityBlock.readFromDB(myComboPooledDataSource); myStopWatch.stop(); if (LOG.isInfoEnabled()) { LOG.info("Finished Loading " + ipBlocks.size() + " IPBlocks Map in " + (myStopWatch.getTime() / 1000) + " Seconds"); } myStopWatch.start(); Map<Integer, GeoLiteCityLocation> locationMap = GeoLiteCityLocation.readFromDB(myComboPooledDataSource); myStopWatch.stop(); if (LOG.isInfoEnabled()) { LOG.info("Finished Loading " + locationMap.size() + " Locations in " + (myStopWatch.getTime() / 1000) + " Seconds"); } startIPs = ipBlocks.keySet().toArray(new Integer[ipBlocks.keySet().size()]); //This should not be necessary but we sort for now until the underlying structures have been // proven Arrays.sort(startIPs); for (GeoLiteCityBlock block : ipBlocks.values()) { block.setTheLocation(locationMap.get(block.getLocId())); } //Mark for GC locationMap.clear(); locationMap = null; } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Exception caught while loading GIS data. GIS DATA LOOKUP WILL NOT BE AVAILABLE!", e); } } finally { if (ipBlocks != null && !ipBlocks.isEmpty() && startIPs != null && startIPs.length > 0) { isAvailable = true; } else { isAvailable = false; } } }
From source file:org.bml.util.time.StopWatchPool.java
/** * A wrapper for/* w w w .j a v a2 s .co m*/ * {@link org.apache.commons.pool.impl.GenericObjectPool#borrowObject()} * this method handles potential exceptions and falls back to new object * creation if the pool is broken. * * @return An instance of StopWatch. */ public StopWatch borrowStopWatch() { StopWatch watch = null; if (this.usePool) { try { watch = borrowObject(); this.stopWatchBorrowCount.incrementAndGet(); return watch; } catch (Exception ex) { if (LOG.isErrorEnabled()) { LOG.error( "An error was encountered while trying to borrow from the StopWatch pool. The pool will be disabled.", ex); } this.usePool = false; } } if (!this.usePool) { return new StopWatch(); } return null; }
From source file:org.bml.util.time.StopWatchPool.java
@Override public StopWatch makeObject() throws Exception { return new StopWatch(); }