本文整理汇总了Java中org.apache.commons.lang3.StringUtils.defaultString方法的典型用法代码示例。如果您正苦于以下问题:Java StringUtils.defaultString方法的具体用法?Java StringUtils.defaultString怎么用?Java StringUtils.defaultString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.commons.lang3.StringUtils
的用法示例。
在下文中一共展示了StringUtils.defaultString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: converter
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
@Override
public DocTag converter(ParamTag o) {
//解析 "@param user :username 用户名|必填" 这种注释
boolean require = false;
String paramDesc = o.parameterComment();
if (paramDesc.contains("|")) {
int endIndex = paramDesc.lastIndexOf("|必填");
require = endIndex > 0;
if (require) {
paramDesc = paramDesc.substring(0, endIndex);
}
}
String paramName = StringUtils.defaultString(o.parameterName());
if (paramDesc.startsWith(":")) {
int index = paramDesc.indexOf(" ");
if (index > 0) {
paramName = paramDesc.substring(1, index);
paramDesc = paramDesc.substring(index + 1);
}
}
return new ParamTagImpl(o.name(), paramName, paramDesc, require);
}
示例2: converteerAfnemerindicatiebestand
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
private void converteerAfnemerindicatiebestand(final long maxAfnemerindicatieId,
final OutputStream os, final LineIterator it) throws IOException {
long voortgang = 0;
final Map<Short, Short> partijConversieMap = partijConversie.getPartijConversieMap();
final Map<Integer, Integer> leveringsautorisatieConversieMap = leveringsautorisatieConversie.getLeveringsautorisatieConversieMap();
while (it.hasNext()) {
final String line = it.nextLine();
final String[] splitLine = StringUtils.split(line, ",");
final long origId = Long.parseLong(splitLine[0]);
final long id = maxAfnemerindicatieId + origId;
final String pers = splitLine[1];
final String afnemer = String.valueOf(partijConversieMap.get(Short.parseShort(splitLine[2])));
final String levsautorisatie = String.valueOf(leveringsautorisatieConversieMap.get(Integer.parseInt(splitLine[3])));
final String dataanvmaterieleperiode = StringUtils.defaultString(StringUtils.trimToNull(splitLine[4]), NULL_VALUE);
final String dateindevolgen = StringUtils.defaultString(StringUtils.trimToNull(splitLine[5]), NULL_VALUE);
final String indag = splitLine[6];
final String newLine = String.format("%s,%s,%s,%s,%s,%s,%s%n", id, pers, afnemer, levsautorisatie,
dataanvmaterieleperiode, dateindevolgen, indag);
IOUtils.write(newLine, os, StandardCharsets.UTF_8);
voortgang++;
if (voortgang % LOG_TRESHOLD == 0) {
LOGGER.info("Voortgang persafnemerindicatie {}", voortgang);
}
}
}
示例3: parse
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
/**
* Validates and parses the given to make sure that all mandatory properties,
* describing genome data, are provided.
* <p>
* The default values will be assigned in cases when it is possible to do. E.g., to treat omitted
* custom name for a genome it's possible to use an original name of corresponded file without
* extension.
*
* @param path {@code File} Path to fasta file
* @param name {@code String} Alternative name
*/
private String parse(final String path, final String name) {
Assert.notNull(path, getMessage(MessageCode.RESOURCE_NOT_FOUND));
// checks that an original file name is provided, because it is used as a name
// for a genome if custom name isn't specified
String fileName = StringUtils.trimToNull(FilenameUtils.getName(path));
Assert.notNull(fileName, getMessage(MessageCode.MANDATORY_FILE_NAME));
// checks that file is in one of supported formats
boolean supported = false;
final Collection<String> formats = FastaUtils.getFastaExtensions();
for (final String ext : formats) {
if (fileName.endsWith(ext)) {
supported = true;
fileName = Utils.removeFileExtension(fileName, ext);
break;
}
}
if (!supported) {
throw new IllegalArgumentException(getMessage("error.reference.illegal.file.type",
StringUtils.join(formats, ", ")));
}
// if no custom name is provided for a genome, then a file name without extension should be
// used by default
return StringUtils.defaultString(StringUtils.trimToNull(name), fileName);
}
示例4: toStringWithRootCause
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
/**
* 拼装 短异常类名: 异常信息 <-- RootCause的短异常类名: 异常信息
*/
public static String toStringWithRootCause(@Nullable Throwable t) {
if (t == null) {
return StringUtils.EMPTY;
}
final String clsName = ClassUtils.getShortClassName(t, null);
final String message = StringUtils.defaultString(t.getMessage());
Throwable cause = getRootCause(t);
StringBuilder sb = new StringBuilder(128).append(clsName).append(": ").append(message);
if (cause != t) {
sb.append("; <---").append(toStringWithShortName(cause));
}
return sb.toString();
}
示例5: setImageLink
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
public void setImageLink(String imageLink) {
imageLink = StringUtils.defaultString(imageLink, "");
if (imageLink.endsWith(".png")) {
try {
String biggerImage = imageLink.replace(".png", "_2x.png");
Request request = new Request.Builder()
.url(biggerImage)
.head()
.build();
Response response = HttpManager.getInstance().getDefaultClient()
.newBuilder()
.followRedirects(false)
.followSslRedirects(false)
.build()
.newCall(request)
.execute();
if (response.code() < 300) {
this.imageLink = biggerImage;
} else {
this.imageLink = imageLink;
}
} catch (Exception e) {
//Ok to throw exception
LogManager.getLogger(App.class).trace(e);
this.imageLink = imageLink;
}
} else {
this.imageLink = imageLink;
}
}
示例6: getDishesFromRow
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
private Stream<Dish> getDishesFromRow(Element row, int rowIndex, LocalDate baseDate, String mensaId) {
Elements categoryCell = row.select("th");
Elements dishCells = row.select("td");
if (!categoryCell.isEmpty() && dishCells.size() == 5) {
String category = StringUtils.defaultString(categoryCell.get(0).text());
AtomicInteger dayIndex = new AtomicInteger(0);
return dishCells.stream().flatMap(cell -> getDishesFromCell(cell, category, rowIndex, baseDate.plusDays(dayIndex.getAndIncrement()), mensaId));
}
return Stream.empty();
}
示例7: getBaseDate
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
@Override
Stream<LocalDate> getBaseDate(Element element) {
Stream<LocalDate> result = Stream.empty();
String text = StringUtils.defaultString(element.text());
try {
result = Stream.of(LocalDate.parse(text, formatter));
} catch (DateTimeParseException e) {
log.warn("Failed to parse base date from string: {}", text);
}
return result;
}
示例8: addAllByName
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
/**
* Find the spaces matching to the given criteria. Look into space key, and
* space name.
*
* @param parameters
* the node parameters.
* @param criteria
* the search criteria.
* @param start
* the cursor position.
* @return <code>true</code> when there are more spaces to fetch.
*/
private boolean addAllByName(final Map<String, String> parameters, final String criteria, final List<Space> result, final int start)
throws IOException {
// The result should be JSON, otherwise, an empty result is mocked
final String spacesAsJson = StringUtils.defaultString(
getConfluenceResource(parameters, "/rest/api/space?type=global&limit=100&start=" + start),
"{\"results\":[],\"_links\":{}}");
// Build the result from JSON
final TypeReference<Map<String, Object>> typeReference = new TypeReference<Map<String, Object>>() {
// Nothing to override
};
final Map<String, Object> readValue = objectMapper.readValue(spacesAsJson, typeReference);
@SuppressWarnings("unchecked")
final Collection<Map<String, Object>> spaces = (Collection<Map<String, Object>>) readValue.get("results");
// Prepare the context, an ordered set of projects
final Format format = new NormalizeFormat();
final String formatCriteria = format.format(criteria);
// Get the projects and parse them
for (final Map<String, Object> spaceRaw : spaces) {
final Space space = toSpaceLight(spaceRaw);
// Check the values of this project
if (format.format(space.getName()).contains(formatCriteria) || format.format(space.getId()).contains(formatCriteria)) {
result.add(space);
}
}
return ((Map<?, ?>) readValue.get("_links")).containsKey("next");
}
示例9: create
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
/**
* 创建模型
*/
@RequestMapping(value = "create", method = RequestMethod.POST)
public void create(@RequestParam("name") String name, @RequestParam("key") String key, @RequestParam("description") String description,
HttpServletRequest request, HttpServletResponse response) {
try {
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);
Model modelData = repositoryService.newModel();
ObjectNode modelObjectNode = objectMapper.createObjectNode();
modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
description = StringUtils.defaultString(description);
modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
modelData.setMetaInfo(modelObjectNode.toString());
modelData.setName(name);
modelData.setKey(StringUtils.defaultString(key));
repositoryService.saveModel(modelData);
repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
response.sendRedirect(request.getContextPath() + "/modeler.html?modelId=" + modelData.getId());
} catch (Exception e) {
logger.error("创建模型失败:", e);
}
}
示例10: transformText
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
protected Resource transformText(String fileName, Resource resource) throws IOException {
if (injectableTextFiles.stream()
.noneMatch(p -> pathMatcher.match(p, fileName))) {
log.trace("{} not in injectable-files, skipping", fileName);
return resource;
} else {
log.trace("transforming {}", fileName);
}
final byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
final String content = new String(bytes, DEFAULT_CHARSET);
final StringBuffer transformed = new StringBuffer();
final Matcher m = TEXT_REPLACE_PATTERN.matcher(content);
while (m.find()) {
final String match = m.group(),
key = m.group(1),
fallback = StringUtils.defaultString(m.group(2), match);
if (log.isTraceEnabled()) {
final String replace = environment.getProperty(key);
if (replace == null) {
if (m.group(2) == null) {
log.trace("{} -> '{}' (property not found, no fallback)", match, fallback);
} else {
log.trace("{} -> '{}' (fallback)", match, fallback);
}
} else {
log.trace("{} -> '{}' (env '{}')", match, replace, key);
}
}
m.appendReplacement(transformed, Matcher.quoteReplacement(environment.getProperty(key, fallback)));
}
m.appendTail(transformed);
return new TransformedResource(resource, transformed.toString().getBytes(DEFAULT_CHARSET));
}
示例11: createAuthToken
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
public AuthToken createAuthToken(ObjectId clientId, String label) {
label = StringUtils.defaultString(label, "new-token");
final AuthToken authToken = authTokenRepository.save(new AuthToken(clientId).setLabel(label));
authToken.setSecret(RandomUtils.nextString(8));
return authTokenRepository.save(authToken);
}
示例12: parseName
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
protected String parseName(final String fileName, final String alternativeName) {
boolean supported = false;
for (final String ext : WIG_EXTENSIONS) {
if (fileName.endsWith(ext)) {
supported = true;
break;
}
}
if (!supported) {
throw new IllegalArgumentException(getMessage("error.illegal.file.type",
StringUtils.join(WIG_EXTENSIONS, ", ")));
}
return StringUtils.defaultString(StringUtils.trimToNull(alternativeName), fileName);
}
示例13: installPrices
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
/**
* Install AWS prices from the JSON file.
*
* @param node
* The related AWS {@link Node}
* @param regions
* The available regions.
* @param api
* The API name, only for log.
* @param endpoint
* The prices end-point JSON URL.
* @param apiClass
* The mapping model from JSON at region level.
* @param mapper
* The mapping function from JSON at region level to JPA entity.
*/
private <R extends AwsRegionPrices, T extends AwsPrices<R>> void installPrices(final Node node, final Map<String, ProvLocation> regions,
final String api, final String endpoint, final Class<T> apiClass, final BiFunction<R, ProvLocation, Integer> mapper)
throws IOException {
log.info("AWS {} prices...", api);
// Track the created instance to cache instance and price type
int priceCounter = 0;
importCatalogResource.nextStep(node.getId(), t -> t.setPhase(api));
try {
// Get the remote prices stream
String rawJson = StringUtils.defaultString(new CurlProcessor().get(endpoint), "callback({\"config\":{\"regions\":[]}});");
// All regions are considered
final int configIndex = rawJson.indexOf('{');
final int configCloseIndex = rawJson.lastIndexOf('}');
final T prices = objectMapper.readValue(rawJson.substring(configIndex, configCloseIndex + 1), apiClass);
// Install the region as needed
prices.getConfig().getRegions().forEach(r -> r
.setRegion(installRegion(regions, mapSpotToNewRegion.getOrDefault(r.getRegion(), r.getRegion()), node).getName()));
nextStep(node, null, 0);
// Install the (EC2 + Spot) prices for each region
priceCounter = prices.getConfig().getRegions().stream().mapToInt(r -> mapper.apply(r, regions.get(r.getRegion()))).sum();
} finally {
// Report
log.info("AWS {} import finished : {} prices", api, priceCounter);
nextStep(node, null, 1);
}
}
示例14: startRequest
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
public void startRequest(HttpServletRequest theRequest) {
if (theRequest == null) {
return;
}
Set<String> headerNames = new TreeSet<String>();
for (Enumeration<String> enums = theRequest.getHeaderNames(); enums.hasMoreElements();) {
headerNames.add(enums.nextElement());
}
ourLog.debug("Request headers: {}", headerNames);
Enumeration<String> forwardedFors = theRequest.getHeaders("x-forwarded-for");
StringBuilder b = new StringBuilder();
for (Enumeration<String> enums = forwardedFors; enums != null && enums.hasMoreElements();) {
if (b.length() > 0) {
b.append(" / ");
}
b.append(enums.nextElement());
}
String forwardedFor = b.toString();
String ip = theRequest.getRemoteAddr();
if (StringUtils.isBlank(forwardedFor)) {
org.slf4j.MDC.put(REMOTE_ADDR, ip);
ourLog.debug("Request is from address: {}", ip);
} else {
org.slf4j.MDC.put(REMOTE_ADDR, forwardedFor);
ourLog.debug("Request is from forwarded address: {}", forwardedFor);
}
String userAgent = StringUtils.defaultString(theRequest.getHeader("user-agent"));
org.slf4j.MDC.put(REMOTE_UA, userAgent);
}
示例15: getAuthenticator
import org.apache.commons.lang3.StringUtils; //导入方法依赖的package包/类
@Override
protected Authenticator<TokenCredentials> getAuthenticator(final Credential credential) {
final TokenCredential tokenCredential = (TokenCredential) credential;
LOGGER.debug("Locating token secret for service [{}]", tokenCredential.getService());
final RegisteredService service = this.servicesManager.findServiceBy(tokenCredential.getService());
final String signingSecret = getRegisteredServiceJwtSigningSecret(service);
final String encryptionSecret = getRegisteredServiceJwtEncryptionSecret(service);
final String signingSecretAlg =
StringUtils.defaultString(getRegisteredServiceJwtSecret(service, TokenConstants.PROPERTY_NAME_TOKEN_SECRET_SIGNING_ALG),
JWSAlgorithm.HS256.getName());
final String encryptionSecretAlg =
StringUtils.defaultString(getRegisteredServiceJwtSecret(service, TokenConstants.PROPERTY_NAME_TOKEN_SECRET_ENCRYPTION_ALG),
JWEAlgorithm.DIR.getName());
final String encryptionSecretMethod =
StringUtils.defaultString(getRegisteredServiceJwtSecret(service, TokenConstants.PROPERTY_NAME_TOKEN_SECRET_ENCRYPTION_METHOD),
EncryptionMethod.A192CBC_HS384.getName());
if (StringUtils.isNotBlank(signingSecret)) {
Set<Algorithm> sets = new HashSet<>();
sets.addAll(JWSAlgorithm.Family.EC);
sets.addAll(JWSAlgorithm.Family.HMAC_SHA);
sets.addAll(JWSAlgorithm.Family.RSA);
sets.addAll(JWSAlgorithm.Family.SIGNATURE);
final JWSAlgorithm signingAlg = findAlgorithmFamily(sets, signingSecretAlg);
final JwtAuthenticator a = new JwtAuthenticator();
a.setSignatureConfiguration(new SecretSignatureConfiguration(signingSecret, signingAlg));
if (StringUtils.isNotBlank(encryptionSecret)) {
sets = new HashSet<>();
sets.addAll(JWEAlgorithm.Family.AES_GCM_KW);
sets.addAll(JWEAlgorithm.Family.AES_KW);
sets.addAll(JWEAlgorithm.Family.ASYMMETRIC);
sets.addAll(JWEAlgorithm.Family.ECDH_ES);
sets.addAll(JWEAlgorithm.Family.PBES2);
sets.addAll(JWEAlgorithm.Family.RSA);
sets.addAll(JWEAlgorithm.Family.SYMMETRIC);
final JWEAlgorithm encAlg = findAlgorithmFamily(sets, encryptionSecretAlg);
sets = new HashSet<>();
sets.addAll(EncryptionMethod.Family.AES_CBC_HMAC_SHA);
sets.addAll(EncryptionMethod.Family.AES_GCM);
final EncryptionMethod encMethod = findAlgorithmFamily(sets, encryptionSecretMethod);
a.setEncryptionConfiguration(new SecretEncryptionConfiguration(encryptionSecret, encAlg, encMethod));
} else {
LOGGER.warn("JWT authentication is configured to share a single key for both signing/encryption");
}
return a;
}
LOGGER.warn("No token signing secret is defined for service [{}]. Ensure [{}] property is defined for service",
service.getServiceId(), TokenConstants.PROPERTY_NAME_TOKEN_SECRET_SIGNING);
return null;
}