Search in sources :

Example 31 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project pmd by pmd.

the class CycloBaseVisitor method visit.

@Override
public Object visit(ASTSwitchStatement node, Object data) {
    int childCount = node.jjtGetNumChildren();
    int lastIndex = childCount - 1;
    for (int n = 0; n < lastIndex; n++) {
        Node childNode = node.jjtGetChild(n);
        if (childNode instanceof ASTSwitchLabel) {
            // default is not considered a decision (same as "else")
            ASTSwitchLabel sl = (ASTSwitchLabel) childNode;
            if (!sl.isDefault()) {
                // check the label is not empty
                childNode = node.jjtGetChild(n + 1);
                if (childNode instanceof ASTBlockStatement) {
                    ((MutableInt) data).increment();
                }
            }
        }
    }
    super.visit(node, data);
    return data;
}
Also used : Node(net.sourceforge.pmd.lang.ast.Node) ASTBlockStatement(net.sourceforge.pmd.lang.java.ast.ASTBlockStatement) MutableInt(org.apache.commons.lang3.mutable.MutableInt) ASTSwitchLabel(net.sourceforge.pmd.lang.java.ast.ASTSwitchLabel)

Example 32 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project Gemma by PavlidisLab.

the class GeneralSearchControllerImpl method fillValueObjects.

