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

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

Introduction

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

Prototype

public void stop() 

Source Link

Document

Stop the stopwatch.

This method ends a new timing session, allowing the time to be retrieved.

Usage

From source file:ubic.gemma.search.SearchServiceImpl.java

/**
 * A database serach for biosequences. Biosequence names are already indexed by compass...
 * /* w w w .  j a va2s. c  om*/
 * @param searchString
 * @return
 */
private Collection<SearchResult> databaseBioSequenceSearch(SearchSettings settings) {

    if (!settings.getUseDatabase())
        return new HashSet<SearchResult>();

    StopWatch watch = startTiming();

    String searchString = settings.getQuery();

    // replace * with % for inexact symbol search
    String inexactString = searchString;
    Pattern pattern = Pattern.compile("\\*");
    Matcher match = pattern.matcher(inexactString);
    inexactString = match.replaceAll("%");

    Collection<BioSequence> bs = bioSequenceService.findByName(inexactString);
    // bioSequenceService.thaw( bs );
    Collection<SearchResult> bioSequenceList = new HashSet<SearchResult>(dbHitsToSearchResult(bs));

    watch.stop();
    if (watch.getTime() > 1000)
        log.info("BioSequence DB search for " + searchString + " took " + watch.getTime() + " ms and found"
                + bioSequenceList.size() + " BioSequences");

    return bioSequenceList;
}

From source file:ubic.gemma.search.SearchServiceImpl.java

/**
 * Search the DB for composite sequences and the genes that are matched to them.
 * //from w ww .j a va2  s  . co  m
 * @param searchString
 * @return
 * @throws Exception
 */
private Collection<SearchResult> databaseCompositeSequenceSearch(final SearchSettings settings) {

    if (!settings.getUseDatabase())
        return new HashSet<SearchResult>();

    StopWatch watch = startTiming();

    Set<Gene> geneSet = new HashSet<Gene>();

    String searchString = settings.getQuery();
    ArrayDesign ad = settings.getPlatformConstraint();

    // search by exact composite sequence name
    Collection<CompositeSequence> matchedCs = new HashSet<CompositeSequence>();
    if (ad != null) {
        CompositeSequence cs = compositeSequenceService.findByName(ad, searchString);
        matchedCs.add(cs);
    } else {
        matchedCs = compositeSequenceService.findByName(searchString);
    }

    /*
     * In case the query _is_ a gene
     */
    Collection<SearchResult> rawGeneResults = this.databaseGeneSearch(settings);
    for (SearchResult searchResult : rawGeneResults) {
        Object j = searchResult.getResultObject();
        if (Gene.class.isAssignableFrom(j.getClass())) {
            geneSet.add((Gene) j);
        }
    }

    for (Gene g : geneSet) {
        if (settings.getPlatformConstraint() != null) {
            matchedCs.addAll(compositeSequenceService.findByGene(g, settings.getPlatformConstraint()));
        } else {
            matchedCs.addAll(compositeSequenceService.findByGene(g));
        }
    }

    // search by associated genes.
    for (CompositeSequence sequence : matchedCs) {
        geneSet.addAll(compositeSequenceService.getGenes(sequence));
    }

    watch.stop();
    if (watch.getTime() > 1000)
        log.info("Gene composite sequence DB search " + searchString + " took " + watch.getTime() + " ms, "
                + geneSet.size() + " items.");

    Collection<SearchResult> results = dbHitsToSearchResult(geneSet);

    results.addAll(dbHitsToSearchResult(matchedCs));

    return results;
}

From source file:ubic.gemma.search.SearchServiceImpl.java

/**
 * Does search on exact string by: id, name and short name. This only returns results if these fields match exactly,
 * but it's fast.//from w w w  .  ja v  a 2s. c o m
 * 
 * @param query
 * @return {@link Collection}
 */
