Example usage for com.google.common.base CharMatcher ASCII

List of usage examples for com.google.common.base CharMatcher ASCII

Introduction

In this page you can find the example usage for com.google.common.base CharMatcher ASCII.

Prototype

CharMatcher ASCII

To view the source code for com.google.common.base CharMatcher ASCII.

Click Source Link

Document

Determines whether a character is ASCII, meaning that its code point is less than 128.

Usage

From source file:apps.Source2XML.java

/**
 * /*from   w  w w  .j ava2s .  c  om*/
 * A good word should start from the letter: it may contain a letter,
 * a dash, or an apostrophe. 
 * 
 * @param text        input
 *     
 * @return true if a good word.
 */
protected static boolean isGoodWord(String text) {
    if (text.isEmpty())
        return false;
    // 
    CharMatcher m = (CharMatcher.JAVA_LETTER_OR_DIGIT).and(CharMatcher.ASCII);
    m = m.or(CharMatcher.is('-'));
    m = m.or(CharMatcher.is('\''));

    return m.matchesAllOf(text);
}

From source file:google.registry.flows.contact.ContactFlowUtils.java

/** Check that an internationalized postal info has only ascii characters. */
static void validateAsciiPostalInfo(@Nullable PostalInfo internationalized) throws EppException {
    if (internationalized != null) {
        Preconditions.checkState(INTERNATIONALIZED.equals(internationalized.getType()));
        ContactAddress address = internationalized.getAddress();
        Set<String> fields = Sets.newHashSet(internationalized.getName(), internationalized.getOrg(),
                address.getCity(), address.getCountryCode(), address.getState(), address.getZip());
        fields.addAll(address.getStreet());
        for (String field : fields) {
            if (field != null && !CharMatcher.ascii().matchesAllOf(field)) {
                throw new BadInternationalizedPostalInfoException();
            }//from   w  ww. j a  va  2 s .com
        }
    }
}

From source file:us.eharning.atomun.mnemonic.spi.electrum.v2.CJKCleanupUtility.java

public String cleanup(String input) {
    /* Check for non-ascii range to short-circuit fast */
    if (CharMatcher.ASCII.matchesAllOf(input)) {
        /* All ascii, skip */
        return input;
    }// ww  w. j  av  a 2 s . c  o m
    /* Split into words and join specially */
    StringBuilder cleanBuilder = new StringBuilder(input.length());
    String previousWord = null;
    Iterator<String> splitIterator = Splitter.on(' ').split(input).iterator();
    /* All one unit - no space removal necessary */
    if (!splitIterator.hasNext()) {
        return input;
    }
    previousWord = splitIterator.next();
    cleanBuilder.append(previousWord);
    while (splitIterator.hasNext()) {
        String nextWord = splitIterator.next();
        if (hasSpaceBetween(previousWord, nextWord)) {
            cleanBuilder.append(' ');
        }
        cleanBuilder.append(nextWord);
        previousWord = nextWord;
    }
    return cleanBuilder.toString();
}

From source file:ru.devhead.jregenerate.Jregenerate.java

private void Button_regenerateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Button_regenerateActionPerformed

    String Password = getRegenerate(Text_Resul.getText());
    boolean isAscii = CharMatcher.ASCII.matchesAllOf(Password);
    if (isAscii == false) {
        Text_Resul.setText(Password);
    } else {/*from ww  w  . ja  v a2s  .c om*/
        Text_Resul.setText("");
    }
}

From source file:android.keystore.cts.Attestation.java

@Override
public String toString() {
    StringBuilder s = new StringBuilder();
    s.append("Attest version: " + attestationVersion);
    s.append("\nAttest security: " + securityLevelToString(attestationSecurityLevel));
    s.append("\nKM version: " + keymasterVersion);
    s.append("\nKM security: " + securityLevelToString(keymasterSecurityLevel));

    s.append("\nChallenge");
    String stringChallenge = new String(attestationChallenge);
    if (CharMatcher.ASCII.matchesAllOf(stringChallenge)) {
        s.append(": [" + stringChallenge + "]");
    } else {//from  w w w.  j  a v  a  2s. com
        s.append(" (base64): [" + BaseEncoding.base64().encode(attestationChallenge) + "]");
    }
    if (uniqueId != null) {
        s.append("\nUnique ID (base64): [" + BaseEncoding.base64().encode(uniqueId) + "]");
    }

    s.append("\n-- SW enforced --");
    s.append(softwareEnforced);
    s.append("\n-- TEE enforced --");
    s.append(teeEnforced);

    return s.toString();
}