@SuppressWarnings("unchecked")
private void fillValueObjects(Class<?> entityClass, List<SearchResult> results, SearchSettings settings) {
    StopWatch timer = new StopWatch();
    timer.start();
    Collection<?> vos;
    if (ExpressionExperiment.class.isAssignableFrom(entityClass)) {
        vos = this.filterEE(expressionExperimentService.loadValueObjects(EntityUtils.getIds(results), false), settings);
        if (!SecurityUtil.isUserAdmin()) {
            auditableUtil.removeTroubledEes((Collection<ExpressionExperimentValueObject>) vos);
        }
    } else if (ArrayDesign.class.isAssignableFrom(entityClass)) {
        vos = this.filterAD(arrayDesignService.loadValueObjectsByIds(EntityUtils.getIds(results)), settings);
        if (!SecurityUtil.isUserAdmin()) {
            auditableUtil.removeTroubledArrayDesigns((Collection<ArrayDesignValueObject>) vos);
        }
    } else if (CompositeSequence.class.isAssignableFrom(entityClass)) {
        Collection<CompositeSequenceValueObject> css = new ArrayList<>();
        for (SearchResult sr : results) {
            CompositeSequenceValueObject csvo = compositeSequenceService.loadValueObject((CompositeSequence) sr.getResultObject());
            css.add(csvo);
        }
        vos = css;
    } else if (BibliographicReference.class.isAssignableFrom(entityClass)) {
        Collection<BibliographicReference> bss = bibliographicReferenceService.load(EntityUtils.getIds(results));
        bss = bibliographicReferenceService.thaw(bss);
        vos = bibliographicReferenceService.loadValueObjects(bss);
    } else if (Gene.class.isAssignableFrom(entityClass)) {
        Collection<Gene> genes = geneService.load(EntityUtils.getIds(results));
        genes = geneService.thawLite(genes);
        vos = geneService.loadValueObjects(genes);
    } else if (Characteristic.class.isAssignableFrom(entityClass)) {
        Collection<CharacteristicValueObject> cvos = new ArrayList<>();
        for (SearchResult sr : results) {
            Characteristic ch = (Characteristic) sr.getResultObject();
            cvos.add(new CharacteristicValueObject(ch));
        }
        vos = cvos;
    } else if (CharacteristicValueObject.class.isAssignableFrom(entityClass)) {
        Collection<CharacteristicValueObject> cvos = new ArrayList<>();
        for (SearchResult sr : results) {
            CharacteristicValueObject ch = (CharacteristicValueObject) sr.getResultObject();
            cvos.add(ch);
        }
        vos = cvos;
    } else if (BioSequenceValueObject.class.isAssignableFrom(entityClass)) {
        return;
    } else if (GeneSet.class.isAssignableFrom(entityClass)) {
        vos = geneSetService.getValueObjects(EntityUtils.getIds(results));
    } else if (ExpressionExperimentSet.class.isAssignableFrom(entityClass)) {
        vos = experimentSetService.loadValueObjects(experimentSetService.load(EntityUtils.getIds(results)));
    } else if (FactorValue.class.isAssignableFrom(entityClass)) {
        Collection<FactorValueValueObject> fvo = new ArrayList<>();
        for (SearchResult sr : results) {
            fvo.add(new FactorValueValueObject((FactorValue) sr.getResultObject()));
        }
        vos = fvo;
    } else {
        throw new UnsupportedOperationException("Don't know how to make value objects for class=" + entityClass);
    }
    if (vos == null || vos.isEmpty()) {
        // it causing front end errors, if vos is empty make sure to get rid of all search results
        for (Iterator<SearchResult> it = results.iterator(); it.hasNext(); ) {
            it.next();
            it.remove();
        }
        return;
    }
    // retained objects...
    Map<Long, Object> idMap = EntityUtils.getIdMap(vos);
    for (Iterator<SearchResult> it = results.iterator(); it.hasNext(); ) {
        SearchResult sr = it.next();
        if (!idMap.containsKey(sr.getId())) {
            it.remove();
            continue;
        }
        sr.setResultObject(idMap.get(sr.getId()));
    }
    if (timer.getTime() > 1000) {
        BaseFormController.log.info("Value object conversion after search: " + timer.getTime() + "ms");
    }
}
Also used : CharacteristicValueObject(ubic.gemma.model.genome.gene.phenotype.valueObject.CharacteristicValueObject) CompositeSequenceValueObject(ubic.gemma.model.expression.designElement.CompositeSequenceValueObject) Gene(ubic.gemma.model.genome.Gene) ExpressionExperimentValueObject(ubic.gemma.model.expression.experiment.ExpressionExperimentValueObject) BioSequenceValueObject(ubic.gemma.model.genome.sequenceAnalysis.BioSequenceValueObject) FactorValueValueObject(ubic.gemma.model.expression.experiment.FactorValueValueObject) FactorValue(ubic.gemma.model.expression.experiment.FactorValue) ArrayDesign(ubic.gemma.model.expression.arrayDesign.ArrayDesign) Characteristic(ubic.gemma.model.common.description.Characteristic) SearchResult(ubic.gemma.core.search.SearchResult) BibliographicReference(ubic.gemma.model.common.description.BibliographicReference) StopWatch(org.apache.commons.lang3.time.StopWatch) ExpressionExperimentSet(ubic.gemma.model.analysis.expression.ExpressionExperimentSet) ArrayDesignValueObject(ubic.gemma.model.expression.arrayDesign.ArrayDesignValueObject) SearchSettingsValueObject(ubic.gemma.model.common.search.SearchSettingsValueObject) FactorValueValueObject(ubic.gemma.model.expression.experiment.FactorValueValueObject) BioSequenceValueObject(ubic.gemma.model.genome.sequenceAnalysis.BioSequenceValueObject) ExpressionExperimentValueObject(ubic.gemma.model.expression.experiment.ExpressionExperimentValueObject) CompositeSequenceValueObject(ubic.gemma.model.expression.designElement.CompositeSequenceValueObject) CharacteristicValueObject(ubic.gemma.model.genome.gene.phenotype.valueObject.CharacteristicValueObject)

Example 33 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project Gemma by PavlidisLab.

the class DifferentialExpressionResultDaoImpl method addToCache.

/**
 * This is to be called after a query for diff ex results is finished for a set of resultSets and genes. It assumes
 * that if a gene is missing from the results, there are none for that resultSet for that gene. It then stores a
 * dummy entry.
 *
 * @param results      - which might be empty.
 * @param resultSetids - the ones which we searched for in the database. Put in dummy results if we have to.
 */
