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:ubic.gemma.search.SearchServiceImpl.java

/**
 * Searches the DB for array designs which have composite sequences whose names match the given search string.
 * Because of the underlying database search, this is acl aware. That is, returned array designs are filtered based
 * on access control list (ACL) permissions.
 * //www .j ava2 s  . c  o m
 * @param searchString
 * @return
 * @throws Exception
 */
private Collection<SearchResult> databaseArrayDesignSearch(SearchSettings settings) {

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

    StopWatch watch = startTiming();

    Collection<ArrayDesign> adSet = new HashSet<ArrayDesign>();

    // search by exact composite sequence name
    Collection<CompositeSequence> matchedCs = compositeSequenceService.findByName(settings.getQuery());
    for (CompositeSequence sequence : matchedCs) {
        adSet.add(sequence.getArrayDesign());
    }

    watch.stop();
    if (watch.getTime() > 1000)
        log.info("Array Design Compositesequence DB search for " + settings + " took " + watch.getTime() + " ms"
                + " found " + adSet.size() + " Ads");

    return dbHitsToSearchResult(adSet);

}

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

/**
 * A database serach for biosequences. Biosequence names are already indexed by compass...
 * // ww w.  j av  a2s .  c  o  m
 * @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.
 * //  w w  w  .  ja va 2 s.c o 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 .  j a v  a  2 s. 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//w  w  w  .  j a va2 s  .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.
 * //from   w w w .  j ava2  s  .c  o  m
 * @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

/**
 * Combines compass style search, the db style search, and the compositeSequence search and returns 1 combined list
 * with no duplicates.//  w ww.j  ava 2s. co m
 * 
 * @param searchSettings
 * @param returnOnDbHit if true and if there is a match for a gene from the database, return immediately
 * @return
 * @throws Exception
 */
private Collection<SearchResult> geneSearch(final SearchSettings settings, boolean returnOnDbHit) {

    StopWatch watch = startTiming();

    String searchString = settings.getQuery();

    Collection<SearchResult> geneDbList = databaseGeneSearch(settings);

    if (returnOnDbHit && geneDbList.size() > 0) {
        return geneDbList;
    }

    Set<SearchResult> combinedGeneList = new HashSet<SearchResult>();
    combinedGeneList.addAll(geneDbList);

    Collection<SearchResult> geneCompassList = compassGeneSearch(settings);
    combinedGeneList.addAll(geneCompassList);

    if (combinedGeneList.size() == 0) {
        Collection<SearchResult> geneCsList = databaseCompositeSequenceSearch(settings);
        for (SearchResult res : geneCsList) {
            if (res.getResultClass().isAssignableFrom(Gene.class))
                combinedGeneList.add(res);
        }
    }

    // filterByTaxon( settings, combinedGeneList); // compass doesn't return filled gene objects, just ids, so do
    // this after objects have been filled

    if (watch.getTime() > 1000)
        log.info("Gene search for " + searchString + " took " + watch.getTime() + " ms; "
                + combinedGeneList.size() + " results.");
    return combinedGeneList;
}

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

/**
 * @param hits//from   w  ww  . j av  a 2s  .  c  o m
 * @return
 */
private Collection<SearchResult> getSearchResults(CompassHits hits) {
    StopWatch timer = new StopWatch();
    timer.start();
    Collection<SearchResult> results = new HashSet<SearchResult>();
    /*
     * Note that hits come in decreasing score order.
     */
    for (int i = 0, len = Math.min(MAX_LUCENE_HITS, hits.getLength()); i < len; i++) {

        SearchResult r = new SearchResult(hits.data(i));

        /*
         * Always give compass hits a lower score so they can be differentiated from exact database hits.
         */
        r.setScore(new Double(hits.score(i) * COMPASS_HIT_SCORE_PENALTY_FACTOR));

        getHighlightedText(hits, i, r);

        if (log.isDebugEnabled())
            log.debug(i + " " + hits.score(i) + " " + r);

        results.add(r);
    }

    if (timer.getTime() > 100) {
        log.info(results.size() + " hits retrieved (out of " + Math.min(MAX_LUCENE_HITS, hits.getLength())
                + " raw hits tested) in " + timer.getTime() + "ms");
    }
    if (timer.getTime() > 5000) {
        log.info("****Extremely long Lucene Search processing! " + results.size() + " hits retrieved (out of "
                + Math.min(MAX_LUCENE_HITS, hits.getLength()) + " raw hits tested) in " + timer.getTime()
                + "ms");
    }

    return results;
}

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

