org.apache.commons.lang3.CharUtils Java Examples

The following examples show how to use org.apache.commons.lang3.CharUtils. 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: ADLImporter.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private String generateToken(String atCode, boolean upFirst) {
	if (!texts.containsKey(atCode))
		return atCode;
  String text = texts.get(atCode).getText();
  boolean lastText = false;
  StringBuilder b = new StringBuilder();
  for (char c : text.toCharArray()) {
  	boolean ok = CharUtils.isAscii(c);
  	if (ok) 
  		if (b.length() == 0)
         ok = Character.isAlphabetic(c);
  		else
  			ok = Character.isAlphabetic(c) || Character.isDigit(c);
  	if (!ok) {
  		lastText = false;
  	} else {
  		if (!lastText && (b.length() > 0 || upFirst)) 
  			b.append(Character.toUpperCase(c));
  		else
  			b.append(Character.toLowerCase(c));
  		lastText = true;
  	}
  }
 	return b.toString();
}
 
Example #2
Source File: Configuration.java    From DataLink with Apache License 2.0 6 votes vote down vote up
/**
 * 根据用户提供的json path,寻址Character对象
 * 
 * @return Character对象,如果path不存在或者Character不存在,返回null
 */
public Character getChar(final String path) {
	String result = this.getString(path);
	if (null == result) {
		return null;
	}

	try {
		return CharUtils.toChar(result);
	} catch (Exception e) {
		throw DataXException.asDataXException(
				CommonErrorCode.CONFIG_ERROR,
				String.format("任务读取配置文件出错. 因为配置文件路径[%s] 值非法,期望是字符类型: %s. 请检查您的配置并作出修改.", path,
						e.getMessage()));
	}
}
 
Example #3
Source File: CaseFormatUtil.java    From raptor with Apache License 2.0 6 votes vote down vote up
/**
 * 判断str是哪种命名格式的,不能保证一定判断对,慎用
 *
 * @param str
 * @return
 */
public static CaseFormat determineFormat(String str) {
    Preconditions.checkNotNull(str);
    String[] split = str.split("_");
    List<String> splitedStrings = Arrays.stream(split).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());

    if (splitedStrings.size() == 1) {
        //camel
        if (CharUtils.isAsciiAlphaUpper(splitedStrings.get(0).charAt(0))) {
            return CaseFormat.UPPER_CAMEL;
        } else {
            return CaseFormat.LOWER_CAMEL;
        }
    } else if (splitedStrings.size() > 1) {
        //underscore
        if (CharUtils.isAsciiAlphaUpper(splitedStrings.get(0).charAt(0))) {
            return CaseFormat.UPPER_UNDERSCORE;
        } else {
            return CaseFormat.LOWER_UNDERSCORE;
        }
    }else{
        //判断不出那个
        return CaseFormat.LOWER_CAMEL;
    }
}
 
Example #4
Source File: NumberUtility.java    From FX-AlgorithmTrading with MIT License 6 votes vote down vote up
/**
 * 文字と数字の混ざった文字列から、数字のみを取り出してLongを作成します。
 * 主に、外部で採番されたIDから数字のIDを作成するために使用します。
 *
 * @param stringWithNumber
 * @return
 */
public static Long extractNumberString(Long headerNumber, String stringWithNumber) {
    StringBuilder sb = new StringBuilder(30);
    if (headerNumber != null) {
        sb.append(headerNumber.longValue());
    }

    for (int i = 0; i < stringWithNumber.length(); i++) {
        if (CharUtils.isAsciiNumeric(stringWithNumber.charAt(i))) {
            sb.append(stringWithNumber.charAt(i));
        }
    }

    if (sb.length() == 0) {
        return NumberUtils.LONG_ZERO;
    } else if(sb.length() >= 19) {
        // 19桁以上の場合は先頭の18文字を使用する
        return Long.valueOf(sb.substring(0, 18));
    } else {
        return Long.valueOf(sb.toString());
    }
}
 
Example #5
Source File: NameUtils.java    From jingtum-lib-java with MIT License 6 votes vote down vote up
/**
 * covert field name to column name userName --> user_name
 * covert class name to column name UserName -- > user_name
 */