From source file:com.francetelecom.clara.cloud.commons.InternetDomainNameCleaner.java

/**
 * Helper method for {@link #fixParts(List)}. Validates that one part of
 * a domain name is valid./*from  w  ww  .j  av  a 2  s. c o  m*/
 *
 * @param part The domain name part to be validated
 * @param isFinalPart Is this the final (rightmost) domain part?
 * @return Whether the part is valid
 */
public static String getFixedPart(String part, boolean isFinalPart) {

    // These tests could be collapsed into one big boolean expression, but
    // they have been left as independent tests for clarity.

    if (part.length() > MAX_DOMAIN_PART_LENGTH) {
        part = StringUtils.left(part, MAX_DOMAIN_PART_LENGTH);
    }

    /*
     * GWT claims to support java.lang.Character's char-classification methods,
     * but it actually only works for ASCII. So for now, assume any non-ASCII
     * characters are valid. The only place this seems to be documented is here:
     * http://osdir.com/ml/GoogleWebToolkitContributors/2010-03/msg00178.html
     *
     * <p>ASCII characters in the part are expected to be valid per RFC 1035,
     * with underscore also being allowed due to widespread practice.
     */

    String asciiChars = CharMatcher.ASCII.retainFrom(part);

    if (!part.isEmpty() && !PART_CHAR_MATCHER.matchesAllOf(asciiChars)) {
        part = PART_CHAR_MATCHER.retainFrom(asciiChars);
    }

    // No initial or final dashes or underscores.

    if (!part.isEmpty() && DASH_MATCHER.matches(part.charAt(0))) {
        part = part.substring(1);
    } else if (!part.isEmpty() && DASH_MATCHER.matches(part.charAt(part.length() - 1))) {
        part = part.substring(0, part.length() - 1);
    }

    /*
     * Note that we allow (in contravention of a strict interpretation of the
     * relevant RFCs) domain parts other than the last may begin with a digit
     * (for example, "3com.com"). It's important to disallow an initial digit in
     * the last part; it's the only thing that stops an IPv4 numeric address
     * like 127.0.0.1 from looking like a valid domain name.
     */

    if (!part.isEmpty() && isFinalPart && CharMatcher.DIGIT.matches(part.charAt(0))) {
        part = part.substring(1);
    }

    return part;
}

From source file:org.sonatype.nexus.proxy.maven.routing.internal.TextFilePrefixSourceMarshaller.java

/**
 * Unmarshalls the prefix source from input stream.
 * /*w  w w  . j  av  a 2 s.  c o m*/
 * @param file
 * @return prefix source
 * @throws InvalidInputException
 * @throws IOException
 */
public final Result read(final StorageFileItem file) throws InvalidInputException, IOException {
    if (file.getLength() > prefixFileMaxSize) {
        throw new InvalidInputException("Prefix file size exceeds maximum allowed size (" + prefixFileMaxSize
                + "), refusing to load it.");
    }
    BufferedReader reader = null;
    try {
        final ArrayList<String> entries = new ArrayList<String>();
        reader = new BufferedReader(new InputStreamReader(file.getInputStream(), CHARSET));
        String line = reader.readLine();

        if (UNSUPPORTED.equals(line)) {
            return RESULT_UNSUPPORTED;
        }

        while (line != null) {
            // trim
            line = line.trim();
            if (!line.startsWith("#") && line.length() > 0) {
                // line length
                if (line.length() > prefixFileMaxLineLength) {
                    throw new InvalidInputException("Prefix file contains line longer than allowed ("
                            + prefixFileMaxLineLength + " characters), refusing to load the file.");
                }
                // line should be ASCII
                if (!CharMatcher.ASCII.matchesAllOf(line)) {
                    throw new InvalidInputException(
                            "Prefix file contains non-ASCII characters, refusing to load the file.");
                }
                // Igor's find command makes path like "./org/apache/"
                while (line.startsWith(".")) {
                    line = line.substring(1);
                }
                // win file separators? Highly unlikely but still...
                line = line.replace('\\', '/');
                // normalization
                entries.add(pathFrom(elementsOf(line)));
            }
            line = reader.readLine();

            // dump big files
            if (entries.size() > prefixFileMaxEntryCount) {
                throw new InvalidInputException("Prefix file entry count exceeds maximum allowed count ("
                        + prefixFileMaxEntryCount + "), refusing to load it.");
            }
        }
        return new Result() {
            @Override
            public boolean supported() {
                return true;
            }

            @Override
            public List<String> entries() {
                return entries;
            }
        };
    } finally {
        Closeables.closeQuietly(reader);
    }
}

