Example usage for org.apache.commons.lang ObjectUtils defaultIfNull

List of usage examples for org.apache.commons.lang ObjectUtils defaultIfNull

Introduction

In this page you can find the example usage for org.apache.commons.lang ObjectUtils defaultIfNull.

Prototype

public static <T> T defaultIfNull(T object, T defaultValue) 

Source Link

Document

Returns a default value if the object passed is null.

 ObjectUtils.defaultIfNull(null, null)      = null ObjectUtils.defaultIfNull(null, "")        = "" ObjectUtils.defaultIfNull(null, "zz")      = "zz" ObjectUtils.defaultIfNull("abc", *)        = "abc" ObjectUtils.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE 

Usage

From source file:org.sonar.batch.issue.tracking.FileHashes.java

public String getHash(int line) {
    // indices in array are shifted one line before
    return (String) ObjectUtils.defaultIfNull(hashes[line - 1], "");
}

From source file:org.sonar.batch.scan.ProjectReactorBuilder.java

/**
 * Transforms a comma-separated list String property in to a array of trimmed strings.
 *
 * This works even if they are separated by whitespace characters (space char, EOL, ...)
 *
 *//* w w w  .ja v  a2 s .c o m*/
static String[] getListFromProperty(Map<String, String> properties, String key) {
    return (String[]) ObjectUtils
            .defaultIfNull(StringUtils.stripAll(StringUtils.split(properties.get(key), ',')), new String[0]);
}

From source file:org.sonar.plugins.core.timemachine.AbstractNewCoverageFileAnalyzer.java

private boolean parse(DecoratorContext context) {
    Measure lastCommits = context.getMeasure(CoreMetrics.SCM_LAST_COMMIT_DATETIMES_BY_LINE);
    Measure hitsByLineMeasure = context.getMeasure(getCoverageLineHitsDataMetric());

    if (lastCommits != null && lastCommits.hasData() && hitsByLineMeasure != null
            && hitsByLineMeasure.hasData()) {
        Map<Integer, Date> datesByLine = KeyValueFormat.parseIntDateTime(lastCommits.getData());
        Map<Integer, Integer> hitsByLine = parseCountByLine(hitsByLineMeasure);
        Map<Integer, Integer> conditionsByLine = parseCountByLine(
                context.getMeasure(getConditionsByLineMetric()));
        Map<Integer, Integer> coveredConditionsByLine = parseCountByLine(
                context.getMeasure(getCoveredConditionsByLineMetric()));

        reset();//www. j  a  v a2s  . c om

        for (Map.Entry<Integer, Integer> entry : hitsByLine.entrySet()) {
            int lineId = entry.getKey();
            int hits = entry.getValue();
            int conditions = (Integer) ObjectUtils.defaultIfNull(conditionsByLine.get(lineId), 0);
            int coveredConditions = (Integer) ObjectUtils.defaultIfNull(coveredConditionsByLine.get(lineId), 0);
            Date date = datesByLine.get(lineId);
            for (PeriodStruct struct : structs) {
                struct.analyze(date, hits, conditions, coveredConditions);
            }
        }

        return true;
    }
    return false;
}

From source file:org.sonar.plugins.core.timemachine.NewCoverageFileAnalyzer.java

private boolean parse(DecoratorContext context) {
    Measure lastCommits = context.getMeasure(CoreMetrics.SCM_LAST_COMMIT_DATETIMES_BY_LINE);
    Measure hitsByLineMeasure = context.getMeasure(CoreMetrics.COVERAGE_LINE_HITS_DATA);

    if (lastCommits != null && lastCommits.hasData() && hitsByLineMeasure != null
            && hitsByLineMeasure.hasData()) {
        Map<Integer, Date> datesByLine = KeyValueFormat.parseIntDateTime(lastCommits.getData());
        Map<Integer, Integer> hitsByLine = parseCountByLine(hitsByLineMeasure);
        Map<Integer, Integer> conditionsByLine = parseCountByLine(
                context.getMeasure(CoreMetrics.CONDITIONS_BY_LINE));
        Map<Integer, Integer> coveredConditionsByLine = parseCountByLine(
                context.getMeasure(CoreMetrics.COVERED_CONDITIONS_BY_LINE));

        reset();/* w w w.j  av a2s. c o m*/

        for (Map.Entry<Integer, Integer> entry : hitsByLine.entrySet()) {
            int lineId = entry.getKey();
            int hits = entry.getValue();
            int conditions = (Integer) ObjectUtils.defaultIfNull(conditionsByLine.get(lineId), 0);
            int coveredConditions = (Integer) ObjectUtils.defaultIfNull(coveredConditionsByLine.get(lineId), 0);
            Date date = datesByLine.get(lineId);
            for (PeriodStruct struct : structs) {
                struct.analyze(date, hits, conditions, coveredConditions);
            }
        }

        return true;
    }
    return false;
}

From source file:org.sonar.plugins.technicaldebt.ComplexityDebtDecorator.java

