Example usage for org.apache.commons.lang.time StopWatch start

List of usage examples for org.apache.commons.lang.time StopWatch start

Introduction

In this page you can find the example usage for org.apache.commons.lang.time StopWatch start.

Prototype

public void start() 

Source Link

Document

Start the stopwatch.

This method starts a new timing session, clearing any previous values.

Usage

From source file:com.mothsoft.alexis.dao.DocumentDaoImpl.java

@SuppressWarnings("unchecked")
public Graph getRelatedTerms(final String queryString, final Long userId, final int howMany) {
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    final FullTextQuery fullTextQuery = this.buildFullTextQuery(queryString, userId, NO_DATE, NO_DATE, false,
            DocumentState.MATCHED_TO_TOPICS, FullTextQuery.ID);

    // find the specified number of terms from the most recent 100 documents
    // that match the query
    final Sort sort = new Sort(new SortField("creationDate", SortField.LONG, true));
    fullTextQuery.setSort(sort);/* www. j av  a  2  s  .c  o  m*/
    fullTextQuery.setFirstResult(0);
    fullTextQuery.setMaxResults(100);

    final List<Long> documentIds = new ArrayList<Long>(100);
    final List<Long> termIds = new ArrayList<Long>(100);

    final List<Object[]> results = fullTextQuery.list();

    for (final Object[] ith : results) {
        final Long id = (Long) ith[0];
        documentIds.add(id);
    }

    final Map<String, Node> nodes = new LinkedHashMap<String, Node>();
    final Node root = new Node(queryString, Boolean.TRUE);
    nodes.put(queryString, root);

    final Map<String, Edge> edges = new HashMap<String, Edge>();

    if (!documentIds.isEmpty()) {
        final Session session = (Session) this.em.getDelegate();
        final org.hibernate.SQLQuery termsQuery = session.createSQLQuery("SELECT term.id "
                + "        FROM document_term dt INNER JOIN term on term.id = dt.term_id "
                + "        WHERE dt.document_id IN (:documentIds) GROUP BY term.id ORDER BY SUM(dt.tf_idf) DESC");
        termsQuery.setParameterList("documentIds", documentIds);
        termsQuery.setMaxResults(100);
        termIds.addAll((List<Long>) termsQuery.list());
    }

    if (!documentIds.isEmpty() && !termIds.isEmpty()) {

        final Session session = (Session) this.em.getDelegate();
        final org.hibernate.SQLQuery associationsQuery = session.createSQLQuery(
                "SELECT CONCAT(a.term_value) term_a_value, CONCAT(b.term_value) term_b_value, SUM(da.association_weight) sum_weight "
                        + "      FROM document_association da "
                        + "      INNER JOIN term a ON da.term_a_id = a.id "
                        + "        AND a.part_of_speech NOT IN (1, 3, 18, 19, 25, 39, 40) "
                        + "        AND length(a.term_value) > 2 "
                        + "      INNER JOIN term b ON da.term_b_id = b.id "
                        + "        AND b.part_of_speech NOT IN (1, 3, 18, 19, 25, 39, 40) "
                        + "        AND length(b.term_value) > 2 "
                        + "      WHERE da.document_id IN (:documentIds) AND (da.term_a_id IN (:termIds) OR da.term_b_id IN (:termIds)) "
                        + "      GROUP BY a.id, b.id ORDER BY sum_weight DESC");
        associationsQuery.setParameterList("documentIds", documentIds);
        associationsQuery.setParameterList("termIds", termIds);
        associationsQuery.setMaxResults(howMany);

        final List<Object[]> relatedTermsResults = associationsQuery.list();

        final Set<String> aNodeKeys = new HashSet<String>();
        final Set<String> bNodeKeys = new HashSet<String>();

        for (final Object[] ith : relatedTermsResults) {
            final String a = (String) ith[0];
            final String b = (String) ith[1];

            if (!nodes.containsKey(a)) {
                final Node node = new Node(a);
                nodes.put(a, node);
            }

            if (!nodes.containsKey(b)) {
                final Node node = new Node(b);
                nodes.put(b, node);
            }

            if (a.equals(b)) {
                continue;
            }

            final String edgeKey = a + "||" + b;
            final String edgeKeyInverse = b + "||" + a;
            if (!edges.containsKey(edgeKey) && !edges.containsKey(edgeKeyInverse)) {
                final Node nodeA = nodes.get(a);
                final Node nodeB = nodes.get(b);

                aNodeKeys.add(a);
                bNodeKeys.add(b);

                final Edge edge = new Edge(nodeA, nodeB);
                edges.put(edgeKey, edge);
            }
        }

        // "orphan" handling, any b that is not also an a needs an edge from
        // root
        final Set<String> orphanKeys = new HashSet<String>();
        orphanKeys.addAll(bNodeKeys);
        orphanKeys.removeAll(aNodeKeys);

        for (final String orphanKey : orphanKeys) {
            final Node orphan = nodes.get(orphanKey);
            final Edge orphanToParent = new Edge(root, orphan);
            edges.put(root.getName() + "||" + orphan.getName(), orphanToParent);
        }
    }

    final List<Node> nodeList = new ArrayList<Node>(nodes.size());
    // keep root as first element
    nodes.remove(root.getName());
    nodeList.add(root);
    nodeList.addAll(nodes.values());

    final Graph graph = new Graph(nodeList, new ArrayList<Edge>(edges.values()));

    stopWatch.stop();
    logger.info("Related terms search took: " + stopWatch.toString());

    return graph;
}

