Example usage for org.apache.commons.lang3 StringUtils strip

List of usage examples for org.apache.commons.lang3 StringUtils strip

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils strip.

Prototype

public static String strip(final String str) 

Source Link

Document

Strips whitespace from the start and end of a String.

This is similar to #trim(String) but removes whitespace.

Usage

From source file:ubic.gemma.core.search.GeneSetSearchImpl.java

private Collection<GeneSet> findByGoId(String query) {
    OntologyTerm goTerm = geneOntologyService.getTermForId(StringUtils.strip(query));

    if (goTerm == null) {
        return new HashSet<>();
    }//from   www  .  j a v  a  2s. c o  m
    // if taxon is null, this returns genesets for all taxa
    return this.goTermToGeneSets(goTerm, GeneSetSearchImpl.MAX_GO_GROUP_SIZE);
}

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

/**
 * Search for the Experiment query in ontologies, including items that are associated with children of matching
 * query terms./*from ww  w .  j a  va2  s.  c o m*/
 * That is, 'brain' should return entities tagged as 'hippocampus'. This method will return results only up to
 * MAX_CHARACTERISTIC_SEARCH_RESULTS. It can handle AND in searches, so Parkinson's AND neuron finds items tagged
 * with both of those terms. The use of OR is handled by the caller.
 *
 * @param classes Classes of characteristic-bound entities. For example, to get matching characteristics of
 *                ExpressionExperiments, pass ExpressionExperiments.class in this collection parameter.
 * @return SearchResults of CharacteristicObjects. Typically to be useful one needs to retrieve the
 * 'parents'
 * (entities which have been 'tagged' with the term) of those Characteristics
 */
private Collection<SearchResult> characteristicSearchWithChildren(Collection<Class<?>> classes, String query) {
    StopWatch timer = this.startTiming();

    /*
     * The tricky part here is if the user has entered a boolean query. If they put in Parkinson's disease AND
     * neuron,
     * then we want to eventually return entities that are associated with both. We don't expect to find single
     * characteristics that match both.
     *
     * But if they put in Parkinson's disease we don't want to do two queries.
     */
    String[] subparts = query.split(" AND ");

    // we would have to first deal with the separate queries, and then apply the logic.
    Collection<SearchResult> allResults = new HashSet<>();

    SearchServiceImpl.log
            .info("Starting characteristic search: " + query + " for type=" + StringUtils.join(classes, ","));
    for (String rawTerm : subparts) {
        String trimmed = StringUtils.strip(rawTerm);
        if (StringUtils.isBlank(trimmed)) {
            continue;
        }
        Collection<SearchResult> subqueryResults = this.characteristicSearchTerm(classes, trimmed);
        if (allResults.isEmpty()) {
            allResults.addAll(subqueryResults);
        } else {
            // this is our Intersection operation.
            allResults.retainAll(subqueryResults);

            // aggregate the highlighted text.
            Map<SearchResult, String> highlights = new HashMap<>();
            for (SearchResult sqr : subqueryResults) {
                highlights.put(sqr, sqr.getHighlightedText());
            }

            for (SearchResult ar : allResults) {
                String k = highlights.get(ar);
                if (StringUtils.isNotBlank(k)) {
                    String highlightedText = ar.getHighlightedText();
                    if (StringUtils.isBlank(highlightedText)) {
                        ar.setHighlightedText(k);
                    } else {
                        ar.setHighlightedText(highlightedText + "," + k);
                    }
                }
            }
        }

        if (timer.getTime() > 1000) {
            SearchServiceImpl.log.info("Characteristic search for '" + rawTerm + "': " + allResults.size()
                    + " hits retained so far; " + timer.getTime() + "ms");
            timer.reset();
            timer.start();
        }

    }

    return allResults;

}

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

/**
 * @return results, if the settings.termUri is populated. This includes gene uris.
 *///from   w  w  w . j a  va2s  .co  m
