下面列出了org.apache.commons.lang3.StringUtils#appendIfMissing ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void givenString_whenAppendingAndPrependingIfMissing_thenCorrect() {
String string = "baeldung.com";
String stringWithSuffix = StringUtils.appendIfMissing(string, ".com");
String stringWithPrefix = StringUtils.prependIfMissing(string, "www.");
assertEquals("baeldung.com", stringWithSuffix);
assertEquals("www.baeldung.com", stringWithPrefix);
}
@Override
public Object apply(List<Object> strings) {
String suffixed;
switch (strings.size()) {
case 2:
suffixed = StringUtils.appendIfMissing((String) strings.get(0), (String) strings.get(1));
break;
case 3:
suffixed = StringUtils.appendIfMissing((String) strings.get(0), (String) strings.get(1), (String) strings.get(2));
break;
default:
throw new IllegalArgumentException("[APPEND_IF_MISSING] incorrect arguments. Usage: APPEND_IF_MISSING <String> <prefix> [<prefix>...]");
}
return suffixed;
}
@Override
public boolean move(String sourceFile, String targetDir, boolean overwriteFile) throws IOException {
FileObject targetFolder = resolveChild(targetDir);
targetFolder.createFolder();
String targetFileName = StringUtils.appendIfMissing(targetFolder.getName().getPath(), "/")
+ StringUtils.substringAfterLast(sourceFile, "/");
FileObject targetFile = targetFolder.resolveFile(targetFileName, NameScope.DESCENDENT);
if (!overwriteFile && targetFile.exists()) {
return false;
}
resolveChild(sourceFile).moveTo(targetFile);
targetFile.close();
return true;
}
private void addSeeds(URI mainApplicationPage, CrawlController controller)
{
controller.addSeed(mainApplicationPage.toString());
if (this.seedRelativeUrls == null)
{
return;
}
String mainApplicationPagePath = StringUtils.appendIfMissing(mainApplicationPage.getPath(), FORWARD_SLASH);
this.seedRelativeUrls.stream()
.map(seedRelativeUrl -> StringUtils.removeStart(seedRelativeUrl, FORWARD_SLASH))
.map(mainApplicationPagePath::concat)
.map(relativeUrl -> UriUtils.buildNewUrl(mainApplicationPage, relativeUrl))
.map(URI::toString)
.forEach(controller::addSeed);
}
@Override
public Resource[] getResources(String resourceLocation, String resourcePattern)
{
String normalizedResourceLocation = StringUtils.appendIfMissing(resourceLocation, SEPARATOR);
String locationPattern = CLASSPATH_ALL_URL_PREFIX + normalizedResourceLocation;
Resource[] allResources = getResources(locationPattern + "**/" + resourcePattern);
List<URL> resourceUrls = new ArrayList<>(allResources.length);
for (Resource resource : allResources)
{
try
{
resourceUrls.add(resource.getURL());
}
catch (IOException e)
{
throw new ResourceLoadException(e);
}
}
Optional<String> deepestResourcePath = resourceUrls.stream()
.map(URL::toString)
.map(resourceUrl -> StringUtils.substringAfter(resourceUrl, normalizedResourceLocation))
.map(this::generatePathByLoadConfig)
.max(Comparator.comparing(String::length));
StringBuilder resourcePatternBuilder = new StringBuilder(locationPattern);
deepestResourcePath.ifPresent(resourcePatternBuilder::append);
String baseResourcePattern = resourcePatternBuilder.toString();
return getResources(baseResourcePattern + resourcePattern);
}
@Override
public String getPathname() {
if (parent != null) {
String parentPathname = StringUtils.appendIfMissing(parent.getPathname(), "/");
return parentPathname + folderName;
}
return "/";
}
public boolean isHostRelatedSrvRecord(String fqdn) {
if (isSrvRecord()) {
String searchString = " " + StringUtils.appendIfMissing(fqdn, ".");
return srvrecord.stream()
.anyMatch(record -> record.endsWith(searchString));
}
return false;
}
/**
* Normalize directory full name, ensure the end path separator.
*
* @param dir directory full name must not be blank
* @return normalized directory full name with end path separator
*/
@NonNull
static String normalizeDirectory(@NonNull String dir) {
Assert.hasText(dir, "Directory full name must not be blank");
return StringUtils.appendIfMissing(dir, FILE_SEPARATOR);
}
/**
* Sanitizes the provided {@code uri}
* @return Sanitized URI; lowercased, with {@value URI_SCHEME}
* prepended to it if it does not specify a scheme, and
* a {@code "/"} appended to it unless it already has one.
*/
public static String sanitizeUri(String uri) {
uri = uri.toLowerCase();
if (!uri.startsWith(URI_SCHEME) && !uri.startsWith(URI_SCHEME_SSL)) {
// use plaintext by default
uri = URI_SCHEME + uri;
}
return StringUtils.appendIfMissing(uri, "/");
}
private List<String> scan() {
// if server name is provided then search that location for input files.
// otherwise search root of inputDir
String inputDir = serverCtx.getServerInfo().isDefaultServer() ? inputLocation
: FileUtil.appendPath(inputLocation, serverCtx.getServerInfo().getName());
FileManager fm = fileManagerFactory.getFor(inputDir);
log.info("Scan for pcap files in: {}", inputDir);
inputDir = StringUtils
.appendIfMissing(inputDir, System.getProperty("file.separator"),
System.getProperty("file.separator"));
// order and skip the newest file if skipfirst is true
List<String> files = fm
.files(inputDir, ".pcap", ".pcap.gz", ".pcap.xz")
.stream()
.sorted()
.skip(skipFirst ? 1 : 0)
.collect(Collectors.toList());
log.info("Found {} file to process", files.size());
if (log.isDebugEnabled()) {
files.stream().forEach(file -> log.debug("Found file: {}", file));
}
return files;
}
public static String appendPath(String parent, String path, String... toAppend) {
String str =
!StringUtils.isBlank(path) ? StringUtils.appendIfMissing(parent, FILE_SEP, FILE_SEP) + path
: parent;
for (int i = 0; i < toAppend.length; i++) {
if (!StringUtils.isBlank(toAppend[i])) {
str = str + FILE_SEP + toAppend[i];
}
}
return str;
}
protected void addUrl(List<String> urls, String outputProfileId, String destination, String originalName,
String modifier, String extension) {
String url = StringUtils.appendIfMissing(destination, delimiter) + originalName + modifier + "." + extension;
url = createUrl(outputProfileId, url);
urls.add(url);
logger.debug("Added url {0}", url);
}
public S3Prefix(String prefix) {
if (!prefix.equals(DELIMITER)) {
prefix = StringUtils.stripStart(prefix, DELIMITER);
prefix = StringUtils.appendIfMissing(prefix, DELIMITER);
}
this.prefix = prefix;
}
public void setSpEntityID(final String spEntityID) {
this.spEntityID = StringUtils.appendIfMissing(spEntityID, "/");
}
/**
* Builds a path to an asset for a particular path and filename.
*/
public static String buildPath(final String path, final String filename) {
return StringUtils.appendIfMissing(path, "/") + filename;
}
protected String getPointerPath(String path) {
return isFolder(path)? path : StringUtils.appendIfMissing(path, "." + fileExtension);
}
@Override
public String getFullPath() {
return getParent() == null
? SyncopeConstants.ROOT_REALM
: StringUtils.appendIfMissing(getParent().getFullPath(), "/") + getName();
}
/**
* {@inheritDoc}
*/
@Override
@ValidateParams
@HasPermission(type = DefaultPermission.class, action = "webdav_write")
public WebDavItem upload(@ValidateStringParam(name = "siteId") @ProtectedResourceId("siteId") final String siteId,
@ValidateStringParam(name = "profileId") final String profileId,
@ValidateStringParam(name = "path") final String path,
@ValidateStringParam(name = "filename") final String filename,
final InputStream content)
throws WebDavException {
WebDavProfile profile = getProfile(siteId, profileId);
String uploadUrl = StringUtils.appendIfMissing(profile.getBaseUrl(), "/");
try {
Sardine sardine = createClient(profile);
if(StringUtils.isNotEmpty(path)) {
String[] folders = StringUtils.split(path, "/");
for(String folder : folders) {
uploadUrl += StringUtils.appendIfMissing(folder, "/");
logger.debug("Checking folder {0}", uploadUrl);
if(!sardine.exists(uploadUrl)) {
logger.debug("Creating folder {0}", uploadUrl);
sardine.createDirectory(uploadUrl);
logger.debug("Folder {0} created", uploadUrl);
} else {
logger.debug("Folder {0} already exists", uploadUrl);
}
}
}
uploadUrl = StringUtils.appendIfMissing(uploadUrl, "/");
String fileUrl = uploadUrl + UriUtils.encode(filename, charset.name());
logger.debug("Starting upload of file {0}", filename);
logger.debug("Uploading file to {0}", fileUrl);
sardine.put(fileUrl, content);
logger.debug("Upload complete for file {0}", fileUrl);
return new WebDavItem(filename, String.format(urlPattern, profileId, path, filename), false);
} catch (Exception e ) {
throw new WebDavException("Error uploading file", e);
}
}
@NamespacePermission(fields = "#request.businessObjectDefinitionKey.namespace", permissions = {NamespacePermissionEnum.WRITE_DESCRIPTIVE_CONTENT,
NamespacePermissionEnum.WRITE})
@Override
public UploadBusinessObjectDefinitionSampleDataFileInitiationResponse initiateUploadSampleFile(
UploadBusinessObjectDefinitionSampleDataFileInitiationRequest request)
{
validateUploadBusinessObjectDefinitionSampleDataFileInitiationRequest(request);
BusinessObjectDefinitionKey businessObjectDefinitionKey = request.getBusinessObjectDefinitionKey();
// Get the business object definition entity and ensure it exists.
BusinessObjectDefinitionEntity businessObjectDefinitionEntity =
businessObjectDefinitionDaoHelper.getBusinessObjectDefinitionEntity(businessObjectDefinitionKey);
businessObjectDefinitionKey.setNamespace(businessObjectDefinitionEntity.getNamespace().getCode());
businessObjectDefinitionKey.setBusinessObjectDefinitionName(businessObjectDefinitionEntity.getName());
UploadBusinessObjectDefinitionSampleDataFileInitiationResponse response = new UploadBusinessObjectDefinitionSampleDataFileInitiationResponse();
StorageEntity storageEntity = storageDaoHelper.getStorageEntity(StorageEntity.SAMPLE_DATA_FILE_STORAGE);
String s3BucketName = storageHelper.getStorageBucketName(storageEntity);
String s3EndPoint = storageHelper.getS3BucketAccessParams(storageEntity).getS3Endpoint();
String awsRoleArn = getStorageUploadRoleArn(storageEntity);
String sessionID = UUID.randomUUID().toString();
String s3KeyPrefix = s3KeyPrefixHelper.buildS3KeyPrefix(storageEntity, businessObjectDefinitionKey);
s3KeyPrefix = StringUtils.appendIfMissing(s3KeyPrefix, "/");
//need to add star for aws authorization
String s3Path = s3KeyPrefix + "*";
Integer awsRoleDurationSeconds = getStorageUploadSessionDuration(storageEntity);
Credentials assumedSessionCredentials = stsDao
.getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(), sessionID, awsRoleArn, awsRoleDurationSeconds,
createUploaderPolicyNoKmsKey(s3BucketName, s3Path));
response.setAwsAccessKey(assumedSessionCredentials.getAccessKeyId());
response.setAwsSecretKey(assumedSessionCredentials.getSecretAccessKey());
response.setAwsSessionToken(assumedSessionCredentials.getSessionToken());
response.setAwsSessionExpirationTime(HerdDateUtils.getXMLGregorianCalendarValue(assumedSessionCredentials.getExpiration()));
response.setAwsS3BucketName(s3BucketName);
response.setBusinessObjectDefinitionKey(businessObjectDefinitionKey);
response.setS3Endpoint(s3EndPoint);
response.setS3KeyPrefix(s3KeyPrefix);
return response;
}
public PreloadedFolder(String path, int depth, Set<String> descendants) {
this.path = StringUtils.appendIfMissing(path, "/");
this.depth = depth;
this.descendants = descendants;
}