Java Code Examples for org.apache.commons.lang.StringUtils#defaultIfBlank()

The following examples show how to use org.apache.commons.lang.StringUtils#defaultIfBlank() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: ymate-platform-v2   File: WebUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String buildRedirectURL(IContext context, HttpServletRequest request, String redirectUrl, boolean needPrefix) {
    String _redirectUrl = StringUtils.trimToNull(redirectUrl);
    if (_redirectUrl == null) {
        _redirectUrl = StringUtils.defaultIfBlank(request.getParameter(Type.Const.REDIRECT_URL), context != null ? context.getContextParams().get(Type.Const.REDIRECT_URL) : "");
        if (StringUtils.isBlank(_redirectUrl)) {
            if (context != null) {
                _redirectUrl = __doGetConfigValue(context.getOwner(), IWebMvcModuleCfg.PARAMS_REDIRECT_HOME_URL, null);
            }
            if (StringUtils.isBlank(_redirectUrl)) {
                _redirectUrl = baseURL(WebContext.getRequest());
            }
        }
    }
    if (needPrefix && !StringUtils.startsWithIgnoreCase(_redirectUrl, "http://") && !StringUtils.startsWithIgnoreCase(_redirectUrl, "https://")) {
        _redirectUrl = WebUtils.buildURL(request, _redirectUrl, true);
    }
    return _redirectUrl;
}
 
Example 2
public String getProperty(String tagName, String defaultValue) {
    String _returnValue = null;
    if (__inited) {
        NodeList _nodes = __rootElement.getElementsByTagName(tagName);
        if (_nodes.getLength() > 0) {
            Element _node = (Element) _nodes.item(0);
            _returnValue = _node.getTextContent();
        }
    }
    return StringUtils.defaultIfBlank(_returnValue, defaultValue);
}
 
Example 3
@Test
public void pullRequestActionable_OnEmptyContributor_AdddFact() {

    // given
    // from @Before
    SCMHead head = new SCMHeadBuilder("Pull Request");

    Job job = mock(Job.class);
    when(run.getParent()).thenReturn(job);

    mockStatic(SCMHead.HeadByItem.class);
    when(SCMHead.HeadByItem.findHead(job)).thenReturn(head);
    when(job.getAction(ObjectMetadataAction.class)).thenReturn(null);

    ContributorMetadataAction contributorMetadataAction = mock(ContributorMetadataAction.class);
    when(contributorMetadataAction.getContributor()).thenReturn(null);
    when(contributorMetadataAction.getContributorDisplayName()).thenReturn("Damian Szczepanik");
    when(job.getAction(ContributorMetadataAction.class)).thenReturn(contributorMetadataAction);

    // when
    Deencapsulation.invoke(actionableBuilder, "pullRequestActionable");

    // then
    String pronoun = StringUtils.defaultIfBlank(
            head.getPronoun(),
            Messages.Office365ConnectorWebhookNotifier_ChangeRequestPronoun());
    FactAssertion.assertThat(factsBuilder)
            .hasName(Messages.Office365ConnectorWebhookNotifier_AuthorHeader(pronoun))
            .hasValue("Damian Szczepanik");
}
 
Example 4
@SuppressWarnings("unchecked")
@Override
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");
	}
}
 
Example 5
@Test
public void pullRequestActionable_OnEmptyContributorDisplayName_AdddFact() {

    // given
    // from @Before
    SCMHead head = new SCMHeadBuilder("Pull Request");

    Job job = mock(Job.class);
    when(run.getParent()).thenReturn(job);

    mockStatic(SCMHead.HeadByItem.class);
    when(SCMHead.HeadByItem.findHead(job)).thenReturn(head);
    when(job.getAction(ObjectMetadataAction.class)).thenReturn(null);

    ContributorMetadataAction contributorMetadataAction = mock(ContributorMetadataAction.class);
    when(contributorMetadataAction.getContributor()).thenReturn("damianszczepanik");
    when(contributorMetadataAction.getContributorDisplayName()).thenReturn(null);
    when(job.getAction(ContributorMetadataAction.class)).thenReturn(contributorMetadataAction);

    // when
    Deencapsulation.invoke(actionableBuilder, "pullRequestActionable");

    // then
    String pronoun = StringUtils.defaultIfBlank(
            head.getPronoun(),
            Messages.Office365ConnectorWebhookNotifier_ChangeRequestPronoun());
    FactAssertion.assertThat(factsBuilder)
            .hasName(Messages.Office365ConnectorWebhookNotifier_AuthorHeader(pronoun))
            .hasValue("damianszczepanik");
}
 
