Java Code Examples for com.google.common.base.Ascii#toLowerCase()

The following examples show how to use com.google.common.base.Ascii#toLowerCase() . 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: InternetDomainName.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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 2
Source File: BasicTokenizer.java    From tflite-android-transformers with Apache License 2.0 6 votes vote down vote up
public List<String> tokenize(String text) {
  String cleanedText = cleanText(text);

  List<String> origTokens = whitespaceTokenize(cleanedText);

  StringBuilder stringBuilder = new StringBuilder();
  for (String token : origTokens) {
    if (doLowerCase) {
      token = Ascii.toLowerCase(token);
    }
    List<String> list = runSplitOnPunc(token);
    for (String subToken : list) {
      stringBuilder.append(subToken).append(" ");
    }
  }
  return whitespaceTokenize(stringBuilder.toString());
}
 
Example 3
Source File: ConsoleRegistrarCreatorAction.java    From nomulus with Apache License 2.0 6 votes vote down vote up
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 4
Source File: Converters.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Override
public TriState convert(String input) throws OptionsParsingException {
  if (input == null) {
    return TriState.AUTO;
  }
  input = Ascii.toLowerCase(input);
  if (input.equals("auto")) {
    return TriState.AUTO;
  }
  if (ENABLED_REPS.contains(input)) {
    return TriState.YES;
  }
  if (DISABLED_REPS.contains(input)) {
    return TriState.NO;
  }
  throw new OptionsParsingException("'" + input + "' is not a boolean");
}
 
Example 5
Source File: AnnotatedElementNameUtil.java    From armeria with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static String toHeaderName(String name) {
    requireNonNull(name, "name");
    checkArgument(!name.isEmpty(), "name is empty.");

    final String upperCased = Ascii.toUpperCase(name);
    if (name.equals(upperCased)) {
        return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name);
    }
    final String lowerCased = Ascii.toLowerCase(name);
    if (name.equals(lowerCased)) {
        return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name);
    }
    // Ensure that the name does not contain '_'.
    // If it contains '_', we give up to make it lower hyphen case. Just converting it to lower case.
    if (name.indexOf('_') >= 0) {
        return lowerCased;
    }
    if (Ascii.isUpperCase(name.charAt(0))) {
        return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name);
    } else {
        return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, name);
    }
}
 
Example 6
Source File: StringModule.java    From bazel with Apache License 2.0 5 votes vote down vote up
@StarlarkMethod(
    name = "lower",
    doc = "Returns the lower case version of this string.",
    parameters = {@Param(name = "self", type = String.class)})
public String lower(String self) {
  return Ascii.toLowerCase(self);
}
 
Example 7
Source File: UrlFetchUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static Optional<String> getHeaderFirstInternal(Iterable<HTTPHeader> hdrs, String name) {
  name = Ascii.toLowerCase(name);
  for (HTTPHeader header : hdrs) {
    if (Ascii.toLowerCase(header.getName()).equals(name)) {
      return Optional.of(header.getValue());
    }
  }
  return Optional.empty();
}
 
Example 8
Source File: DomainNameUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** 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 9
Source File: HostFlowUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Checks that a host name is valid. */
public static InternetDomainName validateHostName(String name) throws EppException {
  checkArgumentNotNull(name, "Must specify host name to validate");
  if (name.length() > 253) {
    throw new HostNameTooLongException();
  }
  String hostNameLowerCase = Ascii.toLowerCase(name);
  if (!name.equals(hostNameLowerCase)) {
    throw new HostNameNotLowerCaseException(hostNameLowerCase);
  }
  try {
    String hostNamePunyCoded = Idn.toASCII(name);
    if (!name.equals(hostNamePunyCoded)) {
      throw new HostNameNotPunyCodedException(hostNamePunyCoded);
    }
    InternetDomainName hostName = InternetDomainName.from(name);
    if (!name.equals(hostName.toString())) {
      throw new HostNameNotNormalizedException(hostName.toString());
    }
    // The effective TLD is, in order of preference, the registry suffix, if the TLD is a real TLD
    // published in the public suffix list (https://publicsuffix.org/, note that a registry suffix
    // is in the "ICANN DOMAINS" in that list); or a TLD managed by Nomulus (in-bailiwick), found
    // by #findTldForName; or just the last part of a domain name.
    InternetDomainName effectiveTld =
        hostName.isUnderRegistrySuffix()
            ? hostName.registrySuffix()
            : findTldForName(hostName).orElse(InternetDomainName.from("invalid"));
    // Checks whether a hostname is deep enough. Technically a host can be just one level beneath
    // the effective TLD (e.g. example.com) but we require by policy that it has to be at least
    // one part beyond that (e.g. ns1.example.com).
    if (hostName.parts().size() < effectiveTld.parts().size() + 2) {
      throw new HostNameTooShallowException();
    }
    return hostName;
  } catch (IllegalArgumentException e) {
    throw new InvalidHostNameException();
  }
}
 
Example 10
Source File: RegistrarSettingsAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if any changes were made to the registrar besides the lastUpdateTime, and if so,
 * sends an email with a diff of the changes to the configured notification email address and all
 * contact addresses and enqueues a task to re-sync the registrar sheet.
 */
