Example usage for org.springframework.util StopWatch StopWatch

List of usage examples for org.springframework.util StopWatch StopWatch

Introduction

In this page you can find the example usage for org.springframework.util StopWatch StopWatch.

Prototype

public StopWatch() 

Source Link

Document

Construct a new StopWatch .

Usage

From source file:com.persistent.cloudninja.scheduler.TenantStorageBWProcessor.java

/** 
 * Calculates storage bandwidth of tenant.
 *///from w  w  w .j  av a 2s .c  o m
@Override
public boolean execute() {
    StopWatch watch = new StopWatch();
    boolean retVal = true;
    List<StorageBandwidthBatchEntity> batchesToProcess = null;
    try {
        LOGGER.debug("In TenantStorageBWProcessor");
        TenantStorageBWQueue queue = (TenantStorageBWQueue) getWorkQueue();
        batchesToProcess = queue.dequeue();
        if (batchesToProcess == null) {
            retVal = false;
        } else {
            watch.start();
            processBatches(batchesToProcess);
            watch.stop();
            taskCompletionDao.updateTaskCompletionDetails(watch.getTotalTimeSeconds(),
                    "GenerateStorageBandwidth", "Batch Size = " + batchesToProcess.size());
        }
    } catch (Exception e) {
        retVal = false;
        LOGGER.error(e.getMessage(), e);
    }
    return retVal;
}

From source file:org.dd4t.core.filters.impl.DefaultLinkResolverFilter.java

protected void resolvePage(GenericPage page) {

    StopWatch stopWatch = null;//  ww  w . j  a  va  2 s  . co m
    if (logger.isDebugEnabled()) {
        stopWatch = new StopWatch();
        stopWatch.start();
    }

    List<ComponentPresentation> cpList = page.getComponentPresentations();
    if (cpList != null) {
        for (ComponentPresentation cp : cpList) {
            resolveComponent((GenericComponent) cp.getComponent(), page);
        }
    }
    resolveMap(page.getMetadata());

    if (logger.isDebugEnabled()) {
        stopWatch.stop();
        logger.debug(
                "ResolvePage for " + page.getId() + " finished in " + stopWatch.getTotalTimeMillis() + " ms");
    }
}

From source file:com.auditbucket.engine.service.MediationFacade.java

public Integer createHeaders(final Company company, final Fortress fortress,
        final List<MetaInputBean> inputBeans) throws DatagioException {
    fortress.setCompany(company);//from  w  w w  .ja v  a  2 s  .co m
    Long id = DateTime.now().getMillis();
    StopWatch watch = new StopWatch();
    watch.start();
    logger.info("Starting Batch [{}] - size [{}]", id, inputBeans.size());
    boolean newMode = true;
    if (newMode) {

        // Tune to balance against concurrency and batch transaction insert efficiency.
        List<List<MetaInputBean>> splitList = Lists.partition(inputBeans, 20);

        for (List<MetaInputBean> metaInputBeans : splitList) {

            class DLCommand implements Command {
                Iterable<MetaInputBean> headers = null;

                DLCommand(List<MetaInputBean> processList) {
                    this.headers = new CopyOnWriteArrayList<>(processList);
                }

                @Override
                public Command execute() throws DatagioException {
                    //fortressService.registerFortress(company, new FortressInputBean(headers.iterator().next().getFortress()), true);
                    Iterable<TrackResultBean> resultBeans = trackService.createHeaders(headers, company,
                            fortress);
                    processLogs(company, resultBeans);
                    return this;
                }
            }
            DeadlockRetry.execute(new DLCommand(metaInputBeans), "creating headers", 20);
        }

    } else {
        logger.info("Processing in slow Transaction mode");
        for (MetaInputBean inputBean : inputBeans) {
            createHeader(company, fortress, inputBean);
        }
    }
    watch.stop();
    logger.info("Completed Batch [{}] - secs= {}, RPS={}", id, f.format(watch.getTotalTimeSeconds()),
            f.format(inputBeans.size() / watch.getTotalTimeSeconds()));
    return inputBeans.size();
}

