Example usage for org.apache.commons.lang StringUtils defaultIfBlank

List of usage examples for org.apache.commons.lang StringUtils defaultIfBlank

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils defaultIfBlank.

Prototype

public static String defaultIfBlank(String str, String defaultStr) 

Source Link

Document

Returns either the passed in String, or if the String is whitespace, empty ("") or null, the value of defaultStr.

Usage

From source file:org.sonar.scanner.scan.filesystem.LanguageDetection.java

public LanguageDetection(Settings settings, LanguagesRepository languages) {
    for (Language language : languages.all()) {
        String[] filePatterns = settings.getStringArray(getFileLangPatternPropKey(language.key()));
        PathPattern[] pathPatterns = PathPattern.create(filePatterns);
        if (pathPatterns.length > 0) {
            patternsByLanguage.put(language.key(), pathPatterns);
        } else {/*from   w  ww .  j  a  v  a  2s.  c  o  m*/
            // If no custom language pattern is defined then fallback to suffixes declared by language
            String[] patterns = language.fileSuffixes().toArray(new String[language.fileSuffixes().size()]);
            for (int i = 0; i < patterns.length; i++) {
                String suffix = patterns[i];
                String extension = sanitizeExtension(suffix);
                patterns[i] = new StringBuilder().append("**/*.").append(extension).toString();
            }
            PathPattern[] defaultLanguagePatterns = PathPattern.create(patterns);
            patternsByLanguage.put(language.key(), defaultLanguagePatterns);
            LOG.debug("Declared extensions of language {} were converted to {}", language,
                    getDetails(language.key()));
        }
    }

    forcedLanguage = StringUtils.defaultIfBlank(settings.getString(CoreProperties.PROJECT_LANGUAGE_PROPERTY),
            null);
    // First try with lang patterns
    if (forcedLanguage != null) {
        if (!patternsByLanguage.containsKey(forcedLanguage)) {
            throw MessageException
                    .of("You must install a plugin that supports the language '" + forcedLanguage + "'");
        }
        LOG.info("Language is forced to {}", forcedLanguage);
        languagesToConsider.add(forcedLanguage);
    } else {
        languagesToConsider.addAll(patternsByLanguage.keySet());
    }
}

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

@VisibleForTesting
protected static void checkMandatoryProperties(Map<String, String> props, String[] mandatoryProps) {
    StringBuilder missing = new StringBuilder();
    for (String mandatoryProperty : mandatoryProps) {
        if (!props.containsKey(mandatoryProperty)) {
            if (missing.length() > 0) {
                missing.append(", ");
            }//  www. j av  a2s  . c  o m
            missing.append(mandatoryProperty);
        }
    }
    String moduleKey = StringUtils.defaultIfBlank(props.get(MODULE_KEY_PROPERTY),
            props.get(CoreProperties.PROJECT_KEY_PROPERTY));
    if (missing.length() != 0) {
        throw MessageException.of("You must define the following mandatory properties for '"
                + (moduleKey == null ? "Unknown" : moduleKey) + "': " + missing);
    }
}

From source file:org.sonar.server.ce.ws.SubmitAction.java

@Override
public void handle(Request wsRequest, Response wsResponse) throws Exception {
    String organizationKey = wsRequest.getParam(PARAM_ORGANIZATION_KEY).emptyAsNull()
            .or(defaultOrganizationProvider.get()::getKey);
    String projectKey = wsRequest.mandatoryParam(PARAM_PROJECT_KEY);
    String projectBranch = wsRequest.param(PARAM_PROJECT_BRANCH);
    String projectName = StringUtils.defaultIfBlank(wsRequest.param(PARAM_PROJECT_NAME), projectKey);

    CeTask task;//ww  w . j  a  va 2 s . c  o m
    try (InputStream report = new BufferedInputStream(wsRequest.paramAsInputStream(PARAM_REPORT_DATA))) {
        task = reportSubmitter.submit(organizationKey, projectKey, projectBranch, projectName, report);
    }

    WsCe.SubmitResponse submitResponse = WsCe.SubmitResponse.newBuilder().setTaskId(task.getUuid())
            .setProjectId(task.getComponentUuid()).build();
    WsUtils.writeProtobuf(submitResponse, wsRequest, wsResponse);
}

From source file:org.sonar.server.computation.queue.report.ReportSubmitter.java

public CeTask submit(String projectKey, @Nullable String projectBranch, @Nullable String projectName,
        InputStream reportInput) {
    String effectiveProjectKey = ComponentKeys.createKey(projectKey, projectBranch);
    ComponentDto project = componentService.getNullableByKey(effectiveProjectKey);
    if (project == null) {
        // the project does not exist -> require global permission
        userSession.checkPermission(SCAN_EXECUTION);

        // the project does not exist -> requires to provision it
        NewComponent newProject = new NewComponent(projectKey,
                StringUtils.defaultIfBlank(projectName, projectKey));
        newProject.setBranch(projectBranch);
        newProject.setQualifier(Qualifiers.PROJECT);
        // no need to verify the permission "provisioning" as it's already handled by componentService
        project = componentService.create(newProject);
        permissionService.applyDefaultPermissionTemplate(project.getKey());
    } else {/*from w  w w .  j  av  a  2s.  c om*/
        // the project exists -> require global or project permission
        userSession.checkComponentPermission(SCAN_EXECUTION, projectKey);
    }

    // the report file must be saved before submitting the task
    CeTaskSubmit.Builder submit = queue.prepareSubmit();
    reportFiles.save(submit.getUuid(), reportInput);

    submit.setType(CeTaskTypes.REPORT);
    submit.setComponentUuid(project.uuid());
    submit.setSubmitterLogin(userSession.getLogin());
    return queue.submit(submit.build());
}

