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

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

Introduction

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

Prototype

public long getTime() 

Source Link

Document

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.

Usage

From source file:org.apache.archiva.scheduler.repository.DefaultRepositoryArchivaTaskScheduler.java

@PostConstruct
public void startup() throws ArchivaException {

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();/* w ww.ja  v a2  s  . co  m*/

    archivaConfiguration.addListener(this);

    List<ManagedRepositoryConfiguration> repositories = archivaConfiguration.getConfiguration()
            .getManagedRepositories();

    RepositorySession repositorySession = repositorySessionFactory.createSession();
    try {
        MetadataRepository metadataRepository = repositorySession.getRepository();
        for (ManagedRepositoryConfiguration repoConfig : repositories) {
            if (repoConfig.isScanned()) {
                try {
                    scheduleRepositoryJobs(repoConfig);
                } catch (SchedulerException e) {
                    throw new ArchivaException("Unable to start scheduler: " + e.getMessage(), e);
                }

                try {
                    if (!isPreviouslyScanned(repoConfig, metadataRepository)) {
                        queueInitialRepoScan(repoConfig);
                    }
                } catch (MetadataRepositoryException e) {
                    log.warn(
                            "Unable to determine if a repository is already scanned, skipping initial scan: {}",
                            e.getMessage(), e);
                }
            }
        }
    } finally {
        repositorySession.close();
    }

    stopWatch.stop();
    log.info("Time to initalize DefaultRepositoryArchivaTaskScheduler: {} ms", stopWatch.getTime());
}

From source file:org.apache.archiva.web.startup.SecuritySynchronization.java

private void executeEnvironmentChecks() throws ArchivaException {
    if ((checkers == null) || CollectionUtils.isEmpty(checkers.values())) {
        throw new ArchivaException("Unable to initialize the Redback Security Environment, "
                + "no Environment Check components found.");
    }//from w w w. j  a v a  2s.c  o  m

    StopWatch stopWatch = new StopWatch();
    stopWatch.reset();
    stopWatch.start();

    List<String> violations = new ArrayList<>();

    for (Entry<String, EnvironmentCheck> entry : checkers.entrySet()) {
        EnvironmentCheck check = entry.getValue();
        List<String> v = new ArrayList<>();
        check.validateEnvironment(v);
        log.info("Environment Check: {} -> {} violation(s)", entry.getKey(), v.size());
        for (String s : v) {
            violations.add("[" + entry.getKey() + "] " + s);
        }
    }

    if (CollectionUtils.isNotEmpty(violations)) {
        StringBuilder msg = new StringBuilder();
        msg.append("EnvironmentCheck Failure.\n");
        msg.append("======================================================================\n");
        msg.append(" ENVIRONMENT FAILURE !! \n");
        msg.append("\n");

        for (String violation : violations) {
            msg.append(violation).append("\n");
        }

        msg.append("\n");
        msg.append("======================================================================");
        log.error(msg.toString());

        throw new ArchivaException("Unable to initialize Redback Security Environment, [" + violations.size()
                + "] violation(s) encountered, See log for details.");
    }

    stopWatch.stop();
    log.info("time to execute all EnvironmentCheck: {} ms", stopWatch.getTime());
}

From source file:org.apache.cocoon.servlet.CocoonServlet.java