private Map<Class<?>, List<SearchResult>> ontologyUriSearch(SearchSettings settings) {
    Map<Class<?>, List<SearchResult>> results = new HashMap<>();

    // 1st check to see if the query is a URI (from an ontology).
    // Do this by seeing if we can find it in the loaded ontologies.
    // Escape with general utilities because might not be doing a lucene backed search. (just a hibernate one).
    String termUri = settings.getTermUri();

    if (StringUtils.isBlank(termUri)) {
        termUri = settings.getQuery();
    }

    if (!termUri.startsWith("http://")) {
        return results;
    }

    OntologyTerm matchingTerm;
    String uriString;

    uriString = StringEscapeUtils.escapeJava(StringUtils.strip(termUri));

    if (StringUtils.containsIgnoreCase(uriString, SearchServiceImpl.NCBI_GENE)) {
        // Perhaps is a valid gene URL. Want to search for the gene in gemma.
        // 1st get objects tagged with the given gene identifier
        Collection<Class<?>> classesToFilterOn = new HashSet<>();
        classesToFilterOn.add(ExpressionExperiment.class);

        Collection<Characteristic> foundCharacteristics = characteristicService.findByUri(classesToFilterOn,
                uriString);
        Map<Characteristic, Object> parentMap = characteristicService.getParents(classesToFilterOn,
                foundCharacteristics);

        Collection<SearchResult> characteristicOwnerResults = this
                .filterCharacteristicOwnersByClass(classesToFilterOn, parentMap);

        if (!characteristicOwnerResults.isEmpty()) {
            results.put(ExpressionExperiment.class, new ArrayList<SearchResult>());
            results.get(ExpressionExperiment.class).addAll(characteristicOwnerResults);
        }

        if (settings.getSearchGenes()) {
            // Get the gene
            String ncbiAccessionFromUri = StringUtils.substringAfterLast(uriString, "/");
            Gene g = null;

            try {
                g = geneService.findByNCBIId(Integer.parseInt(ncbiAccessionFromUri));
            } catch (NumberFormatException e) {
                // ok
            }

            if (g != null) {
                results.put(Gene.class, new ArrayList<SearchResult>());
                results.get(Gene.class).add(new SearchResult(g));
            }
        }
        return results;
    }

    /*
     * Not searching for a gene.
     */
    Collection<SearchResult> matchingResults;
    Collection<Class<?>> classesToSearch = new HashSet<>();
    if (settings.getSearchExperiments()) {
        classesToSearch.add(ExpressionExperiment.class); // not sure ...
        classesToSearch.add(BioMaterial.class);
        classesToSearch.add(FactorValue.class);
    }

    // this doesn't seem to be implemented yet, LiteratureEvidence and GenericEvidence aren't handled in the
    // fillValueObjects method downstream
    /*
     * if ( settings.getSearchPhenotypes() ) { classesToSearch.add( PhenotypeAssociation.class ); }
     */
    matchingTerm = this.ontologyService.getTerm(uriString);
    if (matchingTerm == null || matchingTerm.getUri() == null) {
        /*
         * Maybe the ontology isn't loaded. Look anyway.
         */
        Map<Characteristic, Object> parentMap = characteristicService.getParents(classesToSearch,
                characteristicService.findByUri(classesToSearch, uriString));
        matchingResults = this.filterCharacteristicOwnersByClass(classesToSearch, parentMap);

    } else {

        SearchServiceImpl.log.info("Found ontology term: " + matchingTerm);

        // Was a URI from a loaded ontology soo get the children.
        Collection<OntologyTerm> terms2Search4 = matchingTerm.getChildren(true);
        terms2Search4.add(matchingTerm);

        matchingResults = this.databaseCharacteristicExactUriSearchForOwners(classesToSearch, terms2Search4);
    }

    for (SearchResult searchR : matchingResults) {
        if (results.containsKey(searchR.getResultClass())) {
            results.get(searchR.getResultClass()).add(searchR);
        } else {
            List<SearchResult> rs = new ArrayList<>();
            rs.add(searchR);
            results.put(searchR.getResultClass(), rs);
        }
    }

    return results;
}

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

/**
 * Update characteristics.//from   w w w  .jav a2  s.  c o  m
 * <p>
 * This is used for Experiment tags and the Characteristic browser.
 * <p>
 * For experimental designs, see ExperimentalDesignController.
 *
 * @return
 */
