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.jenkinsci.plugins.mesos.MesosRetentionStrategy.java

private MesosBuiltOnAction createBuiltOnAction(MesosSlave mesosJenkinsAgent) {
    JenkinsScheduler jenkinsScheduler = (JenkinsScheduler) Mesos.getInstance(mesosJenkinsAgent.getCloud())
            .getScheduler();/*w ww  . ja  v  a 2 s  . c  om*/

    String mesosAgentHostname = StringUtils.defaultIfBlank(
            jenkinsScheduler.getResult(mesosJenkinsAgent.getDisplayName()).getSlave().getHostname(), "N/A");

    String jenkinsAgentHostname = "N/A";
    try {
        Computer computer = mesosJenkinsAgent.toComputer();
        if (computer != null) {
            jenkinsAgentHostname = StringUtils.defaultIfBlank(computer.getHostName(), jenkinsAgentHostname);
        }
    } catch (Exception e) {
        LOGGER.log(Level.WARNING, "Error while trying to get hostname of node", e);
    }

    String containerId = StringUtils.defaultIfBlank(mesosJenkinsAgent.getDockerContainerID(), "N/A");

    return new MesosBuiltOnAction(mesosAgentHostname, jenkinsAgentHostname, containerId);
}

From source file:org.jenkinsci.plugins.scriptler.config.Script.java

/** used to merge scripts */
public Script(String id, String name, String comment, String interpreter, String originCatalog,
        String originScript, String originDate, boolean nonAdministerUsing, Parameter[] parameters,
        boolean onlyMaster) {
    this.id = id;
    this.name = name;
    this.comment = comment;
    this.interpreter = StringUtils.defaultIfBlank(interpreter, "groovy");
    this.originCatalog = originCatalog;
    this.originScript = originScript;
    this.originDate = originDate;
    this.nonAdministerUsing = nonAdministerUsing;
    this.parameters = parameters;
    this.onlyMaster = onlyMaster;
}

From source file:org.jtalks.jcommune.model.entity.UserContact.java

/**
 * Replaced stubs in display pattern for this contact type by actual
 * contact value/*from w w w  . ja  v  a2 s .  c  o m*/
 * @return actual ready-to-display contact
 */
public String getDisplayValue() {
    String replacement = StringUtils.defaultIfBlank(value, "");
    return type.getDisplayValue(replacement);
}

From source file:org.kuali.rice.ken.web.spring.BaseSendNotificationController.java

protected String getParameter(HttpServletRequest request, String parameterName, Map<String, Object> model,
        ErrorList errors, String errorMessage, String defaultValue) {
    String parameter = StringUtils.defaultIfBlank(request.getParameter(parameterName), defaultValue);

    if (StringUtils.isNotEmpty(parameter)) {
        model.put(parameterName, parameter);
    } else {/*  www. j  a  va  2s .  co m*/
        errors.addError(errorMessage);
    }

    return parameter;
}

From source file:org.kuali.rice.ken.web.spring.BaseSendNotificationController.java

/**
 * Provides an overridable method in which to customize a created {@link NotificationBo} instance.
 *
 * @param request the servlet request/*w w w . j  a  v a2 s.c om*/
 * @param model the Spring MVC model
 * @param errors the error list
 *
 * @return a new notification
 * @throws ErrorList
 */
