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:org.apache.cocoon.servlet.CocoonServlet.java

/**
 * Process the specified <code>HttpServletRequest</code> producing output
 * on the specified <code>HttpServletResponse</code>.
 *///ww  w. j a  va  2 s  .  com
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>.
 *//*from   w w  w .  j  a v  a  2 s.  c  o m*/
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  ww  w.jav a2  s .  c om
@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 ww.ja  v a  2 s.  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   ww  w .jav  a2 s .c  o 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();
    int i = 0;//from   w w w.j av a 2s.c o m
    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();
    LOGGER.info("\n===== Benchmark Test for {} ({}) =====", window.getClass().getSimpleName(), storageType);
    metricReporter.report();/*from   w ww .  jav a 2s.co  m*/
    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 {//w w  w.j av a  2s .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;
}

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

public GenericServiceAPIResponseEntity updateDatabase(Statement<ModifyResult<String>> statement) {
    GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<>();
    Map<String, Object> meta = new HashMap<>();
    StopWatch stopWatch = new StopWatch();

    try {/*ww  w.ja v a  2s.  c o m*/
        stopWatch.start();
        DataStorage dataStorage = DataStorageManager.getDataStorageByEagleConfig();
        if (dataStorage == null) {
            LOG.error("Data storage is null");
            throw new IllegalDataStorageException("Data storage is null");
        }
        ModifyResult<String> result = statement.execute(dataStorage);
        if (result.isSuccess()) {
            List<String> keys = result.getIdentifiers();
            if (keys != null) {
                response.setObj(keys, String.class);
                meta.put(TOTAL_RESULTS, keys.size());
            } else {
                meta.put(TOTAL_RESULTS, 0);
            }
            meta.put(ELAPSEDMS, stopWatch.getTime());
            response.setMeta(meta);
            response.setSuccess(true);
        }
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        response.setException(e);
    } finally {
        stopWatch.stop();
    }
    return response;
}

From source file:org.apache.eagle.service.jpm.MRJobExecutionResource.java

@GET
@Produces(MediaType.APPLICATION_JSON)/*from   w w w  .  java  2  s  . c  om*/
public GenericServiceAPIResponseEntity listJobs(@QueryParam("query") String query,
        @QueryParam("startTime") String startTime, @QueryParam("endTime") String endTime,
        @QueryParam("pageSize") int pageSize, @QueryParam("startRowkey") String startRowkey,
        @QueryParam("treeAgg") boolean treeAgg, @QueryParam("timeSeries") boolean timeSeries,
        @QueryParam("intervalmin") long intervalmin, @QueryParam("top") int top,
        @QueryParam("filterIfMissing") boolean filterIfMissing, @QueryParam("parallel") int parallel,
        @QueryParam("metricName") String metricName, @QueryParam("verbose") Boolean verbose)
        throws ParseException {
    GenericServiceAPIResponseEntity response = new GenericServiceAPIResponseEntity();

    List<TaggedLogAPIEntity> jobs = new ArrayList<>();
    List<JobExecutionAPIEntity> finishedJobs = new ArrayList<>();
    Set<String> jobIds = new HashSet<>();
    final Map<String, Object> meta = new HashMap<>();
    StopWatch stopWatch = new StopWatch();

    stopWatch.start();
    String jobQuery = String.format(query, Constants.JPA_JOB_EXECUTION_SERVICE_NAME);
    GenericServiceAPIResponseEntity<JobExecutionAPIEntity> res = resource.search(jobQuery, startTime, endTime,
            pageSize, startRowkey, treeAgg, timeSeries, intervalmin, top, filterIfMissing, parallel, metricName,
            verbose);
    if (res.isSuccess() && res.getObj() != null) {
        long maxFinishedTime = DateTimeUtil.humanDateToSeconds(endTime) * DateTimeUtil.ONESECOND;
        for (JobExecutionAPIEntity o : res.getObj()) {
            if (o.getEndTime() <= maxFinishedTime) {
                finishedJobs.add(o);
                jobIds.add(o.getTags().get(MRJobTagName.JOB_ID.toString()));
            }
        }
        jobQuery = String.format(query, Constants.JPA_RUNNING_JOB_EXECUTION_SERVICE_NAME);
        GenericServiceAPIResponseEntity<org.apache.eagle.jpm.mr.runningentity.JobExecutionAPIEntity> runningRes = resource
                .search(jobQuery, startTime, endTime, pageSize, startRowkey, treeAgg, timeSeries, intervalmin,
                        top, filterIfMissing, parallel, metricName, verbose);
        if (runningRes.isSuccess() && runningRes.getObj() != null) {
            for (org.apache.eagle.jpm.mr.runningentity.JobExecutionAPIEntity o : runningRes.getObj()) {
                String key = o.getTags().get(MRJobTagName.JOB_ID.toString());
                if (!ResourceUtils.isDuplicate(jobIds, key)) {
                    jobs.add(o);
                }
            }
            jobs.addAll(finishedJobs);
        }
    }
    stopWatch.stop();
    if (res.isSuccess()) {
        response.setSuccess(true);
    } else {
        response.setSuccess(false);
        response.setException(new Exception(res.getException()));
    }
    meta.put(TOTAL_RESULTS, jobs.size());
    meta.put(ELAPSEDMS, stopWatch.getTime());
    response.setObj(jobs);
    response.setMeta(meta);
    return response;

}