From source file:org.nebulaframework.grid.Grid.java

/**
 * Starts {@link ClusterManager} instance with default settings,
 * read from default properties file./* w  w  w.j a va 2s .  co  m*/
 * 
 * @return ClusterManager
 * 
 * @throws IllegalStateException if a Grid Member (Cluster / Node) has
 * already started with in the current VM. Nebula supports only one Grid
 * Member per VM.
 */
public synchronized static ClusterManager startClusterManager() throws IllegalStateException {

    if (isInitialized()) {
        // A Grid Member has already started in this VM
        throw new IllegalStateException("A Grid Memeber Already Started in VM");
    }

    initializeDefaultExceptionHandler();

    StopWatch sw = new StopWatch();

    try {
        sw.start();
        log.info("ClusterManager Starting...");

        // Set Security Manager
        System.setSecurityManager(new SecurityManager());

        // Detect Configuration
        Properties config = ConfigurationSupport.detectClusterConfiguration();

        // Register with any Colombus Servers
        ClusterDiscoverySupport.registerColombus(config);

        clusterManager = true;

        log.debug("Starting up Spring Container...");

        applicationContext = new NebulaApplicationContext(CLUSTER_SPRING_CONTEXT, config);

        log.debug("Spring Container Started");

        return (ClusterManager) applicationContext.getBean("clusterManager");
    } finally {
        sw.stop();
        log.info("ClusterManager Started Up. " + sw.getLastTaskTimeMillis() + " ms");
    }

}

From source file:org.jason.mapmaker.repository.impl.HibernateGenericRepository.java

public void saveList(List<T> objectList) {

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();/*from   w  w  w .ja  v  a  2  s.c  o  m*/
    /*        for (T obj: objectList) {
    try {
        sessionFactory.getCurrentSession().save(obj);
    } catch (DataIntegrityViolationException ex) {
        // okay, so CVE extends RuntimeException, and you aren't supposed to catch RuntimeExceptions. Do
        // I want to roll back an entire save operation just because the USGS screwed up one particular
        // id number???
        System.out.println("Caught DataIntegrityViolationException");
    }
            }*/

    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    int i = 1;
    for (T obj : objectList) {

        session.save(obj);
        //sessionFactory.getCurrentSession().save(obj);
        i++;
        if (i % 100 == 0) {
            session.flush();
            session.clear();
            //sessionFactory.getCurrentSession().flush();
        }
    }

    tx.commit();
    session.close();

    stopWatch.stop();
    log.debug("Persisted " + i + " objects in " + stopWatch.getTotalTimeSeconds() + " seconds");

    //        Session session = sessionFactory.getCurrentSession();
    //        Transaction tx = session.beginTransaction();
    //        int i = 1;
    //        for (T obj : objectList) {
    //
    //            session.save(obj);
    //            //sessionFactory.getCurrentSession().save(obj);
    //            i++;
    //            if (i % 100 == 0) {
    //                session.flush();
    //                session.clear();
    //                //sessionFactory.getCurrentSession().flush();
    //            }
    //        }
    //        if (!tx.wasCommitted()) {
    //            tx.commit();
    //        }
    //sessionFactory.getCurrentSession().getTransaction().commit();
}

From source file:org.dd4t.core.filters.impl.DefaultLinkResolverFilter.java

protected void resolveComponent(GenericComponent component, GenericPage page) {

    StopWatch stopWatch = null;//from   w w  w . j  a va 2  s.  c o  m
    if (logger.isDebugEnabled()) {
        stopWatch = new StopWatch();
        stopWatch.start();
    }

    if (component != null) {
        // resolve regular content
        resolveMap(component.getContent());
        // resolve metadata
        resolveMap(component.getMetadata());
        /* don't resolve Component itself; 
         * this may very likely lead to performance issues when using
         * the experience manager.
         */
        // getLinkResolver().resolve(component, page);

    }

    if (logger.isDebugEnabled()) {
        stopWatch.stop();
        logger.debug("ResolveComponent for " + component.getId() + " finished in "
                + stopWatch.getTotalTimeMillis() + " ms");
    }
}