protected NotificationBo createNotification(HttpServletRequest request, Map<String, Object> model,
        ErrorList errors) throws ErrorList {
    String channelName = getChannelName(request, model, errors);
    String priorityName = getParameter(request, "priorityName", model, errors, "You must choose a priority.");
    String[] senders = getParameterList(request, "senderNames", model, errors,
            "You must enter at least one sender.");
    String deliveryType = getDeliveryType(request, model, errors);

    Date originalDate = getDate(request.getParameter("originalDateTime"), errors, "Original date is invalid.");

    String sendDateTime = StringUtils.defaultIfBlank(request.getParameter("sendDateTime"),
            Util.getCurrentDateTime());
    Date sendDate = getDate(sendDateTime, errors,
            "You specified an invalid Send Date/Time.  Please use the calendar picker.");
    if (sendDate != null && sendDate.before(originalDate)) {
        errors.addError("Send Date/Time cannot be in the past.");
    }
    model.put("sendDateTime", sendDateTime);

    String autoRemoveDateTime = request.getParameter("autoRemoveDateTime");
    Date removeDate = getDate(autoRemoveDateTime, errors,
            "You specified an invalid Auto-Remove Date/Time.  Please use the calendar picker.");
    if (removeDate != null) {
        if (removeDate.before(originalDate)) {
            errors.addError("Auto-Remove Date/Time cannot be in the past.");
        } else if (sendDate != null && removeDate.before(sendDate)) {
            errors.addError("Auto-Remove Date/Time cannot be before the Send Date/Time.");
        }
    }
    model.put("autoRemoveDateTime", autoRemoveDateTime);

    // user recipient names
    String[] userRecipients = parseUserRecipients(request);

    // workgroup recipient names
    String[] workgroupRecipients = parseWorkgroupRecipients(request);

    // workgroup namespace codes
    String[] workgroupNamespaceCodes = parseWorkgroupNamespaceCodes(request);

    String title = getParameter(request, "title", model, errors, "You must fill in a title.");

    // check to see if there were any errors
    if (!errors.getErrors().isEmpty()) {
        throw errors;
    }

    return createNotification(title, deliveryType, sendDate, removeDate, channelName, priorityName, senders,
            userRecipients, workgroupRecipients, workgroupNamespaceCodes, errors);
}

From source file:org.kuali.rice.krad.demo.uif.components.ComponentLibraryView.java

/**
 * Builds out the documentation tab content by auto-generating the content for properties and documentation and
 * adds it to the tabItems list//from   w ww  .j  a  va  2 s. c  om
 *
 * @param tabItems list of tab items for component details
 */
