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

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

Introduction

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

Prototype

public static String defaultString(final String str, final String defaultStr) 

Source Link

Document

Returns either the passed in String, or if the String is null , the value of defaultStr .

 StringUtils.defaultString(null, "NULL")  = "NULL" StringUtils.defaultString("", "NULL")    = "" StringUtils.defaultString("bat", "NULL") = "bat" 

Usage

From source file:com.navercorp.pinpoint.web.view.ApplicationAgentHostListSerializer.java

private void writeAgent(AgentInfo agentInfo, JsonGenerator jsonGenerator) throws IOException {
    jsonGenerator.writeStringField("agentId", StringUtils.defaultString(agentInfo.getAgentId(), ""));

    final ServiceType serviceType = serviceTypeRegistryService.findServiceType(agentInfo.getServiceTypeCode());
    jsonGenerator.writeStringField("serviceType", StringUtils.defaultString(serviceType.getDesc(), ""));
    jsonGenerator.writeStringField("hostName", StringUtils.defaultString(agentInfo.getHostName(), ""));
    jsonGenerator.writeStringField("ip", StringUtils.defaultString(agentInfo.getIp(), ""));
}

From source file:com.mgmtp.jfunk.data.DefaultDataSet.java

@Override
public String getValue(final String key) {
    return StringUtils.defaultString(data.get(key), "");
}

From source file:de.micromata.genome.gwiki.controls.GWikiDeletedPagesActionBean.java

public Object onViewItem() {
    if (StringUtils.isEmpty(pageId) == true) {
        wikiContext.addValidationError("gwiki.page.edit.DeletedPages.message.pageidnotset");
        list = true;//from ww w  .j a  v a 2 s  .c om
        return null;
    }
    List<GWikiElementInfo> versionsInfos = wikiContext.getWikiWeb().getStorage().getVersions(pageId);
    Collections.sort(versionsInfos, new Comparator<GWikiElementInfo>() {

        public int compare(GWikiElementInfo o1, GWikiElementInfo o2) {
            return o2.getId().compareTo(o1.getId());
        }
    });

    XmlElement ta = GWikiPageInfoActionBean.getStandardTable();
    ta.nest(//
            tr(//
                    th(text(translate("gwiki.page.edit.DeletedPages.col.author"))), //
                    th(text(translate("gwiki.page.edit.DeletedPages.col.time"))), //
                    th(text(translate("gwiki.page.edit.DeletedPages.col.action"))) //
            )//
    );
    for (GWikiElementInfo ei : versionsInfos) {

        ta.nest(//
                tr(//
                        td(text(StringUtils.defaultString(
                                ei.getProps().getStringValue(GWikiPropKeys.MODIFIEDBY), "Unknown"))), //
                        td(text(getDisplayDate(ei.getProps().getDateValue(GWikiPropKeys.MODIFIEDAT)))), //
                        td(//
                                a(attrs("href", wikiContext.localUrl(ei.getId())),
                                        text(translate("gwiki.page.edit.DeletedPages.link.view"))), //
                                a(attrs("href",
                                        wikiContext.localUrl("edit/PageInfo") + "?restoreId=" + ei.getId()
                                                + "&pageId=" + pageId + "&method_onRestore=true"), //
                                        text(translate("gwiki.page.edit.DeletedPages.link.restore"))//
                                )) //
                ));
    }
    versionBox = GWikiPageInfoActionBean.getBoxFrame("Versionen", ta).toString();
    return null;
}

From source file:io.wcm.handler.media.format.MediaFormat.java

/**
 * @return Media format label
 */
public String getLabel() {
    return StringUtils.defaultString(this.label, this.name);
}

From source file:com.mirth.connect.server.api.servlets.UserServlet.java

