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

The following examples show how to use org.apache.commons.lang3.StringUtils#replaceChars() . 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 File: BasicConfigurationService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
public Locale getLocaleFromString(String localeString) {
    // should this just use LocalUtils.toLocale()? - can't - it thinks en_GB is invalid for example
    if (localeString != null) {
        // force en-US (dash separated) values into underscore style
        localeString = StringUtils.replaceChars(localeString, '-', '_');
    } else {
        return null;
    }
    String[] locValues = localeString.trim().split("_");
    if (locValues.length >= 3 && StringUtils.isNotBlank(locValues[2])) {
        return new Locale(locValues[0], locValues[1], locValues[2]); // language, country, variant
    } else if (locValues.length == 2 && StringUtils.isNotBlank(locValues[1])) {
        return new Locale(locValues[0], locValues[1]); // language, country
    } else if (locValues.length == 1 && StringUtils.isNotBlank(locValues[0])) {
        return new Locale(locValues[0]); // language
    } else {
        return Locale.getDefault();
    }
}
 
Example 2
Source File: PathUtilTest.java    From archiva with Apache License 2.0 6 votes vote down vote up
public void testToUrlRelativePath()
{
    Path workingDir = Paths.get( "" );

    String workingDirname = StringUtils.replaceChars( workingDir.toAbsolutePath().toString(), '\\', '/' );

    // Some JVM's retain the "." at the end of the path.  Drop it.
    if ( workingDirname.endsWith( "/." ) )
    {
        workingDirname = workingDirname.substring( 0, workingDirname.length() - 2 );
    }

    if ( !workingDirname.startsWith( "/" ) )
    {
        workingDirname = "/" + workingDirname;
    }

    String path = "path/to/resource.xml";
    String expectedPath = "file:" + workingDirname + "/" + path;

    assertEquals( expectedPath, PathUtil.toUrl( path ) );
}
 