From source file:com.opengamma.bbg.BloombergReferenceDataProvider.java

/**
 * Checks that all the securities are valid.
 * //from  www.ja v a 2  s.  co m
 * @param securityKeys  the set of securities, not null
 */
protected void validateSecurities(Set<String> securityKeys) {
    Set<String> excluded = new HashSet<String>();
    for (String securityKey : securityKeys) {
        if (StringUtils.isEmpty(securityKey)) {
            throw new IllegalArgumentException("Must not have any null or empty securities");
        }
        if (CharMatcher.ASCII.matchesAllOf(securityKey) == false) {
            //[BBG-93] - The C++ interface is declared as UChar, so this just enforces that restriction   
            excluded.add(securityKey);
        }
    }
    if (excluded.size() > 0) {
        //TODO - should we allow the rest of the request to continue? 
        String message = MessageFormatter.format("Request contains invalid securities {} from ({})", excluded,
                securityKeys);
        s_logger.error(message);
        throw new OpenGammaRuntimeException(message);
    }
}

From source file:com.android.messaging.util.EmailAddress.java

/**
 * Ensure the email address is valid, conforming to current RFC2821 and
 * RFC2822 guidelines (although some iffy characters, like ! and ;, are
 * allowed because they are not technically prohibited in the RFC)
 *///www  .  ja  v a 2 s . c o m
private boolean isValidInternal() {
    if ((user == null) || (host == null)) {
        return false;
    }

    if ((user.length() == 0) || (host.length() == 0)) {
        return false;
    }

    // check for white space in the host
    if (ANY_WHITESPACE.indexIn(host) >= 0) {
        return false;
    }

    // ensure the host is above the minimum length
    if (host.length() < 4) {
        return false;
    }

    final int firstDot = host.indexOf('.');

    // ensure host contains at least one dot
    if (firstDot == -1) {
        return false;
    }

    // check if the host contains two continuous dots.
    if (host.indexOf("..") >= 0) {
        return false;
    }

    // check if the first host char is a dot.
    if (host.charAt(0) == '.') {
        return false;
    }

    final int secondDot = host.indexOf(".", firstDot + 1);

    // if there's a dot at the end, there needs to be a second dot
    if (host.charAt(host.length() - 1) == '.' && secondDot == -1) {
        return false;
    }

    // Host must not have any disallowed characters; allowI18n dictates whether
    // host must be ASCII.
    if (!EMAIL_ALLOWED_CHARS.matchesAllOf(host) || (!allowI18n && !CharMatcher.ASCII.matchesAllOf(host))) {
        return false;
    }

    if (user.startsWith("\"")) {
        if (!isQuotedUserValid()) {
            return false;
        }
    } else {
        // check for white space in the user
        if (ANY_WHITESPACE.indexIn(user) >= 0) {
            return false;
        }

        // the user cannot contain two continuous dots
        if (user.indexOf("..") >= 0) {
            return false;
        }

        // User must not have any disallowed characters; allow I18n dictates whether
        // user must be ASCII.
        if (!EMAIL_ALLOWED_CHARS.matchesAllOf(user) || (!allowI18n && !CharMatcher.ASCII.matchesAllOf(user))) {
            return false;
        }
    }
    return true;
}

From source file:org.apache.james.jmap.DownloadServlet.java

private void addContentDispositionHeaderRegardingEncoding(String name, HttpServletResponse resp) {
    if (CharMatcher.ASCII.matchesAllOf(name)) {
        resp.addHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");
    } else {/*w w  w.  ja  v a2 s .c o m*/
        resp.addHeader("Content-Disposition",
                "attachment; filename*=\"" + EncoderUtil.encodeEncodedWord(name, Usage.TEXT_TOKEN) + "\"");
    }
}