From source file:org.fracturedatlas.athena.helper.ticketfactory.manager.TicketFactoryManager.java

public List<Ticket> createTickets(PTicket pTicket) {
    String performanceId = (String) pTicket.getId();
    PTicket performance = athenaStage.get("performance", performanceId);

    //If the performace isn't found, throw a bad request
    if (performance == null) {
        throw new AthenaException("Performance with id [" + performanceId + "] was not found");
    }/*from w  w  w.  j  av a  2  s . co m*/

    StopWatch watch = new StopWatch();
    watch.start("gathering info");

    String chartId = performance.get("chartId");
    String eventId = performance.get("eventId");
    PTicket chart = athenaStage.get("chart", chartId);
    PTicket event = athenaStage.get("event", eventId);

    AthenaSearchConstraint sectionSearch = new AthenaSearchConstraint("chartId", Operator.EQUALS, chartId);
    AthenaSearch athenaSearch = new AthenaSearch.Builder(sectionSearch).build();
    logger.debug("Finding sections for chart [{}]", chartId);
    Collection<PTicket> sections = athenaStage.find("section", athenaSearch);
    logger.debug("Found [{}] sections", sections.size());

    ArrayList<Ticket> ticketsToCreate = new ArrayList<Ticket>();
    watch.stop();

    //for each section
    for (PTicket section : sections) {
        watch.start("section " + section.get("name"));
        Integer capacity = Integer.parseInt(section.get("capacity"));
        logger.debug("capacity of section [{}] is [{}]", section.getId(), capacity);
        for (int seatNum = 0; seatNum < capacity; seatNum++) {
            Ticket ticket = new Ticket(section, performance, event, INITIAL_STATE);
            ticketsToCreate.add(ticket);

        }
        watch.stop();
    }

    watch.start("creating tickets");
    List<Ticket> tickets = saveTickets(ticketsToCreate);
    watch.stop();
    logger.debug("{}", watch.prettyPrint());
    return tickets;
}

From source file:edu.isistan.carcha.lsa.LSARunner.java

/**
 * Discover traceability.//w w w .  j  a  v  a2  s .c o  m
 *
 * @param sspaceFile the sspace file
 * @return the traceability document
 * @throws IOException Signals that an I/O exception has occurred.
 */
private TraceabilityDocument discoverTraceability(File sspaceFile) throws IOException {

    TraceabilityDocument ret = new TraceabilityDocument(concerns, designDecision);
    List<TraceabilityLink> links = new ArrayList<TraceabilityLink>();

    StaticSemanticSpace sspace = new StaticSemanticSpace(sspaceFile);

    //build the document vector to compare sentences
    DocumentVectorBuilder builder = new DocumentVectorBuilder(sspace);

    StopWatch sw = new StopWatch();
    sw.start("LSA - Traceability discovery");

    int untracedCount = 0;
    for (Entity req : concerns) {
        //create vector1
        DoubleVector vector1 = builder.buildVector(
                new BufferedReader(new StringReader(req.getFormattedLabel())), new CompactSparseVector());

        boolean hasTrace = false;
        for (Entity arch : designDecision) {
            //create vector2
            DoubleVector vector2 = builder.buildVector(
                    new BufferedReader(new StringReader(arch.getFormattedLabel())), new CompactSparseVector());

            //Math round is WAY faster than DoubleFormat
            Double linkWeight = ((double) Math.round(Similarity.cosineSimilarity(vector1, vector2) * 100)
                    / 100);

            //add the edge between the two nodes including the calculated weight
            if (linkWeight > threshold) {
                links.add(new TraceabilityLink(req, arch, linkWeight));
                hasTrace = true;
            }
        }
        if (!hasTrace) {
            untracedCount++;
        }
    }
    sw.stop();
    logger.info(sw.prettyPrint());

    //save the traceability results like: untraced count, links, traced count, etc...
    ret.setLinks(links);
    ret.setUntracedConcernCount(untracedCount);
    ret.setTracedConcernCount(concerns.size() - untracedCount);
    return ret;
}