From source file:org.sonar.server.computation.queue.ReportSubmitter.java

private ComponentDto createProject(DbSession dbSession, OrganizationDto organization, String projectKey,
        @Nullable String projectBranch, @Nullable String projectName) {
    userSession.checkPermission(OrganizationPermission.PROVISION_PROJECTS, organization);
    Integer userId = userSession.getUserId();

    boolean wouldCurrentUserHaveScanPermission = permissionTemplateService
            .wouldUserHaveScanPermissionWithDefaultTemplate(dbSession, organization.getUuid(), userId,
                    projectBranch, projectKey, Qualifiers.PROJECT);
    if (!wouldCurrentUserHaveScanPermission) {
        throw insufficientPrivilegesException();
    }/*from   w  w  w. j  av a  2 s . c  om*/

    boolean newProjectPrivate = dbClient.organizationDao().getNewProjectPrivate(dbSession, organization);

    NewComponent newProject = newComponentBuilder().setOrganizationUuid(organization.getUuid())
            .setKey(projectKey).setName(StringUtils.defaultIfBlank(projectName, projectKey))
            .setBranch(projectBranch).setQualifier(Qualifiers.PROJECT).setPrivate(newProjectPrivate).build();
    return componentUpdater.create(dbSession, newProject, userId);
}

From source file:org.sonar.server.computation.ws.SubmitAction.java

@Override
public void handle(Request wsRequest, Response wsResponse) throws Exception {
    String projectKey = wsRequest.mandatoryParam(PARAM_PROJECT_KEY);
    String projectBranch = wsRequest.param(PARAM_PROJECT_BRANCH);
    String projectName = StringUtils.defaultIfBlank(wsRequest.param(PARAM_PROJECT_NAME), projectKey);
    InputStream reportInput = wsRequest.paramAsInputStream(PARAM_REPORT_DATA);

    CeTask task = reportSubmitter.submit(projectKey, projectBranch, projectName, reportInput);

    WsCe.SubmitResponse submitResponse = WsCe.SubmitResponse.newBuilder().setTaskId(task.getUuid())
            .setProjectId(task.getComponentUuid()).build();
    WsUtils.writeProtobuf(submitResponse, wsRequest, wsResponse);
}

From source file:org.sonar.server.database.EmbeddedDatabase.java

private String getSetting(String name, String defaultValue) {
    return StringUtils.defaultIfBlank(settings.getString(name), defaultValue);
}

From source file:org.sonar.server.es.EsClient.java

@Override
public void start() {
    if (nativeClient == null) {
        ESLoggerFactory.setDefaultFactory(new Slf4jESLoggerFactory());
        org.elasticsearch.common.settings.Settings esSettings = org.elasticsearch.common.settings.Settings
                .builder()/*from w ww  .j  a  v a 2s .co  m*/
                .put("node.name",
                        defaultIfEmpty(settings.getString(ProcessProperties.CLUSTER_NODE_NAME),
                                "sq_local_client"))
                .put("node.rack_id",
                        defaultIfEmpty(settings.getString(ProcessProperties.CLUSTER_NODE_NAME), "unknown"))
                .put("cluster.name", StringUtils
                        .defaultIfBlank(settings.getString(ProcessProperties.CLUSTER_NAME), "sonarqube"))
                .build();
        nativeClient = TransportClient.builder().settings(esSettings).build();
        String host = settings.getString(ProcessProperties.SEARCH_HOST);
        try {
            ((TransportClient) nativeClient).addTransportAddress(new InetSocketTransportAddress(
                    InetAddress.getByName(host), settings.getInt(ProcessProperties.SEARCH_PORT)));
        } catch (UnknownHostException e) {
            throw new IllegalStateException("Can not resolve host [" + host + "]", e);
        }
    }
}

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

public boolean assign(DefaultIssue issue, @Nullable UserDto user, IssueChangeContext context) {
    String sanitizedAssignee = null;
    if (user != null) {
        sanitizedAssignee = StringUtils.defaultIfBlank(user.getLogin(), null);
    }/*from w  ww.java 2 s  .com*/
    if (!Objects.equals(sanitizedAssignee, issue.assignee())) {
        String newAssigneeName = user != null ? user.getName() : null;
        issue.setFieldChange(context, ASSIGNEE, UNUSED, newAssigneeName);
        issue.setAssignee(sanitizedAssignee);
        issue.setUpdateDate(context.date());
        issue.setChanged(true);
        issue.setSendNotifications(true);
        return true;
    }
    return false;
}

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

public boolean assign(DefaultIssue issue, @Nullable User user, IssueChangeContext context) {
    String sanitizedAssignee = null;
    if (user != null) {
        sanitizedAssignee = StringUtils.defaultIfBlank(user.login(), null);
    }//from   w ww. j a  v  a2  s. c o  m
    if (!Objects.equals(sanitizedAssignee, issue.assignee())) {
        String newAssigneeName = user != null ? user.name() : null;
        issue.setFieldChange(context, ASSIGNEE, UNUSED, newAssigneeName);
        issue.setAssignee(sanitizedAssignee);
        issue.setUpdateDate(context.date());
        issue.setChanged(true);
        issue.setSendNotifications(true);
        return true;
    }
    return false;
}