下面列出了怎么用com.google.common.base.Ascii的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
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();
}
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);
}
@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;
}
/**
* 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();
}
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);
}
}
}
/**
* 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();
}
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);
}
/**
* 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();
}
}
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();
}
/**
* 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();
}
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());
}
@AutoCodec.Instantiator
public BlazeDirectories(
ServerDirectories serverDirectories,
Path workspace,
Path defaultSystemJavabase,
String productName) {
this.serverDirectories = serverDirectories;
this.workspace = workspace;
this.defaultSystemJavabase = defaultSystemJavabase;
this.productName = productName;
Path outputBase = serverDirectories.getOutputBase();
if (Ascii.equalsIgnoreCase(productName, "blaze")) {
boolean useDefaultExecRootName =
this.workspace == null || this.workspace.getParentDirectory() == null;
if (useDefaultExecRootName) {
// TODO(bazel-team): if workspace is null execRoot should be null, but at the moment there
// is a lot of code that depends on it being non-null.
this.blazeExecRoot = serverDirectories.getExecRootBase().getChild(DEFAULT_EXEC_ROOT);
} else {
this.blazeExecRoot = serverDirectories.getExecRootBase().getChild(workspace.getBaseName());
}
this.blazeOutputPath = blazeExecRoot.getRelative(getRelativeOutputPath());
} else {
this.blazeExecRoot = null;
this.blazeOutputPath = null;
}
this.localOutputPath = outputBase.getRelative(getRelativeOutputPath());
}
private static @Nullable RegistrarAddress toNewAddress(
@Nullable Map<String, ?> args,
final FormField<List<String>, List<String>> streetField,
final FormField<String, String> cityField,
final FormField<String, String> stateField,
final FormField<String, String> zipField) {
if (args == null) {
return null;
}
RegistrarAddress.Builder builder = new RegistrarAddress.Builder();
String countryCode = COUNTRY_CODE_FIELD.extractUntyped(args).get();
builder.setCountryCode(countryCode);
streetField
.extractUntyped(args)
.ifPresent(streets -> builder.setStreet(ImmutableList.copyOf(streets)));
cityField.extractUntyped(args).ifPresent(builder::setCity);
Optional<String> stateFieldValue = stateField.extractUntyped(args);
if (stateFieldValue.isPresent()) {
String state = stateFieldValue.get();
if ("US".equals(countryCode)) {
state = Ascii.toUpperCase(state);
if (!StateCode.US_MAP.containsKey(state)) {
throw new FormFieldException(stateField, "Unknown US state code.");
}
}
builder.setState(state);
}
zipField.extractUntyped(args).ifPresent(builder::setZip);
return builder.build();
}
private static String getMinicapFilePath(Device device, String minicapBasePath) {
String minicapVersionSuffix = device.getSdkVersion();
String abi = device.getAbi();
String buildId = device.getBuildId();
Integer sdkIntVersion = Ints.tryParse(minicapVersionSuffix);
// For PPR1, the standard minicap.so for android-28 doesn't work. Keep this logic here since
// there are still some devices in PPR1.
if (Ascii.toUpperCase(buildId).contains("PPR1")
|| Ascii.toUpperCase(device.getReleaseVersion()).equals("9")) {
minicapVersionSuffix = "28-ppr1";
}
List<String> androidRBuildIdKeyWordList = Arrays.asList("MASTER", "RP1A");
boolean isAndroidRBranch =
androidRBuildIdKeyWordList.stream()
.parallel()
.anyMatch(x -> Ascii.toUpperCase(buildId).contains(x));
// 29 (Android Q) is the max version minicap currently supports.
if (sdkIntVersion == null
|| sdkIntVersion > 29
|| isAndroidRBranch
|| Ascii.equalsIgnoreCase(device.getReleaseVersion(), "11")) {
minicapVersionSuffix = "master";
}
return Paths.get(
minicapBasePath,
"jni",
"minicap-shared",
"aosp",
"libs",
"android-" + minicapVersionSuffix,
abi,
"minicap.so")
.toString();
}
/**
* Returns a new {@link ClassName} instance for the given fully-qualified class name string. This
* method assumes that the input is ASCII and follows typical Java style (lower-case package
* names, upper-camel-case class names) and may produce incorrect results or throw
* {@link IllegalArgumentException} otherwise. For that reason, {@link #fromClass(Class)} and
* {@link #fromClass(Class)} should be preferred as they can correctly create {@link ClassName}
* instances without such restrictions.
*/
public static ClassName bestGuessFromString(String classNameString) {
checkNotNull(classNameString);
List<String> parts = Splitter.on('.').splitToList(classNameString);
int firstClassPartIndex = -1;
for (int i = 0; i < parts.size(); i++) {
String part = parts.get(i);
checkArgument(SourceVersion.isIdentifier(part));
char firstChar = part.charAt(0);
if (Ascii.isLowerCase(firstChar)) {
// looks like a package part
if (firstClassPartIndex >= 0) {
throw new IllegalArgumentException("couldn't make a guess for " + classNameString);
}
} else if (Ascii.isUpperCase(firstChar)) {
// looks like a class part
if (firstClassPartIndex < 0) {
firstClassPartIndex = i;
}
} else {
throw new IllegalArgumentException("couldn't make a guess for " + classNameString);
}
}
int lastIndex = parts.size() - 1;
return new ClassName(
Joiner.on('.').join(parts.subList(0, firstClassPartIndex)),
firstClassPartIndex == lastIndex
? ImmutableList.<String>of()
: ImmutableList.copyOf(parts.subList(firstClassPartIndex, lastIndex)),
parts.get(lastIndex));
}
@Override
protected String execute() throws Exception {
RegistryToolEnvironment currentEnvironment = RegistryToolEnvironment.get();
// Extra confirmation for running in production
checkArgument(
!currentEnvironment.equals(RegistryToolEnvironment.PRODUCTION)
|| confirmProductionImport.equals("PRODUCTION"),
"The confirm_production_import option must be set when restoring production environment.");
Operation importOperation = datastoreAdmin.importBackup(backupUrl, kinds).execute();
String statusCommand =
String.format(
"nomulus -e %s get_operation_status %s",
Ascii.toLowerCase(currentEnvironment.name()), importOperation.getName());
if (async) {
return String.format(
"Datastore import started. Run this command to check its progress:\n%s",
statusCommand);
}
System.out.println(
"Waiting for import to complete.\n"
+ "You may press Ctrl-C at any time, and use this command to check progress:\n"
+ statusCommand);
while (importOperation.isProcessing()) {
waitInteractively(pollingInterval);
importOperation = datastoreAdmin.get(importOperation.getName()).execute();
System.out.printf("\n%s\n", importOperation.getProgress());
}
return String.format(
"\nDatastore import %s %s.",
importOperation.getName(), importOperation.isSuccessful() ? "succeeded" : "failed");
}
/**
* Returns the type of the certificate based on its hash.
*
* @throws IllegalArgumentException if the SHA hash is neither SHA-1 nor SHA-256
*/
@VisibleForTesting
static ShaCertificateType getTypeFromHash(String shaHash) {
Preconditions.checkNotNull(shaHash, "Null shaHash");
shaHash = Ascii.toLowerCase(shaHash);
if (SHA1_PATTERN.matcher(shaHash).matches()) {
return ShaCertificateType.SHA_1;
} else if (SHA256_PATTERN.matcher(shaHash).matches()) {
return ShaCertificateType.SHA_256;
}
throw new IllegalArgumentException("Invalid SHA hash; it is neither SHA-1 nor SHA-256.");
}
@Nullable
static MediaType guessFromPath(String path, @Nullable String contentEncoding) {
if (contentEncoding == null || Ascii.equalsIgnoreCase(contentEncoding, "identity")) {
return guessFromPath(path);
}
requireNonNull(path, "path");
// If the path is for a precompressed file, it will have an additional extension indicating the
// encoding, which we don't want to use when determining content type.
return guessFromPath(path.substring(0, path.lastIndexOf('.')));
}
@Override
public PythonVersion convert(String input) throws OptionsParsingException {
try {
// Although in rule attributes the enum values are case sensitive, the convention from
// EnumConverter is that the options parser is case insensitive.
input = Ascii.toUpperCase(input);
return PythonVersion.parseTargetValue(input);
} catch (IllegalArgumentException ex) {
throw new OptionsParsingException(
"Not a valid Python major version, should be PY2 or PY3", ex);
}
}
public String apply(String input) {
if (!input.isEmpty()) {
if (this == CAPITALIZED && !Ascii.isUpperCase(input.charAt(0))) {
return CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, input);
}
if (this == LOWERIZED && !Ascii.isLowerCase(input.charAt(0))) {
return CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, input);
}
}
return input;
}
public void hasSameContentAs(List<String> expectedContent) {
checkNotNull(expectedContent, "expectedContent");
ImmutableList<String> expected = ImmutableList.copyOf(expectedContent);
if (expected.equals(actual)) {
return;
}
String diffString = diffFormat.generateDiff(expected, actual);
failWithoutActual(
Fact.simpleFact(
Joiner.on('\n')
.join(
"Files differ in content. Displaying " + Ascii.toLowerCase(diffFormat.name()),
diffString)));
}
Alphabet lowerCase() {
if (!hasUpperCase()) {
return this;
} else {
checkState(!hasLowerCase(), "Cannot call lowerCase() on a mixed-case alphabet");
char[] lowerCased = new char[chars.length];
for (int i = 0; i < chars.length; i++) {
lowerCased[i] = Ascii.toLowerCase(chars[i]);
}
return new Alphabet(name + ".lowerCase()", lowerCased);
}
}
int decode(char ch) throws DecodingException {
if (ch > Ascii.MAX || decodabet[ch] == -1) {
throw new DecodingException(
"Unrecognized character: "
+ (CharMatcher.invisible().matches(ch) ? "0x" + Integer.toHexString(ch) : ch));
}
return decodabet[ch];
}
@Override
public String toString() {
List<String> path = Splitter.on('.').splitToList(qualifiedTemplateClass());
for (int topLevel = 0; topLevel < path.size() - 1; topLevel++) {
if (Ascii.isUpperCase(path.get(topLevel).charAt(0))) {
return Joiner.on('_').join(path.subList(topLevel + 1, path.size()));
}
}
return qualifiedTemplateClass();
}
@Before
public void setUp() {
persistResource(
newRegistry(
TLD_REAL,
Ascii.toUpperCase(TLD_REAL),
ImmutableSortedMap.of(START_OF_TIME, GENERAL_AVAILABILITY),
TldType.REAL));
persistResource(
newRegistry(
TLD_TEST,
Ascii.toUpperCase(TLD_TEST),
ImmutableSortedMap.of(START_OF_TIME, GENERAL_AVAILABILITY),
TldType.TEST));
}
@Override
public String apply(DependencyRequest dependency) {
String variableName = dependency.requestElement().getSimpleName().toString();
switch (dependency.kind()) {
case INSTANCE:
return variableName;
case LAZY:
return variableName.startsWith("lazy") && !variableName.equals("lazy")
? Ascii.toLowerCase(variableName.charAt(4)) + variableName.substring(5)
: variableName;
case PROVIDER:
return variableName.endsWith("Provider") && !variableName.equals("Provider")
? variableName.substring(0, variableName.length() - 8)
: variableName;
case MEMBERS_INJECTOR:
return variableName.endsWith("MembersInjector") && !variableName.equals("MembersInjector")
? variableName.substring(0, variableName.length() - 15)
: variableName;
case PRODUCED:
return variableName.startsWith("produced") && !variableName.equals("produced")
? Ascii.toLowerCase(variableName.charAt(8)) + variableName.substring(9)
: variableName;
case PRODUCER:
return variableName.endsWith("Producer") && !variableName.equals("Producer")
? variableName.substring(0, variableName.length() - 8)
: variableName;
default:
throw new AssertionError();
}
}
/**
* 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()));
}
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);
}
}
AbstractCorsPolicyBuilder(List<String> origins) {
requireNonNull(origins, "origins");
checkArgument(!origins.isEmpty(), "origins is empty.");
for (int i = 0; i < origins.size(); i++) {
if (origins.get(i) == null) {
throw new NullPointerException("origins[" + i + ']');
}
}
this.origins = origins.stream().map(Ascii::toLowerCase).collect(toImmutableSet());
}