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:eagle.service.generic.GenericEntityServiceResource.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//from  w ww .ja v a  2s  .c o m
@Produces(MediaType.APPLICATION_JSON)
public GenericServiceAPIResponseEntity create(InputStream inputStream,
        @QueryParam("serviceName") String serviceName) {
    GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<String>();
    Map<String, Object> meta = new HashMap<>();
    StopWatch stopWatch = new StopWatch();
    try {
        stopWatch.start();
        EntityDefinition entityDefinition = EntityDefinitionManager.getEntityByServiceName(serviceName);

        if (entityDefinition == null) {
            throw new IllegalArgumentException("entity definition of service " + serviceName + " not found");
        }

        List<? extends TaggedLogAPIEntity> entities = unmarshalEntitiesByServie(inputStream, entityDefinition);
        DataStorage dataStorage = DataStorageManager.getDataStorageByEagleConfig();
        CreateStatement createStatement = new CreateStatement(entities, entityDefinition);
        ModifyResult<String> result = createStatement.execute(dataStorage);
        if (result.isSuccess()) {
            List<String> keys = result.getIdentifiers();
            if (keys != null) {
                response.setObj(keys, String.class);
                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:com.liferay.portal.search.solr.SolrIndexSearcher.java

@Override
public Hits search(SearchContext searchContext, Query query) throws SearchException {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();/* w ww.  j a  v  a  2s  .  co m*/

    try {
        int total = (int) searchCount(searchContext, query);

        int start = searchContext.getStart();
        int end = searchContext.getEnd();

        if ((searchContext.getStart() == QueryUtil.ALL_POS) && (searchContext.getEnd() == QueryUtil.ALL_POS)) {

            start = 0;
            end = total;
        }

        int[] startAndEnd = SearchPaginationUtil.calculateStartAndEnd(start, end, total);

        start = startAndEnd[0];
        end = startAndEnd[1];

        QueryResponse queryResponse = search(searchContext, query, start, end, false);

        Hits hits = processQueryResponse(queryResponse, searchContext, query);

        hits.setStart(stopWatch.getStartTime());

        return hits;
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }

        if (!_swallowException) {
            throw new SearchException(e.getMessage());
        }

        return new HitsImpl();
    } finally {
        if (_log.isInfoEnabled()) {
            stopWatch.stop();

            _log.info("Searching " + query.toString() + " took " + stopWatch.getTime() + " ms");
        }
    }
}

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

@POST
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces(MediaType.APPLICATION_JSON)// www  . ja v  a  2s . c  om
public GenericServiceAPIResponseEntity create(@FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition cdh, @QueryParam("serviceName") String serviceName) {
    GenericServiceAPIResponseEntity<String> response = new GenericServiceAPIResponseEntity<String>();
    Map<String, Object> meta = new HashMap<>();
    StopWatch stopWatch = new StopWatch();
    try {
        stopWatch.start();
        EntityDefinition entityDefinition = EntityDefinitionManager.getEntityByServiceName(serviceName);

        if (entityDefinition == null) {
            throw new IllegalArgumentException("entity definition of service " + serviceName + " not found");
        }

        List<? extends TaggedLogAPIEntity> entities = unmarshalEntitiesByServie(fileInputStream,
                entityDefinition);
        DataStorage dataStorage = DataStorageManager.getDataStorageByEagleConfig();
        CreateStatement createStatement = new CreateStatement(entities, entityDefinition);
        ModifyResult<String> result = createStatement.execute(dataStorage);
        if (result.isSuccess()) {
            List<String> keys = result.getIdentifiers();
            if (keys != null) {
                response.setObj(keys, String.class);
                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:biz.netcentric.cq.tools.actool.aceservice.impl.AceServiceImpl.java

/** Common entry point for JMX and install hook. */
@Override/*from  w  w w  . j a va2s. c o  m*/
public void installConfigurationFiles(AcInstallationHistoryPojo history,
        Map<String, String> configurationFileContentsByFilename,
        Set<AuthorizableInstallationHistory> authorizableInstallationHistorySet, String[] restrictedToPaths)
        throws Exception {

    String origThreadName = Thread.currentThread().getName();
    try {
        Thread.currentThread().setName(origThreadName + "-ACTool-Config-Worker");
        StopWatch sw = new StopWatch();
        sw.start();
        isExecuting = true;
        String message = "*** Applying AC Tool Configuration...";
        LOG.info(message);
        history.addMessage(message);

        if (configurationFileContentsByFilename != null) {

            history.setConfigFileContentsByName(configurationFileContentsByFilename);

            AcConfiguration acConfiguration = configurationMerger
                    .getMergedConfigurations(configurationFileContentsByFilename, history, configReader);
            history.setAcConfiguration(acConfiguration);

            installMergedConfigurations(history, authorizableInstallationHistorySet, acConfiguration,
                    restrictedToPaths);

            // this runs as "own transaction" after session.save() of ACLs
            removeObsoleteAuthorizables(history, acConfiguration.getObsoleteAuthorizables());

        }
        sw.stop();
        long executionTime = sw.getTime();
        LOG.info("Successfully applied AC Tool configuration in " + msHumanReadable(executionTime));
        history.setExecutionTime(executionTime);
    } catch (Exception e) {
        history.addError(e.toString()); // ensure exception is added to history before it's persisted in log in finally clause
        throw e; // handling is different depending on JMX or install hook case
    } finally {
        try {
            acHistoryService.persistHistory(history);
        } catch (Exception e) {
            LOG.warn("Could not persist history, e=" + e, e);
        }

        Thread.currentThread().setName(origThreadName);
        isExecuting = false;
    }

}

From source file:com.redhat.rhn.taskomatic.task.DailySummary.java

/**
 * DO NOT CALL FROM OUTSIDE THIS CLASS. Queues up the Org Emails for
 * mailing.//  www .  ja v  a 2s.c  o  m
 * @param orgId Org Id to be processed.
 */
public void queueOrgEmails(Long orgId) {
    SelectMode m = ModeFactory.getMode(TaskConstants.MODE_NAME, TaskConstants.TASK_QUERY_USERS_WANTING_REPORTS);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("org_id", orgId);

    StopWatch watch = new StopWatch();
    watch.start();
    List users = m.execute(params);
    for (Iterator itr = users.iterator(); itr.hasNext();) {
        ReportingUser ru = (ReportingUser) itr.next();
        // run_user
        List awol = getAwolServers(ru.idAsLong());
        // send email
        List actions = getActionInfo(ru.idAsLong());
        if ((awol == null || awol.size() == 0) && (actions == null || actions.size() == 0)) {
            log.debug("Skipping ORG " + orgId + " because daily summary info has " + "changed");
            continue;
        }

        String awolMsg = renderAwolServersMessage(awol);
        String actionMsg = renderActionsMessage(actions);

        String emailMsg = prepareEmail(ru.getLogin(), ru.getAddress(), awolMsg, actionMsg);

        LocalizationService ls = LocalizationService.getInstance();
        mail.setSubject(ls.getMessage("dailysummary.email.subject", ls.formatShortDate(new Date())));
        mail.setRecipient(ru.getAddress());

        if (log.isDebugEnabled()) {
            log.debug("Sending email to [" + ru.getAddress() + "]");
        }

        mail.setBody(emailMsg);
        TaskHelper.sendMail(mail, log);
    }
    watch.stop();
    if (log.isDebugEnabled()) {
        log.debug("queued emails of org of " + users.size() + " users in " + watch.getTime() + "ms");
    }
}

From source file:com.liferay.portal.mobile.device.wurfl.WURFLKnownDevices.java

protected void loadWURFLDevices() {
    if (_initialized) {
        return;/*from   w w w. ja v a 2 s.  co m*/
    }

    WURFLUtils wurflUtils = _wurflHolder.getWURFLUtils();

    if (wurflUtils == null) {
        _log.error("Unable to load WURFL devices");

        return;
    }

    StopWatch stopWatch = null;

    if (_log.isDebugEnabled()) {
        stopWatch = new StopWatch();

        stopWatch.start();

        _log.debug("Loading database");
    }

    Map<String, VersionableName> brands = new HashMap<String, VersionableName>();
    Map<String, VersionableName> browsers = new HashMap<String, VersionableName>();
    Map<String, VersionableName> operatingSystems = new HashMap<String, VersionableName>();

    for (Object deviceIdObject : wurflUtils.getAllDevicesId()) {
        String deviceId = (String) deviceIdObject;

        Device device = wurflUtils.getDeviceById(deviceId);

        updateVersionableCapability(device, brands, WURFLConstants.BRAND_NAME, WURFLConstants.MODEL_NAME,
                WURFLConstants.MARKETING_NAME);

        updateVersionableCapability(device, browsers, WURFLConstants.MOBILE_BROWSER,
                WURFLConstants.MOBILE_BROWSER_VERSION, null);

        updateVersionableCapability(device, operatingSystems, WURFLConstants.DEVICE_OS,
                WURFLConstants.DEVICE_OS_VERSION, null);

        updateCapability(device, _pointingMethods, WURFLConstants.POINTING_METHOD);

        updateDevicesIds(device, WURFLConstants.DEVICE_OS);
    }

    _brands = new TreeSet<VersionableName>(brands.values());
    _browsers = new TreeSet<VersionableName>(browsers.values());
    _operatingSystems = new TreeSet<VersionableName>(operatingSystems.values());

    if (_log.isDebugEnabled()) {
        _log.debug("Loaded database in " + stopWatch.getTime() + " ms");
    }

    _initialized = true;
}

From source file:au.id.hazelwood.xmltvguidebuilder.grabber.Grabber.java

private void addListing(ChannelListings channelListings, Config config, ChannelConfig channelConfig,
        String channelTag, DateTime from, DateTime to) {
    StopWatch watch = new StopWatch();
    watch.start();/*www  . ja  v  a  2  s. c  o  m*/
    List<Event> events = getEvents(config, channelTag, from, to);
    LOGGER.debug("Found {} events between {} and {}", events.size(), from, to);
    for (Event event : events) {
        ProgrammeDetail programmeDetails;
        LOGGER.debug("Processing event id {}", event.getEventId());
        DateTime scheduleDate = new DateTime(event.getScheduledDate());
        if (scheduleDate.plusMinutes(event.getDuration()).isAfterNow()
                && scheduleDate.isBefore(from.plusDays(config.getSynopsis()))) {
            LOGGER.debug("Fetching detailed synopsis for {}", event.getEventId());
            try {
                EventDetails eventDetails = getForObject(DETAILS_URI, EventDetails.class, event.getEventId(),
                        config.getRegionId());
                programmeDetails = createProgrammeDetails(eventDetails.getEvent());
            } catch (Exception e) {
                LOGGER.debug("Failed to get detailed synopsis. Using basic details instead.");
                programmeDetails = createProgrammeDetails(event);
            }
        } else {
            programmeDetails = createProgrammeDetails(event);
        }
        channelListings.addProgram(channelConfig.getId(), programmeDetails);
    }
    watch.stop();
    String numberOfPrograms = String.valueOf(channelListings.getNumberOfPrograms(channelConfig.getId()));
    LOGGER.info("{} {} events [took {}]", rightPad(channelConfig.getId() + " - " + channelConfig.getName(), 40),
            leftPad(numberOfPrograms, 4), formatDurationWords(watch.getTime()));
}

From source file:net.craigstars.game.services.util.TurnGenerator.java

/**
 * <pre>//from   w  w  w  .  j av  a 2 s. c  om
 *         Generate a turn
 * 
 *         Stars! Order of Events 
 *         
 *         Scrapping fleets (w/possible tech gain) 
 *         Waypoint 0 unload tasks 
 *         Waypoint 0 Colonization/Ground Combat resolution (w/possible tech gain) 
 *         Waypoint 0 load tasks 
 *         Other Waypoint 0 tasks * 
 *         MT moves 
 *         In-space packets move and decay 
 *         PP packets (de)terraform 
 *         Packets cause damage 
 *         Wormhole entry points jiggle 
 *         Fleets move (run out of fuel, hit minefields (fields reduce as they are hit), stargate, wormhole travel) 
 *         Inner Strength colonists grow in fleets 
 *         Mass Packets still in space and Salvage decay 
 *         Wormhole exit points jiggle 
 *         Wormhole endpoints degrade/jump 
 *         SD Minefields detonate (possibly damaging again fleet that hit minefield during movement) 
 *         Mining 
 *         Production (incl. research, packet launch, fleet/starbase construction) 
 *         SS Spy bonus obtained 
 *         Population grows/dies 
 *         Packets that just launched and reach their destination cause damage 
 *         Random events (comet strikes, etc.) 
 *         Fleet battles (w/possible tech gain) 
 *         Meet MT 
 *         Bombing 
 *         Waypoint 1 unload tasks 
 *         Waypoint 1 Colonization/Ground Combat resolution (w/possible tech gain) 
 *         Waypoint 1 load tasks 
 *         Mine Laying 
 *         Fleet Transfer 
 *         CA Instaforming 
 *         Mine sweeping 
 *         Starbase and fleet repair 
 *         Remote Terraforming
 * </pre>
 */
public void generate() {
    // time this logic
    StopWatch timer = new StopWatch();
    timer.start();

    game.setYear(game.getYear() + 1);

    // initialize the players to starting turn state
    initPlayers();

    performWaypointTasks(0);
    moveMysteryTrader();
    movePackets();
    updateWormholeEntryPoints();
    moveFleets();
    growISFleets();
    decayPackets();
    updateWormholeExitPoints();
    detonateMinefields();
    mine();
    produce();
    ssSpy();
    grow();
    randomEvents();
    battle();
    mysteryTrader();
    bombing();
    performWaypointTasks(0);
    layMines();
    transferFleets();
    terraformCAPlanets();
    sweepMines();
    repairFleets();
    remoteTerraform();

    scan(game);

    // do turn processing
    processTurns(game);

    /*
     * for (Planet planet : game.getPlanets()) { dao.getPlanetDao().save(planet);
     * dao.getProductionQueueDao().save(planet.getQueue()); }
     * 
     * for (Fleet fleet : game.getFleets()) { dao.getFleetDao().save(fleet); }
     */

    game.setStatus(GameStatus.WaitingForSubmit);
    log.info("Generated new turn {}, {} ms", game.getYear(), timer.getTime());

}

From source file:de.unisb.cs.st.javalanche.rhino.RhinoTestDriver.java

private void testDirectory(File dir) {
    baseDir = dir.getAbsolutePath();/*  www.j a  va2 s .c om*/
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    File[] files = getTestFilesForDir(dir);
    List<String> passingTests = new ArrayList<String>();
    List<SingleTestResult> failingTests = new ArrayList<SingleTestResult>();
    logger.info("Searching in " + dir);
    List<String> failingList = Io.getLinesFromFile(new File("failing.txt"));
    List<String> ignoreList = Io
            .getLinesFromFile(new File("output/271545/post-fix/mozilla/js/tests/rhino-n.tests"));

    int ignore = 0;
    for (File f : files) {
        logger.info("File:  " + f);
        String testName = getRelativeLocation(f);
        logger.info("Test name: " + testName);

        if (ignoreList.contains(testName)) {
            logger.info("Not running test because its on the projects ignore list");
            ignore++;
            continue;
        }
        if (failingList.contains(testName)) {
            String message = "Not running test (Failed in previous run)";
            logger.info(message + testName);
            failingTests.add(new SingleTestResult(testName, message, TestOutcome.ERROR, 0));
            continue;
        }
        MutationTestRunnable testRunnable = getTestRunnable(testName);
        runWithTimeout(testRunnable);
        SingleTestResult result = testRunnable.getResult();
        if (result.hasPassed()) {
            logger.info("Test passed: " + testName);
            passingTests.add(testName);
        } else {
            logger.info("Test failed: " + testName);
            logger.info("Reason: " + result);
            failingTests.add(result);
        }

    }

    stopWatch.stop();
    long time = stopWatch.getTime();
    logger.info("Test Suite took " + DurationFormatUtils.formatDurationHMS(time));
    StringBuilder sbPass = new StringBuilder();
    StringBuilder sbFail = new StringBuilder();
    for (String passingTest : passingTests) {
        sbPass.append(passingTest + "\n");
    }
    for (SingleTestResult failingTestResult : failingTests) {
        sbFail.append(failingTestResult.getTestMessage().getTestCaseName()
                /* + "," + failingTestResult.getTestMessage().getMessage() */
                + "\n");
    }
    Io.writeFile(sbPass.toString(), new File("passingTests.txt"));
    Io.writeFile(sbFail.toString(), new File("failingTests.txt"));
    logger.info("Ignored " + ignore + " tests");
}

From source file:com.liferay.portal.lar.PermissionExporter.java

protected void exportUserPermissions(LayoutCache layoutCache, long companyId, long groupId, String resourceName,
        String resourcePrimKey, Element parentElement) throws Exception {

    StopWatch stopWatch = null;

    if (_log.isDebugEnabled()) {
        stopWatch = new StopWatch();

        stopWatch.start();//from   ww w.j  a  v a  2 s.  c  om
    }

    Element userPermissionsElement = SAXReaderUtil.createElement("user-permissions");

    List<User> users = layoutCache.getGroupUsers(groupId);

    for (User user : users) {
        String uuid = user.getUuid();

        Element userActionsElement = SAXReaderUtil.createElement("user-actions");

        List<Permission> permissions = PermissionLocalServiceUtil.getUserPermissions(user.getUserId(),
                companyId, resourceName, ResourceConstants.SCOPE_INDIVIDUAL, resourcePrimKey);

        List<String> actions = ResourceActionsUtil.getActions(permissions);

        for (String action : actions) {
            Element actionKeyElement = userActionsElement.addElement("action-key");

            actionKeyElement.addText(action);
        }

        if (!userActionsElement.elements().isEmpty()) {
            userActionsElement.addAttribute("uuid", uuid);
            userPermissionsElement.add(userActionsElement);
        }
    }

    if (!userPermissionsElement.elements().isEmpty()) {
        parentElement.add(userPermissionsElement);
    }

    if (_log.isDebugEnabled()) {
        _log.debug("Export user permissions for {" + resourceName + ", " + resourcePrimKey + "} with "
                + users.size() + " users takes " + stopWatch.getTime() + " ms");
    }
}