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:com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMNavigator.java

@SuppressWarnings({ "ConstantConditions", "deprecation" })
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", justification = "Only non-null after we set them here!")
private Object readResolve() throws ObjectStreamException {
    if (serverUrl == null) {
        serverUrl = BitbucketEndpointConfiguration.get().readResolveServerUrl(bitbucketServerUrl);
    }// ww w .ja  va 2s .c  o  m
    if (serverUrl == null) {
        LOGGER.log(Level.WARNING, "BitbucketSCMNavigator::readResolve : serverUrl is still empty");
    }
    if (traits == null) {
        // legacy instance, reconstruct traits to reflect legacy behaviour
        traits = new ArrayList<>();
        this.traits.add(new BranchDiscoveryTrait(true, true));
        this.traits.add(new OriginPullRequestDiscoveryTrait(EnumSet.of(ChangeRequestCheckoutStrategy.HEAD)));
        this.traits.add(new ForkPullRequestDiscoveryTrait(EnumSet.of(ChangeRequestCheckoutStrategy.HEAD),
                new ForkPullRequestDiscoveryTrait.TrustEveryone()));
        this.traits.add(new PublicRepoPullRequestFilterTrait());
        if ((includes != null && !"*".equals(includes)) || (excludes != null && !"".equals(excludes))) {
            traits.add(new WildcardSCMHeadFilterTrait(StringUtils.defaultIfBlank(includes, "*"),
                    StringUtils.defaultIfBlank(excludes, "")));
        }
        if (checkoutCredentialsId != null
                && !BitbucketSCMSource.DescriptorImpl.SAME.equals(checkoutCredentialsId)
                && !checkoutCredentialsId.equals(credentialsId)) {
            traits.add(new SSHCheckoutTrait(checkoutCredentialsId));
        }
        traits.add(new WebhookRegistrationTrait(
                autoRegisterHooks ? WebhookRegistration.ITEM : WebhookRegistration.DISABLE));
        if (pattern != null && !".*".equals(pattern)) {
            traits.add(new RegexSCMSourceFilterTrait(pattern));
        }
    }
    return this;
}

From source file:net.sf.authorship.AuthorshipReportView.java

/**
 * @param author//from   w w  w  .  j  a v a2 s .c o  m
 * @return
 */
private String getPomAuthorValue(Author author) {
    StringBuilder authorValue = new StringBuilder();
    authorValue.append("id=" + StringUtils.defaultIfBlank(author.getId(), "<empty>"));
    authorValue.append(", name=" + StringUtils.defaultIfBlank(author.getName(), "<empty>"));
    authorValue.append(", email=" + StringUtils.defaultIfBlank(author.getEmail(), "<empty>"));
    return authorValue.toString();
}

From source file:com.fortify.bugtracker.src.ssc.processor.SSCSourceProcessorSubmitVulnsToTarget.java