Example 3
Source File: ImageUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * SCIPIO: Encodes an arbitrary directory name for secure usage inside a file path/URL used
 * for images - preventing directory separators, zero-char and directory switches ("..").
 * <p>
 * NOTE: This was originally intended for middle pathnames only, such that the filename part
 * should be handled by {@link #cleanFilename(String)}, but this has become moot (2018-11-05).
 * <p>
 * Added 2018-05-04.
 */
public static String cleanPathname(String name) {
    if (name == null || name.isEmpty()) {
        return name;
    }
    String origName = name;
    name = StringUtils.replaceChars(name, "/\\\0", "___");
    // There should be no need for this because the slashes are all removed,
    // so the only danger case is if ".." between unknown path delims
    //name = noMultiDotPat.matcher(name).replaceAll(".");
    if ("..".equals(name)) {
        name = "__";
    }
    if (!origName.equals(name)) {
        Debug.logWarning("cleanPathname: filtered pathname [" + origName + "] to [" + name + "]", module);
    }
    //if (name.startsWith(".")) name = name.substring(1);
    return name;
}
 
Example 4
Source File: LogProcessorTransformBolt.java    From DBus with Apache License 2.0 6 votes vote down vote up
private void emitHbOrStatInfo(Tuple input, Map<String, String> recordMap, Integer partition, Long offset) {
    Long timestamp;
    //心跳数据
    if (StringUtils.equals(recordMap.get("type"),
            inner.logProcessorConf.getProperty(Constants.LOG_HEARTBEAT_TYPE))) {
        //时间戳:logstash或ums的时间戳
        timestamp = getLogTimestamp(recordMap);
        String host = StringUtils.replaceChars(recordMap.get("host"), ".", "_");
        String tableName = null;
        String umsSource = null;
        if (!StringUtils.isEmpty(recordMap.get("tableName"))) {
            tableName = recordMap.get("tableName");
            umsSource = recordMap.get("umsSource");
        }
        //发送active表的统计信息
        String namespace = emitActiveTableInfo(input, timestamp, host, partition, offset, tableName, umsSource);
        //发送abort表的统计信息
        if (StringUtils.isEmpty(namespace)) {
            namespace = emitAbortTableInfo(input, timestamp, host, partition, offset, tableName, umsSource);
        } else {
            emitAbortTableInfo(input, timestamp, host, partition, offset, tableName, umsSource);
        }
        //发送全局统计信息
        emitGlobalStatInfo(input, timestamp, host, namespace);
    }
}
 
Example 5
Source File: QueryTree.java    From cuba with Apache License 2.0 5 votes vote down vote up
public QueryTree(DomainModel model, String query, boolean failOnErrors) {
    Preconditions.checkNotNull(query, "query is null");
    String modifiedQuery = StringUtils.replaceChars(query, "\n\r\t", "   ");

    this.model = model;
    this.queryString = modifiedQuery;
    try {
        this.tree = Parser.parse(modifiedQuery, failOnErrors);
    } catch (RecognitionException e) {
        throw new JPA2RecognitionException("JPA grammar recognition error", e);
    }

    this.idVarSelector = new IdVarSelector(model);
    new TreeVisitor().visit(tree, idVarSelector);
}
 
Example 6
Source File: AbbreviatedColumnGenerator.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public Object generateCell(com.vaadin.v7.ui.Table source, Object itemId, Object columnId) {
    Property property = source.getItem(itemId).getItemProperty(columnId);
    Object value = property.getValue();

    if (value == null) {
        return null;
    }

    String stringValue = value.toString();
    if (columnId instanceof MetaPropertyPath) {
        MetaProperty metaProperty = ((MetaPropertyPath) columnId).getMetaProperty();
        if (DynamicAttributesUtils.isDynamicAttribute(metaProperty)) {
            stringValue = dynamicAttributesTools.getDynamicAttributeValueAsString(metaProperty, value);
        }
    }
    String cellValue = stringValue;
    boolean isMultiLineCell = StringUtils.contains(stringValue, "\n");
    if (isMultiLineCell) {
        cellValue = StringUtils.replaceChars(cellValue, '\n', ' ');
    }

    int maxTextLength = column.getMaxTextLength();
    if (stringValue.length() > maxTextLength + MAX_TEXT_LENGTH_GAP || isMultiLineCell) {
        return StringUtils.abbreviate(cellValue, maxTextLength);
    } else {
        return cellValue;
    }
}
 
Example 7
Source File: BaseUserDirectoryService.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Adjust the eid - trim it to null, and lower case IF we are case insensitive.
 *
 * @param eid
 *        The eid to clean up.
 * @return A cleaned up eid.
 */
protected String cleanEid(String eid)
{
       eid = StringUtils.lowerCase(eid);
       eid = StringUtils.trimToNull(eid);

       if (eid != null) {
           // remove all instances of these chars <>,;:\"
           eid = StringUtils.replaceChars(eid, "<>,;:\\/", "");
       }
       // NOTE: length check is handled later on
       return eid;
}
 
Example 8
Source File: AbstractEndpointGenerationTest.java    From flow with Apache License 2.0 5 votes vote down vote up
private void removeAbsolutePathAndCompare(Class<?> expectedClass,
        String expectedTs, String errorMessage, String actualContent) {
    Matcher matcher = JAVA_PATH_REFERENCE_REGEX.matcher(actualContent);

    Assert.assertTrue(errorMessage, matcher.find());

    String actualJavaFileReference = matcher.group(1);

    String actualContentWithoutPathReference = actualContent
            .replace(actualJavaFileReference, "");
    equalsIgnoreWhiteSpaces(errorMessage, expectedTs,
            actualContentWithoutPathReference);

    String javaFilePathReference = matcher.group(2);

    Class declaringClass = expectedClass;
    while (declaringClass.getDeclaringClass() != null) {
        declaringClass = declaringClass.getDeclaringClass();
    }
    String expectedEndingJavaFilePath = StringUtils.replaceChars(
            declaringClass.getCanonicalName(), '.', File.separatorChar) + ".java";
    String wrongPathMessage = String.format(
            "The generated model class '%s' refers to Java path '%s'. The path should end with '%s'",
            expectedClass, actualJavaFileReference,
            expectedEndingJavaFilePath);
    Assert.assertTrue(wrongPathMessage,
            javaFilePathReference.endsWith(expectedEndingJavaFilePath));
}
 
Example 9
Source File: KafkaAuditCountHttpClient.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public Map<String, Long> fetch (String datasetName, long start, long end)  throws IOException {
  String fullUrl =
          (this.baseUrl.endsWith("/") ? this.baseUrl : this.baseUrl + "/") + StringUtils.replaceChars(datasetName, '/', '.')
                  + "?" + this.startQueryString + "=" + start + "&" + this.endQueryString + "=" + end;
  log.info("Full URL is " + fullUrl);
  String response = getHttpResponse(fullUrl);
 return parseResponse (fullUrl, response, datasetName);
}
 
Example 10
Source File: DesktopTimeField.java    From cuba with Apache License 2.0 5 votes vote down vote up
private void updateTimeFormat() {
    mask = StringUtils.replaceChars(timeFormat, "Hhmsa", "####U");
    try {
        formatter.setMask(mask);
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
    impl.setValue(impl.getValue());
}
 
Example 11
Source File: SvgScript.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Helper for src retrieval and normalization.
 *
 * @return the value of the attribute {@code src} with all line breaks removed
 * or an empty string if that attribute isn't defined.
 */
protected final String getSrcAttributeNormalized() {
    // at the moment StringUtils.replaceChars returns the org string
    // if nothing to replace was found but the doc implies, that we
    // can't trust on this in the future
    final String attrib = getAttributeDirect("src");
    if (ATTRIBUTE_NOT_DEFINED == attrib) {
        return attrib;
    }

    return StringUtils.replaceChars(attrib, "\r\n", "");
}
 
Example 12
Source File: RepositoryModelResolver.java    From archiva with Apache License 2.0 5 votes vote down vote up
protected Path findTimeStampedSnapshotPom( String groupId, String artifactId, String version,
                                           Path parentDirectory )
{

    // reading metadata if there
    Path mavenMetadata = parentDirectory.resolve( METADATA_FILENAME );
    if ( Files.exists(mavenMetadata) )
    {
        try
        {
            ArchivaRepositoryMetadata archivaRepositoryMetadata = metadataReader.read( mavenMetadata );
            SnapshotVersion snapshotVersion = archivaRepositoryMetadata.getSnapshotVersion();
            if ( snapshotVersion != null )
            {
                String lastVersion = snapshotVersion.getTimestamp();
                int buildNumber = snapshotVersion.getBuildNumber();
                String snapshotPath =
                    StringUtils.replaceChars( groupId, '.', '/' ) + '/' + artifactId + '/' + version + '/'
                        + artifactId + '-' + StringUtils.remove( version, "-" + VersionUtil.SNAPSHOT ) + '-'
                        + lastVersion + '-' + buildNumber + ".pom";

                log.debug( "use snapshot path {} for maven coordinate {}:{}:{}", snapshotPath, groupId, artifactId,
                           version );

                StorageAsset model = basedir.resolve( snapshotPath );
                //model = pathTranslator.toFile( basedir, groupId, artifactId, lastVersion, filename );
                if ( model.exists() )
                {
                    return model.getFilePath();
                }
            }
        }
        catch ( RepositoryMetadataException e )
        {
            log.warn( "fail to read {}, {}", mavenMetadata.toAbsolutePath(), e.getCause() );
        }
    }

    return null;
}
 
Example 13
Source File: MetadataToolsTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
private void prepTestRepo( ManagedRepositoryContent repo, ItemSelector reference )
    throws IOException
{
    String groupDir = StringUtils.replaceChars( reference.getNamespace(), '.', '/' );
    String path = groupDir + "/" + reference.getArtifactId();

    Path srcRepoDir = getRepositoryPath( "metadata-repository" );
    Path srcDir = srcRepoDir.resolve( path );
    Path destDir = repo.getRepository().getRoot().getFilePath().resolve( path );

    assertTrue( "Source Dir exists: " + srcDir, Files.exists(srcDir) );
    Files.createDirectories(destDir);

    FileUtils.copyDirectory( srcDir.toFile(), destDir.toFile() );
}
 
Example 14
Source File: SvgScript.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Helper for src retrieval and normalization.
 *
 * @return the value of the attribute {@code src} with all line breaks removed
 * or an empty string if that attribute isn't defined.
 */
protected final String getSrcAttributeNormalized() {
    // at the moment StringUtils.replaceChars returns the org string
    // if nothing to replace was found but the doc implies, that we
    // can't trust on this in the future
    final String attrib = getAttributeDirect(SRC_ATTRIBUTE);
    if (ATTRIBUTE_NOT_DEFINED == attrib) {
        return attrib;
    }

    return StringUtils.replaceChars(attrib, "\r\n", "");
}
 
Example 15
Source File: MaterialUtils.java    From FunnyGuilds with Apache License 2.0 5 votes vote down vote up
public static String getMaterialName(Material material) {
    PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration();

    if (!config.translatedMaterialsEnable) {
        return material.toString();
    }

    if (config.translatedMaterials.containsKey(material)) {
        return ChatUtils.colored(FunnyGuilds.getInstance().getPluginConfiguration().translatedMaterials.get(material));
    }

    return StringUtils.replaceChars(material.toString().toLowerCase(), '_', ' ');
}
 
Example 16
Source File: IgniteConfigurationAdapter.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private void configureName() {
    name = StringUtils.replaceChars(name, '.', '-');
}
 
Example 17
Source File: CubaTimeField.java    From cuba with Apache License 2.0 4 votes vote down vote up
protected void updateTimeFormat() {
    String mask = StringUtils.replaceChars(timeFormat, "Hhmsa", "####U");
    placeholder = StringUtils.replaceChars(mask, "#U", "__");
    getState().mask = mask;
    getState().timeFormat = timeFormat;
}
 
Example 18
Source File: NavLink.java    From Plan with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static String format(String id) {
    return StringUtils.replaceChars(StringUtils.lowerCase(id), ' ', '-');
}
 
Example 19
Source File: IgniteConfigurationAdapter.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private void configureName() {
    name = StringUtils.replaceChars(name, '.', '-');
}
 
Example 20
Source File: CubaDateField.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
protected void updateInternal(String newDateString, Map<String, Integer> resolutions) {
    // CAUTION: copied from AbstractDateField
    Set<String> resolutionNames = getResolutions().map(Enum::name)
            .collect(Collectors.toSet());
    resolutionNames.retainAll(resolutions.keySet());
    if (!isReadOnly()
            && (!resolutionNames.isEmpty() || newDateString != null)) {

        // Old and new dates
        final LocalDate oldDate = getValue();

        LocalDate newDate;

        String mask = StringUtils.replaceChars(getState(false).dateMask, "#U", "__");
        if ("".equals(newDateString)
                || mask.equals(newDateString)) {

            newDate = null;
        } else {
            newDate = reconstructDateFromFields(resolutions, oldDate);
        }

        boolean parseErrorWasSet = currentErrorMessage != null;
        boolean hasChanges = !Objects.equals(dateString, newDateString)
                || !Objects.equals(oldDate, newDate)
                || parseErrorWasSet;

        if (hasChanges) {
            dateString = newDateString;
            currentErrorMessage = null;
            if (newDateString == null || newDateString.isEmpty()) {
                boolean valueChanged = setValue(newDate, true);
                if (!valueChanged && parseErrorWasSet) {
                    doSetValue(newDate);
                }
            } else {
                // invalid date string
                if (resolutions.isEmpty()) {
                    Result<LocalDate> parsedDate = handleUnparsableDateString(
                            dateString);
                    parsedDate.ifOk(v -> setValue(v, true));
                    if (parsedDate.isError()) {
                        dateString = null;
                        currentErrorMessage = parsedDate
                                .getMessage().orElse("Parsing error");

                        if (!isDifferentValue(null)) {
                            doSetValue(null);
                        } else {
                            setValue(null, true);
                        }
                    }
                } else {
                    setValue(newDate, true);
                }
            }
        }
    }
}