From source file:com.datascience.gal.service.Service.java

/**
 * TODO: make async w/ a callback call to run the iterative ds algorithm
 * //www .j  av a2s .com
 * @return success message
 */
@GET
@Path("computeBlocking")
@Produces(MediaType.APPLICATION_JSON)
public Response computeDsBlocking(@QueryParam("iterations") String iterations, @QueryParam("id") String idstr) {
    int its = 1;
    long time = 0;

    String id = 0 + "";
    if (null == idstr) {
        logger.info("no id input, using id 0");
    } else {
        id = idstr;
    }

    try {
        setup(context);
        DawidSkene ds = dscache.getDawidSkene(id);

        StopWatch sw = new StopWatch();
        sw.start();
        its = Math.max(1, null == iterations ? 1 : Integer.parseInt(iterations));
        ds.estimate(its);
        sw.stop();
        time = sw.getTime();
        String message = "performed ds iteration " + its + " times, took: " + time + "ms.";
        logger.info(message);
        dscache.insertDawidSkene(ds);

        return Response.ok(message).build();

    } catch (IOException e) {
        logger.error("ioexception: " + e.getLocalizedMessage());
    } catch (ClassNotFoundException e) {
        logger.error("class not found exception: " + e.getLocalizedMessage());
    } catch (SQLException e) {
        logger.error("sql exception: " + e.getLocalizedMessage());
    } catch (Exception e) {
        logger.error(e.getLocalizedMessage());
    }
    return Response.status(500).build();
}

From source file:com.auditbucket.test.functional.TestAuditIntegration.java

private void doSearchTests(int auditCount, ArrayList<Long> list, StopWatch watch) throws Exception {
    int fortress;
    int searchLoops = 200;
    int search = 0;
    int totalSearchRequests = 0;

    watch.start();

    do {/*www  . j  a v  a  2s  . c  o m*/
        fortress = 0;
        do {
            int x = 1;
            do {
                int random = (int) (Math.random() * ((auditCount) + 1));
                if (random == 0)
                    random = 1;

                MetaHeader header = trackService.findByCallerRefFull(list.get(fortress), "CompanyNode",
                        "ABC" + random);
                assertNotNull("ABC" + random, header);
                assertNotNull("Looks like ab-search is not sending back results", header.getSearchKey());
                //TrackLog when = trackService.getLastAuditLog(header);
                TrackLog trackLog = trackService.getLastLog(header);
                assertNotNull(trackLog);

                //logger.info(header.getMetaKey() + " - " + when);
                assertTrue("fortress " + fortress + " run " + x + " header " + header.getMetaKey() + " - "
                        + trackLog.getId(), trackLog.isIndexed());
                String result = doEsFieldQuery(header.getIndexName(), MetaSearchSchema.META_KEY,
                        header.getMetaKey(), 1);
                totalSearchRequests++;
                validateResultFieds(result);

                x++;
            } while (x < auditCount);
            fortress++;
        } while (fortress < fortressMax);
        search++;
    } while (search < searchLoops);

    watch.stop();
    double end = watch.getTime() / 1000d;
    logger.info("Total Search Requests = " + totalSearchRequests + ". Total time for searches " + end
            + " avg requests per second = " + totalSearchRequests / end);
}