/**
 * Process the specified <code>HttpServletRequest</code> producing output
 * on the specified <code>HttpServletResponse</code>.
 *//*from ww  w.  j a  v  a 2 s .c o m*/
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    /* HACK for reducing class loader problems.                                     */
    /* example: xalan extensions fail if someone adds xalan jars in tomcat3.2.1/lib */
    if (this.initClassLoader) {
        try {
            Thread.currentThread().setContextClassLoader(this.classLoader);
        } catch (Exception e) {
        }
    }

    // used for timing the processing
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    // add the cocoon header timestamp
    if (this.showCocoonVersion) {
        res.addHeader("X-Cocoon-Version", Constants.VERSION);
    }

    // get the request (wrapped if contains multipart-form data)
    HttpServletRequest request;
    try {
        if (this.enableUploads) {
            request = requestFactory.getServletRequest(req);
        } else {
            request = req;
        }
    } catch (Exception e) {
        if (getLogger().isErrorEnabled()) {
            getLogger().error("Problem with Cocoon servlet", e);
        }

        manageException(req, res, null, null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Problem in creating the Request", null, null, e);
        return;
    }

    // Get the cocoon engine instance

    if (reloadCocoon(request.getPathInfo(), request.getParameter(Constants.RELOAD_PARAM))) {
        disposeCocoon();
        initLogger();
        createCocoon();
    }

    // Check if cocoon was initialized
    if (this.cocoon == null) {
        manageException(request, res, null, null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Initialization Problem", null /* "Cocoon was not initialized" */,
                null /* "Cocoon was not initialized, cannot process request" */, this.exception);
        return;
    }

    // We got it... Process the request
    String uri = request.getServletPath();
    if (uri == null) {
        uri = "";
    }
    String pathInfo = request.getPathInfo();
    if (pathInfo != null) {
        // VG: WebLogic fix: Both uri and pathInfo starts with '/'
        // This problem exists only in WL6.1sp2, not in WL6.0sp2 or WL7.0b.
        if (uri.length() > 0 && uri.charAt(0) == '/') {
            uri = uri.substring(1);
        }
        uri += pathInfo;
    }

    if (uri.length() == 0) {
        /* empty relative URI
         -> HTTP-redirect from /cocoon to /cocoon/ to avoid
            StringIndexOutOfBoundsException when calling
            "".charAt(0)
           else process URI normally
        */
        String prefix = request.getRequestURI();
        if (prefix == null) {
            prefix = "";
        }

        res.sendRedirect(res.encodeRedirectURL(prefix + "/"));
        return;
    }

    String contentType = null;
    ContextMap ctxMap = null;

    Environment env;
    try {
        if (uri.charAt(0) == '/') {
            uri = uri.substring(1);
        }
        // Pass uri into environment without URLDecoding, as it is already decoded.
        env = getEnvironment(uri, request, res);
    } catch (Exception e) {
        if (getLogger().isErrorEnabled()) {
            getLogger().error("Problem with Cocoon servlet", e);
        }

        manageException(request, res, null, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Problem in creating the Environment", null, null, e);
        return;
    }

    try {
        try {
            // Initialize a fresh log context containing the object model: it
            // will be used by the CocoonLogFormatter
            ctxMap = ContextMap.getCurrentContext();
            // Add thread name (default content for empty context)
            String threadName = Thread.currentThread().getName();
            ctxMap.set("threadName", threadName);
            // Add the object model
            ctxMap.set("objectModel", env.getObjectModel());
            // Add a unique request id (threadName + currentTime
            ctxMap.set("request-id", threadName + System.currentTimeMillis());

            if (this.cocoon.process(env)) {
                contentType = env.getContentType();
            } else {
                // We reach this when there is nothing in the processing change that matches
                // the request. For example, no matcher matches.
                getLogger().fatalError("The Cocoon engine failed to process the request.");
                manageException(request, res, env, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Request Processing Failed", "Cocoon engine failed in process the request",
                        "The processing engine failed to process the request. This could be due to lack of matching or bugs in the pipeline engine.",
                        null);
                return;
            }
        } catch (ResourceNotFoundException e) {
            if (getLogger().isDebugEnabled()) {
                getLogger().warn(e.getMessage(), e);
            } else if (getLogger().isWarnEnabled()) {
                getLogger().warn(e.getMessage());
            }

            manageException(request, res, env, uri, HttpServletResponse.SC_NOT_FOUND, "Resource Not Found",
                    "Resource Not Found",
                    "The requested resource \"" + request.getRequestURI() + "\" could not be found", e);
            return;

        } catch (ConnectionResetException e) {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug(e.toString(), e);
            } else if (getLogger().isWarnEnabled()) {
                getLogger().warn(e.toString());
            }

        } catch (IOException e) {
            // Tomcat5 wraps SocketException into ClientAbortException which extends IOException.
            if (getLogger().isDebugEnabled()) {
                getLogger().debug(e.toString(), e);
            } else if (getLogger().isWarnEnabled()) {
                getLogger().warn(e.toString());
            }

        } catch (Exception e) {
            if (getLogger().isErrorEnabled()) {
                getLogger().error("Internal Cocoon Problem", e);
            }

            manageException(request, res, env, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Internal Server Error", null, null, e);
            return;
        }

        stopWatch.stop();
        String timeString = null;
        if (getLogger().isInfoEnabled()) {
            timeString = processTime(stopWatch.getTime());
            getLogger().info("'" + uri + "' " + timeString);
        }

        if (contentType != null && contentType.equals("text/html")) {
            String showTime = request.getParameter(Constants.SHOWTIME_PARAM);
            boolean show = this.showTime;
            if (showTime != null) {
                show = !showTime.equalsIgnoreCase("no");
            }
            if (show) {
                if (timeString == null) {
                    timeString = processTime(stopWatch.getTime());
                }
                boolean hide = this.hiddenShowTime;
                if (showTime != null) {
                    hide = showTime.equalsIgnoreCase("hide");
                }
                ServletOutputStream out = res.getOutputStream();
                out.print((hide) ? "<!-- " : "<p>");
                out.print(timeString);
                out.println((hide) ? " -->" : "</p>");
            }
        }
    } finally {
        if (ctxMap != null) {
            ctxMap.clear();
        }

        try {
            if (request instanceof MultipartHttpServletRequest) {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("Deleting uploaded file(s).");
                }
                ((MultipartHttpServletRequest) request).cleanup();
            }
        } catch (IOException e) {
            getLogger().error("Cocoon got an Exception while trying to cleanup the uploaded files.", e);
        }

        /*
         * Servlet Specification 2.2, 6.5 Closure of Response Object:
         *
         *   A number of events can indicate that the servlet has provided all of the
         *   content to satisfy the request and that the response object can be
         *   considered to be closed. The events are:
         *     o The termination of the service method of the servlet.
         *     o When the amount of content specified in the setContentLength method
         *       of the response has been written to the response.
         *     o The sendError method is called.
         *     o The sendRedirect method is called.
         *   When a response is closed, all content in the response buffer, if any remains,
         *   must be immediately flushed to the client.
         *
         * Due to the above, out.flush() and out.close() are not necessary, and sometimes
         * (if sendError or sendRedirect were used) request may be already closed.
         */
    }
}

