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:net.di2e.ecdr.libs.result.relevance.RelevanceNormalizer.java

/**
 * Normalize the relevance score for the results in the query response based on the contextual query criteria
 *
 * @param results//from w  ww  .j av a 2 s. c om
 * @param originalQuery
 * @return
 */
public List<Result> normalize(List<Result> results, Query originalQuery) {

    SortBy sortBy = originalQuery.getSortBy();
    // We want to do relevance sort if no sort order was specfied or if Relevance sort was specified
    if (sortBy == null || sortBy.getPropertyName() == null || sortBy.getPropertyName().getPropertyName() == null
            || Result.RELEVANCE.equals(sortBy.getPropertyName().getPropertyName())) {

        Map<String, String> filterParameters = getFilterParameters(originalQuery);

        if (canNormalizeQuery(filterParameters)) {
            LOGGER.debug(
                    "Query contained search phrase and will be sorted by relevance, performing re-indexing to normalize relevance.");
            Directory directory = null;
            DirectoryReader iReader = null;
            Map<String, Result> docMap = new HashMap<>();
            List<Result> updatedResults = new ArrayList<>();
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            try {
                Analyzer analyzer = new StandardAnalyzer();

                // create memory-stored index
                directory = new RAMDirectory();

                IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer);
                IndexWriter iWriter = new IndexWriter(directory, config);

                // loop through all of the results and add them to the index
                for (Result curResult : results) {
                    Document doc = new Document();
                    String text = TextParser.parseTextFrom(curResult.getMetacard().getMetadata());
                    String uuid = UUID.randomUUID().toString();
                    doc.add(new Field(METADATA_FIELD, text, TextField.TYPE_STORED));
                    doc.add(new Field(ID_FIELD, uuid, TextField.TYPE_STORED));
                    iWriter.addDocument(doc);
                    docMap.put(uuid, curResult);
                }

                IOUtils.closeQuietly(iWriter);
                LOGGER.debug("{} Document indexing finished in {} seconds.", RELEVANCE_TIMER,
                        (double) stopWatch.getTime() / 1000.0);
                // Now search the index:
                iReader = DirectoryReader.open(directory);
                IndexSearcher iSearcher = new IndexSearcher(iReader);
                // Parse a simple query that searches for "text":
                QueryParser parser = new QueryParser(METADATA_FIELD, analyzer);
                org.apache.lucene.search.Query query = getQuery(parser, filterParameters);
                ScoreDoc[] hits = iSearcher.search(query, null, docMap.size()).scoreDocs;
                LOGGER.debug("Got back {} results", hits.length);

                // loop through the indexed search results and update the scores in the original query results
                for (ScoreDoc curHit : hits) {
                    Document doc = iSearcher.doc(curHit.doc);
                    String uuid = doc.getField(ID_FIELD).stringValue();
                    Result result = docMap.get(uuid);
                    docMap.remove(uuid);
                    updatedResults.add(updateResult(result, curHit.score));
                    LOGGER.debug("Relevance for result {} was changed FROM {} TO {}",
                            result.getMetacard().getId(), result.getRelevanceScore(), curHit.score);
                }
                // check if there are any results left that did not match the keyword query
                for (Map.Entry<String, Result> curEntry : docMap.entrySet()) {
                    // add result in with 0 relevance score
                    updatedResults.add(updateResult(curEntry.getValue(), 0));
                }
                // create new query response
                return updatedResults;

            } catch (ParseException | IOException | RuntimeException e) {
                LOGGER.warn(
                        "Received an exception while trying to perform re-indexing, sending original queryResponse on.",
                        e);
                return results;
            } finally {
                IOUtils.closeQuietly(iReader);
                IOUtils.closeQuietly(directory);
                stopWatch.stop();
                LOGGER.debug("{} Total relevance process took {} seconds.", RELEVANCE_TIMER,
                        (double) stopWatch.getTime() / 1000.0);
            }
        } else {
            LOGGER.debug(
                    "Query is not sorted based on relevance with contextual criteria. Skipping relevance normalization.");
        }
    } else {
        LOGGER.debug(
                "Query is not sorted based on relevance with contextual criteria. Skipping relevance normalization.");
    }
    return results;
}

From source file:io.cloudslang.lang.cli.SlangCli.java