public ComplexityDebtDecorator(Configuration configuration) {
    String complexityConfiguration = configuration.getString(TechnicalDebtPlugin.COMPLEXITY_THRESHOLDS,
            TechnicalDebtPlugin.COMPLEXITY_THRESHOLDS_DEFVAL);
    Map<String, Double> complexityLimits = KeyValueFormat.parse(complexityConfiguration,
            new KeyValueFormat.StringNumberPairTransformer());
    classThreshold = (Double) ObjectUtils.defaultIfNull(complexityLimits.get("CLASS"), Double.MAX_VALUE);
    methodThreshold = (Double) ObjectUtils.defaultIfNull(complexityLimits.get("METHOD"), Double.MAX_VALUE);

    classSplitCost = configuration.getDouble(TechnicalDebtPlugin.COST_CLASS_COMPLEXITY,
            TechnicalDebtPlugin.COST_CLASS_COMPLEXITY_DEFVAL);
    methodSplitCost = configuration.getDouble(TechnicalDebtPlugin.COST_METHOD_COMPLEXITY,
            TechnicalDebtPlugin.COST_METHOD_COMPLEXITY_DEFVAL);
}

From source file:org.sonar.scanner.index.DefaultIndex.java

private Bucket doIndex(Resource resource, @Nullable Resource parentReference) {
    Bucket bucket = getBucket(resource);
    if (bucket != null) {
        return bucket;
    }//www .  j  av a 2 s . c om

    if (StringUtils.isBlank(resource.getKey())) {
        LOG.warn("Unable to index a resource without key " + resource);
        return null;
    }

    Resource parent = (Resource) ObjectUtils.defaultIfNull(parentReference, currentProject);

    Bucket parentBucket = getBucket(parent);
    if (parentBucket == null && parent != null) {
        LOG.warn("Resource ignored, parent is not indexed: " + resource);
        return null;
    }

    if (ResourceUtils.isProject(resource)
            || /* For technical projects */ResourceUtils.isRootProject(resource)) {
        resource.setEffectiveKey(resource.getKey());
    } else {
        resource.setEffectiveKey(ComponentKeys.createEffectiveKey(currentProject, resource));
    }
    bucket = new Bucket(resource).setParent(parentBucket);
    addBucket(resource, bucket);

    Resource parentResource = parentBucket != null ? parentBucket.getResource() : null;
    BatchComponent component = componentCache.add(resource, parentResource);
    if (ResourceUtils.isProject(resource)) {
        component.setInputComponent(new DefaultInputModule(resource.getEffectiveKey()));
    }

    return bucket;
}

From source file:org.sonar.server.db.migrations.v44.ConvertProfileMeasuresMigration.java

@Override
public void execute() {
    DbSession session = db.openSession(false);
    try {//from   www.  j a v  a  2 s .  co  m
        int i = 0;
        Date now = new Date();
        Migration44Mapper mapper = session.getMapper(Migration44Mapper.class);
        for (ProfileMeasure profileMeasure : mapper.selectProfileMeasures()) {
            boolean updated = false;
            Integer version = mapper.selectProfileVersion(profileMeasure.getSnapshotId());
            QProfileDto44 profile = mapper.selectProfileById(profileMeasure.getProfileId());
            if (profile != null) {
                Date date = now;
                if (version != null) {
                    date = (Date) ObjectUtils.defaultIfNull(
                            mapper.selectProfileVersionDate(profileMeasure.getProfileId(), version), now);
                }
                // see format of JSON in org.sonar.batch.rule.UsedQProfiles
                StringWriter writer = new StringWriter();
                JsonWriter json = JsonWriter.of(writer);
                json.beginArray().beginObject().prop("key", profile.getKee())
                        .prop("language", profile.getLanguage()).prop("name", profile.getName())
                        .prop("rulesUpdatedAt", UtcDateUtils.formatDateTime(date)).endObject().endArray()
                        .close();
                mapper.updateProfileMeasure(profileMeasure.getId(), writer.toString());
                updated = true;
            }
            if (!updated) {
                mapper.deleteProfileMeasure(profileMeasure.getId());
            }
            if (i % 100 == 0) {
                session.commit();
                i++;
            }
        }
        session.commit();
    } finally {
        session.close();
    }
}

From source file:org.sonar.server.db.migrations.v44.FeedQProfileDatesMigration.java

@Override
public void execute() {
    DbSession session = db.openSession(false);
    try {/*from  ww w.  ja va 2s.  c o m*/
        Date now = new Date(system.now());
        int i = 0;
        QualityProfileMapper profileMapper = session.getMapper(QualityProfileMapper.class);
        Migration44Mapper migrationMapper = session.getMapper(Migration44Mapper.class);
        for (QualityProfileDto profile : profileMapper.selectAll()) {
            Date createdAt = (Date) ObjectUtils
                    .defaultIfNull(migrationMapper.selectProfileCreatedAt(profile.getId()), now);
            Date updatedAt = (Date) ObjectUtils
                    .defaultIfNull(migrationMapper.selectProfileUpdatedAt(profile.getId()), now);

            migrationMapper.updateProfileDates(profile.getId(), createdAt, updatedAt,
                    UtcDateUtils.formatDateTime(updatedAt));
            if (i % 100 == 0) {
                session.commit();
                i++;
            }
        }
        session.commit();
    } finally {
        session.close();
    }
}