From source file:org.apache.cocoon.servlet.RequestProcessor.java

/**
 * Process the specified <code>HttpServletRequest</code> producing output
 * on the specified <code>HttpServletResponse</code>.
 *//*w w w  .  j  a v a  2  s.  c  om*/
public void service(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
    // used for timing the processing
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    // add the cocoon version header stamp
    if (this.servletSettings.isShowVersion()) {
        res.addHeader("X-Cocoon-Version", Constants.VERSION);
    }

    // We got it... Process the request
    final String uri = getURI(request, res);
    if (uri == null) {
        // a redirect occured, so we are finished
        return;
    }

    Environment env;
    try {
        // Pass uri into environment without URLDecoding, as it is already decoded.
        env = getEnvironment(uri, request, res);
    } catch (Exception e) {
        if (getLogger().isErrorEnabled()) {
            getLogger().error("Problem with Cocoon servlet", e);
        }

        if (rethrowExceptions()) {
            throw new ServletException(e);
        }

        RequestUtil.manageException(request, res, null, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Problem in creating the Environment", null, null, e, this.servletSettings, getLogger(), this);
        return;
    }

    String contentType = null;
    try {
        if (process(env)) {
            contentType = env.getContentType();
        } else {
            // We reach this when there is nothing in the processing chain that matches
            // the request. For example, no matcher matches.
            getLogger().fatal("The Cocoon engine failed to process the request.");

            if (rethrowExceptions()) {
                throw new ServletException("The Cocoon engine failed to process the request.");
            }

            RequestUtil.manageException(request, res, env, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Request Processing Failed", "Cocoon engine failed in processing the request",
                    "The processing engine failed to process the request. This could be due to lack of matching or bugs in the pipeline engine.",
                    null, this.servletSettings, getLogger(), this);
            return;
        }
    } catch (ResourceNotFoundException e) {
        if (getLogger().isDebugEnabled()) {
            getLogger().warn(e.getMessage(), e);
        } else if (getLogger().isWarnEnabled()) {
            getLogger().warn(e.getMessage());
        }

        if (rethrowExceptions()) {
            throw new ServletException(e);
        }

        RequestUtil.manageException(request, res, env, uri, HttpServletResponse.SC_NOT_FOUND,
                "Resource Not Found", "Resource Not Found",
                "The requested resource \"" + request.getRequestURI() + "\" could not be found", e,
                this.servletSettings, getLogger(), this);
        return;

    } catch (ConnectionResetException e) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug(e.toString(), e);
        } else if (getLogger().isWarnEnabled()) {
            getLogger().warn(e.toString());
        }

    } catch (IOException e) {
        // Tomcat5 wraps SocketException into ClientAbortException which extends IOException.
        if (getLogger().isDebugEnabled()) {
            getLogger().debug(e.toString(), e);
        } else if (getLogger().isWarnEnabled()) {
            getLogger().warn(e.toString());
        }

    } catch (Exception e) {
        if (getLogger().isErrorEnabled()) {
            getLogger().error("Internal Cocoon Problem", e);
        }

        if (rethrowExceptions()) {
            throw new ServletException(e);
        }

        RequestUtil.manageException(request, res, env, uri, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Internal Server Error", null, null, e, this.servletSettings, getLogger(), this);
        return;
    }

    stopWatch.stop();
    String timeString = null;
    if (getLogger().isInfoEnabled()) {
        timeString = processTime(stopWatch.getTime());
        getLogger().info("'" + uri + "' " + timeString);
    }

    if (contentType != null && contentType.equals("text/html")) {
        String showTime = request.getParameter(Constants.SHOWTIME_PARAM);
        boolean show = this.servletSettings.isShowTime();
        if (showTime != null) {
            show = !showTime.equalsIgnoreCase("no");
        }
        if (show) {
            if (timeString == null) {
                timeString = processTime(stopWatch.getTime());
            }
            boolean hide = this.servletSettings.isHideShowTime();
            if (showTime != null) {
                hide = showTime.equalsIgnoreCase("hide");
            }
            ServletOutputStream out = res.getOutputStream();
            out.print((hide) ? "<!-- " : "<p>");
            out.print(timeString);
            out.println((hide) ? " -->" : "</p>");
        }
    }

    /*
     * Servlet Specification 2.2, 6.5 Closure of Response Object:
     *
     *   A number of events can indicate that the servlet has provided all of the
     *   content to satisfy the request and that the response object can be
     *   considered to be closed. The events are:
     *     o The termination of the service method of the servlet.
     *     o When the amount of content specified in the setContentLength method
     *       of the response has been written to the response.
     *     o The sendError method is called.
     *     o The sendRedirect method is called.
     *   When a response is closed, all content in the response buffer, if any remains,
     *   must be immediately flushed to the client.
     *
     * Due to the above, out.flush() and out.close() are not necessary, and sometimes
     * (if sendError or sendRedirect were used) request may be already closed.
     */
}