@Override
@DontCheckAuthorized/*from  w w w.j  a v a 2 s  . co  m*/
public LoginStatus login(String username, String password) {
    LoginStatus loginStatus = null;

    try {
        int tryCount = 0;
        int status = configurationController.getStatus();
        while (status != ConfigurationController.STATUS_INITIAL_DEPLOY
                && status != ConfigurationController.STATUS_OK) {
            if (tryCount >= 5) {
                loginStatus = new LoginStatus(Status.FAIL,
                        "Server is still starting or otherwise unavailable. Please try again shortly.");
                break;
            }

            Thread.sleep(1000);
            status = configurationController.getStatus();
            tryCount++;
        }

        if (loginStatus == null) {
            ConfigurationController configurationController = ControllerFactory.getFactory()
                    .createConfigurationController();

            HttpSession session = request.getSession();

            loginStatus = userController.authorizeUser(username, password);
            username = StringUtils.defaultString(loginStatus.getUpdatedUsername(), username);

            User validUser = null;

            if ((loginStatus.getStatus() == LoginStatus.Status.SUCCESS)
                    || (loginStatus.getStatus() == LoginStatus.Status.SUCCESS_GRACE_PERIOD)) {
                validUser = userController.getUser(null, username);

                /*
                 * There must be a user to login with and store in the session, even if an
                 * Authorization Plugin returned a LoginStatus of SUCCESS
                 */
                if (validUser == null) {
                    loginStatus = new LoginStatus(LoginStatus.Status.FAIL,
                            "Could not find a valid user with username: " + username);
                } else {
                    // set the sessions attributes
                    session.setAttribute(SESSION_USER, validUser.getId());
                    session.setAttribute(SESSION_AUTHORIZED, true);

                    // this prevents the session from timing out
                    session.setMaxInactiveInterval(-1);

                    // set the user status to logged in in the database
                    userController.loginUser(validUser);

                    // add the user's session to to session map
                    UserSessionCache.getInstance().registerSessionForUser(session, validUser);
                }
            }

            // Manually audit the Login event with the username since the user ID has not been stored to the session yet
            ServerEvent event = new ServerEvent(configurationController.getServerId(),
                    operation.getDisplayName());
            if (validUser != null) {
                event.setUserId(validUser.getId());
            }
            event.setIpAddress(getRequestIpAddress());
            event.setLevel(Level.INFORMATION);

            // Set the outcome to the result of the login attempt
            event.setOutcome(((loginStatus.getStatus() == LoginStatus.Status.SUCCESS)
                    || (loginStatus.getStatus() == LoginStatus.Status.SUCCESS_GRACE_PERIOD)) ? Outcome.SUCCESS
                            : Outcome.FAILURE);

            Map<String, String> attributes = new HashMap<String, String>();
            attributes.put("username", username);
            event.setAttributes(attributes);

            eventController.dispatchEvent(event);
        }
    } catch (Exception e) {
        throw new MirthApiException(e);
    }

    if (loginStatus.getStatus() != Status.SUCCESS && loginStatus.getStatus() != Status.SUCCESS_GRACE_PERIOD) {
        throw new MirthApiException(Response.status(Response.Status.UNAUTHORIZED).entity(loginStatus).build());
    }

    return loginStatus;
}

From source file:net.andydvorak.intellij.lessc.ui.notifier.NotificationListenerImpl.java

private void handleViewFileEvent(@NotNull final Notification notification,
        @NotNull final HyperlinkEvent event) {
    final String eventDescription = event.getDescription(); // retrieves the "href" attribute of the hyperlink
    final String curFilePath = StringUtils.defaultString(this.filePath, eventDescription);
    final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(curFilePath);
    openFileInEditor(notification, file);
}

From source file:ch.ifocusit.livingdoc.plugin.GherkinMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    if (!gerkinSeparateFeature) {
        appendTitle(get(pageCount.get()));
    }//  w ww.  j a  v a  2s. c  o m

    readFeatures().forEach(path -> {

        if (gerkinSeparateFeature) {
            // read feature title
            try {
                Map<String, Object> parsed = MapFormatter
                        .parse(readFileToString(FileUtils.getFile(path), defaultCharset()));
                String title = StringUtils.defaultString(getTitle(), EMPTY)
                        + String.valueOf(parsed.get("name"));
                appendTitle(get(pageCount.get()), title);
            } catch (IOException e) {
                throw new IllegalStateException("Error reading " + path, e);
            }
        }
        get(pageCount.get()).textLine(String.format("gherkin::%s[%s]", path, gherkinOptions));
        get(pageCount.get()).textLine(EMPTY);
        somethingWasGenerated = true;

        if (gerkinSeparateFeature) {
            pageCount.incrementAndGet();
        }
    });

    if (!somethingWasGenerated) {
        // nothing generated
        return;
    }

    write(docBuilders.get(0));
}