/**
 * Runs inside Compass transaction/*from   w w  w  . j av a 2 s.c om*/
 * 
 * @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.security.authorization.acl.AclAfterFilterValueObjectCollectionProvider.java

@Override
@SuppressWarnings("unchecked")
public final Object decide(Authentication authentication, Object object, Collection<ConfigAttribute> config,
        Object returnedObject) throws AccessDeniedException {
    Iterator<ConfigAttribute> iter = config.iterator();

    while (iter.hasNext()) {
        ConfigAttribute attr = iter.next();

        if (this.supports(attr)) {
            // Need to process the Collection for this invocation
            if (returnedObject == null) {
                logger.debug("Return object is null, skipping");
                return returnedObject;
            }//from w w w  .  jav a2s .  co m

            Filterer<Object> filterer = null;

            if (returnedObject instanceof Collection) {
                Collection<Object> collection = (Collection<Object>) returnedObject;
                filterer = new CollectionFilterer<Object>(collection);
            } else if (returnedObject.getClass().isArray()) {
                Object[] array = (Object[]) returnedObject;
                filterer = new ArrayFilterer<Object>(array);
            } else {
                throw new UnsupportedOperationException("Must be a Collection");
            }

            // Locate unauthorised Collection elements
            Iterator<Object> collectionIter = filterer.iterator();

            /*
             * Collect up the securevalueobjects
             */
            Collection<SecureValueObject> securablesToFilter = new HashSet<SecureValueObject>();
            while (collectionIter.hasNext()) {
                Object domainObject = collectionIter.next();
                if (!SecureValueObject.class.isAssignableFrom(domainObject.getClass())) {
                    continue;
                }
                securablesToFilter.add((SecureValueObject) domainObject);
            }

            Map<SecureValueObject, Boolean> hasPerm = securityService.hasPermission(securablesToFilter,
                    this.requirePermission, authentication);

            for (SecureValueObject s : hasPerm.keySet()) {
                if (!hasPerm.get(s)) {
                    filterer.remove(s);
                }
            }

            if (((Collection<SecureValueObject>) filterer.getFilteredObject()).isEmpty()) {
                return filterer.getFilteredObject();
            }

            // Following are only relevant if you are logged in.
            if (!SecurityServiceImpl.isUserLoggedIn()) {
                return filterer.getFilteredObject();
            }

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

            Map<Securable, Acl> acls = securityService
                    .getAcls((Collection<SecureValueObject>) filterer.getFilteredObject());

            Map<Securable, Boolean> areOwnedByCurrentUser = securityService
                    .areOwnedByCurrentUser((Collection<SecureValueObject>) filterer.getFilteredObject());
            boolean userIsAdmin = SecurityServiceImpl.isUserAdmin();

            // Only need to check for write permissions if we can't already infer it.
            Map<SecureValueObject, Boolean> canWrite = new HashMap<SecureValueObject, Boolean>();
            if (!userIsAdmin && !requirePermission.contains(BasePermission.WRITE)) {
                List<Permission> writePermissions = new ArrayList<Permission>();
                writePermissions.add(BasePermission.WRITE);
                canWrite = securityService.hasPermission(securablesToFilter, this.requirePermission,
                        authentication);
            }

            for (Securable s : acls.keySet()) {

                /*
                 * Populate optional fields in the ValueObject.
                 */

                SecureValueObject svo = (SecureValueObject) s;

                // this should be fast, but could be even faster.
                Acl acl = acls.get(s);
                svo.setIsPublic(!SecurityUtil.isPrivate(acl));
                svo.setIsShared(SecurityUtil.isShared(acl));
                svo.setUserOwned(areOwnedByCurrentUser.get(s));

                if (svo.getUserOwned() || userIsAdmin || requirePermission.contains(BasePermission.WRITE)) {
                    svo.setUserCanWrite(true);
                } else {
                    svo.setUserCanWrite(canWrite.containsKey(s) && canWrite.get(s));
                }
            }

            if (timer.getTime() > 100) {
                logger.info("Fill in security details on " + acls.keySet().size() + " value objects: "
                        + timer.getTime() + "ms");
            }
            return filterer.getFilteredObject();
        }
    }

    return returnedObject;
}