private Collection<SearchResult> databaseExpressionExperimentSearch(final SearchSettings settings) {

    if (!settings.getUseDatabase())
        return new HashSet<SearchResult>();

    StopWatch watch = startTiming();

    Map<ExpressionExperiment, String> results = new HashMap<ExpressionExperiment, String>();
    String query = StringEscapeUtils.unescapeJava(settings.getQuery());
    Collection<ExpressionExperiment> ees = expressionExperimentService.findByName(query);
    if (!ees.isEmpty()) {
        for (ExpressionExperiment ee : ees) {
            results.put(ee, ee.getName());
        }
    } else {
        ExpressionExperiment ee = expressionExperimentService.findByShortName(query);
        if (ee != null) {
            results.put(ee, ee.getShortName());
        } else {

            ees = expressionExperimentService.findByAccession(query);
            for (ExpressionExperiment e : ees) {
                results.put(e, e.getId().toString());
            }

            if (results.isEmpty()) {
                try {
                    // maybe user put in a primary key value.
                    ee = expressionExperimentService.load(new Long(query));
                    if (ee != null)
                        results.put(ee, ee.getId().toString());
                } catch (NumberFormatException e) {
                    // no-op - it's not an ID.
                }
            }
        }
    }

    watch.stop();
    if (watch.getTime() > 1000)
        log.info("DB Expression Experiment search for " + settings + " took " + watch.getTime()
                + " ms and found " + results.size() + " EEs");

    Collection<SearchResult> r = dbHitsToSearchResult(results);
    return r;
}

From source file:ubic.gemma.search.SearchServiceImpl.java

/**
 * Search the DB for genes that exactly match the given search string searches geneProducts, gene and bioSequence
 * tables// www . j a va2s.c o  m
 * 
 * @param searchString
 * @return
 * @throws Exception
 */
private Collection<SearchResult> databaseGeneSearch(SearchSettings settings) {

    if (!settings.getUseDatabase())
        return new HashSet<SearchResult>();

    StopWatch watch = startTiming();
    String searchString = StringEscapeUtils.unescapeJava(settings.getQuery());
    if (StringUtils.isBlank(searchString))
        return new HashSet<SearchResult>();

    Collection<SearchResult> results = new HashSet<SearchResult>();

    /*
     * First search by accession. If we find it, stop.
     */
    Gene result = null;
    try {
        result = geneService.findByNCBIId(Integer.parseInt(searchString));
    } catch (NumberFormatException e) {
        //
    }
    if (result != null) {
        results.add(this.dbHitToSearchResult(null, result));
    } else {
        result = geneService.findByAccession(searchString, null);
        if (result != null) {
            results.add(this.dbHitToSearchResult(null, result));
        }
    }
    if (results.size() > 0) {
        filterByTaxon(settings, results, true);
        watch.stop();
        if (watch.getTime() > 1000)
            log.info("Gene DB search for " + searchString + " took " + watch.getTime() + " ms and found "
                    + results.size() + " genes");
        return results;
    }

    // replace * at end with % for inexact symbol search
    String inexactString = searchString;
    Pattern pattern = Pattern.compile("\\*$");
    Matcher match = pattern.matcher(inexactString);
    inexactString = match.replaceAll("%");
    // note that at this point, the inexactString might not have a wildcard - only if the user asked for it.

    String exactString = inexactString.replaceAll("%", "");

    // if the query is shortish, always do a wild card search. This gives better behavior in 'live
    // search' situations. If we do wildcards on very short queries we get too many results.
    Collection<Gene> geneSet = new HashSet<Gene>();
    if (searchString.length() <= 2) {
        // case 0: user entered a very short string. We search only for exact matches.
        geneSet.addAll(geneService.findByOfficialSymbolInexact(exactString));
    } else if (searchString.length() > 2 && inexactString.endsWith("%")) {
        // case 1: user asked for wildcard. We allow this on strings of length 3 or more.
        geneSet.addAll(geneService.findByOfficialSymbolInexact(inexactString));
    } else if (searchString.length() > 3 && searchString.length() < 6) {
        // case 2: user did not ask for a wildcard, but we add it anyway, if the string is 4 or 5 characters.
        if (!inexactString.endsWith("%")) {
            inexactString = inexactString + "%";
        }
        geneSet.addAll(geneService.findByOfficialSymbolInexact(inexactString));

    } else {
        // case 3: string is long enough, and user did not ask for wildcard.
        geneSet.addAll(geneService.findByOfficialSymbol(exactString));
    }

    /*
     * If we found a match using official symbol or name, don't bother with this
     */
    if (geneSet.isEmpty()) {
        geneSet.addAll(geneService.findByAlias(exactString));
        geneSet.addAll(geneProductService.getGenesByName(exactString));
        geneSet.addAll(geneProductService.getGenesByNcbiId(exactString));
        geneSet.addAll(bioSequenceService.getGenesByAccession(exactString));
        geneSet.addAll(bioSequenceService.getGenesByName(exactString));
        geneSet.addAll(geneService.findByEnsemblId(exactString));
    }

    watch.stop();
    if (watch.getTime() > 1000)
        log.info("Gene DB search for " + searchString + " took " + watch.getTime() + " ms and found "
                + geneSet.size() + " genes");

    results = dbHitsToSearchResult(geneSet);
    filterByTaxon(settings, results, true);
    return results;
}