From source file:org.apache.crunch.impl.mr.exec.MRExecutorIT.java

/**
 * Tests that the pipeline should be stopped immediately when one of the jobs
 * get failed. The rest of running jobs should be killed.
 *//*from  w w w  . j a v a 2  s . c o m*/
@Test
public void testStopPipelineImmediatelyOnJobFailure() throws Exception {
    String inPath = tmpDir.copyResourceFileName("shakes.txt");
    MRPipeline pipeline = new MRPipeline(MRExecutorIT.class);

    // Issue two jobs that sleep forever.
    PCollection<String> in = pipeline.read(From.textFile(inPath));
    for (int i = 0; i < 2; i++) {
        in.count().values().parallelDo(new SleepForeverFn(), longs())
                .write(To.textFile(tmpDir.getPath("out_" + i)));
    }
    MRPipelineExecution exec = pipeline.runAsync();

    // Wait until both of the two jobs are submitted.
    List<MRJob> jobs = exec.getJobs();
    assertEquals(2, jobs.size());
    StopWatch watch = new StopWatch();
    watch.start();
    int numOfJobsSubmitted = 0;
    while (numOfJobsSubmitted < 2 && watch.getTime() < 10000) {
        numOfJobsSubmitted = 0;
        for (MRJob job : jobs) {
            if (job.getJobState() == MRJob.State.RUNNING) {
                numOfJobsSubmitted++;
            }
        }
        Thread.sleep(100);
    }
    assertEquals(2, numOfJobsSubmitted);

    // Kill one of them.
    Job job0 = jobs.get(0).getJob();
    job0.killJob();

    // Expect the pipeline exits and the other job is killed.
    StopWatch watch2 = new StopWatch();
    watch2.start();
    Job job1 = jobs.get(1).getJob();
    while (!job1.isComplete() && watch2.getTime() < 10000) {
        Thread.sleep(100);
    }
    assertTrue(job1.isComplete());
    assertEquals(PipelineExecution.Status.FAILED, exec.getStatus());
}

