com.google.common.base.Ascii Java Examples
The following examples show how to use
com.google.common.base.Ascii.
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: TargetingGenerator.java From bundletool with Apache License 2.0 | 6 votes |
private static Abi checkAbiName(String token, String forFileOrDirectory) { Optional<AbiName> abiName = AbiName.fromLibSubDirName(token); if (!abiName.isPresent()) { Optional<AbiName> abiNameLowerCase = AbiName.fromLibSubDirName(token.toLowerCase()); if (abiNameLowerCase.isPresent()) { throw InvalidBundleException.builder() .withUserMessage( "Expecting ABI name in file or directory '%s', but found '%s' " + "which is not recognized. Did you mean '%s'?", forFileOrDirectory, token, Ascii.toLowerCase(token)) .build(); } throw InvalidBundleException.builder() .withUserMessage( "Expecting ABI name in file or directory '%s', but found '%s' " + "which is not recognized.", forFileOrDirectory, token) .build(); } return Abi.newBuilder().setAlias(abiName.get().toProto()).build(); }
Example #2
Source File: InternetDomainName.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Constructor used to implement {@link #from(String)}, and from subclasses. */ InternetDomainName(String name) { // Normalize: // * ASCII characters to lowercase // * All dot-like characters to '.' // * Strip trailing '.' name = Ascii.toLowerCase(DOTS_MATCHER.replaceFrom(name, '.')); if (name.endsWith(".")) { name = name.substring(0, name.length() - 1); } checkArgument(name.length() <= MAX_LENGTH, "Domain name too long: '%s':", name); this.name = name; this.parts = ImmutableList.copyOf(DOT_SPLITTER.split(name)); checkArgument(parts.size() <= MAX_PARTS, "Domain has too many parts: '%s'", name); checkArgument(validateSyntax(parts), "Not a valid domain name: '%s'", name); this.publicSuffixIndex = findPublicSuffix(); }
Example #3
Source File: AggregationMode.java From buck with Apache License 2.0 | 6 votes |
public static AggregationMode fromString(String aggregationModeString) { switch (Ascii.toLowerCase(aggregationModeString)) { case "shallow": return SHALLOW; case "none": return NONE; case "auto": return AUTO; default: try { // See if a number was passed. return new AggregationMode(Integer.parseInt(aggregationModeString)); } catch (NumberFormatException e) { throw new HumanReadableException( "Invalid aggregation mode value %s.", aggregationModeString); } } }
Example #4
Source File: GitHubApi.java From copybara with Apache License 2.0 | 6 votes |
String toParams() { StringBuilder result = new StringBuilder(); if (state != null) { result.append("&state=").append(Ascii.toLowerCase(state.toString())); } if (head != null) { result.append("&head=").append(head); } if (base != null) { result.append("&base=").append(base); } if (sort != null) { result.append("&sort=").append(Ascii.toLowerCase(sort.toString())); } if (direction != null) { result.append("&direction=").append(Ascii.toLowerCase(direction.toString())); } return result.toString(); }
Example #5
Source File: MimeTypeUtil.java From armeria with Apache License 2.0 | 6 votes |
@Nullable static MediaType guessFromPath(String path) { requireNonNull(path, "path"); final int dotIdx = path.lastIndexOf('.'); final int slashIdx = path.lastIndexOf('/'); if (dotIdx < 0 || slashIdx > dotIdx) { // No extension return null; } final String extension = Ascii.toLowerCase(path.substring(dotIdx + 1)); final MediaType mediaType = EXTENSION_TO_MEDIA_TYPE.get(extension); if (mediaType != null) { return mediaType; } final String guessedContentType = URLConnection.guessContentTypeFromName(path); return guessedContentType != null ? MediaType.parse(guessedContentType) : null; }
Example #6
Source File: MapMaker.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Returns a string representation for this MapMaker instance. The exact form of the returned * string is not specificed. */ @Override public String toString() { MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this); if (initialCapacity != UNSET_INT) { s.add("initialCapacity", initialCapacity); } if (concurrencyLevel != UNSET_INT) { s.add("concurrencyLevel", concurrencyLevel); } if (keyStrength != null) { s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString())); } if (valueStrength != null) { s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString())); } if (keyEquivalence != null) { s.addValue("keyEquivalence"); } return s.toString(); }
Example #7
Source File: LaunchNotice.java From nomulus with Apache License 2.0 | 6 votes |
/** * Validate the checksum of the notice against the domain label. */ public void validate(String domainLabel) throws InvalidChecksumException { // According to http://tools.ietf.org/html/draft-lozano-tmch-func-spec-08#section-6.3, a TCNID // is always 8 chars of checksum + 19 chars of a decimal notice id. Check the length before // taking substrings to avoid an IndexOutOfBoundsException. String tcnId = getNoticeId().getTcnId(); checkArgument(tcnId.length() == 27); int checksum = Ints.fromByteArray(base16().decode(Ascii.toUpperCase(tcnId.substring(0, 8)))); String noticeId = tcnId.substring(8); checkArgument(CharMatcher.inRange('0', '9').matchesAllOf(noticeId)); // The checksum in the first 8 chars must match the crc32 of label + expiration + notice id. String stringToHash = domainLabel + MILLISECONDS.toSeconds(getExpirationTime().getMillis()) + noticeId; int computedChecksum = crc32().hashString(stringToHash, UTF_8).asInt(); if (checksum != computedChecksum) { throw new InvalidChecksumException(); } }
Example #8
Source File: AppBundleObfuscationPreprocessor.java From bundletool with Apache License 2.0 | 6 votes |
private static ZipPath obfuscateZipPath( ZipPath oldZipPath, ImmutableMap<String, String> resourceNameMapping) { HashCode hashCode = Hashing.sha256().hashString(oldZipPath.toString(), StandardCharsets.UTF_8); String encodedString = Base64.getUrlEncoder() .encodeToString(Arrays.copyOf(hashCode.asBytes(), RESOURCE_NAME_LENGTH)); while (resourceNameMapping.containsValue("res/" + encodedString)) { encodedString = handleCollision(hashCode.asBytes()); } String fileExtension = FileUtils.getFileExtension(oldZipPath); // The "xml" extension has to be preserved, because the Android Platform requires it if (Ascii.equalsIgnoreCase(fileExtension, "xml")) { encodedString = encodedString + "." + fileExtension; } return RESOURCES_DIRECTORY.resolve(encodedString); }
Example #9
Source File: ConsoleRegistrarCreatorAction.java From nomulus with Apache License 2.0 | 6 votes |
private void sendExternalUpdates() { if (!sendEmailUtils.hasRecipients()) { return; } String environment = Ascii.toLowerCase(String.valueOf(RegistryEnvironment.get())); String body = String.format( "The following registrar was created in %s by %s:\n", environment, registrarAccessor.userIdForLogging()) + toEmailLine(clientId, "clientId") + toEmailLine(name, "name") + toEmailLine(billingAccount, "billingAccount") + toEmailLine(ianaId, "ianaId") + toEmailLine(referralEmail, "referralEmail") + toEmailLine(driveId, "driveId") + String.format("Gave user %s web access to the registrar\n", consoleUserEmail.get()); sendEmailUtils.sendEmail( String.format("Registrar %s created in %s", clientId.get(), environment), body); }
Example #10
Source File: InternetDomainName.java From codebuff with BSD 2-Clause "Simplified" License | 6 votes |
/** * Constructor used to implement {@link #from(String)}, and from subclasses. */ InternetDomainName(String name) { // Normalize: // * ASCII characters to lowercase // * All dot-like characters to '.' // * Strip trailing '.' name = Ascii.toLowerCase(DOTS_MATCHER.replaceFrom(name, '.')); if (name.endsWith(".")) { name = name.substring(0, name.length() - 1); } checkArgument(name.length() <= MAX_LENGTH, "Domain name too long: '%s':", name); this.name = name; this.parts = ImmutableList.copyOf(DOT_SPLITTER.split(name)); checkArgument(parts.size() <= MAX_PARTS, "Domain has too many parts: '%s'", name); checkArgument(validateSyntax(parts), "Not a valid domain name: '%s'", name); this.publicSuffixIndex = findPublicSuffix(); }
Example #11
Source File: ImportRewriteDisabler.java From immutables with Apache License 2.0 | 6 votes |
private static boolean shouldDisableFor(Reporter reporter, Element element) { while (element != null) { if (element.getKind() == ElementKind.PACKAGE) { for (String segment : DOT_SPLITTER.split(((PackageElement) element).getQualifiedName())) { if (!segment.isEmpty() && Ascii.isUpperCase(segment.charAt(0))) { reporter.warning(About.INCOMPAT, WARNING_START + " uppercase package names"); return true; } } } if (element.getKind().isClass() || element.getKind().isInterface()) { if (Ascii.isLowerCase(element.getSimpleName().charAt(0))) { reporter.warning(About.INCOMPAT, WARNING_START + " lowercase class names"); return true; } } element = element.getEnclosingElement(); } return false; }
Example #12
Source File: ConsoleOteSetupAction.java From nomulus with Apache License 2.0 | 6 votes |
private void sendExternalUpdates(ImmutableMap<String, String> clientIdToTld) { if (!sendEmailUtils.hasRecipients()) { return; } String environment = Ascii.toLowerCase(String.valueOf(RegistryEnvironment.get())); StringBuilder builder = new StringBuilder(); builder.append( String.format( "The following entities were created in %s by %s:\n", environment, registrarAccessor.userIdForLogging())); clientIdToTld.forEach( (clientId, tld) -> builder.append( String.format(" Registrar %s with access to TLD %s\n", clientId, tld))); builder.append(String.format("Gave user %s web access to these Registrars\n", email.get())); sendEmailUtils.sendEmail( String.format("OT&E for registrar %s created in %s", clientId.get(), environment), builder.toString()); }
Example #13
Source File: BaseEncoding.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
Alphabet upperCase() { if (!hasLowerCase()) { return this; } else { checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet"); char[] upperCased = new char[chars.length]; for (int i = 0; i < chars.length; i++) { upperCased[i] = Ascii.toUpperCase(chars[i]); } return new Alphabet(name + ".upperCase()", upperCased); } }
Example #14
Source File: FeeCheckCommandExtensionItemV12.java From nomulus with Apache License 2.0 | 5 votes |
@Override public CommandName getCommandName() { // Require the xml string to be lowercase. if (commandName != null && commandName.toLowerCase(Locale.ENGLISH).equals(commandName)) { try { return CommandName.valueOf(Ascii.toUpperCase(commandName)); } catch (IllegalArgumentException e) { // Swallow this and return UNKNOWN below because there's no matching CommandName. } } return CommandName.UNKNOWN; }
Example #15
Source File: BaseEncoding.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
private boolean hasLowerCase() { for (char c : chars) { if (Ascii.isLowerCase(c)) { return true; } } return false; }
Example #16
Source File: MediaType.java From armeria with Apache License 2.0 | 5 votes |
private static boolean containsValue(String expectedValue, List<String> actualValues) { final int numActualValues = actualValues.size(); for (int i = 0; i < numActualValues; i++) { if (Ascii.equalsIgnoreCase(expectedValue, actualValues.get(i))) { return true; } } return false; }
Example #17
Source File: BlazeIcons.java From intellij with Apache License 2.0 | 5 votes |
private static Icon loadForBuildSystem(String basename) { // Guessing the build system name may result in an NPE if (e.g.) it was called from a // unit-testing scenario where there aren't Application/ProjectManager instances yet. if (ApplicationManager.getApplication() == null || ProjectManager.getInstance() == null) { // Default to the blaze icons. return load("blaze/" + basename); } else { return load(Ascii.toLowerCase(Blaze.guessBuildSystemName()) + "/" + basename); } }
Example #18
Source File: DomainNameUtils.java From nomulus with Apache License 2.0 | 5 votes |
/** Canonicalizes a domain name by lowercasing and converting unicode to punycode. */ public static String canonicalizeDomainName(String label) { String labelLowercased = Ascii.toLowerCase(label); try { return Idn.toASCII(labelLowercased); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format("Error ASCIIfying label '%s'", label), e); } }
Example #19
Source File: LobbyGameDao.java From triplea with GNU General Public License v3.0 | 5 votes |
default void recordChat(final ChatMessageUpload chatMessageUpload) { final int rowInsert = insertChatMessage( chatMessageUpload.getGameId(), chatMessageUpload.getFromPlayer(), Ascii.truncate(chatMessageUpload.getChatMessage(), MESSAGE_COLUMN_LENGTH, "")); Postconditions.assertState(rowInsert == 1, "Failed to insert message: " + chatMessageUpload); }
Example #20
Source File: BaseEncoding.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
private boolean hasUpperCase() { for (char c : chars) { if (Ascii.isUpperCase(c)) { return true; } } return false; }
Example #21
Source File: BaseEncoding.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
Alphabet upperCase() { if (!hasLowerCase()) { return this; } else { checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet"); char[] upperCased = new char[chars.length]; for (int i = 0; i < chars.length; i++) { upperCased[i] = Ascii.toUpperCase(chars[i]); } return new Alphabet(name + ".upperCase()", upperCased); } }
Example #22
Source File: BaseEncoding.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
private boolean hasUpperCase() { for (char c : chars) { if (Ascii.isUpperCase(c)) { return true; } } return false; }
Example #23
Source File: PathAndQueryTest.java From armeria with Apache License 2.0 | 5 votes |
@Test public void encodedUnicode() { final String encodedPath = "/%ec%95%88"; final String encodedQuery = "%eb%85%95"; final PathAndQuery res = PathAndQuery.parse(encodedPath + '?' + encodedQuery); assertThat(res).isNotNull(); assertThat(res.path()).isEqualTo(Ascii.toUpperCase(encodedPath)); assertThat(res.query()).isEqualTo(Ascii.toUpperCase(encodedQuery)); }
Example #24
Source File: IcannHttpReporter.java From nomulus with Apache License 2.0 | 5 votes |
private String makeUrl(String filename) { // Filename is in the format tld-reportType-yearMonth.csv String tld = getTld(filename); // Remove the tld- prefix and csv suffix String remainder = filename.substring(tld.length() + 1, filename.length() - 4); List<String> elements = Splitter.on('-').splitToList(remainder); ReportType reportType = ReportType.valueOf(Ascii.toUpperCase(elements.get(0))); // Re-add hyphen between year and month, because ICANN is inconsistent between filename and URL String yearMonth = YearMonth.parse(elements.get(1), DateTimeFormat.forPattern("yyyyMM")).toString("yyyy-MM"); return String.format("%s/%s/%s", getUrlPrefix(reportType), tld, yearMonth); }
Example #25
Source File: BaseEncoding.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
private boolean hasLowerCase() { for (char c : chars) { if (Ascii.isLowerCase(c)) { return true; } } return false; }
Example #26
Source File: SerializationFormatProvider.java From armeria with Apache License 2.0 | 5 votes |
/** * Creates a new instance. */ public Entry(String uriText, MediaType primaryMediaType, MediaType... alternativeMediaTypes) { this.uriText = Ascii.toLowerCase(requireNonNull(uriText, "uriText")); this.primaryMediaType = requireNonNull(primaryMediaType, "primaryMediaType"); requireNonNull(alternativeMediaTypes, "alternativeMediaTypes"); mediaTypes = MediaTypeSet.of(ImmutableList.<MediaType>builder() .add(primaryMediaType) .add(alternativeMediaTypes) .build()); }
Example #27
Source File: HttpUtils.java From bazel with Apache License 2.0 | 5 votes |
static String getExtension(String path) { int index = path.lastIndexOf('.'); if (index == -1) { return ""; } return Ascii.toLowerCase(path.substring(index + 1)); }
Example #28
Source File: DatastoreHelper.java From nomulus with Apache License 2.0 | 5 votes |
public static void createTld(String tld, ImmutableSortedMap<DateTime, TldState> tldStates) { // Coerce the TLD string into a valid ROID suffix. String roidSuffix = Ascii.toUpperCase(tld.replaceFirst(ACE_PREFIX_REGEX, "").replace('.', '_')) .replace('-', '_'); createTld(tld, roidSuffix.length() > 8 ? roidSuffix.substring(0, 8) : roidSuffix, tldStates); }
Example #29
Source File: OAuth1aTokenBuilder.java From armeria with Apache License 2.0 | 5 votes |
/** * Sets the specified {@code key}-{@code value} parameter. If the {@code key} is not one of the * pre-defined parameters, then the {@code key}-{@code value} pair is set as an additional parameter. * If the {@code key} is one of the pre-defined parameters, then the corresponding property is * automatically set. * * <pre>{@code * OAuth1aToken.builder().put("oauth_signature_method", "foo"); * // is equivalent to * OAuth1aToken.builder().signatureMethod("foo"); * * // This is just an additional parameter. * OAuth1aToken.builder().put("just_an_additional_parameter", "bar"); * }</pre> */ public OAuth1aTokenBuilder put(String key, String value) { requireNonNull(key, "key"); requireNonNull(value, "value"); final String lowerCased = Ascii.toLowerCase(key); switch (lowerCased) { case REALM: realm(value); break; case OAUTH_CONSUMER_KEY: consumerKey(value); break; case OAUTH_TOKEN: token(value); break; case OAUTH_SIGNATURE_METHOD: signatureMethod(value); break; case OAUTH_SIGNATURE: signature(value); break; case OAUTH_TIMESTAMP: timestamp(value); break; case OAUTH_NONCE: nonce(value); break; case OAUTH_VERSION: version(value); break; default: additionalsBuilder.put(key, value); } return this; }
Example #30
Source File: BaseEncoding.java From codebuff with BSD 2-Clause "Simplified" License | 5 votes |
Alphabet upperCase() { if (!hasLowerCase()) { return this; } else { checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet"); char[] upperCased = new char[chars.length]; for (int i = 0; i < chars.length; i++) { upperCased[i] = Ascii.toUpperCase(chars[i]); } return new Alphabet(name + ".upperCase()", upperCased); } }