From source file:ubic.gemma.search.SearchServiceImpl.java

/**
 * A general search for expression experiments. This search does both an database search and a compass search.
 * /*  w w w. j  a  v  a2  s  .c om*/
 * @param settings
 * @return {@link Collection}
 */
private Collection<SearchResult> expressionExperimentSearch(final SearchSettings settings) {
    StopWatch watch = startTiming();

    Collection<SearchResult> results = new HashSet<SearchResult>();

    if (settings.getUseDatabase()) {
        results.addAll(databaseExpressionExperimentSearch(settings));
    }

    if (results.size() == 0) {
        /*
         * User didn't put in an exact id, so they get a slower more thorough search.
         */

        if (settings.getUseIndices()) {
            results.addAll(compassExpressionSearch(settings));
        }

        // a submethod of this one (ontologySearchAnnotatedObject) takes a long time
        if (settings.getUseCharacteristics()) {
            results.addAll(characteristicExpressionExperimentSearch(settings));
        }
    }

    /*
     * Find data sets that match the platform -- TODO make this do something intelligent with GPL570 + brain.
     */
    if (results.size() == 0) {
        Collection<SearchResult> matchingPlatforms = arrayDesignSearch(settings, null);
        for (SearchResult adRes : matchingPlatforms) {
            if (adRes.getResultObject() instanceof ArrayDesign) {
                ArrayDesign ad = (ArrayDesign) adRes.getResultObject();
                Collection<ExpressionExperiment> expressionExperiments = this.arrayDesignService
                        .getExpressionExperiments(ad);
                if (expressionExperiments.size() > 0)
                    results.addAll(dbHitsToSearchResult(expressionExperiments));
            }
        }
    }

    if (results.size() == 0) {
        /*
         * Search for bib refs
         */
        List<BibliographicReferenceValueObject> bibrefs = bibliographicReferenceService
                .search(settings.getQuery());

        if (!bibrefs.isEmpty()) {
            Collection<BibliographicReference> refs = new HashSet<BibliographicReference>();
            Collection<SearchResult> r = this.compassBibliographicReferenceSearch(settings);
            for (SearchResult searchResult : r) {
                refs.add((BibliographicReference) searchResult.getResultObject());
            }

            Map<BibliographicReference, Collection<ExpressionExperiment>> relatedExperiments = this.bibliographicReferenceService
                    .getRelatedExperiments(refs);
            for (Entry<BibliographicReference, Collection<ExpressionExperiment>> e : relatedExperiments
                    .entrySet()) {
                results.addAll(dbHitsToSearchResult(e.getValue()));
            }
        }
    }

    watch.stop();
    if (watch.getTime() > 1000)
        log.info("Expression Experiment search for '" + settings + "' took " + watch.getTime() + " ms, "
                + results.size() + " hits.");

    return results;
}

From source file:ubic.gemma.search.SearchServiceImpl.java