@CliCommand(value = "run", help = RUN_HELP)
public String run(@CliOption(key = { "", "f", "file" }, mandatory = true, help = FILE_HELP) final File file,
        @CliOption(key = { "cp",
                "classpath" }, mandatory = false, help = CLASSPATH_HELP) final List<String> classPath,
        @CliOption(key = { "i",
                "inputs" }, mandatory = false, help = INPUTS_HELP) final Map<String, ? extends Serializable> inputs,
        @CliOption(key = { "if",
                "input-file" }, mandatory = false, help = INPUT_FILE_HELP) final List<String> inputFiles,
        @CliOption(key = { "v",
                "verbose" }, mandatory = false, help = "default, quiet, debug(print each step outputs). e.g. run --f c:/.../your_flow.sl --v quiet", specifiedDefaultValue = "debug", unspecifiedDefaultValue = "default") final String verbose,
        @CliOption(key = { "spf",
                "system-property-file" }, mandatory = false, help = SYSTEM_PROPERTY_FILE_HELP) final List<String> systemPropertyFiles) {

    if (invalidVerboseInput(verbose)) {
        throw new IllegalArgumentException("Verbose argument is invalid.");
    }/*from   w  w w  .ja va 2s  .  c  o m*/

    CompilationArtifact compilationArtifact = compilerHelper.compile(file.getAbsolutePath(), classPath);
    Set<SystemProperty> systemProperties = compilerHelper.loadSystemProperties(systemPropertyFiles);
    Map<String, Value> inputsFromFile = compilerHelper.loadInputsFromFile(inputFiles);
    Map<String, Value> mergedInputs = new HashMap<>();

    if (MapUtils.isNotEmpty(inputsFromFile)) {
        mergedInputs.putAll(inputsFromFile);
    }
    if (MapUtils.isNotEmpty(inputs)) {
        mergedInputs.putAll(io.cloudslang.lang.entities.utils.MapUtils.convertMapNonSensitiveValues(inputs));
    }
    boolean quiet = QUIET.equalsIgnoreCase(verbose);
    boolean debug = DEBUG.equalsIgnoreCase(verbose);

    Long id;
    if (!triggerAsync) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        id = scoreServices.triggerSync(compilationArtifact, mergedInputs, systemProperties, quiet, debug);
        stopWatch.stop();
        return quiet ? StringUtils.EMPTY : triggerSyncMsg(id, stopWatch.toString());
    }
    id = scoreServices.trigger(compilationArtifact, mergedInputs, systemProperties);
    return quiet ? StringUtils.EMPTY : triggerAsyncMsg(id, compilationArtifact.getExecutionPlan().getName());
}

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