From source file:org.openmrs.module.diabetesmanagement.web.controller.SimulationFormController.java

/**
 * The onSubmit method receives the form/command object that was modified by the input form and
 * saves it to the database./*  w w w. j a  v a 2s.  c  o  m*/
 * 
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 * @param request Current servlet request.
 * @param response Current servlet response.
 * @param command Form object with request parameters bound onto it.
 * @param errors Holder without errors.
 * @return The prepared model and view, or null.
 * @throws Exception In case of errors.
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
    Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_PATIENTS);
    try {
        if (Context.isAuthenticated()) {
            StopWatch stopwatch = new StopWatch();
            ObjectOutputStream out = null;
            File f = null;
            File root = OpenmrsUtil.getDirectoryInApplicationDataDirectory("diabetesmanagement/simulation");
            String sessionId = request.getSession().getId() + "_";

            // Benchmarking the simulation model run
            Simulation sim = (Simulation) command;
            stopwatch.start();
            sim.runSimulation();
            stopwatch.stop();
            sim.setExecutionTime(stopwatch.getTotalTimeSeconds());

            // Serializing current results, if available
            if (sim.getResultsAvailableCurrent()) {
                // Current plasma glucose
                f = new File(root.getAbsolutePath(), sessionId + FILENAME_PLASMA_GLUCOSE_CURRENT);
                f.delete();
                out = new ObjectOutputStream(new FileOutputStream(f));
                out.writeObject(sim.getResultGlucoseCurrent());
                out.close();
                // Current plasma insulin
                f = new File(root.getAbsolutePath(), sessionId + FILENAME_PLASMA_INSULIN_CURRENT);
                f.delete();
                out = new ObjectOutputStream(new FileOutputStream(f));
                out.writeObject(sim.getResultInsulinCurrent());
                out.close();
                // Current meals
                if (sim.getMealsCurrent() != null) {
                    f = new File(root.getAbsolutePath(), sessionId + FILENAME_MEALS_CURRENT);
                    f.delete();
                    out = new ObjectOutputStream(new FileOutputStream(f));
                    out.writeObject(sim.getMealsCurrent());
                    out.close();
                }
                // Current insulin injections (1)
                if (sim.getInsulinInjections1() != null) {
                    f = new File(root.getAbsolutePath(), sessionId + FILENAME_INJECTIONS_1);
                    f.delete();
                    out = new ObjectOutputStream(new FileOutputStream(f));
                    out.writeObject(sim.getInsulinInjections1());
                    out.close();
                }
                // Current insulin injections (2)
                if (sim.getInsulinInjections2() != null) {
                    f = new File(root.getAbsolutePath(), sessionId + FILENAME_INJECTIONS_2);
                    f.delete();
                    out = new ObjectOutputStream(new FileOutputStream(f));
                    out.writeObject(sim.getInsulinInjections2());
                    out.close();
                }
            }

            // Serializing previous results, if available
            if (sim.getResultsAvailablePrevious()) {
                // Previous plasma glucose
                f = new File(root.getAbsolutePath(), sessionId + FILENAME_PLASMA_GLUCOSE_PREVIOUS);
                f.delete();
                out = new ObjectOutputStream(new FileOutputStream(f));
                out.writeObject(sim.getResultGlucosePrevious());
                out.close();
                // Previous plasma insulin
                f = new File(root.getAbsolutePath(), sessionId + FILENAME_PLASMA_INSULIN_PREVIOUS);
                f.delete();
                out = new ObjectOutputStream(new FileOutputStream(f));
                out.writeObject(sim.getResultInsulinPrevious());
                out.close();
                // Previous meals
                if (sim.getMealsPrevious() != null) {
                    f = new File(root.getAbsolutePath(), sessionId + FILENAME_MEALS_PREVIOUS);
                    f.delete();
                    out = new ObjectOutputStream(new FileOutputStream(f));
                    out.writeObject(sim.getMealsCurrent());
                    out.close();
                }
            }
        }
    } finally {
        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_PATIENTS);
    }

    return showForm(request, response, errors);
}