private void processDocumentationTab(List<Component> tabItems) {
    MessageService messageService = KRADServiceLocatorWeb.getMessageService();

    try {
        Class<?> componentClass = Class.forName(javaFullClassPath);
        Method methodsArray[] = componentClass.getMethods();

        //get top level documentation for this class
        String classMessage = messageService.getMessageText("KR-SAP", null, javaFullClassPath);

        if (classMessage == null) {
            classMessage = "NO DOCUMENTATION AVAILABLE/FOUND... we are working on it!";
        }

        //scrub class message of @link and @code
        classMessage = classMessage.replaceAll("\\{[@#]link (.*?)\\}", "<i>$1</i>");
        classMessage = classMessage.replaceAll("\\{[@#]code (.*?)\\}", "<i>$1</i>");

        //Generate schema and bean Id reference table
        String schemaTable = "<table class='demo-schemaIdDocTable'><tr><th>Schema Name</th>"
                + "<th>Uif Bean Id</th></tr>";
        if (componentClass.isAnnotationPresent(BeanTag.class)) {
            BeanTag beanTag = componentClass.getAnnotation(BeanTag.class);
            schemaTable = schemaTable + "<tr><td>" + beanTag.name() + "</td><td>" + beanTag.parent()
                    + "</td></tr>";
            schemaTable = schemaTable + "</table>";
        } else if (componentClass.isAnnotationPresent(BeanTags.class)) {
            BeanTags beanTags = componentClass.getAnnotation(BeanTags.class);
            BeanTag[] beanTagArray = beanTags.value();
            for (BeanTag beanTag : beanTagArray) {
                schemaTable = schemaTable + "<tr><td>" + beanTag.name() + "</td><td>" + beanTag.parent()
                        + "</td></tr>";
            }
            schemaTable = schemaTable + "</table>";
        } else {
            schemaTable = "";
        }

        String componentName = StringUtils.defaultIfBlank(StringUtils.defaultString(getComponentName()) + " ",
                "");

        String javadocTitle = messageService.getMessageText("KR-SAP", null, "componentLibrary.javaDoc");
        String kradGuideTitle = messageService.getMessageText("KR-SAP", null, "componentLibrary.kradGuide");
        String devDocumentationTitle = messageService.getMessageText("KR-SAP", null,
                "componentLibrary.devDocumentation");
        String beanDefsTitle = messageService.getMessageText("KR-SAP", null, "componentLibrary.beanDefs");

        //build documentation links from javadoc address and docbook address/anchor
        String docLinkDiv = "<div class='demo-docLinks'> "
                + "<label>Additional Resources:</label><a class='demo-documentationLink'" + " href='"
                + getRootJavadocAddress() + javaFullClassPath.replace('.', '/') + ".html' target='_blank'>"
                + javadocTitle + "</a>" + "<a class='demo-documentationLink'" + " href='"
                + getRootDocBookAddress() + getDocBookAnchor() + "' target='_blank'>" + kradGuideTitle + "</a>"
                + "</div>";

        //initialize the documentation content
        String documentationMessageContent = "<H3 class=\"uif-documentationHeader\">" + componentName
                + devDocumentationTitle + "</H3>" + docLinkDiv + classMessage + "<H3>" + beanDefsTitle + "</H3>"
                + schemaTable;

        List<String> propertyDescriptions = new ArrayList<String>();
        Map<String, List<String>> inheritedProperties = new HashMap<String, List<String>>();

        List<Method> methods = Arrays.asList(methodsArray);

        //alphabetize the methods by name
        Collections.sort(methods, new Comparator<Method>() {
            @Override
            public int compare(Method method1, Method method2) {
                String name1 = getPropName(method1);
                String name2 = getPropName(method2);
                return name1.compareTo(name2); //To change body of implemented methods use File | Settings | File Templates.
            }
        });

        //Process all methods on this class
        for (Method method : methods) {
            BeanTagAttribute attribute = method.getAnnotation(BeanTagAttribute.class);
            if (attribute != null) {
                //property variables
                String name = getPropName(method);
                String methodClass = method.getDeclaringClass().getName();
                String returnType = method.getReturnType().getName();
                returnType = returnType.replaceAll("<.*?>", "");
                String returnTypeShort = returnType.substring(returnType.lastIndexOf(".") + 1);

                //get property documentation message
                String key = methodClass + "|" + name + "|" + returnTypeShort;
                String propertyMessage = messageService.getMessageText("KR-SAP", null, key);

                if (propertyMessage == null) {
                    propertyMessage = "NO DOCUMENTATION AVAILABLE... we are working on it!";
                }

                //scrub property message of @link and @code
                propertyMessage = propertyMessage.replaceAll("\\{[@#]link (.*?)\\}", "<i>$1</i>");
                propertyMessage = propertyMessage.replaceAll("\\{[@#]code (.*?)\\}", "<i>$1</i>");

                //wrap in link if a kuali type
                if (returnType.startsWith("org.kuali")) {
                    returnTypeShort = "<a href='" + getRootJavadocAddress() + returnType.replace('.', '/')
                            + ".html' target='_blank'>" + returnTypeShort + "</a>";
                }

                //html propertyMessage content
                propertyMessage = "<div class='demo-propertyItem'>" + "<h4 class='demo-propertyName'>" + name
                        + "</h4>" + "<div class='demo-propertyType'>" + returnTypeShort + "</div>"
                        + "<div class='demo-propertyDesc'>" + propertyMessage + "</div></div>";

                if (!methodClass.equals(javaFullClassPath)) {
                    //if this method comes from a parent and not this class, put it in the inheritedPropertiesMap
                    List<String> classProperties = inheritedProperties.get(methodClass);
                    if (classProperties == null) {
                        classProperties = new ArrayList<String>();
                    }
                    classProperties.add(propertyMessage);
                    inheritedProperties.put(methodClass, classProperties);
                } else {
                    propertyDescriptions.add(propertyMessage);
                }
            }
        }

        documentationMessageContent = documentationMessageContent
                + "<H3>Properties</H3><div class='demo-propertiesContent'>";
        for (String desc : propertyDescriptions) {
            documentationMessageContent = documentationMessageContent + desc;
        }
        documentationMessageContent = documentationMessageContent + "</div>";

        Group documentationGroup = ComponentFactory.getVerticalBoxGroup();

        //properties header
        Header documentationHeader = (Header) ComponentFactory.getNewComponentInstance("Uif-SubSectionHeader");
        documentationHeader.setHeaderLevel("H3");
        documentationHeader
                .setHeaderText(messageService.getMessageText("KR-SAP", null, "componentLibrary.documentation"));
        documentationHeader.setRender(false);
        documentationGroup.setHeader(documentationHeader);

        List<Component> propertiesItems = new ArrayList<Component>();
        Message propertiesMessage = ComponentFactory.getMessage();
        propertiesMessage.setParseComponents(false);
        propertiesMessage.setMessageText(documentationMessageContent);
        propertiesItems.add(propertiesMessage);

        //create the inherited properties disclosures
        if (!inheritedProperties.isEmpty()) {

            //todo sort alphabetically here?
            for (String className : inheritedProperties.keySet()) {
                String messageContent = "";
                List<String> inheritedPropertyDescriptions = inheritedProperties.get(className);

                for (String desc : inheritedPropertyDescriptions) {
                    messageContent = messageContent + desc;
                }

                Group iPropertiesGroup = ComponentFactory.getVerticalBoxGroup();

                //inherited properties header
                Header iPropHeader = (Header) ComponentFactory.getNewComponentInstance("Uif-SubSectionHeader");
                iPropHeader.setHeaderLevel("H3");
                iPropHeader.setHeaderText(
                        messageService.getMessageText("KR-SAP", null, "componentLibrary.inheritedFrom") + " "
                                + className);
                //iPropHeader.setRender(false);
                iPropertiesGroup.setHeader(iPropHeader);
                iPropertiesGroup.getDisclosure().setRender(true);
                iPropertiesGroup.getDisclosure().setDefaultOpen(false);

                List<Component> iPropertiesItems = new ArrayList<Component>();
                Message iPropertiesMessage = ComponentFactory.getMessage();
                iPropertiesMessage.setParseComponents(false);
                iPropertiesMessage.setMessageText(messageContent);
                iPropertiesItems.add(iPropertiesMessage);
                iPropertiesGroup.setItems(iPropertiesItems);

                propertiesItems.add(iPropertiesGroup);
            }
        }

        documentationGroup.setItems(propertiesItems);

        tabItems.add(documentationGroup);
    } catch (Exception e) {
        throw new RuntimeException("Error loading class: " + javaFullClassPath, e);
    }
}