From source file:eagle.service.generic.GenericEntityServiceResource.java

/**
 * @param serviceName entity service name
 * @return GenericServiceAPIResponseEntity
 *///from www .  j  av a2 s. c o m
@POST
@Path(ROWKEY_PATH)
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public GenericServiceAPIResponseEntity search(InputStream inputStream,
        @QueryParam("serviceName") String serviceName) {
    GenericServiceAPIResponseEntity response = new GenericServiceAPIResponseEntity();
    Map<String, Object> meta = new HashMap<>();
    DataStorage dataStorage;

    StopWatch stopWatch = null;
    try {
        if (serviceName == null)
            throw new IllegalArgumentException("serviceName is null");

        final List<String> values = unmarshalAsStringlist(inputStream);
        final RowkeyQueryStatement queryStatement = new RowkeyQueryStatement(values, serviceName);

        stopWatch = new StopWatch();
        stopWatch.start();
        dataStorage = DataStorageManager.getDataStorageByEagleConfig();
        if (dataStorage == null) {
            LOG.error("Data storage is null");
            throw new IllegalDataStorageException("Data storage is null");
        }
        QueryResult<?> result = queryStatement.execute(dataStorage);
        if (result.isSuccess()) {
            meta.put(FIRST_TIMESTAMP, result.getFirstTimestamp());
            meta.put(LAST_TIMESTAMP, result.getLastTimestamp());
            meta.put(TOTAL_RESULTS, result.getSize());
            meta.put(ELAPSEDMS, stopWatch.getTime());
            response.setObj(result.getData());
            response.setType(result.getEntityType());
            response.setSuccess(true);
            response.setMeta(meta);
            return response;
        }
    } catch (Exception e) {
        response.setException(e);
        LOG.error(e.getMessage(), e);
    } finally {
        if (stopWatch != null)
            stopWatch.stop();
    }
    return response;
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java

private List<SingleTestResult> runNormalTests(List<String> tests) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    int counter = 0;
    int size = tests.size();
    List<SingleTestResult> failing = new ArrayList<SingleTestResult>();
    for (String testName : tests) {
        counter++;//w w w. ja  v  a  2  s.c o m
        String duration = DurationFormatUtils.formatDurationHMS(stopWatch.getTime());
        logger.info(duration + " (" + counter + " / " + size + ") Running test:  " + testName);
        MutationTestRunnable runnable = getTestRunnable(testName);
        testStart(testName);

        runWithTimeout(runnable);
        SingleTestResult result = runnable.getResult();
        logger.debug(result.getTestMessage());
        if (!result.hasPassed()) {
            failing.add(result);
            logger.warn("Test has not passed " + testName);
        }
        testEnd(testName);
    }
    return failing;
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

public void storeEnvelopes(long folderId, Folder jxFolder, Message[] jxMessages) throws PortalException {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    try {/*from w  w  w  . ja va2 s  .  c  om*/
        FetchProfile fetchProfile = new FetchProfile();

        fetchProfile.add(UIDFolder.FetchProfileItem.ENVELOPE);
        fetchProfile.add(UIDFolder.FetchProfileItem.FLAGS);
        fetchProfile.add(UIDFolder.FetchProfileItem.UID);

        jxFolder.fetch(jxMessages, fetchProfile);

        for (Message jxMessage : jxMessages) {
            String sender = InternetAddressUtil.toString(jxMessage.getFrom());
            String to = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.TO));
            String cc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.CC));
            String bcc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.BCC));
            Date sentDate = jxMessage.getSentDate();
            String subject = jxMessage.getSubject();
            String flags = getFlags(jxMessage);
            long remoteMessageId = getUID(jxFolder, jxMessage);
            String contentType = jxMessage.getContentType();

            try {
                MessageLocalServiceUtil.getMessage(folderId, remoteMessageId);
            } catch (NoSuchMessageException nsme) {
                MessageLocalServiceUtil.addMessage(_user.getUserId(), folderId, sender, to, cc, bcc, sentDate,
                        subject, StringPool.BLANK, flags, remoteMessageId, contentType);
            }
        }

        com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.getFolder(folderId);

        FolderLocalServiceUtil.updateFolder(folderId, folder.getFullName(), folder.getDisplayName(),
                jxFolder.getMessageCount());
    } catch (MessagingException me) {
        throw new MailException(me);
    }

    if (_log.isDebugEnabled()) {
        stopWatch.stop();

        _log.debug("Downloaded " + jxMessages.length + " messages from folder " + jxFolder.getFullName()
                + " completed in " + stopWatch.getTime() + " ms");
    }
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java