@SuppressWarnings("unchecked")
@Override//from w  w w .ja  va2  s. c  o m
public void updateVulnerabilityStateForNewIssue(Context context, String bugTrackerName,
        TargetIssueLocatorAndFields targetIssueLocatorAndFields, Collection<Object> vulnerabilities) {
    SSCAuthenticatingRestConnection conn = SSCConnectionFactory.getConnection(context);
    String applicationVersionId = ICLIOptionsSSC.CLI_SSC_APPLICATION_VERSION_ID.getValue(context);
    Map<String, String> customTagValues = getExtraCustomTagValues(context, targetIssueLocatorAndFields,
            vulnerabilities);

    if (StringUtils.isNotBlank(getConfiguration().getBugLinkCustomTagName())) {
        customTagValues.put(getConfiguration().getBugLinkCustomTagName(),
                targetIssueLocatorAndFields.getLocator().getDeepLink());
    }
    if (!customTagValues.isEmpty()) {
        conn.api(SSCCustomTagAPI.class).setCustomTagValues(applicationVersionId, customTagValues,
                vulnerabilities);
        LOG.info("[SSC] Updated custom tag values for SSC vulnerabilities");
    }
    if (getConfiguration().isAddNativeBugLink()) {
        Map<String, Object> issueDetails = new HashMap<String, Object>();
        issueDetails.put("existingBugLink", targetIssueLocatorAndFields.getLocator().getDeepLink());
        List<String> issueInstanceIds = ContextSpringExpressionUtil.evaluateExpression(context, vulnerabilities,
                "#root.![issueInstanceId]", List.class);

        SSCBugTrackerAPI bugTrackerAPI = conn.api(SSCBugTrackerAPI.class);
        if (bugTrackerAPI.isBugTrackerAuthenticationRequired(applicationVersionId)) {
            // If SSC bug tracker username/password are not specified, we use dummy values;
            // 'Add Existing Bugs' doesn't care about credentials but requires authentication
            // to work around SSC 17.20+ bugs
            String btUserName = StringUtils.defaultIfBlank(
                    context.get(ICLIOptionsSSC.PRP_SSC_BUG_TRACKER_USER_NAME, String.class), "dummy");
            String btPassword = StringUtils.defaultIfBlank(
                    context.get(ICLIOptionsSSC.PRP_SSC_BUG_TRACKER_PASSWORD, String.class), "dummy");
            bugTrackerAPI.authenticateForBugFiling(applicationVersionId, btUserName, btPassword);
        }

        conn.api(SSCBugTrackerAPI.class).fileBug(applicationVersionId, issueDetails, issueInstanceIds);
        LOG.info("[SSC] Added bug link for SSC vulnerabilities using '"
                + getConfiguration().getAddNativeBugLinkBugTrackerName() + "' bug tracker");
    }
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.endpoints.BitbucketEndpointConfiguration.java

/**
 * Fix a serverUrl./*w w  w  .j  a v  a2 s  . c  om*/
 *
 * @param serverUrl the server URL.
 * @return the normalized server URL.
 */
@NonNull
public static String normalizeServerUrl(@CheckForNull String serverUrl) {
    serverUrl = StringUtils.defaultIfBlank(serverUrl, BitbucketCloudEndpoint.SERVER_URL);
    try {
        URI uri = new URI(serverUrl).normalize();
        String scheme = uri.getScheme();
        if ("http".equals(scheme) || "https".equals(scheme)) {
            // we only expect http / https, but also these are the only ones where we know the authority
            // is server based, i.e. [userinfo@]server[:port]
            // DNS names must be US-ASCII and are case insensitive, so we force all to lowercase

            String host = uri.getHost() == null ? null : uri.getHost().toLowerCase(Locale.ENGLISH);
            int port = uri.getPort();
            if ("http".equals(scheme) && port == 80) {
                port = -1;
            } else if ("https".equals(scheme) && port == 443) {
                port = -1;
            }
            serverUrl = new URI(scheme, uri.getUserInfo(), host, port, uri.getPath(), uri.getQuery(),
                    uri.getFragment()).toASCIIString();
        }
    } catch (URISyntaxException e) {
        // ignore, this was a best effort tidy-up
    }
    return serverUrl.replaceAll("/$", "");
}

From source file:ips1ap101.lib.base.BaseBundle.java

public static String defaultIfBlank(String key, String defaultString) {
    if (StringUtils.isNotBlank(key)) {
        try {//from   w w  w.  jav  a2 s .  c  om
            String string = resourceBundle.getString(key);
            return StringUtils.defaultIfBlank(string, defaultString);
        } catch (MissingResourceException e) {
        }
    }
    return defaultString;
}

From source file:net.duckling.ddl.util.ResourceQuery.java

private static List<Integer> getTagIds(HttpServletRequest request) {
    String tagIdsStr = StringUtils.defaultIfBlank(request.getParameter("tagId"), null);
    if (tagIdsStr == null) {
        int[] tagIds = WebParamUtil.getIntegerValues(request, "tag");
        List<Integer> ids = new ArrayList<Integer>();
        for (int i : tagIds) {
            ids.add(i);//from www  .  j a v  a  2s . c  om
        }
        return ids;
    }
    String[] tagIdsArray = tagIdsStr.split("_");
    List<Integer> tagIds = new ArrayList<Integer>();
    if (tagIdsArray != null && tagIdsArray.length > 0) {
        for (String tagIdTemp : tagIdsArray) {
            tagIds.add(Integer.parseInt(tagIdTemp));
        }
    }
    return tagIds;
}

From source file:dk.dma.vessel.track.model.VesselTarget.java

/**
 * Update the static information fields from the AIS message
 * @param message the AIS message/*from  w  ww . j  a  v a 2  s.  c om*/
 * @param date the date of the message
 * @return if any fields were updated
 */
private boolean updateVesselStaticMessage(AisStaticCommon message, Date date) {

    // Check that this is a newer static update
    if (lastStaticReport != null && lastStaticReport.getTime() >= date.getTime()) {
        return false;
    }

    boolean updated = false;

    // Update the name
    String name = AisMessage.trimText(message.getName());
    if (StringUtils.isNotBlank(name) && !name.equals(this.name)) {
        this.name = name;
        updated = true;
    }

    // Update the call-sign
    String callsign = AisMessage.trimText(message.getCallsign());
    if (StringUtils.isNotBlank(callsign) && !callsign.equals(this.callsign)) {
        this.callsign = callsign;
        updated = true;
    }

    // Update the vessel type
    Integer vesselType = message.getShipType();
    if (!vesselType.equals(this.vesselType)) {
        this.vesselType = vesselType;
        updated = true;
    }

    if (message instanceof AisMessage5) {
        AisMessage5 msg5 = (AisMessage5) message;
        AisTargetDimensions dim = new AisTargetDimensions(msg5);

        // Update length
        Short length = (short) (dim.getDimBow() + dim.getDimStern());
        if (!length.equals(this.length)) {
            this.length = length;
            updated = true;
        }

        // Update width
        Short width = (short) (dim.getDimPort() + dim.getDimStarboard());
        if (!width.equals(this.width)) {
            this.width = width;
            updated = true;
        }

        // Update destination
        String destination = StringUtils.defaultIfBlank(AisMessage.trimText(msg5.getDest()), null);
        if (destination != null && !destination.equals(this.destination)) {
            this.destination = destination;
            updated = true;
        }

        // Update draught
        Float draught = msg5.getDraught() / 10.0f;
        if (msg5.getDraught() > 0 && !compare(draught, this.draught)) {
            this.draught = draught;
            updated = true;
        }

        // Update ETA
        Date eta = msg5.getEtaDate();
        if (eta != null && !eta.equals(this.eta)) {
            this.eta = eta;
            updated = true;
        }

        // Update IMO
        Long imo = msg5.getImo();
        if (msg5.getImo() > 0 && !imo.equals(this.imoNo)) {
            this.imoNo = imo;
            updated = true;
        }
    }

    // Only update lastStaticReport if any static field has been updated
    if (updated) {
        lastStaticReport = date;
    }

    return updated;
}

From source file:net.sf.authorship.AuthorshipReportView.java

/**
 * @param authors//from   w w  w.  j ava2 s  .  co m
 * @param sink
 */
private void generateAuthorsTable(Set<Author> authors, Sink sink) {
    sink.table();
    sink.tableRow();
    sink.tableCell();
    sink.bold();
    sink.text("Id");
    sink.bold_();
    sink.tableCell_();
    sink.tableCell();
    sink.bold();
    sink.text("Name");
    sink.bold_();
    sink.tableCell_();
    sink.tableCell();
    sink.bold();
    sink.text("E-mail");
    sink.bold_();
    sink.tableCell_();
    sink.tableCell();
    sink.bold();
    sink.text("URL");
    sink.bold_();
    sink.tableCell_();
    sink.tableRow_();

    for (Author author : authors) {
        sink.tableRow();
        sink.tableCell();
        sink.text(StringUtils.defaultIfBlank(author.getId(), ""));
        sink.tableCell_();
        sink.tableCell();
        sink.text(StringUtils.defaultIfBlank(author.getName(), ""));
        sink.tableCell_();
        sink.tableCell();
        sink.text(StringUtils.defaultIfBlank(author.getEmail(), ""));
        sink.tableCell_();
        sink.tableCell();
        sink.text(StringUtils.defaultIfBlank(author.getUrl(), ""));
        sink.tableCell_();
        sink.tableRow_();
    }
    sink.table_();
}

From source file:com.sonicle.webtop.core.app.shiro.WTRealm.java

private Principal authenticateUser(String domainId, String internetDomain, String username, char[] password)
        throws AuthenticationException {
    WebTopApp wta = WebTopApp.getInstance();
    WebTopManager wtMgr = wta.getWebTopManager();
    AuthenticationDomain authAd = null, priAd = null;
    boolean autoCreate = false, impersonate = false;

    try {// w  w w  .  j ava2s . c om
        DirectoryManager dirManager = DirectoryManager.getManager();

        // Defines authentication domains for the auth phase and for 
        // building the right principal
        logger.debug("Building the authentication domain");
        if (isSysAdmin(internetDomain, username)) {
            impersonate = false;
            authAd = priAd = wtMgr.createSysAdminAuthenticationDomain();

        } else {
            if (wta.isInMaintenance())
                throw new MaintenanceException("Maintenance is active. Only sys-admin can login.");
            ODomain domain = null;
            if (!StringUtils.isBlank(internetDomain)) {
                List<ODomain> domains = wtMgr.listByInternetDomain(internetDomain);
                if (domains.isEmpty())
                    throw new WTException("No enabled domains match specified internet domain [{}]",
                            internetDomain);
                if (domains.size() != 1)
                    throw new WTException("Multiple domains match specified internet domain [{}]",
                            internetDomain);
                domain = domains.get(0);
            } else {
                domain = wtMgr.getDomain(domainId);
                if ((domain == null) || !domain.getEnabled())
                    throw new WTException("Domain not found [{}]", domainId);
            }

            if (isSysAdminImpersonate(username)) {
                impersonate = true;
                authAd = wtMgr.createSysAdminAuthenticationDomain();
                priAd = wtMgr.createAuthenticationDomain(domain);
            } else if (isDomainAdminImpersonate(username)) {
                impersonate = true;
                authAd = priAd = wtMgr.createAuthenticationDomain(domain);
            } else {
                impersonate = false;
                authAd = priAd = wtMgr.createAuthenticationDomain(domain);
            }
            autoCreate = domain.getUserAutoCreation();
        }

        DirectoryOptions opts = wta.createDirectoryOptions(authAd);
        AbstractDirectory directory = dirManager.getDirectory(authAd.getDirUri().getScheme());
        if (directory == null)
            throw new WTException("Directory not supported [{}]", authAd.getDirUri().getScheme());

        // Prepare principal for authentication
        String authUsername = impersonate ? "admin" : directory.sanitizeUsername(opts, username);
        Principal authPrincipal = new Principal(authAd, impersonate, authAd.getDomainId(), authUsername,
                password);
        logger.debug("Authenticating principal [{}, {}]", authPrincipal.getDomainId(),
                authPrincipal.getUserId());
        AuthUser userEntry = directory.authenticate(opts, authPrincipal);

        // Authentication phase passed succesfully, now build the right principal!
        Principal principal = null;
        if (impersonate) {
            String impUsername = sanitizeImpersonateUsername(username);
            principal = new Principal(priAd, impersonate, priAd.getDomainId(), impUsername, password);

            UserProfileId pid = new UserProfileId(principal.getDomainId(), principal.getUserId());
            OUser ouser = wta.getWebTopManager().getUser(pid);
            // We cannot continue if the user is not present, impersonation needs it!
            if (ouser == null)
                throw new WTException("User not found [{}]", pid.toString());
            principal.setDisplayName(ouser.getDisplayName());

        } else {
            // Authentication result points to the right userId...
            principal = new Principal(priAd, impersonate, priAd.getDomainId(), userEntry.userId, password);
            principal.setDisplayName(StringUtils.defaultIfBlank(userEntry.displayName, userEntry.userId));
        }

        if (autoCreate)
            principal.pushDirectoryEntry(userEntry);
        return principal;

    } catch (URISyntaxException | WTException | DirectoryException ex) {
        logger.error("Authentication error", ex);
        throw new AuthenticationException(ex);
    }
}

From source file:com.hack23.cia.web.impl.ui.application.views.common.chartfactory.impl.DocumentChartDataManagerImpl.java

@Override
public void createDocumentHistoryPartyChart(final AbstractOrderedLayout content, final String org) {
    final DataSeries dataSeries = new DataSeries();
    final Series series = new Series();

    final Map<String, List<ViewRiksdagenPartyDocumentDailySummary>> allMap = getViewRiksdagenPartyDocumentDailySummaryMap();

    final List<ViewRiksdagenPartyDocumentDailySummary> itemList = allMap
            .get(org.toUpperCase(Locale.ENGLISH).replace(UNDER_SCORE, EMPTY_STRING).trim());

    if (itemList != null) {

        final Map<String, List<ViewRiksdagenPartyDocumentDailySummary>> map = itemList.parallelStream()
                .filter(t -> t != null).collect(Collectors.groupingBy(
                        t -> StringUtils.defaultIfBlank(t.getEmbeddedId().getDocumentType(), NO_INFO)));

        addDocumentHistoryByPartyData(dataSeries, series, map);
    }/*w  ww .  j a v a  2  s  . co  m*/

    addChart(content, "Document history party", new DCharts().setDataSeries(dataSeries)
            .setOptions(chartOptions.createOptionsXYDateFloatLegendOutside(series)).show());
}