public static String getUnderlineName(String propertyName) {
	if (null == propertyName) {
		return "";
	}
	StringBuilder sbl = new StringBuilder(propertyName);
	sbl.setCharAt(0, Character.toLowerCase(sbl.charAt(0)));
	propertyName = sbl.toString();
	char[] chars = propertyName.toCharArray();
	StringBuffer sb = new StringBuffer();
	for (char c : chars) {
		if (CharUtils.isAsciiAlphaUpper(c)) {
			sb.append("_" + StringUtils.lowerCase(CharUtils.toString(c)));
		} else {
			sb.append(c);
		}
	}
	return sb.toString();
}
 
Example #6
Source File: JavaCompilerUtils.java    From tracingplane-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Replaces characters preceded by underscores with uppercase version, eg:
 * 
 * 'hello_world' => 'helloWorld' 'hello_World' => 'helloWorld' 'hello__world' => 'hello_World'
 */
public static String formatCamelCase(String name) {
    StringBuilder formatted = new StringBuilder();
    for (int i = 0; i < name.length(); i++) {
        char ci = name.charAt(i);
        if (i < name.length() - 1 && ci == '_' && CharUtils.isAscii(ci)) {
            char cii = name.charAt(i + 1);
            if (CharUtils.isAsciiAlphaLower(cii)) {
                formatted.append(StringUtils.upperCase(String.valueOf(cii)));
                i++;
            }
        } else {
            formatted.append(name.charAt(i));
        }
    }
    return formatted.toString();
}
 
Example #7
Source File: ToDoApp.java    From gradle-in-action-source with MIT License 5 votes vote down vote up
public static void main(String args[]) {
    CommandLineInputHandler commandLineInputHandler = new CommandLineInputHandler();
    char command = DEFAULT_INPUT;

    while (CommandLineInput.EXIT.getShortCmd() != command) {
        commandLineInputHandler.printOptions();
        String input = commandLineInputHandler.readInput();
        System.out.println("-----> " + CharUtils.toChar(input, DEFAULT_INPUT));
        command = CharUtils.toChar(input, DEFAULT_INPUT);
        CommandLineInput commandLineInput = CommandLineInput.getCommandLineInputForInput(command);
        commandLineInputHandler.processInput(commandLineInput);
    }
}
 
Example #8
Source File: InspectFile.java    From count-db with MIT License 5 votes vote down vote up
private static String replaceNonAscii(String valueToPrint) {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < valueToPrint.length(); i++) {
        if (CharUtils.isAscii(valueToPrint.charAt(i))) {
            result.append(valueToPrint.charAt(i));
        } else {
            result.append("?");
        }
    }
    return result.toString();
}
 
Example #9
Source File: RandomStringUtilsTest.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
private static boolean isAsciiNumeric(String value) {
    for (char c : value.toCharArray()) {
        if (!CharUtils.isAsciiNumeric(c))
            return false;
    }
    return true;
}
 
Example #10
Source File: RandomStringUtilsTest.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
private static boolean isAsciiAlphanumeric(String value) {
    for (char c : value.toCharArray()) {
        if (!CharUtils.isAsciiAlphanumeric(c))
            return false;
    }
    return true;
}
 
Example #11
Source File: RandomStringUtilsTest.java    From OpenEstate-IO with Apache License 2.0 5 votes vote down vote up
private static boolean isAsciiAlpha(String value) {
    for (char c : value.toCharArray()) {
        if (!CharUtils.isAsciiAlpha(c))
            return false;
    }
    return true;
}
 
Example #12
Source File: Hive13DdlGenerator.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the DDL character value based on the specified configured character value. This method supports UTF-8 encoded strings and will "Hive" escape any
 * non-ASCII printable characters using '\(value)'.
 *
 * @param string the configured character value.
 * @param escapeSingleBackslash specifies if we need to escape a single backslash character with an extra backslash
 *
 * @return the DDL character value.
 */
public String getDdlCharacterValue(String string, boolean escapeSingleBackslash)
{
    // Assume the empty string for the return value.
    StringBuilder returnValueStringBuilder = new StringBuilder();

    // If we have an actual character, set the return value based on our rules.
    if (StringUtils.isNotEmpty(string))
    {
        // Convert the string to UTF-8 so we can the proper characters that were sent via XML.
        String utf8String = new String(string.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);

        // Loop through each character and add each one to the return value.
        for (int i = 0; i < utf8String.length(); i++)
        {
            // Default to the character itself.
            Character character = string.charAt(i);
            String nextValue = character.toString();

            // If the character isn't ASCII printable, then "Hive" escape it.
            if (!CharUtils.isAsciiPrintable(character))
            {
                // If the character is unprintable, then display it as the ASCII octal value in \000 format.
                nextValue = String.format("\\%03o", (int) character);
            }

            // Add this character to the return value.
            returnValueStringBuilder.append(nextValue);
        }

        // Check if we need to escape a single backslash character with an extra backslash.
        if (escapeSingleBackslash && returnValueStringBuilder.toString().equals("\\"))
        {
            returnValueStringBuilder.append('\\');
        }
    }

    // Return the value.
    return returnValueStringBuilder.toString();
}
 