/**
 * Runs inside Compass transaction//  w w w.j  av  a  2s .c  o  m
 * 
 * @param query
 * @param session
 * @return
 */
Collection<SearchResult> performSearch(SearchSettings settings, CompassSession session) {
    StopWatch watch = startTiming();

    String query = settings.getQuery().trim();
    // Search results should contain all the words from the query.
    query = query.replaceAll("\\s+", " AND ");

    if (StringUtils.isBlank(query) || query.length() < MINIMUM_STRING_LENGTH_FOR_FREE_TEXT_SEARCH
            || query.equals("*"))
        return new ArrayList<SearchResult>();

    CompassQuery compassQuery = session.queryBuilder().queryString(query).toQuery();
    CompassHits hits = compassQuery.hits();

    watch.stop();
    if (watch.getTime() > 100) {
        log.info("Getting " + hits.getLength() + " lucene hits for " + query + " took " + watch.getTime()
                + " ms");
    }
    if (watch.getTime() > 5000) {
        log.info("*****Extremely long Lucene Index Search!  " + hits.getLength() + " lucene hits for " + query
                + " took " + watch.getTime() + " ms");
    }

    return getSearchResults(hits);
}

From source file:ubic.gemma.tasks.maintenance.CharacteristicUpdateTaskImpl.java

/**
 * @param command/* w  ww.  j  av  a2 s.  c o  m*/
 * @return
 */
