Java Code Examples for org.apache.commons.lang3.StringUtils#appendIfMissing()

The following examples show how to use org.apache.commons.lang3.StringUtils#appendIfMissing() . 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: tutorials   File: StringUtilsUnitTest.java    License: MIT License 6 votes vote down vote up
@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);
}
 
Example 2
Source Project: metron   File: StringFunctions.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 3
@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;
}
 
Example 4
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);
}
 
Example 5
Source Project: vividus   File: BddResourceLoader.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 6
Source Project: ghidra   File: TestDummyDomainFolder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getPathname() {
	if (parent != null) {
		String parentPathname = StringUtils.appendIfMissing(parent.getPathname(), "/");
		return parentPathname + folderName;
	}
	return "/";
}
 
Example 7
Source Project: cloudbreak   File: DnsRecord.java    License: Apache License 2.0 5 votes vote down vote up
public boolean isHostRelatedSrvRecord(String fqdn) {
    if (isSrvRecord()) {
        String searchString = " " + StringUtils.appendIfMissing(fqdn, ".");
        return srvrecord.stream()
                .anyMatch(record -> record.endsWith(searchString));
    }
    return false;
}
 
Example 8
Source Project: halo   File: FileHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 9
/**
 * 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, "/");
}
 
Example 10
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;
}
 
Example 11
Source Project: entrada   File: FileUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 12
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);
}
 
Example 13
Source Project: engine   File: S3Prefix.java    License: GNU General Public License v3.0 5 votes vote down vote up
public S3Prefix(String prefix) {
    if (!prefix.equals(DELIMITER)) {
        prefix = StringUtils.stripStart(prefix, DELIMITER);
        prefix = StringUtils.appendIfMissing(prefix, DELIMITER);
    }

    this.prefix = prefix;
}
 
Example 14
Source Project: syncope   File: SAML2ReceivedResponseTO.java    License: Apache License 2.0 4 votes vote down vote up
public void setSpEntityID(final String spEntityID) {
    this.spEntityID = StringUtils.appendIfMissing(spEntityID, "/");
}
 
Example 15
/**
 * 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;
}
 
Example 16
protected String getPointerPath(String path) {
    return isFolder(path)? path : StringUtils.appendIfMissing(path, "." + fileExtension);
}
 
Example 17
Source Project: syncope   File: JPARealm.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public String getFullPath() {
    return getParent() == null
            ? SyncopeConstants.ROOT_REALM
            : StringUtils.appendIfMissing(getParent().getFullPath(), "/") + getName();
}
 
Example 18
/**
 * {@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);
    }
}
 
Example 19
Source Project: herd   File: UploadDownloadServiceImpl.java    License: Apache License 2.0 4 votes vote down vote up
@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;
}
 
Example 20
public PreloadedFolder(String path, int depth, Set<String> descendants) {
    this.path = StringUtils.appendIfMissing(path, "/");
    this.depth = depth;
    this.descendants = descendants;
}