private void addToCache(Map<Long, Map<Long, DiffExprGeneSearchResult>> results, Collection<Long> resultSetids, Collection<Long> geneIds) {
    StopWatch timer = new StopWatch();
    timer.start();
    int i = 0;
    for (Long resultSetId : resultSetids) {
        Map<Long, DiffExprGeneSearchResult> resultSetResults = results.get(resultSetId);
        for (Long geneId : geneIds) {
            if (resultSetResults != null && resultSetResults.containsKey(geneId)) {
                this.differentialExpressionResultCache.addToCache(resultSetResults.get(geneId));
            } else {
                // put in a dummy, so we don't bother searching for it later.
                this.differentialExpressionResultCache.addToCache(new MissingResult(resultSetId, geneId));
            }
            i++;
        }
    }
    if (timer.getTime() > 10) {
        AbstractDao.log.info("Add " + i + " results to cache: " + timer.getTime() + "ms");
    }
}
Also used : StopWatch(org.apache.commons.lang3.time.StopWatch)

Example 34 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project Gemma by PavlidisLab.

the class DEDVController method handleRequestInternal.

/**
 * Handle case of text export of the results.
 */
@RequestMapping("/downloadDEDV.html")
protected ModelAndView handleRequestInternal(HttpServletRequest request) {
    StopWatch watch = new StopWatch();
    watch.start();
    // might not be any
    Collection<Long> geneIds = ControllerUtils.extractIds(request.getParameter("g"));
    // might not be there
    Collection<Long> eeIds = ControllerUtils.extractIds(request.getParameter("ee"));
    ModelAndView mav = new ModelAndView(new TextView());
    if (eeIds == null || eeIds.isEmpty()) {
        mav.addObject("text", "Input empty for finding DEDVs: " + geneIds + " and " + eeIds);
        return mav;
    }
    String threshSt = request.getParameter("thresh");
    String resultSetIdSt = request.getParameter("rs");
    Double thresh = 100.0;
    if (StringUtils.isNotBlank(threshSt)) {
        try {
            thresh = Double.parseDouble(threshSt);
        } catch (NumberFormatException e) {
            throw new RuntimeException("Threshold was not a valid value: " + threshSt);
        }
    }
    Map<ExpressionExperimentValueObject, Map<Long, Collection<DoubleVectorValueObject>>> result;
    if (request.getParameter("pca") != null) {
        int component = Integer.parseInt(request.getParameter("component"));
        Long eeId = eeIds.iterator().next();
        Map<ProbeLoading, DoubleVectorValueObject> topLoadedVectors = this.svdService.getTopLoadedVectors(eeId, component, thresh.intValue());
        if (topLoadedVectors == null)
            return null;
        mav.addObject("text", format4File(topLoadedVectors.values()));
        return mav;
    }
    /*
         * The following should be set if we're viewing diff. ex results.
         */
    Long resultSetId = null;
    if (StringUtils.isNumeric(resultSetIdSt)) {
        resultSetId = Long.parseLong(resultSetIdSt);
    }
    if (resultSetId != null) {
        /*
             * Diff ex case.
             */
        Long eeId = eeIds.iterator().next();
        Collection<DoubleVectorValueObject> diffExVectors = processedExpressionDataVectorService.getDiffExVectors(resultSetId, thresh, MAX_RESULTS_TO_RETURN);
        if (diffExVectors == null || diffExVectors.isEmpty()) {
            mav.addObject("text", "No results");
            return mav;
        }
        /*
             * Organize the vectors in the same way expected by the ee+gene type of request.
             */
        ExpressionExperimentValueObject ee = expressionExperimentService.loadValueObject(expressionExperimentService.load(eeId));
        result = new HashMap<>();
        Map<Long, Collection<DoubleVectorValueObject>> gmap = new HashMap<>();
        for (DoubleVectorValueObject dv : diffExVectors) {
            for (Long g : dv.getGenes()) {
                if (!gmap.containsKey(g)) {
                    gmap.put(g, new HashSet<DoubleVectorValueObject>());
                }
                gmap.get(g).add(dv);
            }
        }
        result.put(ee, gmap);
    } else {
        // Generic listing.
        result = getDEDV(eeIds, geneIds);
    }
    if (result == null || result.isEmpty()) {
        mav.addObject("text", "No results");
        return mav;
    }
    mav.addObject("text", format4File(result));
    watch.stop();
    Long time = watch.getTime();
    if (time > 100) {
        log.info("Retrieved and Formated" + result.keySet().size() + " DEDVs for eeIDs: " + eeIds + " and GeneIds: " + geneIds + " in : " + time + " ms.");
    }
    return mav;
}
Also used : ModelAndView(org.springframework.web.servlet.ModelAndView) ProbeLoading(ubic.gemma.model.analysis.expression.pca.ProbeLoading) StopWatch(org.apache.commons.lang3.time.StopWatch) TextView(ubic.gemma.web.view.TextView) DoubleVectorValueObject(ubic.gemma.model.expression.bioAssayData.DoubleVectorValueObject) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 35 with EMPTY