From source file:org.kuali.rice.krad.uif.view.TransactionalDocumentView.java

/**
 * Generates the messages that warn users that the document has been locked for editing by another user.
 *
 * @param form form instance containing the transactional document data
 *///from ww  w  .  j  av a 2  s  .  com
protected void generatePessimisticLockMessages(TransactionalDocumentFormBase form) {
    Document document = form.getDocument();
    Person user = GlobalVariables.getUserSession().getPerson();

    for (PessimisticLock lock : document.getPessimisticLocks()) {
        if (!lock.isOwnedByUser(user)) {
            String lockDescriptor = StringUtils.defaultIfBlank(lock.getLockDescriptor(), "full");
            String lockOwner = lock.getOwnedByUser().getName();
            String lockTime = RiceConstants.getDefaultTimeFormat().format(lock.getGeneratedTimestamp());
            String lockDate = RiceConstants.getDefaultDateFormat().format(lock.getGeneratedTimestamp());

            GlobalVariables.getMessageMap().putError(KRADConstants.GLOBAL_ERRORS,
                    RiceKeyConstants.ERROR_TRANSACTIONAL_LOCKED, lockDescriptor, lockOwner, lockTime, lockDate);
        }
    }
}

From source file:org.kuali.student.enrollment.class2.courseoffering.controller.TestStatePropagationController.java