protected void loadWURFLDevices() {
    if (_initialized) {
        return;//w w w  .  j  av  a 2  s .  com
    }

    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:fr.inria.edelweiss.kgdqp.test.TestDQP.java

public void testLocal() throws EngineException, MalformedURLException, IOException {
    Graph graph = Graph.create();/*  www .  jav a  2 s . c  o  m*/
    QueryProcess exec = QueryProcessDQP.create(graph);

    StopWatch sw = new StopWatch();
    sw.start();
    logger.info("Initializing GraphEngine, entailments: " + graph.getEntailment());
    Load ld = Load.create(graph);
    logger.info("Initialized GraphEngine: " + sw.getTime() + " ms");

    sw.reset();
    sw.start();
    try {
        ld.parseDir(TestDQP.class.getClassLoader().getResource("demographie").getPath() + "/cog-2012.ttl");
    } catch (LoadException ex) {
        LogManager.getLogger(TestDQP.class.getName()).log(Level.ERROR, "", ex);
    }

    try {
        ld.parseDir(TestDQP.class.getClassLoader().getResource("demographie").getPath() + "/popleg-2010.ttl");
    } catch (LoadException ex) {
        LogManager.getLogger(TestDQP.class.getName()).log(Level.ERROR, "", ex);
    }

    logger.info("Graph size: " + graph.size());

    for (String q : queries.values()) {
        logger.info("Querying with : \n" + q);
        for (int i = 0; i < 10; i++) {
            sw.reset();
            sw.start();
            Mappings results = exec.query(q);
            logger.info(results.size() + " results: " + sw.getTime() + " ms");
        }
    }
}

From source file:adams.gui.visualization.image.plugins.Barcode.java

/**
 * Processes the image./*from w  w w.ja v  a  2  s  . c  o  m*/
 */
@Override
protected String process() {
    String result;
    BufferedImageContainer cont;
    TextContainer text;
    TextDialog dialog;
    AbstractBarcodeDecoder decoder;
    StopWatch watch;

    result = null;

    try {
        cont = new BufferedImageContainer();
        cont.setImage(m_CurrentPanel.getCurrentImage());
        watch = new StopWatch();
        watch.start();
        decoder = (AbstractBarcodeDecoder) getLastSetup();
        text = decoder.decode(cont);
        watch.stop();
        if (m_CurrentPanel.getParentDialog() != null)
            dialog = new TextDialog(m_CurrentPanel.getParentDialog());
        else
            dialog = new TextDialog(m_CurrentPanel.getParentFrame());
        if (m_CurrentPanel.getCurrentFile() != null)
            dialog.setDialogTitle("Barcode - " + m_CurrentPanel.getCurrentFile().getName() + " ["
                    + m_CurrentPanel.getCurrentFile().getParent() + "]");
        else
            dialog.setDialogTitle("Barcode");
        dialog.setEditable(false);
        if (text != null) {
            dialog.setContent(text.getContent() + "\n\nTime (ms): " + watch.getTime() + "\n\nMeta-data\n\n"
                    + text.getReport());
            dialog.setSize(GUIHelper.getInteger("DefaultTinyDialog.Width", 400),
                    GUIHelper.getInteger("DefaultTinyDialog.Width", 400));
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
        } else {
            result = "Failed to extract barcode! None present?";
        }
    } catch (Exception e) {
        result = "Failed to extract barcode: " + Utils.throwableToString(e);
    }

    return result;
}

From source file:com.mothsoft.alexis.engine.predictive.OpenNLPMaxentModelTrainerTask.java

@Transactional
@Override/*from  w  w  w  .  j av a 2s.  c  om*/
public void execute() {
    final Long modelId = findAndMark();

    if (modelId != null) {
        logger.info(String.format("Training model %d", modelId));

        final StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        final Model model = this.modelDao.get(modelId);
        train(model);
        stopWatch.stop();

        logger.info(String.format("Training model %d took: %s", modelId, stopWatch.toString()));
    }
}

From source file:com.mothsoft.alexis.engine.predictive.OpenNLPMaxentModelExecutorTask.java

@Override
public void execute() {
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    final List<Long> modelIds = findModelsToExecute();
    final int size = modelIds.size();
    logger.info(String.format("Found %d models in state READY", size));

    int executed = 0;

    for (final Long modelId : modelIds) {
        boolean success = execute(modelId);
        if (success) {
            executed++;/*from  ww  w. j ava2  s.  c  om*/
        }
    }

    stopWatch.stop();
    logger.info(String.format("Executed %d of %d models, took: %s", executed, size, stopWatch.toString()));
}

From source file:net.nan21.dnet.core.web.controller.data.AbstractDsWriteController.java

/**
 * Default handler for delete action./*from www.j  a v  a 2s.com*/
 * 
 * @param resourceName
 * @param dataformat
 * @param idsString
 * @param paramString
 * @return
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.POST, params = Constants.REQUEST_PARAM_ACTION + "="
        + Constants.DS_ACTION_DELETE + "ById")
@ResponseBody
public String deleteById(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_DATA, required = false, defaultValue = "{}") String idsString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    try {

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

        this.prepareRequest(request, response);

        this.authorizeDsAction(resourceName, Constants.DS_ACTION_DELETE, null);

        if (!idsString.startsWith("[")) {
            idsString = "[" + idsString + "]";
        }
        IDsService<M, F, P> service = this.findDsService(resourceName);
        IDsMarshaller<M, F, P> marshaller = service.createMarshaller(IDsMarshaller.JSON);

        List<Object> list = marshaller.readListFromString(idsString, Object.class);

        service.deleteByIds(list);

        IActionResultDelete result = this.packResultDelete();
        stopWatch.stop();
        result.setExecutionTime(stopWatch.getTime());

        String out = null;

        if (dataFormat.equals(IDsMarshaller.XML)) {
            IDsMarshaller<M, F, P> resultMarshaller = service.createMarshaller(dataFormat);
            out = resultMarshaller.writeResultToString(result);
            response.setContentType("text/xml; charset=UTF-8");
        } else {
            out = marshaller.writeResultToString(result);
            response.setContentType("text/plain; charset=UTF-8");
        }

        return out;
    } catch (Exception e) {
        this.handleException(e, response);
        return null;
    } finally {
        this.finishRequest();
    }
}