private TaskResult doUpdate() {
    Collection<AnnotationValueObject> avos = command.getAnnotationValueObjects();
    if (avos.size() == 0)
        return new TaskResult(command, false);
    log.info("Updating " + avos.size() + " characteristics or uncharacterized factor values...");
    StopWatch timer = new StopWatch();
    timer.start();

    Collection<Characteristic> asChars = convertToCharacteristic(avos);
    Collection<FactorValue> factorValues = convertToFactorValuesWithCharacteristics(avos);

    if (asChars.size() == 0 && factorValues.size() == 0) {
        log.info("Nothing to update");
        return new TaskResult(command, false);
    }

    for (FactorValue factorValue : factorValues) {
        factorValueService.update(factorValue);
    }

    if (asChars.size() == 0)
        return new TaskResult(command, true);

    Map<Characteristic, Object> charToParent = characteristicService.getParents(asChars);

    for (Characteristic cFromClient : asChars) {
        Long characteristicId = cFromClient.getId();
        if (characteristicId == null) {
            continue;
        }
        Characteristic cFromDatabase = characteristicService.load(characteristicId);

        if (cFromDatabase == null) {
            log.warn("No such characteristic with id=" + characteristicId);
            continue;
        }

        VocabCharacteristic vcFromClient = (cFromClient instanceof VocabCharacteristic)
                ? (VocabCharacteristic) cFromClient
                : null;
        VocabCharacteristic vcFromDatabase = (cFromDatabase instanceof VocabCharacteristic)
                ? (VocabCharacteristic) cFromDatabase
                : null;

        /*
         * if one of the characteristics is a VocabCharacteristic and the other is not, we have to change the
         * characteristic in the database so that it matches the one from the client; since we can't change the
         * class of the object, we have to delete the old characteristic and make a new one of the appropriate
         * class.
         */
        Object parent = charToParent.get(cFromDatabase);

        /*
         * Check needed because Characteristics are not securable.
         */
        if (parent != null && Securable.class.isAssignableFrom(parent.getClass())
                && !securityService.isEditable((Securable) parent)) {
            throw new AccessDeniedException("Access is denied");
        }

        if (vcFromClient != null && vcFromDatabase == null) {
            VocabCharacteristic vc = VocabCharacteristic.Factory.newInstance();
            vc.setValue(cFromDatabase.getValue());
            vc.setEvidenceCode(cFromDatabase.getEvidenceCode());
            vc.setDescription(cFromDatabase.getDescription());
            vc.setCategory(cFromDatabase.getCategory());
            vc.setName(cFromDatabase.getName());

            vcFromDatabase = (VocabCharacteristic) characteristicService.create(vc);

            removeFromParent(cFromDatabase, parent);
            characteristicService.delete(cFromDatabase);
            addToParent(vcFromDatabase, parent);
            cFromDatabase = vcFromDatabase;
        } else if (vcFromClient == null && vcFromDatabase != null) {
            cFromDatabase = characteristicService.create(
                    Characteristic.Factory.newInstance(vcFromDatabase.getValue(), vcFromDatabase.getCategory(),
                            null, null, vcFromDatabase.getName(), vcFromDatabase.getDescription() // don't copy AuditTrail or Status to avoid
                            // cascade
                            // error... vcFromDatabase.getAuditTrail()
                            , vcFromDatabase.getEvidenceCode()));
            removeFromParent(vcFromDatabase, parent);
            characteristicService.delete(vcFromDatabase);
            addToParent(cFromDatabase, parent);
        }

        /*
         * at this point, cFromDatabase points to the class-corrected characteristic in the database that must be
         * updated with the information coming from the client.
         */
        cFromDatabase.setValue(cFromClient.getValue());
        cFromDatabase.setCategory(cFromClient.getCategory());
        if (cFromDatabase instanceof VocabCharacteristic) {
            vcFromDatabase = (VocabCharacteristic) cFromDatabase;

            if (vcFromClient != null) {
                if (vcFromDatabase.getValueUri() == null || vcFromDatabase.getValueUri() == null
                        || !vcFromDatabase.getValueUri().equals(vcFromClient.getValueUri())) {
                    log.info("Characteristic value update: " + vcFromDatabase + " "
                            + vcFromDatabase.getValueUri() + " -> " + vcFromClient.getValueUri()
                            + " associated with " + parent);
                    vcFromDatabase.setValueUri(vcFromClient.getValueUri());
                }

                if (vcFromDatabase.getCategory() == null || vcFromDatabase.getCategoryUri() == null
                        || !vcFromDatabase.getCategoryUri().equals(vcFromClient.getCategoryUri())) {
                    log.info("Characteristic category update: " + vcFromDatabase + " "
                            + vcFromDatabase.getCategoryUri() + " -> " + vcFromClient.getCategoryUri()
                            + " associated with " + parent);
                    vcFromDatabase.setCategoryUri(vcFromClient.getCategoryUri());
                }
            }
        }

        if (cFromClient.getEvidenceCode() == null) {
            cFromDatabase.setEvidenceCode(GOEvidenceCode.IC); // characteristic has been manually updated
        } else {
            if (!cFromDatabase.getEvidenceCode().equals(cFromClient.getEvidenceCode())) {
                log.info("Characteristic evidence code update: " + cFromDatabase + " "
                        + cFromDatabase.getEvidenceCode() + " -> " + cFromClient.getEvidenceCode());
            }
            cFromDatabase.setEvidenceCode(cFromClient.getEvidenceCode()); // let them change it.
        }

        characteristicService.update(cFromDatabase);
    }
    timer.stop();
    if (timer.getTime() > 1000) {
        log.info("Update took: " + timer.getTime());
    }

    return new TaskResult(command, true);

}

From source file:ubic.gemma.util.SpringContextUtil.java

/**
 * @param testing If true, it will get a test configured-BeanFactory
 * @param isWebApp If true, configuration specific to the web application will be included.
 * @param additionalConfigurationLocations, like "classpath*:/myproject/applicationContext-mine.xml"
 * @return BeanFactory or null if no context could be created.
 *///from  w w  w  .j a  va 2 s  .c o  m
public static BeanFactory getApplicationContext(boolean testing, boolean isWebApp,
        String[] additionalConfigurationLocations) {
    if (ctx == null) {
        String[] paths = getConfigLocations(testing, isWebApp);

        if (additionalConfigurationLocations != null) {
            paths = addPaths(additionalConfigurationLocations, paths);
        }

        StopWatch timer = new StopWatch();
        timer.start();
        ctx = new ClassPathXmlApplicationContext(paths);
        timer.stop();
        if (ctx != null) {
            log.info("Got context in " + timer.getTime() + "ms");
        } else {
            log.fatal("Failed to load context!");
        }
    }
    return ctx;
}