use of org.apache.commons.lang3.StringUtils.EMPTY in project halyard by spinnaker.

the class OpenstackAccountValidator method validate.

@Override
public void validate(ConfigProblemSetBuilder psBuilder, OpenstackAccount account) {
    DaemonTaskHandler.message("Validating " + account.getNodeName() + " with " + OpenstackAccountValidator.class.getSimpleName());
    String environment = account.getEnvironment();
    String accountType = account.getAccountType();
    String username = account.getUsername();
    String password = account.getPassword();
    String projectName = account.getPassword();
    String domainName = account.getDomainName();
    String authUrl = account.getAuthUrl();
    List<String> regions = account.getRegions();
    Boolean insecure = account.getInsecure();
    String heatTemplateLocation = account.getHeatTemplateLocation();
    OpenstackAccount.OpenstackLbaasOptions lbaas = account.getLbaas();
    ConsulConfig consulConfig = new ConsulConfig();
    String userDataFile = account.getUserDataFile();
    if (StringUtils.isEmpty(environment)) {
        psBuilder.addProblem(Problem.Severity.ERROR, "You must provide an environment name");
    }
    if (StringUtils.isEmpty(password) || StringUtils.isEmpty(username)) {
        psBuilder.addProblem(Problem.Severity.ERROR, "You must provide a both a username and a password");
    }
    if (StringUtils.isEmpty(projectName)) {
        psBuilder.addProblem(Problem.Severity.ERROR, "You must provide a project name");
    }
    if (!StringUtils.endsWith(authUrl, "/v3")) {
        psBuilder.addProblem(Problem.Severity.WARNING, "You must use Keystone v3. The default auth url will be of the format IP:5000/v3.");
    }
    if (StringUtils.isEmpty(domainName)) {
        psBuilder.addProblem(Problem.Severity.ERROR, "You must provide a domain name");
    }
    if (regions.size() == 0 || StringUtils.isEmpty(regions.get(0))) {
        psBuilder.addProblem(Problem.Severity.ERROR, "You must provide one region");
    }
    if (insecure) {
        psBuilder.addProblem(Problem.Severity.WARNING, "You've chosen to not validate SSL connections. This setup is not recommended in production deployments.");
    }
    if (heatTemplateLocation != null && heatTemplateLocation.isEmpty()) {
        psBuilder.addProblem(Problem.Severity.ERROR, "Not a valid Heat template location: ''");
    }
    if (lbaas.getPollInterval() < 0) {
        psBuilder.addProblem(Problem.Severity.ERROR, "Poll interval cannot be less than 0.").setRemediation("Update this value to be reasonable. Default is 5.");
    }
    if (lbaas.getPollTimeout() < 0) {
        psBuilder.addProblem(Problem.Severity.ERROR, "Poll timeout cannot be less than 0.").setRemediation("Update this value to be reasonable. Default is 60.");
    }
    boolean userDataProvided = userDataFile != null && !userDataFile.isEmpty();
    if (userDataProvided) {
        String resolvedUserData = ValidatingFileReader.contents(psBuilder, userDataFile);
        if (resolvedUserData == null) {
            return;
        } else if (resolvedUserData.isEmpty()) {
            psBuilder.addProblem(Problem.Severity.WARNING, "The supplied user data file is empty.").setRemediation("Please provide a non empty file, or remove the user data file.");
        }
        List<String> validTokens = Arrays.asList("account", "accounttype", "env", "region", "group", "autogrp", "cluster", "stack", "detail", "launchconfig");
        List<String> tokens = Arrays.asList(StringUtils.substringsBetween(resolvedUserData, "%%", "%%"));
        List<String> invalidTokens = tokens.stream().filter(t -> !validTokens.contains(t)).collect(Collectors.toList());
        if (invalidTokens.size() != 0) {
            psBuilder.addProblem(Problem.Severity.WARNING, "The supplied user data file contains tokens that won't be replaced. " + "Tokens \"" + StringUtils.join(invalidTokens, ", ") + "\" are not supported.").setRemediation("Please use only the supported tokens \"" + StringUtils.join(validTokens, ", ") + "\".");
        }
    }
    OpenstackConfigurationProperties.LbaasConfig lbaasConfig = new OpenstackConfigurationProperties.LbaasConfig();
    lbaasConfig.setPollInterval(lbaas.getPollInterval());
    lbaasConfig.setPollTimeout(lbaas.getPollTimeout());
    try {
        OpenstackNamedAccountCredentials openstackCredentials = new OpenstackNamedAccountCredentials.Builder().name(account.getName()).environment(environment).accountType(accountType).authUrl(authUrl).username(username).password(password).projectName(projectName).domainName(domainName).regions(regions).insecure(insecure).heatTemplateLocation(heatTemplateLocation).consulConfig(consulConfig).lbaasConfig(lbaasConfig).userDataFile(userDataFile).build();
        credentialsList.add(openstackCredentials);
    // TODO(emjburns) verify that these credentials can connect w/o error to the openstack instance
    } catch (Exception e) {
        psBuilder.addProblem(Problem.Severity.ERROR, "Failed to instantiate openstack credentials for account \"" + account.getName() + "\".");
    }
}
Also used : OpenstackNamedAccountCredentials(com.netflix.spinnaker.clouddriver.openstack.security.OpenstackNamedAccountCredentials) Arrays(java.util.Arrays) OpenstackConfigurationProperties(com.netflix.spinnaker.clouddriver.openstack.config.OpenstackConfigurationProperties) OpenstackAccount(com.netflix.spinnaker.halyard.config.model.v1.providers.openstack.OpenstackAccount) EqualsAndHashCode(lombok.EqualsAndHashCode) ConfigProblemSetBuilder(com.netflix.spinnaker.halyard.config.problem.v1.ConfigProblemSetBuilder) StringUtils(org.apache.commons.lang3.StringUtils) Collectors(java.util.stream.Collectors) DaemonTaskHandler(com.netflix.spinnaker.halyard.core.tasks.v1.DaemonTaskHandler) ConsulConfig(com.netflix.spinnaker.clouddriver.consul.config.ConsulConfig) List(java.util.List) Validator(com.netflix.spinnaker.halyard.config.model.v1.node.Validator) Data(lombok.Data) Problem(com.netflix.spinnaker.halyard.core.problem.v1.Problem) ValidatingFileReader(com.netflix.spinnaker.halyard.config.validate.v1.util.ValidatingFileReader) ConsulConfig(com.netflix.spinnaker.clouddriver.consul.config.ConsulConfig) OpenstackConfigurationProperties(com.netflix.spinnaker.clouddriver.openstack.config.OpenstackConfigurationProperties) OpenstackNamedAccountCredentials(com.netflix.spinnaker.clouddriver.openstack.security.OpenstackNamedAccountCredentials) OpenstackAccount(com.netflix.spinnaker.halyard.config.model.v1.providers.openstack.OpenstackAccount)

Aggregations

List (java.util.List)44 Map (java.util.Map)42 ArrayList (java.util.ArrayList)41 StringUtils (org.apache.commons.lang3.StringUtils)38 Collectors (java.util.stream.Collectors)37 HashMap (java.util.HashMap)33 IOException (java.io.IOException)27 Set (java.util.Set)25 HashSet (java.util.HashSet)22 LoggerFactory (org.slf4j.LoggerFactory)22 Pair (org.apache.commons.lang3.tuple.Pair)20 Logger (org.slf4j.Logger)20 Optional (java.util.Optional)19 Collections (java.util.Collections)17 ImmutablePair (org.apache.commons.lang3.tuple.ImmutablePair)17 java.util (java.util)15 Arrays.asList (java.util.Arrays.asList)14 Collection (java.util.Collection)14 Stream (java.util.stream.Stream)14 Arrays (java.util.Arrays)12