Example 6
Source Project: rebuild   File: AppUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取后台抛出的错误消息
 * 
 * @param request
 * @param exception
 * @return
 */
public static String getErrorMessage(HttpServletRequest request, Throwable exception) {
	// 已知异常
    if (exception != null) {
        Throwable know = ThrowableUtils.getRootCause(exception);
           if (know instanceof DataTruncation) {
               return "字段长度超出限制";
           } else if (know instanceof AccessDeniedException) {
			return Languages.lang("Error403");
		}
       }

	String errorMsg = (String) request.getAttribute(ServletUtils.ERROR_MESSAGE);
	if (StringUtils.isNotBlank(errorMsg)) {
		return errorMsg;
	}

	if (exception == null) {
		exception = (Throwable) request.getAttribute(ServletUtils.ERROR_EXCEPTION);
	}
	if (exception == null) {
		exception = (Throwable) request.getAttribute(ServletUtils.JSP_JSP_EXCEPTION);
	}

	if (exception == null) {
		Integer state = (Integer) request.getAttribute(ServletUtils.ERROR_STATUS_CODE);
		if (state != null && state == 404) {
			return Languages.lang("Error404");
		} else if (state != null && state == 403) {
			return Languages.lang("Error403");
		} else {
			return Languages.lang("ErrorUnknow");
		}
	} else {
		exception = ThrowableUtils.getRootCause(exception);
		errorMsg = StringUtils.defaultIfBlank(exception.getLocalizedMessage(), Languages.lang("ErrorUnknow"));
		return exception.getClass().getSimpleName() + ": " + errorMsg;
	}
}
 
Example 7
Source Project: rebuild   File: KVStorage.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param key
 * @param reload
 * @param defaultValue
 * @return
 */
protected static String getValue(final String key, boolean reload, Object defaultValue) {

    String value = null;

    if (Application.serversReady()) {
        value = Application.getCommonCache().get(key);
        if (value != null && !reload) {
            return value;
        }

        // 1. 首先从数据库
        Object[] fromDb = Application.createQueryNoFilter(
                "select value from SystemConfig where item = ?")
                .setParameter(1, key)
                .unique();
        value = fromDb == null ? null : StringUtils.defaultIfBlank((String) fromDb[0], null);
    }

    // 2. 从配置文件/命令行加载
    if (value == null) {
        value = AesPreferencesConfigurer.getItem(key);
    }

    // 3. 默认值
    if (value == null && defaultValue != null) {
        value = defaultValue.toString();
    }

    if (Application.serversReady()) {
        if (value == null) {
            Application.getCommonCache().evict(key);
        } else {
            Application.getCommonCache().put(key, value);
        }
    }
    
    return value;
}
 
Example 8
Source Project: rebuild   File: FlowNode.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * @return
 */
public String getSignMode() {
	return StringUtils.defaultIfBlank(getDataMap().getString("signMode"), SIGN_OR);
}
 
Example 9
@Override
protected boolean __doStart() {
    __heartbeatMessage = StringUtils.defaultIfBlank(getClient().clientCfg().getParam(IServ.Const.PARAMS_HEARTBEAT_MESSAGE), "0");
    return super.__doStart();
}
 
Example 10
Source Project: ymate-platform-v2   File: Speedometer.java    License: Apache License 2.0 4 votes vote down vote up
public Speedometer(String name) {
    __name = StringUtils.defaultIfBlank(name, "default");
    __data = new LinkedList<Long>();
    __sorted = new LinkedList<Long>();
}
 
Example 11
public BridgeMessageContent(String mime, String encoding, byte[] content) {
    this.mime = mime;
    this.encoding = StringUtils.defaultIfBlank(encoding, "");
    this.content = content;
}
 
Example 12
Source Project: ymate-platform-v2   File: WebUtils.java    License: Apache License 2.0 4 votes vote down vote up
public static String errorCodeI18n(IWebMvc owner, String resourceName, IExceptionProcessor.Result result) {
    String _msg = WebUtils.errorCodeI18n(owner, resourceName, result.getCode(), result.getMessage());
    return StringUtils.defaultIfBlank(_msg, result.getMessage());
}
 