private TaskResult doUpdate() {
    Collection<AnnotationValueObject> avos = taskCommand.getAnnotationValueObjects();
    if (avos.size() == 0)
        return new TaskResult(taskCommand, 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(taskCommand, false);
    }

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

    if (asChars.size() == 0)
        return new TaskResult(taskCommand, 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;
        }

        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");
        }

        assert cFromDatabase != null;

        // preserve original data (which might have been entered by us, but may be from GEO)
        if (StringUtils.isBlank(cFromDatabase.getOriginalValue())) {
            cFromDatabase.setOriginalValue(cFromDatabase.getValue());
        }

        cFromDatabase.setValue(StringUtils.strip(cFromClient.getValue())); // remove whitespace we added to force dirty check
        cFromDatabase.setCategory(StringUtils.strip(cFromClient.getCategory()));

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

        if ((cFromDatabase.getCategoryUri() == null && cFromClient.getCategoryUri() != null)
                || (cFromDatabase.getCategoryUri() != null
                        && !cFromDatabase.getCategoryUri().equals(cFromClient.getCategoryUri()))) {
            log.info("Characteristic category update: " + cFromDatabase + " " + cFromDatabase.getCategoryUri()
                    + " -> " + cFromClient.getCategoryUri() + " associated with " + parent);
            cFromDatabase.setCategoryUri(cFromClient.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(taskCommand, true);

}

From source file:ubic.gemma.web.controller.expression.experiment.ExperimentalDesignControllerImpl.java

/**
 * Filter the characteristicValues to those that we want to display in columns in the biomaterialvalue table.
 *
 * @param result// w w  w .  ja v  a  2s. c  om
 */
private void filterCharacteristics(Collection<BioMaterialValueObject> result) {

    int c = result.size();

    // build map of categories to bmos. No category: can't use.
    Map<String, Collection<BioMaterialValueObject>> map = new HashMap<>();
    for (BioMaterialValueObject bmo : result) {
        for (CharacteristicValueObject ch : bmo.getCharacteristics()) {

            String category = ch.getCategory();
            if (StringUtils.isBlank(category)) {

                /*
                Experimental: split on ":", use first part as the category.
                 */
                if (StringUtils.isNotBlank(ch.getValue()) && ch.getValue().contains(":")) {
                    String[] split = ch.getValue().split(":");
                    category = StringUtils.strip(split[0]);
                } else {
                    continue;
                }
            }

            if (!map.containsKey(category)) {
                map.put(category, new HashSet<BioMaterialValueObject>());
            }
            map.get(category).add(bmo);
        }
    }

    /*
    find ones that don't have a value for each sample, or which have more values than samples, or which are constants
     */
    Collection<String> toremove = new HashSet<>();
    for (String category : map.keySet()) {
        // log.info( ">>>>>>>>>> " + category + ", " + map.get( category ).size() + " items" );
        if (map.get(category).size() != result.size()) {
            toremove.add(category);
            continue;
        }

        // TODO add more exclusions; see also ExpresionExperimentDao.getAnnotationsByBioMaterials
        if (category.equals("LabelCompound") || category.equals("MaterialType")
                || category.equals("molecular entity")) {
            toremove.add(category);
            continue;
        }

        Collection<String> vals = new HashSet<>();
        boolean keeper = false;
        bms: for (BioMaterialValueObject bm : map.get(category)) {
            // log.info( "inspecting " + bm );
            // Find the characteristic that had this category
            for (CharacteristicValueObject ch : bm.getCharacteristics()) {
                String mappedCategory = ch.getCategory();
                String mappedValue = ch.getValue();

                if (StringUtils.isBlank(mappedCategory)) {
                    // redo split (will refactor later)
                    if (StringUtils.isNotBlank(mappedValue) && mappedValue.contains(":")) {
                        String[] split = mappedValue.split(":");
                        mappedCategory = StringUtils.strip(split[0]);
                    } else {
                        continue bms;
                    }
                }

                if (mappedCategory.equals(category)) {
                    if (!vals.contains(mappedValue)) {
                        if (log.isDebugEnabled())
                            log.debug(category + " -> " + mappedValue);
                        vals.add(mappedValue);
                    }

                    //  populate this into the biomaterial
                    //  log.info( category + " -> " + mappedValue );
                    bm.getCharacteristicValues().put(mappedCategory, mappedValue);
                }
            }

            //                if ( vals.size() > 1 ) {
            //                    if ( log.isDebugEnabled() )
            //                        log.debug( category + " -- Keeper with " + vals.size() + " values" );
            //
            //                    keeper = true;
            //                }
        }

        if (vals.size() < 2) {
            toremove.add(category);
        }
    }

    // finally, clean up the bmos.
    for (BioMaterialValueObject bmo : result) {
        for (String lose : toremove) {
            bmo.getCharacteristicValues().remove(lose);
        }
    }

}

From source file:ubic.gemma.web.controller.expression.experiment.ExperimentalDesignControllerImpl.java

@Override
@RequestMapping("/showExperimentalDesign.html")
public ModelAndView show(HttpServletRequest request, HttpServletResponse response) {

    String idstr = request.getParameter("eeid");
    String edStr = request.getParameter("edid");
    if (StringUtils.isBlank(idstr) && StringUtils.isBlank(edStr)) {
        throw new IllegalArgumentException("Must supply 'eeid' or 'edid' parameter");
    }//www .  j a v a2s . c o  m

    Long designId;
    ExpressionExperiment ee;
    ExperimentalDesign experimentalDesign;
    if (StringUtils.isNotBlank(idstr)) {
        try {
            Long id = Long.parseLong(idstr);
            ee = expressionExperimentService.load(id);

            if (ee == null) {
                throw new EntityNotFoundException(
                        "Expression experiment with id=" + id + " cannot be accessed");
            }

            designId = ee.getExperimentalDesign().getId();
            experimentalDesign = experimentalDesignService.load(designId);
            if (experimentalDesign == null) {
                throw new EntityNotFoundException(designId + " not found");
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("eeid must be a number");
        }
    } else {
        try {
            designId = Long.parseLong(edStr);
            experimentalDesign = experimentalDesignService.load(designId);
            if (experimentalDesign == null) {
                throw new EntityNotFoundException(designId + " not found");
            }
            ee = experimentalDesignService.getExpressionExperiment(experimentalDesign);

        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("edid must be a number");
        }
    }

    request.setAttribute("id", designId);

    ee = expressionExperimentService.thawLite(ee);

    // strip white spaces
    String desc = ee.getDescription();
    ee.setDescription(StringUtils.strip(desc));

    ModelAndView mnv = new ModelAndView("experimentalDesign.detail");
    mnv.addObject("taxonId", expressionExperimentService.getTaxon(ee).getId());
    mnv.addObject("hasPopulatedDesign", ee.getExperimentalDesign().getExperimentalFactors().size() > 0);
    mnv.addObject("experimentalDesign", ee.getExperimentalDesign());
    mnv.addObject("expressionExperiment", ee);
    mnv.addObject("currentUserCanEdit", securityService.isEditable(ee) ? "true" : "");
    mnv.addObject("expressionExperimentUrl", AnchorTagUtil.getExpressionExperimentUrl(ee.getId()));

    return mnv;
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentController.java

public ExpressionExperimentDetailsValueObject updateBasics(UpdateEEDetailsCommand command) throws Exception {
    if (command.getEntityId() == null) {
        throw new IllegalArgumentException("Id cannot be null");
    }//from   w  w w  .  ja va  2 s .c  om

    /*
     * This should be fast so I'm not using a background task.
     */
    String details = "Changed: ";
    boolean changed = false;
    Long entityId = command.getEntityId();
    ExpressionExperiment ee = expressionExperimentService.load(entityId);
    if (ee == null)
        throw new IllegalArgumentException("Cannot locate or access experiment with id=" + entityId);

    if (StringUtils.isNotBlank(command.getShortName()) && !command.getShortName().equals(ee.getShortName())) {
        if (expressionExperimentService.findByShortName(command.getShortName()) != null) {
            throw new IllegalArgumentException("An experiment with short name '" + command.getShortName()
                    + "' already exists, you must use a unique name");
        }
        details += "short name (" + ee.getShortName() + " -> " + command.getShortName() + ")";
        changed = true;
        ee.setShortName(command.getShortName());
    }
    if (StringUtils.isNotBlank(command.getName()) && !command.getName().equals(ee.getName())) {
        details += (changed ? ", " : "") + "name (" + ee.getName() + " -> " + command.getName() + ")";
        changed = true;
        ee.setName(command.getName());
    }
    if (StringUtils.isNotBlank(command.getDescription())
            && !command.getDescription().equals(ee.getDescription())) {
        details += (changed ? ", " : "") + "description (" + ee.getDescription() + " -> "
                + command.getDescription() + ")";
        changed = true;
        ee.setDescription(StringUtils.strip(command.getDescription()));
    }
    if (!command.isRemovePrimaryPublication() && StringUtils.isNotBlank(command.getPubMedId())) {
        if (ee.getPrimaryPublication() != null) {
            details += (changed ? ", " : "") + "primary publication (id " + ee.getPrimaryPublication().getId()
                    + " -> " + command.getPubMedId() + ")";
        } else {
            details += (changed ? ", " : "") + "primary publication ( none -> " + command.getPubMedId() + ")";
        }
        changed = true;
        this.updatePubMed(entityId, command.getPubMedId());
    } else if (command.isRemovePrimaryPublication()) {
        details += (changed ? ", " : "") + "removed primary publication";
        changed = true;
        this.removePrimaryPublication(entityId);
    }

    if (changed) {
        ExpressionExperimentController.log.info("Updating " + ee);
        auditTrailService.addUpdateEvent(ee, CommentedEvent.Factory.newInstance(), "Updated experiment details",
                details);
        expressionExperimentService.update(ee);
    }

    return this.loadExpressionExperimentDetails(ee.getId());
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentLoadController.java

public String load(ExpressionExperimentLoadTaskCommand command) {
    // remove stray whitespace.
    command.setAccession(StringUtils.strip(command.getAccession()));

    if (StringUtils.isBlank(command.getAccession())) {
        throw new IllegalArgumentException("Must provide an accession");
    }//from   w w  w .  j av a 2 s.  c o  m

    return taskRunningService.submitRemoteTask(command);
}

From source file:ubic.gemma.web.services.rest.AnnotationsWebService.java

/**
 * Finds characteristics by either a plain text or URI.
 *
 * @param arg the array arg containing all the strings to search for.
 * @return a collection of characteristics matching the input query.
 *//*  ww w .  ja  va  2 s .co  m*/
private Collection<AnnotationSearchResultValueObject> getTerms(ArrayStringArg arg) {
    Collection<AnnotationSearchResultValueObject> vos = new LinkedList<>();
    for (String query : arg.getValue()) {
        query = query.trim();
        if (query.startsWith(AnnotationsWebService.URL_PREFIX)) {
            this.addAsSearchResults(vos, characteristicService.loadValueObjects(
                    characteristicService.findByUri(StringEscapeUtils.escapeJava(StringUtils.strip(query)))));
        } else {
            this.addAsSearchResults(vos, ontologyService.findExperimentsCharacteristicTags(query, true));
        }
    }
    return vos;
}

From source file:uk.org.funcube.fcdw.satellite.TLE.java

/**
  * Constructor./*ww w.  j a v a 2s  .c  o  m*/
  * 
  * @param tle the three line elements
  * @throws IllegalArgumentException here was something wrong with the TLE
  */
public TLE(final String[] tle) throws IllegalArgumentException {

    if (null == tle) {
        throw new IllegalArgumentException("TLE was null");
    }

    if (tle.length != THREELINES) {
        throw new IllegalArgumentException("TLE had " + tle.length + " elements");
    }

    int lineCount = 0;

    for (final String line : tle) {

        testArguments(lineCount, line);

        lineCount++;
    }

    catnum = Integer.parseInt(StringUtils.strip(tle[1].substring(2, 7)));
    name = tle[0].trim();
    setnum = Integer.parseInt(StringUtils.strip(tle[1].substring(64, 68)));
    year = Integer.parseInt(StringUtils.strip(tle[1].substring(18, 20)));
    refepoch = Double.parseDouble(tle[1].substring(20, 32));
    incl = Double.parseDouble(tle[2].substring(8, 16));
    raan = Double.parseDouble(tle[2].substring(17, 25));
    eccn = 1.0e-07 * Double.parseDouble(tle[2].substring(26, 33));
    argper = Double.parseDouble(tle[2].substring(34, 42));
    meanan = Double.parseDouble(tle[2].substring(43, 51));
    meanmo = Double.parseDouble(tle[2].substring(52, 63));
    drag = Double.parseDouble(tle[1].substring(33, 43));

    double tempnum = 1.0e-5 * Double.parseDouble(tle[1].substring(44, 50));
    nddot6 = tempnum / Math.pow(10.0, Double.parseDouble(tle[1].substring(51, 52)));

    tempnum = 1.0e-5 * Double.parseDouble(tle[1].substring(53, 59));

    bstar = tempnum / Math.pow(10.0, Double.parseDouble(tle[1].substring(60, 61)));

    orbitnum = Integer.parseInt(StringUtils.strip(tle[2].substring(63, 68)));

    /* reassign the values to thse which get used in calculations */
    epoch = (1000.0 * getYear()) + getRefepoch();

    xndt2o = drag;

    double temp = incl;
    temp *= DEG2RAD;
    xincl = temp;

    temp = raan;
    temp *= DEG2RAD;
    xnodeo = temp;

    eo = eccn;

    temp = argper;
    temp *= DEG2RAD;
    omegao = temp;

    temp = meanan;
    temp *= DEG2RAD;
    xmo = temp;

    xno = meanmo;

    /* Preprocess tle set */

    preProcessTLESet();
}