From source file:ubic.gemma.web.services.GenesAtPhysicalLocationEndpoint.java

/**
 * Reads the given <code>requestElement</code>, and sends a the response back.
 * //from w  w  w. ja v a2  s  .  c  o m
 * @param requestElement the contents of the SOAP message as DOM elements
 * @param document a DOM document to be used for constructing <code>Node</code>s
 * @return the response element
 */
@Override
protected Element invokeInternal(Element requestElement, Document document) {
    StopWatch watch = new StopWatch();
    watch.start();

    setLocalName(GENES_PLOC_LOCAL_NAME);
    String startNucleotide = getLastSingleNodeValue(requestElement, "startNucleotide");
    String endNucleotide = getLastSingleNodeValue(requestElement, "endNucleotide");
    String taxId = getLastSingleNodeValue(requestElement, "taxon_id");
    String chromosomeName = getLastSingleNodeValue(requestElement, "chromosome");

    Long taxonId = Long.parseLong(taxId);
    Taxon taxon = taxonService.load(taxonId);

    Long startN = Long.parseLong(startNucleotide);
    Long endN = Long.parseLong(endNucleotide);
    Long length = endN - startN;

    log.info("GenesAtPhysicalLocationEndpoint XML input: startNucleotide,endNucleotide,taxon,chromosome "
            + startN + " ," + endN + ", " + taxonId + " ," + chromosomeName);

    Collection<Chromosome> chroms = this.chromosomeService.find(chromosomeName, taxon);

    PhysicalLocation physicalLocation = PhysicalLocation.Factory.newInstance();
    physicalLocation.setNucleotide(startN);
    physicalLocation.setNucleotideLength(length.intValue());
    physicalLocation.setStrand(null);

    Set<Long> results = new HashSet<Long>(); //so we don't get duplicates didn't want to compare strings when i have longs....
    Set<String> geneIdResults = new HashSet<String>();

    for (Chromosome chrom : chroms) {
        physicalLocation.setChromosome(chrom);
        RelativeLocationData rld = geneService.findNearest(physicalLocation, false);
        if (rld != null && results.add(rld.getNearestGene().getId()))
            geneIdResults.add(rld.getNearestGene().getId().toString());
    }

    Element result = this.buildWrapper(document, geneIdResults, GENES_PLOC_LOCAL_NAME);

    watch.stop();
    Long time = watch.getTime();
    log.debug("XML response for physical location result built in " + time + "ms.");

    return result;
}

From source file:ubic.gemma.web.services.PhysicalLocationEndpoint.java

/**
 * Reads the given <code>requestElement</code>, and sends a the response back.
 * //  w w  w  .ja  va  2  s .  com
 * @param requestElement the contents of the SOAP message as DOM elements
 * @param document a DOM document to be used for constructing <code>Node</code>s
 * @return the response element
 */
@Override
protected Element invokeInternal(Element requestElement, Document document) {
    StopWatch watch = new StopWatch();
    watch.start();

    setLocalName(PLOC_LOCAL_NAME);
    Collection<String> geneResults = getSingleNodeValue(requestElement, "gene_id");
    String geneId = "";

    for (String id : geneResults) {
        geneId = id;
    }

    log.debug("XML input read: gene id, " + geneId);

    Gene gene = geneService.load(Long.parseLong(geneId));

    gene = geneService.thaw(gene);
    PhysicalLocation physicalLocation = geneService.getMaxPhysicalLength(gene);
    log.info("Webservice - Phyisical location for gene: " + gene.getOfficialSymbol() + "physicallocation is: "
            + physicalLocation);

    Element wrapper = buildLocationWrapper(document, physicalLocation.getChromosome().getName(),
            physicalLocation.getNucleotide(), physicalLocation.getNucleotideLength());

    watch.stop();
    Long time = watch.getTime();
    log.debug("XML response for physical location result built in " + time + "ms.");
    return wrapper;
}