Example 13
/**
 * {@inheritDoc}
 */
@Override
public void buildMaintenanceActionLink(Link actionLink, Object model, String maintenanceMethodToCall) {
    LookupForm lookupForm = (LookupForm) model;

    Map<String, Object> actionLinkContext = actionLink.getContext();
    Object dataObject = actionLinkContext == null ? null : actionLinkContext.get(
            UifConstants.ContextVariableNames.LINE);

    List<String> pkNames = getLegacyDataAdapter().listPrimaryKeyFieldNames(getDataObjectClass());

    // build maintenance link href if needed
    if (StringUtils.isBlank(actionLink.getHref())) {
        String href = getMaintenanceActionUrl(lookupForm, dataObject, maintenanceMethodToCall, pkNames);
        if (StringUtils.isBlank(href)) {
            actionLink.setRender(false);

            return;
        }

        actionLink.setHref(href);
    }

    // build action title if not set
    if (StringUtils.isBlank(actionLink.getTitle())) {
        List<String> linkLabels = new ArrayList<String>();

        // get the link text
        String linkText = actionLink.getLinkText();

        // if the link text is available, then add it to the link label
        if (StringUtils.isNotBlank(linkText)) {
            linkLabels.add(linkText);
        }

        // get the data object label
        DataObjectEntry dataObjectEntry = getDataDictionaryService().getDataDictionary().getDataObjectEntry(
                getDataObjectClass().getName());
        String dataObjectLabel = dataObjectEntry != null ? dataObjectEntry.getObjectLabel() : null;

        // if the data object label is available, then add it to the link label
        if (StringUtils.isNotBlank(dataObjectLabel)) {
            linkLabels.add(dataObjectLabel);
        }

        // get the prepend text
        String titleActionUrlPrependText = getConfigurationService().getPropertyValueAsString(
                KRADConstants.Lookup.TITLE_ACTION_URL_PREPENDTEXT_PROPERTY);

        // get the primary keys for the object
        Map<String, String> primaryKeyValues = KRADUtils.getPropertyKeyValuesFromDataObject(pkNames, dataObject);

        // if the prepend text is available and there are primary key values, then add it to the link label
        if (StringUtils.isNotBlank(titleActionUrlPrependText) && !primaryKeyValues.isEmpty()) {
            linkLabels.add(titleActionUrlPrependText);
        }

        String linkLabel = StringUtils.defaultIfBlank(StringUtils.join(linkLabels, " "), StringUtils.EMPTY);
        String title = KRADUtils.buildAttributeTitleString(linkLabel, getDataObjectClass(), primaryKeyValues);
        actionLink.setTitle(title);
    }
}
 
Example 14
Source Project: rice   File: Inquiry.java    License: Educational Community License v2.0 4 votes vote down vote up
/**
  * Gets text to prepend to the inquiry link title
  *
  * @param dataObjectClass data object class being inquired into
  * @return inquiry link title
  */
 public String createTitleText(Class<?> dataObjectClass, Map<String,String> inquiryKeyValues) {
     // use manually configured title if exists
     if (StringUtils.isNotBlank(getTitle())) {
         return getTitle();
     }

     List<String> titleTexts = new ArrayList<String>();

     // get the title prefix
     String titlePrefix = CoreApiServiceLocator.getKualiConfigurationService().getPropertyValueAsString(
             INQUIRY_TITLE_PREFIX);

     // if the title prefix is available, add it to the title text
     if (StringUtils.isNotBlank(titlePrefix)) {
         titleTexts.add(titlePrefix);
     }

     // get the data object label
     DataObjectEntry dataObjectEntry = KRADServiceLocatorWeb.getDataDictionaryService().getDataDictionary()
             .getDataObjectEntry(dataObjectClass.getName());
     String dataObjectLabel = dataObjectEntry != null ? dataObjectEntry.getObjectLabel() : null;

     // if the data object label is available, then add it to the title text
     if (StringUtils.isNotBlank(dataObjectLabel)) {
         titleTexts.add(dataObjectLabel);
     }

     // get the prepend text configuration
     String titleUrlPrependText = CoreApiServiceLocator.getKualiConfigurationService().getPropertyValueAsString(
             KRADConstants.Lookup.TITLE_ACTION_URL_PREPENDTEXT_PROPERTY);

     // if the prepend text is available and there are primary key values, then add it to the link label
     if (StringUtils.isNotBlank(titleUrlPrependText) && !inquiryKeyValues.isEmpty()) {
         titleTexts.add(titleUrlPrependText);
     }

     String titleText = StringUtils.defaultIfBlank(StringUtils.join(titleTexts, " "), StringUtils.EMPTY);

     return KRADUtils.buildAttributeTitleString(titleText, dataObjectClass, inquiryKeyValues);
}
 