From source file:io.wcm.config.core.impl.ParameterProviderBridge.java

@SuppressWarnings("unchecked")
private ConfigurationMetadata toConfigMetadata(List<Parameter<?>> parameters) {
    SortedSet<PropertyMetadata<?>> properties = new TreeSet<>(new Comparator<PropertyMetadata<?>>() {
        @Override//  ww w .  j  av a 2 s.  com
        public int compare(PropertyMetadata<?> o1, PropertyMetadata<?> o2) {
            String sort1 = StringUtils.defaultString(o1.getLabel(), o1.getName());
            String sort2 = StringUtils.defaultString(o2.getLabel(), o2.getName());
            return sort1.compareTo(sort2);
        }
    });

    for (Parameter<?> parameter : parameters) {
        PropertyMetadata<?> property;
        if (parameter.getType().equals(Map.class)) {
            property = toPropertyStringArray((Parameter<Map>) parameter);
        } else {
            property = toProperty(parameter);
        }
        String label = (String) parameter.getProperties().get(EditorProperties.LABEL);
        String description = (String) parameter.getProperties().get(EditorProperties.DESCRIPTION);
        String group = (String) parameter.getProperties().get(EditorProperties.GROUP);
        if (group != null) {
            label = group + ": " + StringUtils.defaultString(label, parameter.getName());
        }
        properties.add(property.label(label).description(description));
    }

    return new ConfigurationMetadata(DEFAULT_CONFIG_NAME, properties, false)
            .label("wcm.io Configuration Parameters");
}

From source file:alfio.controller.AdminConfigurationController.java

@RequestMapping(CONNECT_REDIRECT_PATH)
public String authorize(Principal principal, @RequestParam("state") String state,
        @RequestParam(value = "code", required = false) String code,
        @RequestParam(value = "error", required = false) String errorCode,
        @RequestParam(value = "error_description", required = false) String errorDescription,
        HttpSession session, RedirectAttributes redirectAttributes) {

    return Optional.ofNullable(session.getAttribute(STRIPE_CONNECT_ORG)).map(Integer.class::cast)
            .filter(orgId -> userManager
                    .isOwnerOfOrganization(userManager.findUserByUsername(principal.getName()), orgId))
            .map(orgId -> {/* w  ww.  j  av  a2  s .c  o  m*/
                session.removeAttribute(STRIPE_CONNECT_ORG);
                String persistedState = (String) session.getAttribute(STRIPE_CONNECT_STATE_PREFIX + orgId);
                session.removeAttribute(STRIPE_CONNECT_STATE_PREFIX + orgId);
                boolean stateVerified = Objects.equals(persistedState, state);
                if (stateVerified && code != null) {
                    StripeManager.ConnectResult connectResult = stripeManager.storeConnectedAccountId(code,
                            Configuration.from(orgId));
                    if (connectResult.isSuccess()) {
                        return "redirect:/admin/#/configuration/organization/" + orgId;
                    }
                } else if (stateVerified && StringUtils.isNotEmpty(errorCode)) {
                    log.warn("error from stripe. {}={}", errorCode, errorDescription);
                    redirectAttributes.addFlashAttribute("errorMessage",
                            StringUtils.defaultString(errorDescription, errorCode));
                    return "redirect:/admin/";
                }
                redirectAttributes.addFlashAttribute("errorMessage",
                        "Couldn't connect your account. Please retry.");
                return "redirect:/admin/";
            }).orElse("redirect:/admin/");
}

From source file:com.cognifide.aet.job.common.modifiers.login.LoginModifierConfig.java

private String getParameter(Map<String, String> params, String key, String defaultValue) {
    return StringUtils.defaultString(params.get(key), defaultValue);
}