/**
 * Runs the tests without applying any changes. This method is used to check
 * if the driver works correctly./*ww w.  j a  va2s .  c  o m*/
 */
private void runNormalTests() {
    logger.info("Running tests of project " + configuration.getProjectPrefix());
    // addMutationTestListener(new AdabuListener());
    addListenersFromProperty();
    List<String> allTests = getAllTests();
    int counter = 0;
    int size = allTests.size();
    timeout = Integer.MAX_VALUE;
    boolean allPass = true;
    List<SingleTestResult> failing = new ArrayList<SingleTestResult>();
    testsStart();
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    coldRun(allTests);
    for (String testName : allTests) {
        counter++;
        logger.info(DurationFormatUtils.formatDurationHMS(stopWatch.getTime()) + " (" + counter + " / " + size
                + ") Running test:  " + testName);
        MutationTestRunnable runnable = getTestRunnable(testName);
        testStart(testName);
        stopWatch.reset();
        stopWatch.start();
        runWithTimeout(runnable);
        SingleTestResult result = runnable.getResult();
        logger.info("Test took " + DurationFormatUtils.formatDurationHMS(stopWatch.getTime()) + " " + testName);
        if (!result.hasPassed()) {
            allPass = false;
            failing.add(result);
            logger.warn("Test has not passed " + result.getTestMessage());
        }
        testEnd(testName);
    }
    testsEnd();
    if (allPass) {
        String message = "All " + allTests.size() + " tests passed ";
        System.out.println(message);
        logger.info(message);
    } else {
        logger.warn("Not all tests passed");
        for (SingleTestResult str : failing) {
            logger.warn(str.getTestMessage().getTestCaseName() + ": " + str.getTestMessage());
        }
        File outFile = new File(configuration.getOutputDir(), "/failed-tests.xml");
        XmlIo.toXML(failing, outFile);
    }
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java

protected long runWithTimeout(MutationTestRunnable r) {
    long[] preIds = threadMxBean.getAllThreadIds();
    FutureTask<Object> future = new FutureTask<Object>(Executors.callable(r));
    Thread thread = new Thread(future);
    thread.setDaemon(true);/*from  w  w  w.java  2s  . c  o  m*/
    logger.debug("Start  test: ");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    thread.start();
    String exceptionMessage = null;
    Throwable capturedThrowable = null;
    try {
        future.get(timeout, TimeUnit.SECONDS);
        logger.debug("Second timeout");
    } catch (InterruptedException e) {
        capturedThrowable = e;
    } catch (ExecutionException e) {
        capturedThrowable = e;
    } catch (TimeoutException e) {
        exceptionMessage = JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE + "Mutation causes test timeout";
        capturedThrowable = e;
    } catch (Throwable t) {
        capturedThrowable = t;
    } finally {
        if (capturedThrowable != null) {
            if (exceptionMessage == null) {
                exceptionMessage = "Exception caught during test execution.";
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            capturedThrowable.printStackTrace(new PrintStream(out));
            logger.debug(
                    "Setting test failed. Message: " + exceptionMessage + " Exception " + capturedThrowable);
            r.setFailed(exceptionMessage, capturedThrowable);
        }
    }
    if (!future.isDone()) {
        r.setFailed(JavalancheMessages.MUTATION_TIME_LIMIT_MESSAGE
                + "Mutated Thread is still running after timeout.", null);
        switchOfMutation(future);
    }
    stopWatch.stop();
    if (!checkAllFinished(preIds)) {
        if (configuration.useThreadStop()) {
            stopThreads(preIds);
        } else {
            shutDown(r, stopWatch);
        }
    }
    logger.debug("End timed test, it took " + stopWatch.getTime() + " ms");
    return stopWatch.getTime();
}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java

/**
 * Runs given test in a new thread with specified timeout
 * (DEFAULT_TIMEOUT_IN_SECONDS) and stores the results in given testResult.
 * /*from   w ww  .  ja  va2s . c  o  m*/
 * @param r
 *            the test to be run
 * @return the time needed for executing the test
 */
protected long runWithTimeoutOld(MutationTestRunnable r) {
    // ArrayList<Thread> threadsPre = ThreadUtil.getThreads();
    ExecutorService service = Executors.newSingleThreadExecutor();
    Future<?> future = service.submit(r);
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    service.shutdown();
    String exceptionMessage = null;
    Throwable capturedThrowable = null;
    try {
        logger.debug("Start  test: ");
        boolean terminated = service.awaitTermination(timeout, TimeUnit.SECONDS);
        logger.debug("First timeout");
        long time1 = stopWatch.getTime();
        if (!terminated) {
            service.shutdownNow();
        }
        future.get(1, TimeUnit.SECONDS);
        logger.debug("Second timeout");
        long time2 = stopWatch.getTime();
        if (time2 - time1 > 1000) {
            logger.info("Process got some extra time: " + (time2 - time1) + "  " + time2);
        }
        future.cancel(true);

    } catch (InterruptedException e) {
        capturedThrowable = e;
    } catch (ExecutionException e) {
        capturedThrowable = e;
    } catch (TimeoutException e) {
        exceptionMessage = "Mutation causes test timeout";
        capturedThrowable = e;
    } catch (Throwable t) {
        capturedThrowable = t;
    } finally {
        if (capturedThrowable != null) {
            if (exceptionMessage == null) {
                exceptionMessage = "Exception caught during test execution.";
            }
            r.setFailed(exceptionMessage, capturedThrowable);
        }
    }
    if (!future.isDone()) {
        r.setFailed("Mutated Thread is still running after timeout.", null);
        switchOfMutation(future);
    }
    stopWatch.stop();

    if (!r.hasFinished()) {
        shutDown(r, stopWatch);
    }
    logger.debug("End timed test, it took " + stopWatch.getTime() + " ms");
    return stopWatch.getTime();
}

From source file:com.ecyrd.jspwiki.ReferenceManager.java

/**
 *  Serializes hashmaps to disk.  The format is private, don't touch it.
 *//*w ww.j  av a2s  .co  m*/
private synchronized void serializeToDisk() {
    ObjectOutputStream out = null;

    try {
        StopWatch sw = new StopWatch();
        sw.start();

        File f = new File(m_engine.getWorkDir(), SERIALIZATION_FILE);

        out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(f)));

        out.writeLong(serialVersionUID);
        out.writeLong(System.currentTimeMillis()); // Timestamp
        out.writeObject(m_refersTo);
        out.writeObject(m_referredBy);

        out.close();

        sw.stop();

        log.debug("serialization done - took " + sw);
    } catch (IOException e) {
        log.error("Unable to serialize!");

        try {
            if (out != null)
                out.close();
        } catch (IOException ex) {
        }
    }
}