@Transactional
@RequestMapping(params = "methodToCall=changeSocState")
public ModelAndView changeSocState(@ModelAttribute("KualiForm") TestStatePropagationForm form)
        throws PermissionDeniedException, OperationFailedException, OperationNotSupportedException,
        InvalidParameterException, MissingParameterException, DoesNotExistException,
        DataValidationErrorException, VersionMismatchException, ReadOnlyException {

    String environment = StringUtils.defaultIfBlank(
            ConfigContext.getCurrentContextConfig().getProperty("environment"), StringUtils.EMPTY);
    if (!"DEV".equalsIgnoreCase(environment)) {
        throw new OperationNotSupportedException(
                "Cannot change state of SOC in non-dev environment (env is:" + environment + ")");
    }//from   www . ja va 2  s  . c om

    // update soc-state
    ContextInfo contextInfo = new ContextInfo();
    SocInfo targetSocInfo = getTargetSocInfoForTerm(form.getTermCodeForSocStateChange(), contextInfo);
    targetSocInfo.setStateKey(form.getNewSocStateForSocStateChange());
    putBypassBusinessLogicFlagOntoContext(contextInfo);
    this.getSocService().updateSoc(targetSocInfo.getId(), targetSocInfo, contextInfo);

    populateFormWithTargetSocInfo(form);

    return getUIFModelAndView(form);
}

From source file:org.ngrinder.home.controller.HomeController.java

private void setLanguage(String lan, HttpServletResponse response, HttpServletRequest request) {
    LocaleResolver localeResolver = checkNotNull(RequestContextUtils.getLocaleResolver(request),
            "No LocaleResolver found!");
    LocaleEditor localeEditor = new LocaleEditor();
    String language = StringUtils.defaultIfBlank(lan,
            getConfig().getControllerProperties().getProperty(PROP_CONTROLLER_DEFAULT_LANG));
    localeEditor.setAsText(language);// w w  w. j  a v a 2 s  .  c om
    localeResolver.setLocale(request, response, (Locale) localeEditor.getValue());
}

From source file:org.ngrinder.infra.spring.UserHandlerMethodArgumentResolver.java

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    User currentUser = getUserContext().getCurrentUser();

    String userParam = webRequest.getParameter("ownerId");
    if (StringUtils.isNotBlank(userParam) && currentUser.getRole().hasPermission(Permission.SWITCH_TO_ANYONE)) {
        return getUserService().getOne(userParam);
    }//from w  w w .ja  v  a 2  s.c o  m

    // User want to do something through other User status and this
    // switchUser is other user Id
    String switchUser = null;
    Cookie[] cookies = getCookies(webRequest);
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if ("switchUser".equals(cookie.getName()) && cookie.getMaxAge() != 0) {
                switchUser = cookie.getValue();
            }
        }
    }
    // Let this can be done with parameter as well.
    switchUser = StringUtils.defaultIfBlank(webRequest.getParameter("switchUser"), switchUser);

    if (currentUser.getUserId().equals(switchUser)) {
        currentUser.setOwnerUser(null);
    } else if (StringUtils.isNotEmpty(switchUser)) {
        User ownerUser = getUserService().getOne(switchUser);
        // CurrentUser should remember whose status he used
        if (currentUser.getRole().hasPermission(Permission.SWITCH_TO_ANYONE)
                || (ownerUser.getFollowers() != null && ownerUser.getFollowers().contains(currentUser))) {
            currentUser.setOwnerUser(ownerUser);
            return ownerUser;
        }
    } else if (StringUtils.isEmpty(switchUser)) {
        currentUser.setOwnerUser(null);
    }

    return currentUser.getFactualUser();
}