From source file:org.sonar.server.db.migrations.v44.FeedQProfileDatesMigrationStep.java

@Override
public void execute() {
    DbSession session = db.openSession(false);
    try {/*from   w  w  w . j ava2 s.co m*/
        Date now = new Date(system.now());
        int i = 0;
        Migration44Mapper migrationMapper = session.getMapper(Migration44Mapper.class);
        for (QProfileDto44 profile : migrationMapper.selectAllProfiles()) {
            Date createdAt = (Date) ObjectUtils
                    .defaultIfNull(migrationMapper.selectProfileCreatedAt(profile.getId()), now);
            Date updatedAt = (Date) ObjectUtils
                    .defaultIfNull(migrationMapper.selectProfileUpdatedAt(profile.getId()), now);

            migrationMapper.updateProfileDates(profile.getId(), createdAt, updatedAt,
                    UtcDateUtils.formatDateTime(updatedAt));
            if (i % 100 == 0) {
                session.commit();
                i++;
            }
        }
        session.commit();
    } finally {
        session.close();
    }
}

From source file:org.sonar.server.issue.IssueQueryService.java

public IssueQuery createFromMap(Map<String, Object> params) {
    DbSession session = dbClient.openSession(false);
    try {/*  w w  w . j  a  v a2s. c o m*/

        IssueQuery.Builder builder = IssueQuery.builder(userSession)
                .issueKeys(RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_ISSUES)))
                .severities(RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_SEVERITIES)))
                .statuses(RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_STATUSES)))
                .resolutions(RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_RESOLUTIONS)))
                .resolved(RubyUtils.toBoolean(params.get(IssuesWsParameters.PARAM_RESOLVED)))
                .rules(toRules(params.get(IssuesWsParameters.PARAM_RULES)))
                .assignees(buildAssignees(RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_ASSIGNEES))))
                .languages(RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_LANGUAGES)))
                .tags(RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_TAGS)))
                .types(RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_TYPES)))
                .assigned(RubyUtils.toBoolean(params.get(IssuesWsParameters.PARAM_ASSIGNED)))
                .hideRules(RubyUtils.toBoolean(params.get(IssuesWsParameters.PARAM_HIDE_RULES)))
                .createdAt(RubyUtils.toDate(params.get(IssuesWsParameters.PARAM_CREATED_AT)))
                .createdAfter(buildCreatedAfterFromDates(RubyUtils.toDate(params.get(PARAM_CREATED_AFTER)),
                        (String) params.get(PARAM_CREATED_IN_LAST)))
                .createdBefore(RubyUtils.toDate(parseEndingDateOrDateTime(
                        (String) params.get(IssuesWsParameters.PARAM_CREATED_BEFORE))));

        Set<String> allComponentUuids = Sets.newHashSet();
        boolean effectiveOnComponentOnly = mergeDeprecatedComponentParameters(session,
                RubyUtils.toBoolean(params.get(IssuesWsParameters.PARAM_ON_COMPONENT_ONLY)),
                RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_COMPONENTS)),
                RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_COMPONENT_UUIDS)),
                RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_COMPONENT_KEYS)),
                RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_COMPONENT_ROOT_UUIDS)),
                RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_COMPONENT_ROOTS)), allComponentUuids);

        addComponentParameters(builder, session, effectiveOnComponentOnly, allComponentUuids,
                RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_PROJECT_UUIDS)),
                RubyUtils.toStrings(ObjectUtils.defaultIfNull(params.get(IssuesWsParameters.PARAM_PROJECT_KEYS),
                        params.get(IssuesWsParameters.PARAM_PROJECTS))),
                RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_MODULE_UUIDS)),
                RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_DIRECTORIES)),
                RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_FILE_UUIDS)),
                RubyUtils.toStrings(params.get(IssuesWsParameters.PARAM_AUTHORS)));

        String sort = (String) params.get(IssuesWsParameters.PARAM_SORT);
        if (!Strings.isNullOrEmpty(sort)) {
            builder.sort(sort);
            builder.asc(RubyUtils.toBoolean(params.get(IssuesWsParameters.PARAM_ASC)));
        }
        String facetMode = (String) params.get(IssuesWsParameters.FACET_MODE);
        if (!Strings.isNullOrEmpty(facetMode)) {
            builder.facetMode(facetMode);
        } else {
            builder.facetMode(IssuesWsParameters.FACET_MODE_COUNT);
        }
        return builder.build();

    } finally {
        session.close();
    }
}