From source file:chibi.gemmaanalysis.ArrayDesignStatCli.java

@Override
protected Exception doWork(String[] args) {
    Collection<String> failedAds = new ArrayList<>();
    Exception err = processCommandLine(args);
    if (err != null)
        return err;
    if (arrayDesignsToProcess == null || arrayDesignsToProcess.size() == 0) {
        this.arrayDesignsToProcess = adService.loadAll();
    }/* w  w w.j  a va2  s .  c  o  m*/
    Map<Taxon, Collection<ArrayDesign>> taxon2arraydesign = new HashMap<Taxon, Collection<ArrayDesign>>();
    Collection<Long> adIds = new HashSet<Long>();
    for (ArrayDesign ad : this.arrayDesignsToProcess) {

        Taxon taxon = ad.getPrimaryTaxon();
        if (taxon == null) {
            System.err.println("ArrayDesign " + ad.getName() + " doesn't have a taxon");
            continue;
        }
        taxon = taxonService.load(taxon.getId());

        if (taxon != null && taxon.getCommonName() == null) {
            log.warn(ad.getShortName() + " taxon common name is null");
            failedAds.add(ad.getShortName());
            continue;
        }

        // filter out taxon
        if (this.taxon != null && this.taxon.getCommonName() != null
                && !taxon.getCommonName().equalsIgnoreCase(this.taxon.getCommonName())) {
            continue;
        }

        adIds.add(ad.getId());

        Collection<ArrayDesign> ads = null;
        ads = taxon2arraydesign.get(taxon);
        if (ads == null) {
            ads = new HashSet<ArrayDesign>();
            taxon2arraydesign.put(taxon, ads);
        }
        ads.add(ad);
    }
    Map<Long, Boolean> isMerged = adService.isMerged(adIds);
    Map<Long, Boolean> isSubsumed = adService.isSubsumed(adIds);
    StopWatch timer = new StopWatch();
    timer.start();
    int lineCount = 0;
    try (FileWriter out = new FileWriter(new File(this.outFile));) {
        String header = "taxon\tshortName\tname\tisTroubled\texperiments\tmergees\tsubsumes\tsubsumedBy\tgenes\tprobes\tcsWithGenes\tcsBioSequences\tcsBlatResults\tP2G_0";
        out.write(header);
        for (int i = 1; i <= MAXIMUM_COUNT; i++)
            out.write("\tP2G_" + i);
        for (int i = 1; i <= MAXIMUM_COUNT; i++)
            out.write("\tG2P_" + i);
        out.write("\n");
        System.err.print(header + "\n");
        for (Taxon taxon : taxon2arraydesign.keySet()) {
            Collection<ArrayDesign> ads = taxon2arraydesign.get(taxon);
            Collection<Gene> allGenes = geneService.getGenesByTaxon(taxon);
            for (Gene gene : allGenes) {
                geneIds.add(gene.getId());

            }
            for (ArrayDesign ad : ads) {

                try {
                    Status status = statusService.getStatus(ad);
                    String isTroubled = status != null ? Boolean.toString(status.getTroubled().booleanValue())
                            : NA;
                    ad = arrayDesignService.thawLite(ad);
                    long mergees = ad.getMergees().size();
                    long subsumes = ad.getSubsumedArrayDesigns().size();
                    String subsumedBy = ad.getSubsumingArrayDesign() != null
                            ? ad.getSubsumingArrayDesign().getShortName()
                            : NA;
                    long numEEs = arrayDesignService.getExpressionExperiments(ad).size();
                    // boolean merged = isMerged.get( ad.getId() );
                    // if ( merged ) continue;
                    // boolean subsumed = isSubsumed.get( ad.getId() );
                    // if ( subsumed ) continue;
                    long numProbes = getArrayDesignService().getCompositeSequenceCount(ad).longValue();
                    long numCsBioSequences = getArrayDesignService().numCompositeSequenceWithBioSequences(ad);
                    long numCsBlatResults = getArrayDesignService().numCompositeSequenceWithBlatResults(ad);
                    long numCsGenes = getArrayDesignService().numCompositeSequenceWithGenes(ad);
                    long numGenes = getArrayDesignService().numGenes(ad);
                    Collection<CompositeSequence> allCSs = getArrayDesignService().getCompositeSequences(ad);
                    Collection<Long> csIds = new HashSet<Long>();
                    for (CompositeSequence cs : allCSs)
                        csIds.add(cs.getId());
                    // FIXME this used to provide only known genes.
                    Map<Long, Collection<Long>> csId2geneIds = this.getCs2GeneMap(csIds);
                    Map<Long, Collection<Long>> geneId2csIds = getGeneId2CSIdsMap(csId2geneIds);
                    int[] csStats = getStats(csId2geneIds, false);
                    int[] geneStats = getStats(geneId2csIds, true);
                    int cs2NoneGene = allCSs.size() - csId2geneIds.keySet().size();
                    String line = taxon.getCommonName() + "\t" + ad.getShortName() + "\t" + ad.getName() + "\t"
                            + isTroubled + "\t" + numEEs + "\t" + mergees + "\t" + subsumes + "\t" + subsumedBy
                            + "\t" + numGenes + "\t" + numProbes + "\t" + numCsGenes + "\t" + numCsBioSequences
                            + "\t" + numCsBlatResults + "\t" + cs2NoneGene;
                    out.write(line);
                    for (int i = 0; i < MAXIMUM_COUNT; i++) {
                        out.write("\t" + csStats[i]);
                    }
                    for (int i = 0; i < MAXIMUM_COUNT; i++) {
                        out.write("\t" + geneStats[i]);
                    }
                    out.write("\n");
                    System.err.print(line + "\n");

                    lineCount++;
                } catch (Exception e) {
                    log.error(e, e);
                    failedAds.add(ad.getShortName());
                    continue;
                }
            }
        }
        out.close();
        log.info("Skipped " + failedAds.size() + " array designs : " + Arrays.toString(failedAds.toArray()));
        log.info("Finished running in " + timer.getTime() + " ms.");
        log.info("Wrote " + lineCount + " lines to " + outFile);

    } catch (Exception e) {
        return e;
    }
    return null;
}