Example 15
@Override
public void execute(OperatingContext operatingContext) {
	final JSONObject content = (JSONObject) context.getActionContent();
	
	JSONArray sendTo = content.getJSONArray("sendTo");
	List<String> sendToList = new ArrayList<>();
	for (Object o : sendTo) {
		sendToList.add((String) o);
	}
	Set<ID> toUsers = UserHelper.parseUsers(sendToList, context.getSourceRecord());
	if (toUsers.isEmpty()) {
		return;
	}

	final int type = content.getIntValue("type");
	if (type == TYPE_MAIL && !SMSender.availableMail()) {
		LOG.warn("Could not send because email-service is unavailable");
	} else if (type == TYPE_SMS && !SMSender.availableSMS()) {
		LOG.warn("Could not send because sms-service is unavailable");
	}

	// 这里等待一会,因为主事物可能未完成,如果有变量可能脏读
	ThreadPool.waitFor(3000);

	String message = content.getString("content");
	message = ContentWithFieldVars.replaceWithRecord(message, context.getSourceRecord());

	// for email
	String subject = StringUtils.defaultIfBlank(content.getString("title"), "你有一条新通知");

	for (ID user : toUsers) {
	    if (type == TYPE_MAIL) {
			String emailAddr = Application.getUserStore().getUser(user).getEmail();
	        if (emailAddr != null) {
				SMSender.sendMail(emailAddr, subject, message);
               }

           } else if (type == TYPE_SMS) {
			String mobile = Application.getUserStore().getUser(user).getWorkphone();
	    	if (RegexUtils.isCNMobile(mobile)) {
				SMSender.sendSMS(mobile, message);
			}

           }
	    // default: TYPE_NOTIFICATION
	    else {
   			Message m = MessageBuilder.createMessage(user, message, context.getSourceRecord());
    		Application.getNotifications().send(m);

           }
	}
}
 
Example 16
Source Project: ymate-platform-v2   File: ConfigInfo.java    License: Apache License 2.0 4 votes vote down vote up
public String namedFilter(String original) {
    if (this.namedFilter != null) {
        return StringUtils.defaultIfBlank(this.namedFilter.doFilter(original), original);
    }
    return original;
}
 
Example 17
Source Project: SpringCloud   File: MyMetaObjectHandler.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 获取当前操作的用户名
 *
 * @return 当前操作用户名,若为空置为system
 */
private String getUsername() {
    return StringUtils.defaultIfBlank(UserContextHolder.getInstance().getUsername(), BasePo.DEFAULT_USERNAME);
}
 
Example 18
Source Project: SpringCloud   File: PoMetaObjectHandler.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 获取当前交易的用户,为空返回默认system
 *
 * @return
 */
private String getCurrentUsername() {
    return StringUtils.defaultIfBlank(UserContextHolder.getInstance().getUsername(), BasePo.DEFAULT_USERNAME);
}
 
Example 19
/**
 * @param value
 * @param field
 * @return
 * @see ClassificationManager
 */
public JSON wrapClassification(Object value, EasyMeta field) {
    ID id = (ID) value;
    String text = StringUtils.defaultIfBlank(ClassificationManager.instance.getFullName(id), MISS_REF_PLACE);
	return wrapMixValue(id, text);
}
 
Example 20
/**
 * Get the base command for running this utility
 * @return
 */
protected String getBaseCommand() {
	return "java [-DlogLevel=<logLevel>] [-DlogFile=<logFile>] -jar "+StringUtils.defaultIfBlank(getJarName(), "<jar name>");
}