From source file:org.apache.eagle.alert.engine.serialization.PartitionedEventSerializerTest.java

@SuppressWarnings("deprecation")
@Test/*from  w w w  .j  ava  2s  .co m*/
public void testPartitionEventSerializationEfficiency() throws IOException {
    PartitionedEvent partitionedEvent = MockSampleMetadataFactory
            .createPartitionedEventGroupedByName("sampleStream", System.currentTimeMillis());
    ;
    PartitionedEventSerializerImpl serializer = new PartitionedEventSerializerImpl(
            MockSampleMetadataFactory::createSampleStreamDefinition);

    int count = 100000;
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    int i = 0;
    while (i < count) {
        ByteArrayDataOutput dataOutput1 = ByteStreams.newDataOutput();
        serializer.serialize(partitionedEvent, dataOutput1);
        byte[] serializedBytes = dataOutput1.toByteArray();
        PartitionedEvent deserializedEvent = serializer.deserialize(ByteStreams.newDataInput(serializedBytes));
        Assert.assertEquals(partitionedEvent, deserializedEvent);
        i++;
    }
    stopWatch.stop();
    LOG.info("Cached Stream: {} ms", stopWatch.getTime());
    stopWatch.reset();
    PartitionedEventSerializerImpl compressSerializer = new PartitionedEventSerializerImpl(
            MockSampleMetadataFactory::createSampleStreamDefinition, true);
    i = 0;
    stopWatch.start();
    while (i < count) {
        byte[] serializedBytesCompressed = compressSerializer.serialize(partitionedEvent);
        PartitionedEvent deserializedEventCompressed = compressSerializer
                .deserialize(serializedBytesCompressed);
        Assert.assertEquals(partitionedEvent, deserializedEventCompressed);
        i++;
    }
    stopWatch.stop();
    LOG.info("Compressed Cached Stream: {} ms", stopWatch.getTime());
    stopWatch.reset();

    i = 0;
    stopWatch.start();
    while (i < count) {
        PartitionedEventDigestSerializer serializer2 = new PartitionedEventDigestSerializer(
                MockSampleMetadataFactory::createSampleStreamDefinition);
        ByteArrayDataOutput dataOutput2 = ByteStreams.newDataOutput();
        serializer2.serialize(partitionedEvent, dataOutput2);
        byte[] serializedBytes2 = dataOutput2.toByteArray();
        ByteArrayDataInput dataInput2 = ByteStreams.newDataInput(serializedBytes2);
        PartitionedEvent deserializedEvent2 = serializer2.deserialize(dataInput2);
        Assert.assertEquals(partitionedEvent, deserializedEvent2);
        i++;
    }
    stopWatch.stop();
    LOG.info("Cached Stream&Partition: {} ms", stopWatch.getTime());
    stopWatch.reset();
    i = 0;
    stopWatch.start();
    while (i < count) {
        byte[] javaSerialization = new DefaultSerializationDelegate().serialize(partitionedEvent);
        PartitionedEvent javaSerializedEvent = (PartitionedEvent) new DefaultSerializationDelegate()
                .deserialize(javaSerialization);
        Assert.assertEquals(partitionedEvent, javaSerializedEvent);
        i++;
    }
    stopWatch.stop();
    LOG.info("Java Native: {} ms", stopWatch.getTime());
    stopWatch.reset();
    i = 0;
    stopWatch.start();
    Kryo kryo = new DefaultKryoFactory.KryoSerializableDefault();
    while (i < count) {
        Output output = new Output(10000);
        kryo.writeClassAndObject(output, partitionedEvent);
        byte[] kryoBytes = output.toBytes();
        Input input = new Input(kryoBytes);
        PartitionedEvent kryoDeserializedEvent = (PartitionedEvent) kryo.readClassAndObject(input);
        Assert.assertEquals(partitionedEvent, kryoDeserializedEvent);
        i++;
    }
    stopWatch.stop();
    LOG.info("Kryo: {} ms", stopWatch.getTime());
}