From source file:net.nan21.dnet.core.web.controller.data.AbstractDsWriteController.java

/**
 * Default handler for insert action.//  w w  w. j a  v a  2  s  .c o  m
 * 
 * @param resourceName
 * @param dataformat
 * @param dataString
 * @param paramString
 * @return
 * @throws Exception
 */
@RequestMapping(method = RequestMethod.POST, params = Constants.REQUEST_PARAM_ACTION + "="
        + Constants.DS_ACTION_INSERT)
@ResponseBody
public String insert(@PathVariable String resourceName, @PathVariable String dataFormat,
        @RequestParam(value = Constants.REQUEST_PARAM_DATA, required = false, defaultValue = "{}") String dataString,
        @RequestParam(value = Constants.REQUEST_PARAM_PARAMS, required = false, defaultValue = "{}") String paramString,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {

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

        if (logger.isInfoEnabled()) {
            logger.info("Processing request: {}.{} -> action = {} ",
                    new String[] { resourceName, dataFormat, Constants.DS_ACTION_INSERT });
        }

        if (logger.isDebugEnabled()) {
            logger.debug("  --> request-data: {} ", new String[] { dataString });
            logger.debug("  --> request-params: {} ", new String[] { paramString });
        }

        this.prepareRequest(request, response);

        this.authorizeDsAction(resourceName, Constants.DS_ACTION_INSERT, null);

        if (!dataString.startsWith("[")) {
            dataString = "[" + dataString + "]";
        }

        IDsService<M, F, P> service = this.findDsService(resourceName);
        IDsMarshaller<M, F, P> marshaller = service.createMarshaller(IDsMarshaller.JSON);

        List<M> list = marshaller.readListFromString(dataString);
        P params = marshaller.readParamsFromString(paramString);

        service.insert(list, params);

        IActionResultSave result = this.packResultSave(list, params);
        stopWatch.stop();
        result.setExecutionTime(stopWatch.getTime());

        String out = null;

        if (dataFormat.equals(IDsMarshaller.XML)) {
            IDsMarshaller<M, F, P> resultMarshaller = service.createMarshaller(dataFormat);
            out = resultMarshaller.writeResultToString(result);
            response.setContentType("text/xml; charset=UTF-8");
        } else {
            out = marshaller.writeResultToString(result);
            response.setContentType("text/plain; charset=UTF-8");
        }

        return out;

    } catch (Exception e) {
        return this.handleException(e, response);
    } finally {
        this.finishRequest();
    }
}