Example #13
Source File: ApiNameGenerator.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
private static boolean startsWithAlphaOrUnderscore(String string) {
  if (Strings.isNullOrEmpty(string)) {
    return false;
  }
  char firstCharacter = string.charAt(0);
  return CharUtils.isAsciiAlpha(firstCharacter) || firstCharacter == API_NAME_FILLER_CHAR;
}
 
Example #14
Source File: ApiNameGenerator.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Replaces all non alphanumeric characters in input string with {@link
 * ApiNameGenerator#API_NAME_FILLER_CHAR}
 */
private static String replaceNonAlphanumericChars(String input, boolean allowDots) {
  StringBuilder alphaNumeric = new StringBuilder();
  for (char hostnameChar : input.toCharArray()) {
    if (CharUtils.isAsciiAlphanumeric(hostnameChar) || (allowDots && hostnameChar == SEPARATOR)) {
      alphaNumeric.append(hostnameChar);
    } else {
      alphaNumeric.append(API_NAME_FILLER_CHAR);
    }
  }
  return alphaNumeric.toString();
}
 
Example #15
Source File: StringProUtils.java    From spring-boot-start-current with Apache License 2.0 5 votes vote down vote up
public static String nonAsciiToUnicode ( String s ) {
    StringBuffer sb = new StringBuffer( s.length() );
    for ( Character c : s.toCharArray() ) {
        if ( ! CharUtils.isAscii( c ) ) {
            sb.append( CharUtils.unicodeEscaped( c ) );
        } else {
            sb.append( c );
        }
    }

    return sb.toString();
}
 
Example #16
Source File: PermissionOverwrite.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
public void parse(char c) {
    if(CharUtils.isAsciiNumeric(c)) {
        int intValue = CharUtils.toIntValue(c);
        this.read = (intValue & 4) > 0;
        this.write = (intValue & 2) > 0;
        this.execute = (intValue & 1) > 0;
    }
    else {
        if(c == MULTIPLE_VALUES) {
            this.read = this.write = this.execute = null;
        }
    }
}
 
Example #17
Source File: AbstractHostCollection.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @param h Bookmark
 * @return User comment for bookmark or null
 */
public String getComment(final Host h) {
    if(StringUtils.isNotBlank(h.getComment())) {
        return StringUtils.remove(StringUtils.remove(h.getComment(), CharUtils.LF), CharUtils.CR);
    }
    return null;
}
 
Example #18
Source File: NameUtils.java    From jingtum-lib-java with MIT License 5 votes vote down vote up
/**
 * covert field name to column name
 */
public static String getCamelName(String fieldName) {
	if (null == fieldName) {
		return "";
	}
	StringBuffer sb = new StringBuffer();
	if (fieldName.contains("_")) {
		fieldName = fieldName.toLowerCase();
	}
	char[] chars = fieldName.toCharArray();
	if (isUpper(chars[0])) {
		chars[0] = toLower(chars[0]);
	}
	for (int i = 0; i < chars.length; i++) {
		char c = chars[i];
		if (c == '_') {
			int j = i + 1;
			if (j < chars.length) {
				sb.append(StringUtils.upperCase(CharUtils.toString(chars[j])));
				i++;
			}
		} else {
			sb.append(c);
		}
	}
	return sb.toString();
}
 
Example #19
Source File: DateTimeFormatTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void test(final String... string) throws Exception {
    final StringBuilder html = new StringBuilder(HtmlPageTest.STANDARDS_MODE_PREFIX_
        + "<html><head>\n"
        + "<script>\n"
        + "  function test() {\n"
        + "    var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n"
        + "    try {\n");
    for (int i = 0; i < string.length - 1; i++) {
        html.append(string[i]).append("\n");
    }
    html.append(
        "      alert(" + string[string.length - 1] + ");\n"
        + "    } catch(e) {alert('exception')}\n"
        + "  }\n"
        + "</script>\n"
        + "</head><body onload='test()'>\n"
        + "</body></html>");

    try {
        loadPageWithAlerts2(html.toString());
    }
    catch (final ComparisonFailure e) {
        final String msg = e.getMessage();
        for (int i = 0; i < msg.length(); i++) {
            final char c = msg.charAt(i);
            if (CharUtils.isAscii(c)) {
                System.out.print(c);
            }
            else {
                System.out.print(CharUtils.unicodeEscaped(c));
            }
        }
        System.out.println();
        throw e;
    }
}
 
Example #20
Source File: Local.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
public Local(final Local parent, final String name, final String delimiter) {
    this(parent.isRoot() ?
        String.format("%s%s", parent.getAbsolute(), name) :
        String.format("%s%c%s", parent.getAbsolute(), CharUtils.toChar(delimiter), name));
}
 
Example #21
Source File: Local.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
public Local(final String parent, final String name, final String delimiter) {
    this(parent.endsWith(delimiter) ?
        String.format("%s%s", parent, name) :
        String.format("%s%c%s", parent, CharUtils.toChar(delimiter), name));
}
 
Example #22
Source File: TextQuery.java    From onedev with MIT License 4 votes vote down vote up
private boolean isWordChar(char ch) {
	return CharUtils.isAsciiAlphanumeric(ch) || ch == '_';
}
 
Example #23
Source File: JacksonCSVRecordReader.java    From nifi with Apache License 2.0 4 votes vote down vote up
public JacksonCSVRecordReader(final InputStream in, final ComponentLog logger, final RecordSchema schema, final CSVFormat csvFormat, final boolean hasHeader, final boolean ignoreHeader,
                              final String dateFormat, final String timeFormat, final String timestampFormat, final String encoding) throws IOException {
    super(logger, schema, hasHeader, ignoreHeader, dateFormat, timeFormat, timestampFormat);

    final Reader reader = new InputStreamReader(new BOMInputStream(in));

    CsvSchema.Builder csvSchemaBuilder = CsvSchema.builder()
            .setColumnSeparator(csvFormat.getDelimiter())
            .setLineSeparator(csvFormat.getRecordSeparator())
            // Can only use comments in Jackson CSV if the correct marker is set
            .setAllowComments("#" .equals(CharUtils.toString(csvFormat.getCommentMarker())))
            // The call to setUseHeader(false) in all code paths is due to the way Jackson does data binding/mapping. Missing or extra columns may not
            // be handled correctly when using the header for mapping.
            .setUseHeader(false);

    csvSchemaBuilder = (csvFormat.getQuoteCharacter() == null) ? csvSchemaBuilder : csvSchemaBuilder.setQuoteChar(csvFormat.getQuoteCharacter());
    csvSchemaBuilder = (csvFormat.getEscapeCharacter() == null) ? csvSchemaBuilder : csvSchemaBuilder.setEscapeChar(csvFormat.getEscapeCharacter());

    if (hasHeader) {
        if (ignoreHeader) {
            csvSchemaBuilder = csvSchemaBuilder.setSkipFirstDataRow(true);
        }
    }

    CsvSchema csvSchema = csvSchemaBuilder.build();

    // Add remaining config options to the mapper
    List<CsvParser.Feature> features = new ArrayList<>();
    features.add(CsvParser.Feature.INSERT_NULLS_FOR_MISSING_COLUMNS);
    if (csvFormat.getIgnoreEmptyLines()) {
        features.add(CsvParser.Feature.SKIP_EMPTY_LINES);
    }
    if (csvFormat.getTrim()) {
        features.add(CsvParser.Feature.TRIM_SPACES);
    }

    ObjectReader objReader = mapper.readerFor(String[].class)
            .with(csvSchema)
            .withFeatures(features.toArray(new CsvParser.Feature[features.size()]));

    recordStream = objReader.readValues(reader);
}
 
Example #24
Source File: SensitiveFilter.java    From MyCommunity with Apache License 2.0 4 votes vote down vote up
private boolean isSymbol(Character c) {
    // 0x2E80~0x9FFF 是东亚文字范围
    return !CharUtils.isAsciiAlphanumeric(c) && (c < 0x2E80 || c > 0x9FFF);
}