下面列出了org.apache.commons.lang3.StringUtils#defaultString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* {@inheritDoc} This implementation works similar to {@code nodeKey()}, but
* always adds an index expression to the resulting key.
*/
@Override
public <T> String canonicalKey(final T node, final String parentKey,
final NodeHandler<T> handler)
{
final T parent = handler.getParent(node);
if (parent == null)
{
// this is the root node
return StringUtils.defaultString(parentKey);
}
final StringBuilder buf = new StringBuilder(BUF_SIZE);
if (StringUtils.isNotEmpty(parentKey))
{
buf.append(parentKey).append(PATH_DELIMITER);
}
buf.append(handler.nodeName(node));
buf.append(START_INDEX);
buf.append(determineIndex(parent, node, handler));
buf.append(END_INDEX);
return buf.toString();
}
/**
* Translates NewValue of history entry. It works in the same way as
* {@link RecipientStatusHistoryDtoConverter#getOldTranslatedValue(String, String, Locale)} but
* contains additional checking for deleted Binding and deleted Mailing list.
*
* @param changeValue value which was changed.
* @param changedField type of change.
* @param locale locale for current user.
* @return translated Value.
*/
private String getNewTranslatedValue(String changeValue, String changedField, Locale locale) {
String deletedText = I18nString.getLocaleString("target.Deleted", locale);
// in case of we don't have the rule for current kind of change we return value without any changes
RecipientMutableFields fieldByText = RecipientMutableFields.getByCode(changedField);
if (Objects.isNull(fieldByText)) {
return StringUtils.defaultString(changeValue, NOT_SET);
}
// deletion actions have a special behaviour. They applicable only for `NewValue`
switch (fieldByText) {
case MAILINGLIST_DELETED:
String mailinglistText = I18nString.getLocaleString("Mailinglist", locale);
return String.format("%s %s", mailinglistText, deletedText).toUpperCase();
case CUSTOMER_BINDING_DELETED:
String bindingText = I18nString.getLocaleString("Binding", locale);
return String.format("%s %s", bindingText, deletedText).toUpperCase();
default:
// going ahead if it's not deletion action
return getOldTranslatedValue(changeValue, changedField, locale);
}
}
public static String getRepositoryName( final String href )
{
String requestPathInfo = StringUtils.defaultString( href );
//remove prefix ie /repository/blah becomes /blah
requestPathInfo = removePrefix( requestPathInfo );
// Remove prefixing slash as the repository id doesn't contain it;
if ( requestPathInfo.startsWith( "/" ) )
{
requestPathInfo = requestPathInfo.substring( 1 );
}
// Find first element, if slash exists.
int slash = requestPathInfo.indexOf( '/' );
if ( slash > 0 )
{
// Filtered: "central/org/apache/maven/" -> "central"
return requestPathInfo.substring( 0, slash );
}
return requestPathInfo;
}
@Override
public String getSubjectOrPatient(){
// ids do not contain spaces, do not perform expensive load from db
if (getEntity().getPatId() != null && !getEntity().getPatId().contains(" ")) {
IContact contact = getContact();
if (contact != null) {
if (contact.isPatient()) {
contact = CoreModelServiceHolder.get()
.load(getEntity().getPatId(), IPatient.class, false, false).orElse(null);
}
return contact.getLabel();
}
}
return StringUtils.defaultString(getEntity().getPatId());
}
public MessageAdapter(MessageRow args) {
id = Long.parseLong(args.getID());
name = StringUtils.defaultString(args.getMsgName(), " ");
namespace = StringUtils.defaultString(args.getMsgNamespace(), " ");
timestamp = args.getTimestamp();
from = StringUtils.defaultString(args.getFrom(), " ");
to = StringUtils.defaultString(args.getTo(), " ");
humanReadable = StringUtils.defaultString(args.getContent(), " ");
json = StringUtils.defaultString(args.getJson(), humanReadable);//FIXME: This code used for backward compatibility, refactore after a few months
rawMessage = args.getRawMessage();
printableMessage = args.getPrintableMessage();
fields = MessageParser.parseFields(json);
rejectReason = StringUtils.defaultString(args.getRejectReason(), "");
}
static ComparisonResult compareRequestAsJson(String expectedRequestBody, String actualBody, Set<String> ignoringPaths, String mode) {
String defaultExpectedRequestBody = StringUtils.defaultString(expectedRequestBody);
String defaultActualBody = StringUtils.defaultString(actualBody);
ObjectMapper om = new ObjectMapper();
try {
om.readValue(defaultExpectedRequestBody, Object.class);
om.readValue(defaultActualBody, Object.class);
} catch (Exception e) {
throw new JsonParsingException(e);
}
ComparisonResult comparisonResult;
try {
List<Customization> customizations = ignoringPaths.stream()
.map(p -> new Customization(p, (o1, o2) -> true))
.collect(Collectors.toList());
JSONCompareMode compareMode = StringUtils.isEmpty(mode) ? JSONCompareMode.STRICT : JSONCompareMode.valueOf(mode);
JSONAssert.assertEquals(defaultExpectedRequestBody.replaceAll("\\s", " "),
defaultActualBody.replaceAll("\\s", " "),
new IgnoringComparator(compareMode, customizations));
comparisonResult = new ComparisonResult(false, "", expectedRequestBody, actualBody);
} catch (Throwable assertionError) {
if (!(assertionError instanceof AssertionError)) {
log.error("Exception while parse json {} {} {} {}", expectedRequestBody, actualBody, ignoringPaths, mode, assertionError);
}
comparisonResult = new ComparisonResult(true, assertionError.getMessage(), expectedRequestBody, actualBody);
}
return comparisonResult;
}
private void renderSortableHiddenFields() throws JspException {
String sortByLabel = ListTagUtil.makeSortByLabel(getUniqueName());
String sortDirLabel = ListTagUtil.makeSortDirLabel(getUniqueName());
HtmlTag sortByInputTag = new HtmlTag("input");
sortByInputTag.setAttribute("type", "hidden");
sortByInputTag.setAttribute("name", sortByLabel);
sortByInputTag.setAttribute("id",
ListTagUtil.makeSortById(getUniqueName()));
sortByInputTag.setAttribute("value", StringEscapeUtils.escapeHtml4(StringUtils
.defaultString(pageContext.getRequest().getParameter(sortByLabel))));
HtmlTag sortByDirTag = new HtmlTag("input");
sortByDirTag.setAttribute("type", "hidden");
sortByDirTag.setAttribute("name", sortDirLabel);
sortByDirTag.setAttribute("id", ListTagUtil.
makeSortDirId(getUniqueName()));
String dir = StringUtils.defaultString(pageContext.getRequest().getParameter(
sortDirLabel));
if (dir.equals(RequestContext.SORT_ASC)) {
sortByDirTag.setAttribute("value", RequestContext.SORT_ASC);
}
else if (dir.equals(RequestContext.SORT_DESC)) {
sortByDirTag.setAttribute("value", RequestContext.SORT_DESC);
}
else {
sortByDirTag.setAttribute("value", "");
}
ListTagUtil.write(pageContext, sortByInputTag.render());
ListTagUtil.write(pageContext, sortByDirTag.render());
}
/**
* 创建模型
* @throws UnsupportedEncodingException
*/
public org.activiti.engine.repository.Model create(String name, String key, String description, String category) throws UnsupportedEncodingException {
ObjectMapper objectMapper = new ObjectMapper();
ObjectNode editorNode = objectMapper.createObjectNode();
editorNode.put("id", "canvas");
editorNode.put("resourceId", "canvas");
ObjectNode stencilSetNode = objectMapper.createObjectNode();
stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
editorNode.put("stencilset", stencilSetNode);
org.activiti.engine.repository.Model modelData = repositoryService.newModel();
description = StringUtils.defaultString(description);
modelData.setKey(StringUtils.defaultString(key));
modelData.setName(name);
modelData.setCategory(category);
modelData.setVersion(Integer.parseInt(String.valueOf(repositoryService.createModelQuery().modelKey(modelData.getKey()).count()+1)));
ObjectNode modelObjectNode = objectMapper.createObjectNode();
modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, modelData.getVersion());
modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
modelData.setMetaInfo(modelObjectNode.toString());
repositoryService.saveModel(modelData);
repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
return modelData;
}
/**
* Construct the label text used in the brat user interface.
*
* @param aAdapter the adapter.
* @param aFs the annotation.
* @param aFeatures the features.
* @return the label.
*/
public static String getUiLabelText(TypeAdapter aAdapter, FeatureStructure aFs,
List<AnnotationFeature> aFeatures)
{
StringBuilder bratLabelText = new StringBuilder();
for (AnnotationFeature feature : aFeatures) {
if (!feature.isEnabled() || !feature.isVisible()
|| !MultiValueMode.NONE.equals(feature.getMultiValueMode())) {
continue;
}
Feature labelFeature = aFs.getType().getFeatureByBaseName(feature.getName());
String label = StringUtils.defaultString(aFs.getFeatureValueAsString(labelFeature));
if (bratLabelText.length() > 0 && label.length() > 0) {
bratLabelText.append(TypeAdapter.FEATURE_SEPARATOR);
}
bratLabelText.append(label);
}
if (bratLabelText.length() > 0) {
return bratLabelText.toString();
}
else {
// If there are no label features at all, then use the layer UI name
return "(" + aAdapter.getLayer().getUiName() + ")";
}
}
/**
* Fonction retournant une numéro de séquence depuis une séquence générique, et une date
*
* @param sequence
* @return
*/
@Transactional
public String getSequenceNumber(Sequence sequence, LocalDate refDate) {
SequenceVersion sequenceVersion = getVersion(sequence, refDate);
String seqPrefixe = StringUtils.defaultString(sequence.getPrefixe(), ""),
seqSuffixe = StringUtils.defaultString(sequence.getSuffixe(), ""),
sequenceValue;
if (sequence.getSequenceTypeSelect() == SequenceTypeSelect.NUMBERS) {
sequenceValue =
StringUtils.leftPad(
sequenceVersion.getNextNum().toString(), sequence.getPadding(), PADDING_STRING);
} else {
sequenceValue = findNextLetterSequence(sequenceVersion);
}
sequenceVersion.setNextNum(sequenceVersion.getNextNum() + sequence.getToBeAdded());
String nextSeq =
(seqPrefixe + sequenceValue + seqSuffixe)
.replaceAll(PATTERN_FULL_YEAR, Integer.toString(refDate.get(ChronoField.YEAR_OF_ERA)))
.replaceAll(PATTERN_YEAR, refDate.format(DateTimeFormatter.ofPattern("yy")))
.replaceAll(PATTERN_MONTH, Integer.toString(refDate.getMonthValue()))
.replaceAll(PATTERN_FULL_MONTH, refDate.format(DateTimeFormatter.ofPattern("MM")))
.replaceAll(PATTERN_DAY, Integer.toString(refDate.getDayOfMonth()))
.replaceAll(
PATTERN_WEEK, Integer.toString(refDate.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR)));
log.debug("nextSeq : : : : {}", nextSeq);
sequenceVersionRepository.save(sequenceVersion);
return nextSeq;
}
@Override
public boolean checkIfTargetNameAlreadyExists(@VelocityCheck int companyId, String targetName, int targetId) {
String existingName = StringUtils.defaultString(targetDao.getTargetName(targetId, companyId, true));
// Allow to keep existing name anyway.
return !existingName.equals(targetName) && targetDao.isTargetNameInUse(companyId, targetName, false);
}
public String getSenderName(int adminId) {
if (adminId > 0) {
String query = "SELECT fullname, company_name FROM admin_tbl WHERE admin_id = ?";
String name = selectObjectDefaultNull(logger, query, senderNameRowMapper, adminId);
return StringUtils.defaultString(name);
}
return "";
}
@Override
public void setFullUrl(String fullUrl) {
this.fullUrl = StringUtils.defaultString(fullUrl);
}
@Nonnull
protected String getContentDispositionHeaderValue( @Nullable String extensibleFilename, @Nullable String compressionExtension )
{
final String suffix = (compressionExtension == null) ? "" : "." + compressionExtension;
return "attachment; filename=" + StringUtils.defaultString( extensibleFilename, "metadata" ) + "." + fileExtension + suffix;
}
public String getContent() {
return StringUtils.defaultString(content);
}
private String getBetaApiExtensionName(String defaultBetaApiExtensionName, Options options) {
return StringUtils.defaultString(options.getBetaApiExtensionName(), defaultBetaApiExtensionName);
}
/**
* Returns the value of this StringType, or an empty string ("") if the
* value is <code>null</code>. This method is provided as a convenience to
* users of this API.
*/
public String getValueNotNull() {
return StringUtils.defaultString(getValue());
}
/**
* Returns the example to verify the parser.
*
* @return the example
*/
public String getExample() {
return StringUtils.defaultString(example);
}
/**
* Constructor uses in case of your ResultSet contains default names of columns with some prefix.
* Maybe useful when you calls one RowMapper inside the second one.
*
* @param columnNamePrefix prefix for column names.
*/
public PlainRowMapper(String columnNamePrefix) {
this.columnNamePrefix = StringUtils.defaultString(columnNamePrefix, StringUtils.EMPTY);
}
/**
* Returns the separator to be used for the given property. This method
* is called by {@code writeProperty()}. The string returned here
* is used as separator between the property key and its value. Per
* default the method checks whether a global separator is set. If this
* is the case, it is returned. Otherwise the separator returned by
* {@code getCurrentSeparator()} is used, which was set by the
* associated layout object. Derived classes may implement a different
* strategy for defining the separator.
*
* @param key the property key
* @param value the value
* @return the separator to be used
* @since 1.7
*/
protected String fetchSeparator(final String key, final Object value)
{
return getGlobalSeparator() != null ? getGlobalSeparator()
: StringUtils.defaultString(getCurrentSeparator());
}