From source file:org.apache.eagle.alert.engine.sorter.StreamSortHandlerTest.java

public void testWithUnsortedEventsIn1hWindow(int count) throws InterruptedException {
    MockPartitionedCollector mockCollector = new MockPartitionedCollector();
    StreamTimeClockInLocalMemory timeClock = new StreamTimeClockInLocalMemory("sampleStream_1");
    Ordering<PartitionedEvent> timeOrdering = Ordering.from(PartitionedEventTimeOrderingComparator.INSTANCE);
    StreamSortWindowHandlerImpl sortHandler = new StreamSortWindowHandlerImpl();
    sortHandler.prepare("sampleStream_1",
            MockSampleMetadataFactory.createSampleStreamSortSpec("sampleStream_1", "PT1h", 5000),
            mockCollector);/*from  w w  w  . jav a 2s . co m*/
    List<PartitionedEvent> unsortedList = new LinkedList<>();

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    int i = 0;
    while (i < count) {
        PartitionedEvent event = MockSampleMetadataFactory
                .createRandomOutOfTimeOrderEventGroupedByName("sampleStream_1");
        sortHandler.nextEvent(event);
        unsortedList.add(event);
        if (event.getEvent().getTimestamp() > timeClock.getTime()) {
            timeClock.moveForward(event.getEvent().getTimestamp());
        }
        sortHandler.onTick(timeClock, System.currentTimeMillis());
        i++;
    }
    stopWatch.stop();
    LOG.info("Produced {} events in {} ms", count, stopWatch.getTime());
    sortHandler.close();
    Assert.assertFalse(timeOrdering.isOrdered(unsortedList));
    Assert.assertTrue(timeOrdering.isOrdered(mockCollector.get()));
    Assert.assertTrue(mockCollector.get().size() >= 0);
}