private void sendExternalUpdatesIfNecessary(
    Registrar existingRegistrar,
    ImmutableSet<RegistrarContact> existingContacts,
    Registrar updatedRegistrar,
    ImmutableSet<RegistrarContact> updatedContacts) {
  if (!sendEmailUtils.hasRecipients() && existingContacts.isEmpty()) {
    return;
  }

  Map<?, ?> diffs =
      DiffUtils.deepDiff(
          expandRegistrarWithContacts(existingContacts, existingRegistrar),
          expandRegistrarWithContacts(updatedContacts, updatedRegistrar),
          true);
  @SuppressWarnings("unchecked")
  Set<String> changedKeys = (Set<String>) diffs.keySet();
  if (CollectionUtils.difference(changedKeys, "lastUpdateTime").isEmpty()) {
    return;
  }
  enqueueRegistrarSheetSync(appEngineServiceUtils.getCurrentVersionHostname("backend"));
  String environment = Ascii.toLowerCase(String.valueOf(RegistryEnvironment.get()));
  sendEmailUtils.sendEmail(
      String.format(
          "Registrar %s (%s) updated in registry %s environment",
          existingRegistrar.getRegistrarName(), existingRegistrar.getClientId(), environment),
      String.format(
          "The following changes were made in registry %s environment to "
              + "the registrar %s by %s:\n\n%s",
          environment,
          existingRegistrar.getClientId(),
          authResult.userIdForLogging(),
          DiffUtils.prettyPrintDiffedMap(diffs, null)),
      existingContacts.stream()
          .filter(c -> c.getTypes().contains(Type.ADMIN))
          .map(RegistrarContact::getEmailAddress)
          .collect(toImmutableList()));
}
 
Example 11
Source File: TypeStringProvider.java    From immutables with Apache License 2.0 5 votes vote down vote up
void process() {
  if (startType.getKind().isPrimitive()) {
    // taking a shortcut for primitives
    String typeName = Ascii.toLowerCase(startType.getKind().name());
    this.rawTypeName = typeName;
    this.returnTypeName = typeName;
    List<? extends AnnotationMirror> annotations = AnnotationMirrors.from(startType);
    if (!annotations.isEmpty()) {
      returnTypeName = typeAnnotationsToBuffer(annotations, false).append(typeName).toString();
    }
  } else {
    this.buffer = new StringBuilder(100);
    caseType(startType);

    if (workaroundTypeString != null) {
      // to not mix the mess, we just replace buffer with workaround produced type string
      this.buffer = new StringBuilder(workaroundTypeString);
    }

    // It seems that array type annotations are not exposed in javac
    // Nested type argument's type annotations are not exposed as well (in javac)
    // So currently we instert only for top level, declared type (here),
    // and primitives (see above)
    TypeKind k = startType.getKind();
    if (k == TypeKind.DECLARED || k == TypeKind.ERROR) {
      insertTypeAnnotationsIfPresent(startType, 0, rawTypeName.length());
    }

    this.returnTypeName = buffer.toString();
  }
}
 
Example 12
Source File: FeeExtensionCommandDescriptor.java    From nomulus with Apache License 2.0 5 votes vote down vote up
public static FeeExtensionCommandDescriptor
    create(CommandName commandName, String phase, String subphase) {
  FeeExtensionCommandDescriptor commandDescriptor = new FeeExtensionCommandDescriptor();
  commandDescriptor.command = Ascii.toLowerCase(commandName.name());
  commandDescriptor.phase = phase;
  commandDescriptor.subphase = subphase;
  return commandDescriptor;
}
 
Example 13
Source File: StringModule.java    From bazel with Apache License 2.0 5 votes vote down vote up
@StarlarkMethod(
    name = "capitalize",
    doc =
        "Returns a copy of the string with its first character (if any) capitalized and the rest "
            + "lowercased. This method does not support non-ascii characters. ",
    parameters = {@Param(name = "self", type = String.class, doc = "This string.")})
public String capitalize(String self) throws EvalException {
  if (self.isEmpty()) {
    return self;
  }
  return Character.toUpperCase(self.charAt(0)) + Ascii.toLowerCase(self.substring(1));
}
 
Example 14
Source File: DnsEndpointGroupBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
DnsEndpointGroupBuilder(String hostname) {
    this.hostname = Ascii.toLowerCase(IDN.toASCII(requireNonNull(hostname, "hostname"),
                                                  IDN.ALLOW_UNASSIGNED));
}
 
Example 15
Source File: FeeCheckResponseExtensionItemCommandV12.java    From nomulus with Apache License 2.0 4 votes vote down vote up
public Builder setCommandName(CommandName commandName) {
  getInstance().commandName = Ascii.toLowerCase(commandName.name());
  return this;
}
 
Example 16
Source File: MediaType.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private static String normalizeParameterValue(String attribute, String value) {
  return CHARSET_ATTRIBUTE.equals(attribute) ? Ascii.toLowerCase(value) : value;
}
 
Example 17
Source File: MediaType.java    From codebuff with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private static String normalizeToken(String token) {
  checkArgument(TOKEN_MATCHER.matchesAllOf(token));
  return Ascii.toLowerCase(token);
}
 
Example 18
Source File: TurbineTypeMirror.java    From turbine with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
  return Ascii.toLowerCase(type.primkind().toString());
}
 
Example 19
Source File: NullSafeAscii.java    From sfs with Apache License 2.0 4 votes vote down vote up
public static String toLowerCase(String string) {
    if (string != null) {
        return Ascii.toLowerCase(string);
    }
    return null;
}
 
Example 20
Source File: BuildApksCommand.java    From bundletool with Apache License 2.0 votes vote down vote up
public final String getLowerCaseName() {
  return Ascii.toLowerCase(name());
}