From source file:org.apache.eagle.alert.engine.sorter.StreamWindowBenchmarkTest.java

public void sendDESCOrderedEventsToWindow(StreamWindow window, StreamWindowRepository.StorageType storageType,
        int num) {
    LOGGER.info("Sending {} events to {} ({})", num, window.getClass().getSimpleName(), storageType);
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();//w w  w .  ja v  a2 s.  c o m
    int i = 0;
    while (i < num) {
        PartitionedEvent event = MockSampleMetadataFactory.createPartitionedEventGroupedByName("sampleStream_1",
                (window.startTime() + i));
        window.add(event);
        i++;
    }
    stopWatch.stop();
    performanceReport.put(num + "\tInsertTime\t" + storageType, stopWatch.getTime());
    LOGGER.info("Inserted {} events in {} ms", num, stopWatch.getTime());
    stopWatch.reset();
    stopWatch.start();
    window.flush();
    stopWatch.stop();
    performanceReport.put(num + "\tReadTime\t" + storageType, stopWatch.getTime());
}

From source file:org.apache.eagle.alert.engine.sorter.StreamWindowBenchmarkTest.java

private void benchmarkTest(StreamWindow window, StreamWindowRepository.StorageType storageType) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();//from  w  ww  .j a va  2  s. co  m
    LOGGER.info("\n===== Benchmark Test for {} ({}) =====", window.getClass().getSimpleName(), storageType);
    metricReporter.report();
    sendDESCOrderedEventsToWindow(window, storageType, 1000);
    metricReporter.report();
    sendDESCOrderedEventsToWindow(window, storageType, 10000);
    metricReporter.report();
    sendDESCOrderedEventsToWindow(window, storageType, 100000);
    metricReporter.report();
    sendDESCOrderedEventsToWindow(window, storageType, 1000000);
    metricReporter.report();
    stopWatch.stop();
    LOGGER.info("\n===== Finished in total {} ms =====\n", stopWatch.getTime());
}

From source file:org.apache.eagle.jpm.mr.history.MRHistoryJobDailyReporter.java

private Map<String, Object> buildAlertData(String site, long startTime, long endTime) {
    StopWatch watch = new StopWatch();
    Map<String, Object> data = new HashMap<>();
    this.client = new EagleServiceClientImpl(config);
    String startTimeStr = DateTimeUtil.millisecondsToHumanDateWithSeconds(startTime);
    String endTimeStr = DateTimeUtil.millisecondsToHumanDateWithSeconds(endTime);
    LOG.info("Going to report job summery info for site {} from {} to {}", site, startTimeStr, endTimeStr);
    try {//from  ww w.jav  a2s  . c om
        watch.start();
        data.putAll(buildJobSummery(site, startTime, endTime));
        data.put(NUM_TOP_USERS_KEY, numTopUsers);
        data.put(JOB_OVERTIME_LIMIT_KEY, jobOvertimeLimit);
        data.put(ALERT_TITLE_KEY, String.format("[%s] Job Report for 12 Hours", site.toUpperCase()));
        data.put(REPORT_RANGE_KEY,
                String.format("%s ~ %s %s", startTimeStr, endTimeStr, DateTimeUtil.CURRENT_TIME_ZONE.getID()));
        data.put(EAGLE_JOB_LINK_KEY, String.format("http://%s:%d/#/site/%s/jpm/list?startTime=%s&endTime=%s",
                config.getString(SERVICE_HOST), config.getInt(SERVICE_PORT), site, startTimeStr, endTimeStr));
        watch.stop();
        LOG.info("Fetching DailyJobReport tasks {} seconds", watch.getTime() / DateTimeUtil.ONESECOND);
    } finally {
        try {
            client.close();
        } catch (IOException e) {
            LOG.info("fail to close eagle service client");
        }
    }
    return data;
}