diff --git a/kms/src/main/java/com/example/Asymmetric.java b/kms/src/main/java/com/example/Asymmetric.java
index dc8b59d928b..5ef4ae786e7 100644
--- a/kms/src/main/java/com/example/Asymmetric.java
+++ b/kms/src/main/java/com/example/Asymmetric.java
@@ -28,7 +28,6 @@
import com.google.cloud.kms.v1.KeyRingName;
import com.google.common.io.BaseEncoding;
import com.google.protobuf.ByteString;
-
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
@@ -42,15 +41,13 @@
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
-//CHECKSTYLE OFF: AbbreviationAsWordInName
+// CHECKSTYLE OFF: AbbreviationAsWordInName
public class Asymmetric {
// [START kms_create_asymmetric_key]
- /**
- * Creates an RSA encrypt/decrypt key pair with the given id.
- */
- public static CryptoKey createAsymmetricKey(String projectId, String locationId, String keyRingId,
- String cryptoKeyId)
+ /** Creates an RSA encrypt/decrypt key pair with the given id. */
+ public static CryptoKey createAsymmetricKey(
+ String projectId, String locationId, String keyRingId, String cryptoKeyId)
throws IOException {
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
@@ -59,13 +56,10 @@ public static CryptoKey createAsymmetricKey(String projectId, String locationId,
CryptoKeyPurpose purpose = CryptoKeyPurpose.ASYMMETRIC_DECRYPT;
CryptoKeyVersionAlgorithm algorithm = CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256;
- CryptoKeyVersionTemplate version = CryptoKeyVersionTemplate.newBuilder()
- .setAlgorithm(algorithm)
- .build();
- CryptoKey cryptoKey = CryptoKey.newBuilder()
- .setPurpose(purpose)
- .setVersionTemplate(version)
- .build();
+ CryptoKeyVersionTemplate version =
+ CryptoKeyVersionTemplate.newBuilder().setAlgorithm(algorithm).build();
+ CryptoKey cryptoKey =
+ CryptoKey.newBuilder().setPurpose(purpose).setVersionTemplate(version).build();
CryptoKey createdKey = client.createCryptoKey(parent, cryptoKeyId, cryptoKey);
@@ -78,10 +72,10 @@ public static CryptoKey createAsymmetricKey(String projectId, String locationId,
/**
* Retrieves the public key from a saved asymmetric key pair on Cloud KMS
*
- * Example keyName:
- * "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
+ * Example keyName:
+ * "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
*/
- public static PublicKey getAsymmetricPublicKey(String keyName)
+ public static PublicKey getAsymmetricPublicKey(String keyName)
throws IOException, GeneralSecurityException {
// Create the Cloud KMS client.
@@ -102,8 +96,9 @@ public static PublicKey getAsymmetricPublicKey(String keyName)
} else if (pub.getAlgorithm().name().contains("EC")) {
return KeyFactory.getInstance("EC").generatePublic(keySpec);
} else {
- throw new UnsupportedOperationException(String.format(
- "key at path '%s' is of unsupported type '%s'.", keyName, pub.getAlgorithm()));
+ throw new UnsupportedOperationException(
+ String.format(
+ "key at path '%s' is of unsupported type '%s'.", keyName, pub.getAlgorithm()));
}
}
}
@@ -111,17 +106,17 @@ public static PublicKey getAsymmetricPublicKey(String keyName)
// [START kms_decrypt_rsa]
/**
- * Decrypt a given ciphertext using an 'RSA_DECRYPT_OAEP_2048_SHA256' private key
- * stored on Cloud KMS
+ * Decrypt a given ciphertext using an 'RSA_DECRYPT_OAEP_2048_SHA256' private key stored on Cloud
+ * KMS
*
- * Example keyName:
- * "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
+ *
Example keyName:
+ * "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
*/
public static byte[] decryptRSA(String keyName, byte[] ciphertext) throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
- AsymmetricDecryptResponse response = client.asymmetricDecrypt(
- keyName, ByteString.copyFrom(ciphertext));
+ AsymmetricDecryptResponse response =
+ client.asymmetricDecrypt(keyName, ByteString.copyFrom(ciphertext));
return response.getPlaintext().toByteArray();
}
}
@@ -129,13 +124,13 @@ public static byte[] decryptRSA(String keyName, byte[] ciphertext) throws IOExce
// [START kms_encrypt_rsa]
/**
- * Encrypt data locally using an 'RSA_DECRYPT_OAEP_2048_SHA256' public key
- * retrieved from Cloud KMS
+ * Encrypt data locally using an 'RSA_DECRYPT_OAEP_2048_SHA256' public key retrieved from Cloud
+ * KMS
*
- * Example keyName:
- * "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
+ *
Example keyName:
+ * "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
*/
- public static byte[] encryptRSA(String keyName, byte[] plaintext)
+ public static byte[] encryptRSA(String keyName, byte[] plaintext)
throws IOException, GeneralSecurityException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
@@ -153,8 +148,9 @@ public static byte[] encryptRSA(String keyName, byte[] plaintext)
// For other key algorithms:
// https://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
- OAEPParameterSpec oaepParams = new OAEPParameterSpec(
- "SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
+ OAEPParameterSpec oaepParams =
+ new OAEPParameterSpec(
+ "SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT);
cipher.init(Cipher.ENCRYPT_MODE, rsaKey, oaepParams);
return cipher.doFinal(plaintext);
@@ -164,10 +160,10 @@ public static byte[] encryptRSA(String keyName, byte[] plaintext)
// [START kms_sign_asymmetric]
/**
- * Create a signature for a message using a private key stored on Cloud KMS
+ * Create a signature for a message using a private key stored on Cloud KMS
*
- * Example keyName:
- * "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
+ *
Example keyName:
+ * "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
*/
public static byte[] signAsymmetric(String keyName, byte[] message)
throws IOException, NoSuchAlgorithmException {
@@ -178,10 +174,11 @@ public static byte[] signAsymmetric(String keyName, byte[] message)
// For example, EC_SIGN_P384_SHA384 requires SHA-384
byte[] messageHash = MessageDigest.getInstance("SHA-256").digest(message);
- AsymmetricSignRequest request = AsymmetricSignRequest.newBuilder()
- .setName(keyName)
- .setDigest(Digest.newBuilder().setSha256(ByteString.copyFrom(messageHash)))
- .build();
+ AsymmetricSignRequest request =
+ AsymmetricSignRequest.newBuilder()
+ .setName(keyName)
+ .setDigest(Digest.newBuilder().setSha256(ByteString.copyFrom(messageHash)))
+ .build();
AsymmetricSignResponse response = client.asymmetricSign(request);
return response.getSignature().toByteArray();
@@ -191,11 +188,10 @@ public static byte[] signAsymmetric(String keyName, byte[] message)
// [START kms_verify_signature_rsa]
/**
- * Verify the validity of an 'RSA_SIGN_PKCS1_2048_SHA256' signature for the
- * specified message
+ * Verify the validity of an 'RSA_SIGN_PKCS1_2048_SHA256' signature for the specified message
*
- * Example keyName:
- * "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
+ *
Example keyName:
+ * "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
*/
public static boolean verifySignatureRSA(String keyName, byte[] message, byte[] signature)
throws IOException, GeneralSecurityException {
@@ -224,12 +220,11 @@ public static boolean verifySignatureRSA(String keyName, byte[] message, byte[]
// [END kms_verify_signature_rsa]
// [START kms_verify_signature_ec]
- /**
- * Verify the validity of an 'EC_SIGN_P256_SHA256' signature for the
- * specified message
+ /**
+ * Verify the validity of an 'EC_SIGN_P256_SHA256' signature for the specified message
*
- * Example keyName:
- * "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
+ *
Example keyName:
+ * "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys/KEY_ID/cryptoKeyVersions/1"
*/
public static boolean verifySignatureEC(String keyName, byte[] message, byte[] signature)
throws IOException, GeneralSecurityException {
@@ -257,5 +252,4 @@ public static boolean verifySignatureEC(String keyName, byte[] message, byte[] s
}
// [END kms_verify_signature_ec]
}
-//CHECKSTYLE ON: AbbreviationAsWordInName
-
+// CHECKSTYLE ON: AbbreviationAsWordInName
diff --git a/kms/src/main/java/com/example/CryptFile.java b/kms/src/main/java/com/example/CryptFile.java
index 26e39152ff6..1f0117ed62d 100644
--- a/kms/src/main/java/com/example/CryptFile.java
+++ b/kms/src/main/java/com/example/CryptFile.java
@@ -21,7 +21,6 @@
import com.google.cloud.kms.v1.EncryptResponse;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.protobuf.ByteString;
-
import java.io.IOException;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
@@ -30,9 +29,7 @@ public class CryptFile {
// [START kms_encrypt]
- /**
- * Encrypts the given plaintext using the specified crypto key.
- */
+ /** Encrypts the given plaintext using the specified crypto key. */
public static byte[] encrypt(
String projectId, String locationId, String keyRingId, String cryptoKeyId, byte[] plaintext)
throws IOException {
@@ -54,9 +51,7 @@ public static byte[] encrypt(
// [START kms_decrypt]
- /**
- * Decrypts the provided ciphertext with the specified crypto key.
- */
+ /** Decrypts the provided ciphertext with the specified crypto key. */
public static byte[] decrypt(
String projectId, String locationId, String keyRingId, String cryptoKeyId, byte[] ciphertext)
throws IOException {
diff --git a/kms/src/main/java/com/example/CryptFileCommands.java b/kms/src/main/java/com/example/CryptFileCommands.java
index 7a418e37b7a..b2060da6bed 100644
--- a/kms/src/main/java/com/example/CryptFileCommands.java
+++ b/kms/src/main/java/com/example/CryptFileCommands.java
@@ -26,13 +26,9 @@
import org.kohsuke.args4j.spi.SubCommandHandler;
import org.kohsuke.args4j.spi.SubCommands;
-/**
- * Defines the different sub-commands and their parameters, for command-line invocation.
- */
+/** Defines the different sub-commands and their parameters, for command-line invocation. */
class CryptFileCommands {
- /**
- * An interface for a command-line sub-command.
- */
+ /** An interface for a command-line sub-command. */
interface Command {
void run() throws IOException;
}
@@ -42,22 +38,28 @@ interface Command {
static class Args {
@Option(name = "--project-id", aliases = "-p", required = true, usage = "Your GCP project ID")
String projectId;
+
@Argument(metaVar = "locationId", required = true, index = 0, usage = "The key location")
String locationId;
+
@Argument(metaVar = "keyRingId", required = true, index = 1, usage = "The key ring id")
String keyRingId;
+
@Argument(metaVar = "cryptoKeyId", required = true, index = 2, usage = "The crypto key id")
String cryptoKeyId;
+
@Argument(metaVar = "inFile", required = true, index = 3, usage = "The source file")
String inFile;
+
@Argument(metaVar = "outFile", required = true, index = 4, usage = "The destination file")
String outFile;
}
public static class EncryptCommand extends Args implements Command {
public void run() throws IOException {
- byte[] encrypted = CryptFile.encrypt(
- projectId, locationId, keyRingId, cryptoKeyId, Files.readAllBytes(Paths.get(inFile)));
+ byte[] encrypted =
+ CryptFile.encrypt(
+ projectId, locationId, keyRingId, cryptoKeyId, Files.readAllBytes(Paths.get(inFile)));
try (FileOutputStream stream = new FileOutputStream(outFile)) {
stream.write(encrypted);
@@ -67,8 +69,9 @@ public void run() throws IOException {
public static class DecryptCommand extends Args implements Command {
public void run() throws IOException {
- byte[] decrypted = CryptFile.decrypt(
- projectId, locationId, keyRingId, cryptoKeyId, Files.readAllBytes(Paths.get(inFile)));
+ byte[] decrypted =
+ CryptFile.decrypt(
+ projectId, locationId, keyRingId, cryptoKeyId, Files.readAllBytes(Paths.get(inFile)));
try (FileOutputStream stream = new FileOutputStream(outFile)) {
stream.write(decrypted);
@@ -76,11 +79,14 @@ public void run() throws IOException {
}
}
- @Argument(metaVar = "command", required = true, handler = SubCommandHandler.class,
+ @Argument(
+ metaVar = "command",
+ required = true,
+ handler = SubCommandHandler.class,
usage = "The subcommand to run")
@SubCommands({
@SubCommand(name = "encrypt", impl = EncryptCommand.class),
@SubCommand(name = "decrypt", impl = DecryptCommand.class)
- })
+ })
Command command;
}
diff --git a/kms/src/main/java/com/example/Quickstart.java b/kms/src/main/java/com/example/Quickstart.java
index bdadb770424..e27b513e94e 100644
--- a/kms/src/main/java/com/example/Quickstart.java
+++ b/kms/src/main/java/com/example/Quickstart.java
@@ -19,17 +19,11 @@
// [START kms_quickstart]
// Imports the Google Cloud client library
-import com.google.api.gax.core.CredentialsProvider;
-import com.google.api.gax.core.GoogleCredentialsProvider;
-import com.google.auth.Credentials;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyManagementServiceClient.ListKeyRingsPagedResponse;
-import com.google.cloud.kms.v1.KeyManagementServiceSettings;
import com.google.cloud.kms.v1.KeyRing;
import com.google.cloud.kms.v1.LocationName;
-import java.io.IOException;
-
public class Quickstart {
public static void main(String... args) throws Exception {
diff --git a/kms/src/main/java/com/example/SnippetCommands.java b/kms/src/main/java/com/example/SnippetCommands.java
index 81a862a44aa..c71fe1dff08 100644
--- a/kms/src/main/java/com/example/SnippetCommands.java
+++ b/kms/src/main/java/com/example/SnippetCommands.java
@@ -23,13 +23,9 @@
import org.kohsuke.args4j.spi.SubCommandHandler;
import org.kohsuke.args4j.spi.SubCommands;
-/**
- * Defines the different sub-commands and their parameters, for command-line invocation.
- */
+/** Defines the different sub-commands and their parameters, for command-line invocation. */
class SnippetCommands {
- /**
- * An interface for a command-line sub-command.
- */
+ /** An interface for a command-line sub-command. */
interface Command {
void run() throws IOException;
}
@@ -61,7 +57,6 @@ static class KeyVersionArgs extends KeyArgs {
String version;
}
-
public static class CreateKeyRingCommand extends KeyRingArgs implements Command {
public void run() throws IOException {
Snippets.createKeyRing(projectId, locationId, keyRingId);
@@ -142,14 +137,23 @@ public void run() throws IOException {
}
public static class AddMemberToKeyRingPolicyCommand extends KeyRingArgs implements Command {
- @Argument(metaVar = "member", required = true, index = 1,
- usage = "The member to add.\n"
- + "See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding "
- + "for valid values.")
+ @Argument(
+ metaVar = "member",
+ required = true,
+ index = 1,
+ usage =
+ "The member to add.\n"
+ + "See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding "
+ + "for valid values.")
String member;
- @Argument(metaVar = "role", required = true, index = 2,
- usage = "The role for the member.\n"
- + "See https://g.co/cloud/iam/docs/understanding-roles for valid values.")
+
+ @Argument(
+ metaVar = "role",
+ required = true,
+ index = 2,
+ usage =
+ "The role for the member.\n"
+ + "See https://g.co/cloud/iam/docs/understanding-roles for valid values.")
String role;
public void run() throws IOException {
@@ -158,31 +162,49 @@ public void run() throws IOException {
}
public static class AddMemberToCryptoKeyPolicyCommand extends KeyArgs implements Command {
- @Argument(metaVar = "member", required = true, index = 2,
- usage = "The member to add.\n"
- + "See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding "
- + "for valid values.")
+ @Argument(
+ metaVar = "member",
+ required = true,
+ index = 2,
+ usage =
+ "The member to add.\n"
+ + "See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding "
+ + "for valid values.")
String member;
- @Argument(metaVar = "role", required = true, index = 3,
- usage = "The role for the member.\n"
- + "See https://g.co/cloud/iam/docs/understanding-roles for valid values.")
+
+ @Argument(
+ metaVar = "role",
+ required = true,
+ index = 3,
+ usage =
+ "The role for the member.\n"
+ + "See https://g.co/cloud/iam/docs/understanding-roles for valid values.")
String role;
public void run() throws IOException {
- Snippets
- .addMemberToCryptoKeyPolicy(projectId, locationId, keyRingId, cryptoKeyId, member, role);
+ Snippets.addMemberToCryptoKeyPolicy(
+ projectId, locationId, keyRingId, cryptoKeyId, member, role);
}
}
public static class RemoveMemberFromKeyRingPolicyCommand extends KeyRingArgs implements Command {
- @Argument(metaVar = "member", required = true, index = 1,
- usage = "The member to add.\n"
- + "See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding "
- + "for valid values.")
+ @Argument(
+ metaVar = "member",
+ required = true,
+ index = 1,
+ usage =
+ "The member to add.\n"
+ + "See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding "
+ + "for valid values.")
String member;
- @Argument(metaVar = "role", required = true, index = 2,
- usage = "The role for the member.\n"
- + "See https://g.co/cloud/iam/docs/understanding-roles for valid values.")
+
+ @Argument(
+ metaVar = "role",
+ required = true,
+ index = 2,
+ usage =
+ "The role for the member.\n"
+ + "See https://g.co/cloud/iam/docs/understanding-roles for valid values.")
String role;
public void run() throws IOException {
@@ -191,24 +213,35 @@ public void run() throws IOException {
}
public static class RemoveMemberFromCryptoKeyPolicyCommand extends KeyArgs implements Command {
- @Argument(metaVar = "member", required = true, index = 2,
- usage = "The member to add.\n"
- + "See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding "
- + "for valid values.")
+ @Argument(
+ metaVar = "member",
+ required = true,
+ index = 2,
+ usage =
+ "The member to add.\n"
+ + "See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding "
+ + "for valid values.")
String member;
- @Argument(metaVar = "role", required = true, index = 3,
- usage = "The role for the member.\n"
- + "See https://g.co/cloud/iam/docs/understanding-roles for valid values.")
+
+ @Argument(
+ metaVar = "role",
+ required = true,
+ index = 3,
+ usage =
+ "The role for the member.\n"
+ + "See https://g.co/cloud/iam/docs/understanding-roles for valid values.")
String role;
public void run() throws IOException {
- Snippets
- .removeMemberFromCryptoKeyPolicy(projectId, locationId, keyRingId, cryptoKeyId, member,
- role);
+ Snippets.removeMemberFromCryptoKeyPolicy(
+ projectId, locationId, keyRingId, cryptoKeyId, member, role);
}
}
- @Argument(metaVar = "command", required = true, handler = SubCommandHandler.class,
+ @Argument(
+ metaVar = "command",
+ required = true,
+ handler = SubCommandHandler.class,
usage = "The subcommand to run")
@SubCommands({
@SubCommand(name = "createKeyRing", impl = CreateKeyRingCommand.class),
@@ -225,11 +258,14 @@ public void run() throws IOException {
@SubCommand(name = "getCryptoKeyPolicy", impl = GetCryptoKeyPolicyCommand.class),
@SubCommand(name = "setPrimaryVersion", impl = SetPrimaryVersionCommand.class),
@SubCommand(name = "addMemberToKeyRingPolicy", impl = AddMemberToKeyRingPolicyCommand.class),
- @SubCommand(name = "addMemberToCryptoKeyPolicy",
+ @SubCommand(
+ name = "addMemberToCryptoKeyPolicy",
impl = AddMemberToCryptoKeyPolicyCommand.class),
- @SubCommand(name = "removeMemberFromKeyRingPolicy",
+ @SubCommand(
+ name = "removeMemberFromKeyRingPolicy",
impl = RemoveMemberFromKeyRingPolicyCommand.class),
- @SubCommand(name = "removeMemberFromCryptoKeyPolicy",
+ @SubCommand(
+ name = "removeMemberFromCryptoKeyPolicy",
impl = RemoveMemberFromCryptoKeyPolicyCommand.class)
})
Command command;
diff --git a/kms/src/main/java/com/example/Snippets.java b/kms/src/main/java/com/example/Snippets.java
index 7499fa25a5d..eef7d67b972 100644
--- a/kms/src/main/java/com/example/Snippets.java
+++ b/kms/src/main/java/com/example/Snippets.java
@@ -33,11 +33,9 @@
import com.google.iam.v1.Policy;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
@@ -45,9 +43,7 @@ public class Snippets {
// [START kms_create_keyring]
- /**
- * Creates a new key ring with the given id.
- */
+ /** Creates a new key ring with the given id. */
public static KeyRing createKeyRing(String projectId, String locationId, String keyRingId)
throws IOException {
// Create the Cloud KMS client.
@@ -66,11 +62,9 @@ public static KeyRing createKeyRing(String projectId, String locationId, String
// [START kms_create_cryptokey]
- /**
- * Creates a new crypto key with the given id.
- */
- public static CryptoKey createCryptoKey(String projectId, String locationId, String keyRingId,
- String cryptoKeyId)
+ /** Creates a new crypto key with the given id. */
+ public static CryptoKey createCryptoKey(
+ String projectId, String locationId, String keyRingId, String cryptoKeyId)
throws IOException {
// Create the Cloud KMS client.
@@ -79,9 +73,8 @@ public static CryptoKey createCryptoKey(String projectId, String locationId, Str
String parent = KeyRingName.format(projectId, locationId, keyRingId);
// This will allow the API access to the key for encryption and decryption.
- CryptoKey cryptoKey = CryptoKey.newBuilder()
- .setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT)
- .build();
+ CryptoKey cryptoKey =
+ CryptoKey.newBuilder().setPurpose(CryptoKeyPurpose.ENCRYPT_DECRYPT).build();
// Create the CryptoKey for your project.
CryptoKey createdKey = client.createCryptoKey(parent, cryptoKeyId, cryptoKey);
@@ -93,9 +86,7 @@ public static CryptoKey createCryptoKey(String projectId, String locationId, Str
// [START kms_create_cryptokey_version]
- /**
- * Creates a new crypto key version for the given id.
- */
+ /** Creates a new crypto key version for the given id. */
public static CryptoKeyVersion createCryptoKeyVersion(
String projectId, String locationId, String keyRingId, String cryptoKeyId)
throws IOException {
@@ -115,9 +106,7 @@ public static CryptoKeyVersion createCryptoKeyVersion(
// [START kms_disable_cryptokey_version]
- /**
- * Disables the given version of the crypto key.
- */
+ /** Disables the given version of the crypto key. */
public static CryptoKeyVersion disableCryptoKeyVersion(
String projectId, String locationId, String keyRingId, String cryptoKeyId, String version)
throws IOException {
@@ -125,17 +114,18 @@ public static CryptoKeyVersion disableCryptoKeyVersion(
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
- String versionName = CryptoKeyVersionName.format(
- projectId, locationId, keyRingId, cryptoKeyId, version);
+ String versionName =
+ CryptoKeyVersionName.format(projectId, locationId, keyRingId, cryptoKeyId, version);
// Retrieve the current state
CryptoKeyVersion current = client.getCryptoKeyVersion(versionName);
// Build a copy that updates the state to disabled
- CryptoKeyVersion updated = CryptoKeyVersion.newBuilder()
- .setName(current.getName())
- .setState(CryptoKeyVersionState.DISABLED)
- .build();
+ CryptoKeyVersion updated =
+ CryptoKeyVersion.newBuilder()
+ .setName(current.getName())
+ .setState(CryptoKeyVersionState.DISABLED)
+ .build();
// Create a FieldMask that only allows 'state' to be updated
FieldMask fieldMask = FieldMaskUtil.fromString(CryptoKeyVersion.class, "state");
@@ -149,9 +139,7 @@ public static CryptoKeyVersion disableCryptoKeyVersion(
// [END kms_disable_cryptokey_version]
// [START kms_enable_cryptokey_version]
- /**
- * Enables the given version of the crypto key.
- */
+ /** Enables the given version of the crypto key. */
public static CryptoKeyVersion enableCryptoKeyVersion(
String projectId, String locationId, String keyRingId, String cryptoKeyId, String version)
throws IOException {
@@ -160,17 +148,18 @@ public static CryptoKeyVersion enableCryptoKeyVersion(
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
- String versionName = CryptoKeyVersionName.format(
- projectId, locationId, keyRingId, cryptoKeyId, version);
+ String versionName =
+ CryptoKeyVersionName.format(projectId, locationId, keyRingId, cryptoKeyId, version);
// Retrieve the current state
CryptoKeyVersion current = client.getCryptoKeyVersion(versionName);
// Build a copy that updates the state to enabled
- CryptoKeyVersion updated = CryptoKeyVersion.newBuilder()
- .setName(current.getName())
- .setState(CryptoKeyVersionState.ENABLED)
- .build();
+ CryptoKeyVersion updated =
+ CryptoKeyVersion.newBuilder()
+ .setName(current.getName())
+ .setState(CryptoKeyVersionState.ENABLED)
+ .build();
// Create a FieldMask that only allows 'state' to be updated
FieldMask fieldMask = FieldMaskUtil.fromString(CryptoKeyVersion.class, "state");
@@ -185,9 +174,7 @@ public static CryptoKeyVersion enableCryptoKeyVersion(
// [START kms_destroy_cryptokey_version]
- /**
- * Marks the given version of a crypto key to be destroyed at a scheduled future point.
- */
+ /** Marks the given version of a crypto key to be destroyed at a scheduled future point. */
public static CryptoKeyVersion destroyCryptoKeyVersion(
String projectId, String locationId, String keyRingId, String cryptoKeyId, String version)
throws IOException {
@@ -196,8 +183,8 @@ public static CryptoKeyVersion destroyCryptoKeyVersion(
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
- String versionName = CryptoKeyVersionName.format(
- projectId, locationId, keyRingId, cryptoKeyId, version);
+ String versionName =
+ CryptoKeyVersionName.format(projectId, locationId, keyRingId, cryptoKeyId, version);
// Destroy the cryptoKey version
CryptoKeyVersion destroyed = client.destroyCryptoKeyVersion(versionName);
@@ -209,9 +196,7 @@ public static CryptoKeyVersion destroyCryptoKeyVersion(
// [START kms_restore_cryptokey_version]
- /**
- * Restores the given version of a crypto key that is currently scheduled for destruction.
- */
+ /** Restores the given version of a crypto key that is currently scheduled for destruction. */
public static CryptoKeyVersion restoreCryptoKeyVersion(
String projectId, String locationId, String keyRingId, String cryptoKeyId, String version)
throws IOException {
@@ -220,8 +205,8 @@ public static CryptoKeyVersion restoreCryptoKeyVersion(
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// The resource name of the cryptoKey version
- String versionName = CryptoKeyVersionName.format(
- projectId, locationId, keyRingId, cryptoKeyId, version);
+ String versionName =
+ CryptoKeyVersionName.format(projectId, locationId, keyRingId, cryptoKeyId, version);
CryptoKeyVersion restored = client.restoreCryptoKeyVersion(versionName);
@@ -232,9 +217,7 @@ public static CryptoKeyVersion restoreCryptoKeyVersion(
// [START kms_get_cryptokey_policy]
- /**
- * Retrieves the IAM policy for the given crypto key.
- */
+ /** Retrieves the IAM policy for the given crypto key. */
public static Policy getCryptoKeyPolicy(
String projectId, String locationId, String keyRingId, String cryptoKeyId)
throws IOException {
@@ -255,9 +238,7 @@ public static Policy getCryptoKeyPolicy(
// [START kms_get_keyring_policy]
- /**
- * Retrieves the IAM policy for the given crypto key.
- */
+ /** Retrieves the IAM policy for the given crypto key. */
public static Policy getKeyRingPolicy(String projectId, String locationId, String keyRingId)
throws IOException {
// Create the Cloud KMS client.
@@ -284,17 +265,18 @@ public static Policy getKeyRingPolicy(String projectId, String locationId, Strin
* @param keyRingId The id of the keyring.
* @param cryptoKeyId The id of the crypto key.
* @param member The member to add. Must be in the proper format, eg:
- *
- * allUsers user:$userEmail serviceAccount:$serviceAccountEmail
- *
- * See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding for more details.
+ *
allUsers user:$userEmail serviceAccount:$serviceAccountEmail
+ *
See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding for more details.
* @param role Must be in one of the following formats: roles/[role]
- * organizations/[organizationId]/roles/[role] projects/[projectId]/roles/[role]
- *
- * See https://g.co/cloud/iam/docs/understanding-roles for available values for [role].
+ * organizations/[organizationId]/roles/[role] projects/[projectId]/roles/[role]
+ *
See https://g.co/cloud/iam/docs/understanding-roles for available values for [role].
*/
public static Policy addMemberToCryptoKeyPolicy(
- String projectId, String locationId, String keyRingId, String cryptoKeyId, String member,
+ String projectId,
+ String locationId,
+ String keyRingId,
+ String cryptoKeyId,
+ String member,
String role)
throws IOException {
@@ -308,16 +290,10 @@ public static Policy addMemberToCryptoKeyPolicy(
Policy iamPolicy = client.getIamPolicy(keyName);
// Create a new binding with the selected role and member
- Binding newBinding = Binding.newBuilder()
- .setRole(role)
- .addMembers(member)
- .build();
+ Binding newBinding = Binding.newBuilder().setRole(role).addMembers(member).build();
// Create a new IAM policy containing the existing settings plus the new binding.
- Policy newPolicy = Policy.newBuilder()
- .mergeFrom(iamPolicy)
- .addBindings(newBinding)
- .build();
+ Policy newPolicy = Policy.newBuilder().mergeFrom(iamPolicy).addBindings(newBinding).build();
// Set the new IAM Policy.
Policy policyResult = client.setIamPolicy(keyName, newPolicy);
@@ -336,14 +312,11 @@ public static Policy addMemberToCryptoKeyPolicy(
* @param locationId The location id of the key.
* @param keyRingId The id of the keyring.
* @param member The member to add. Must be in the proper format, eg:
- *
- * allUsers user:$userEmail serviceAccount:$serviceAccountEmail
- *
- * See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding for more details.
+ *
allUsers user:$userEmail serviceAccount:$serviceAccountEmail
+ *
See https://g.co/cloud/kms/docs/reference/rest/v1/Policy#binding for more details.
* @param role Must be in one of the following formats: roles/[role]
- * organizations/[organizationId]/roles/[role] projects/[projectId]/roles/[role]
- *
- * See https://g.co/cloud/iam/docs/understanding-roles for available values for [role].
+ * organizations/[organizationId]/roles/[role] projects/[projectId]/roles/[role]
+ *
See https://g.co/cloud/iam/docs/understanding-roles for available values for [role].
*/
public static Policy addMemberToKeyRingPolicy(
String projectId, String locationId, String keyRingId, String member, String role)
@@ -359,16 +332,10 @@ public static Policy addMemberToKeyRingPolicy(
Policy iamPolicy = client.getIamPolicy(keyRingName);
// Create a new binding with the selected role and member
- Binding newBinding = Binding.newBuilder()
- .setRole(role)
- .addMembers(member)
- .build();
+ Binding newBinding = Binding.newBuilder().setRole(role).addMembers(member).build();
// Create a new IAM policy containing the existing settings plus the new binding.
- Policy newPolicy = Policy.newBuilder()
- .mergeFrom(iamPolicy)
- .addBindings(newBinding)
- .build();
+ Policy newPolicy = Policy.newBuilder().mergeFrom(iamPolicy).addBindings(newBinding).build();
// Set the new IAM Policy.
Policy policyResult = client.setIamPolicy(keyRingName, newPolicy);
@@ -380,11 +347,13 @@ public static Policy addMemberToKeyRingPolicy(
// [START kms_remove_member_from_cryptokey_policy]
- /**
- * Removes the given member from the given policy.
- */
+ /** Removes the given member from the given policy. */
public static Policy removeMemberFromCryptoKeyPolicy(
- String projectId, String locationId, String keyRingId, String cryptoKeyId, String member,
+ String projectId,
+ String locationId,
+ String keyRingId,
+ String cryptoKeyId,
+ String member,
String role)
throws IOException {
@@ -414,9 +383,7 @@ public static Policy removeMemberFromCryptoKeyPolicy(
newBindings.add(builder.build());
}
- Policy newIamPolicy = Policy.newBuilder()
- .addAllBindings(newBindings)
- .build();
+ Policy newIamPolicy = Policy.newBuilder().addAllBindings(newBindings).build();
// Set the new IAM Policy.
Policy result = client.setIamPolicy(keyName, newIamPolicy);
@@ -428,9 +395,7 @@ public static Policy removeMemberFromCryptoKeyPolicy(
// [START kms_remove_member_from_keyring_policy]
- /**
- * Removes the given member from the given policy.
- */
+ /** Removes the given member from the given policy. */
public static Policy removeMemberFromKeyRingPolicy(
String projectId, String locationId, String keyRingId, String member, String role)
throws IOException {
@@ -460,9 +425,7 @@ public static Policy removeMemberFromKeyRingPolicy(
}
}
- Policy newIamPolicy = Policy.newBuilder()
- .addAllBindings(newBindings)
- .build();
+ Policy newIamPolicy = Policy.newBuilder().addAllBindings(newBindings).build();
// Set the new IAM Policy.
Policy result = client.setIamPolicy(keyRingName, newIamPolicy);
@@ -472,9 +435,7 @@ public static Policy removeMemberFromKeyRingPolicy(
}
// [END kms_remove_member_from_keyring_policy]
- /**
- * Lists all the key rings in the given project.
- */
+ /** Lists all the key rings in the given project. */
public static List listKeyRings(String projectId, String locationId) throws IOException {
// Create the Cloud KMS client.
@@ -495,12 +456,9 @@ public static List listKeyRings(String projectId, String locationId) th
}
}
- /**
- * Lists all crypto keys in the given key ring.
- */
+ /** Lists all crypto keys in the given key ring. */
public static List listCryptoKeys(
- String projectId, String locationId, String keyRingId)
- throws IOException {
+ String projectId, String locationId, String keyRingId) throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
@@ -520,9 +478,7 @@ public static List listCryptoKeys(
}
}
- /**
- * Lists all the versions for the given crypto key.
- */
+ /** Lists all the versions for the given crypto key. */
public static List listCryptoKeyVersions(
String projectId, String locationId, String keyRingId, String cryptoKeyId)
throws IOException {
@@ -547,11 +503,10 @@ public static List listCryptoKeyVersions(
}
}
- /**
- * Sets a version as the primary version for a crypto key.
- */
- public static CryptoKey setPrimaryVersion(String projectId, String locationId, String keyRingId,
- String cryptoKeyId, String versionId) throws IOException {
+ /** Sets a version as the primary version for a crypto key. */
+ public static CryptoKey setPrimaryVersion(
+ String projectId, String locationId, String keyRingId, String cryptoKeyId, String versionId)
+ throws IOException {
// Create the Cloud KMS client.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
@@ -565,7 +520,6 @@ public static CryptoKey setPrimaryVersion(String projectId, String locationId, S
}
}
-
public static void main(String[] args) throws IOException, CmdLineException {
SnippetCommands commands = new SnippetCommands();
CmdLineParser parser = new CmdLineParser(commands);
diff --git a/kms/src/test/java/com/example/AsymmetricIT.java b/kms/src/test/java/com/example/AsymmetricIT.java
index 3d61283264f..e6494fb6837 100644
--- a/kms/src/test/java/com/example/AsymmetricIT.java
+++ b/kms/src/test/java/com/example/AsymmetricIT.java
@@ -30,23 +30,19 @@
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
-
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.PublicKey;
import java.util.Arrays;
-
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Integration (system) tests for {@link Asymmetric}.
- */
+/** Integration (system) tests for {@link Asymmetric}. */
@RunWith(JUnit4.class)
-//CHECKSTYLE OFF: AbbreviationAsWordInName
+// CHECKSTYLE OFF: AbbreviationAsWordInName
public class AsymmetricIT {
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
private static final String LOCATION = "global";
@@ -58,7 +54,7 @@ public class AsymmetricIT {
private static final String RSA_DECRYPT_PATH =
CryptoKeyVersionName.format(PROJECT_ID, LOCATION, KEY_RING, RSA_DECRYPT_ID, "1");
- private static final String RSA_SIGN_PATH =
+ private static final String RSA_SIGN_PATH =
CryptoKeyVersionName.format(PROJECT_ID, LOCATION, KEY_RING, RSA_SIGN_ID, "1");
private static final String EC_SIGN_PATH =
CryptoKeyVersionName.format(PROJECT_ID, LOCATION, KEY_RING, EC_SIGN_ID, "1");
@@ -71,16 +67,15 @@ private static boolean createKeyHelper(
String keyId, CryptoKeyPurpose purpose, CryptoKeyVersionAlgorithm algorithm)
throws GeneralSecurityException, IOException {
- CryptoKey cryptoKey = CryptoKey.newBuilder()
- .setPurpose(purpose)
- .setVersionTemplate(CryptoKeyVersionTemplate.newBuilder().setAlgorithm(algorithm).build())
- .build();
+ CryptoKey cryptoKey =
+ CryptoKey.newBuilder()
+ .setPurpose(purpose)
+ .setVersionTemplate(
+ CryptoKeyVersionTemplate.newBuilder().setAlgorithm(algorithm).build())
+ .build();
try {
- client.createCryptoKey(
- KeyRingName.format(PROJECT_ID, LOCATION, KEY_RING),
- keyId,
- cryptoKey);
+ client.createCryptoKey(KeyRingName.format(PROJECT_ID, LOCATION, KEY_RING), keyId, cryptoKey);
return true;
} catch (AlreadyExistsException e) {
return false;
@@ -98,12 +93,21 @@ public static void setUpClass() throws Exception {
// If it already exists, we can just continue.
}
- boolean s1 = createKeyHelper(RSA_DECRYPT_ID, CryptoKeyPurpose.ASYMMETRIC_DECRYPT,
- CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256);
- boolean s2 = createKeyHelper(RSA_SIGN_ID, CryptoKeyPurpose.ASYMMETRIC_SIGN,
- CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256);
- boolean s3 = createKeyHelper(EC_SIGN_ID, CryptoKeyPurpose.ASYMMETRIC_SIGN,
- CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256);
+ boolean s1 =
+ createKeyHelper(
+ RSA_DECRYPT_ID,
+ CryptoKeyPurpose.ASYMMETRIC_DECRYPT,
+ CryptoKeyVersionAlgorithm.RSA_DECRYPT_OAEP_2048_SHA256);
+ boolean s2 =
+ createKeyHelper(
+ RSA_SIGN_ID,
+ CryptoKeyPurpose.ASYMMETRIC_SIGN,
+ CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256);
+ boolean s3 =
+ createKeyHelper(
+ EC_SIGN_ID,
+ CryptoKeyPurpose.ASYMMETRIC_SIGN,
+ CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256);
if (s1 || s2 || s3) {
// leave time for keys to initialize
@@ -120,8 +124,7 @@ public void testGetPublicKey() throws Exception {
PublicKey ecSignKey = Asymmetric.getAsymmetricPublicKey(EC_SIGN_PATH);
assertEquals("invalid EC key.", "EC", ecSignKey.getAlgorithm());
- String fakeKeyPath = CryptoKeyVersionName.format(
- PROJECT_ID, LOCATION, KEY_RING, "FAKE", "1");
+ String fakeKeyPath = CryptoKeyVersionName.format(PROJECT_ID, LOCATION, KEY_RING, "FAKE", "1");
try {
Asymmetric.getAsymmetricPublicKey(fakeKeyPath);
// should throw exception above
@@ -163,5 +166,4 @@ public void testECSignVerify() throws Exception {
assertFalse("EC verification failed. Invalid message accepted", verifiedInvalid);
}
}
-//CHECKSTYLE ON: AbbreviationAsWordInName
-
+// CHECKSTYLE ON: AbbreviationAsWordInName
diff --git a/kms/src/test/java/com/example/CryptFileIT.java b/kms/src/test/java/com/example/CryptFileIT.java
index 1d98676831d..2b9a1658b23 100644
--- a/kms/src/test/java/com/example/CryptFileIT.java
+++ b/kms/src/test/java/com/example/CryptFileIT.java
@@ -21,19 +21,15 @@
import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.KeyRing;
-
import java.util.List;
import java.util.UUID;
-
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Integration (system) tests for {@link Quickstart}.
- */
+/** Integration (system) tests for {@link Quickstart}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class CryptFileIT {
@@ -42,35 +38,34 @@ public class CryptFileIT {
private static final String LOCATION_ID = "global";
private static final String KEY_RING_ID = "test-key-ring-" + UUID.randomUUID().toString();
private static final String CRYPTO_KEY_ID = UUID.randomUUID().toString();
- private static final String ENCRYPT_STRING =
+ private static final String ENCRYPT_STRING =
"Everyone shall sit under their own vine and fig tree";
- /**
- * Creates a CryptoKey for use during this test run.
- */
+ /** Creates a CryptoKey for use during this test run. */
@BeforeClass
public static void setUpClass() throws Exception {
KeyRing keyRing = Snippets.createKeyRing(PROJECT_ID, LOCATION_ID, KEY_RING_ID);
assertThat(keyRing.getName()).contains("keyRings/" + KEY_RING_ID);
- CryptoKey cryptoKey =
+ CryptoKey cryptoKey =
Snippets.createCryptoKey(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
- assertThat(cryptoKey.getName()).contains(String.format(
- "keyRings/%s/cryptoKeys/%s", KEY_RING_ID, CRYPTO_KEY_ID));
+ assertThat(cryptoKey.getName())
+ .contains(String.format("keyRings/%s/cryptoKeys/%s", KEY_RING_ID, CRYPTO_KEY_ID));
}
- /**
- * Destroys all the key versions created during this test run.
- */
+ /** Destroys all the key versions created during this test run. */
@AfterClass
public static void tearDownClass() throws Exception {
- List versions =
+ List versions =
Snippets.listCryptoKeyVersions(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
for (CryptoKeyVersion version : versions) {
if (!version.getState().equals(CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED)) {
Snippets.destroyCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID,
+ PROJECT_ID,
+ LOCATION_ID,
+ KEY_RING_ID,
+ CRYPTO_KEY_ID,
SnippetsIT.parseVersionId(version.getName()));
}
}
@@ -79,13 +74,14 @@ public static void tearDownClass() throws Exception {
@Test
public void encryptDecrypt_encryptsAndDecrypts() throws Exception {
// Encrypt ENCRYPT_STRING with the current primary version.
- byte[] ciphertext = CryptFile.encrypt(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, ENCRYPT_STRING.getBytes());
+ byte[] ciphertext =
+ CryptFile.encrypt(
+ PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, ENCRYPT_STRING.getBytes());
assertThat(new String(ciphertext)).isNotEqualTo(ENCRYPT_STRING);
- byte[] plaintext = CryptFile.decrypt(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, ciphertext);
+ byte[] plaintext =
+ CryptFile.decrypt(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, ciphertext);
assertThat(new String(plaintext)).isEqualTo(ENCRYPT_STRING);
}
diff --git a/kms/src/test/java/com/example/QuickstartIT.java b/kms/src/test/java/com/example/QuickstartIT.java
index d59271af378..d8e955518d6 100644
--- a/kms/src/test/java/com/example/QuickstartIT.java
+++ b/kms/src/test/java/com/example/QuickstartIT.java
@@ -21,21 +21,17 @@
import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKeyVersion;
import com.google.cloud.kms.v1.KeyRing;
-
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.UUID;
-
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Integration (system) tests for {@link Quickstart}.
- */
+/** Integration (system) tests for {@link Quickstart}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class QuickstartIT {
@@ -45,32 +41,31 @@ public class QuickstartIT {
private static final String KEY_RING_ID = "test-key-ring-" + UUID.randomUUID().toString();
private static final String CRYPTO_KEY_ID = UUID.randomUUID().toString();
- /**
- * Creates a CryptoKey for use during this test run.
- */
+ /** Creates a CryptoKey for use during this test run. */
@BeforeClass
public static void setUpClass() throws Exception {
KeyRing keyRing = Snippets.createKeyRing(PROJECT_ID, LOCATION_ID, KEY_RING_ID);
assertThat(keyRing.getName()).contains("keyRings/" + KEY_RING_ID);
- CryptoKey cryptoKey =
+ CryptoKey cryptoKey =
Snippets.createCryptoKey(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
- assertThat(cryptoKey.getName()).contains(String.format(
- "keyRings/%s/cryptoKeys/%s", KEY_RING_ID, CRYPTO_KEY_ID));
+ assertThat(cryptoKey.getName())
+ .contains(String.format("keyRings/%s/cryptoKeys/%s", KEY_RING_ID, CRYPTO_KEY_ID));
}
- /**
- * Destroys all the key versions created during this test run.
- */
+ /** Destroys all the key versions created during this test run. */
@AfterClass
public static void tearDownClass() throws Exception {
- List versions =
+ List versions =
Snippets.listCryptoKeyVersions(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
for (CryptoKeyVersion v : versions) {
if (!v.getState().equals(CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED)) {
Snippets.destroyCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID,
+ PROJECT_ID,
+ LOCATION_ID,
+ KEY_RING_ID,
+ CRYPTO_KEY_ID,
SnippetsIT.parseVersionId(v.getName()));
}
}
diff --git a/kms/src/test/java/com/example/SnippetsIT.java b/kms/src/test/java/com/example/SnippetsIT.java
index 01f256c8ae8..bf31d2818af 100644
--- a/kms/src/test/java/com/example/SnippetsIT.java
+++ b/kms/src/test/java/com/example/SnippetsIT.java
@@ -24,21 +24,17 @@
import com.google.cloud.kms.v1.KeyRing;
import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
-
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Integration (system) tests for {@link Snippets}.
- */
+/** Integration (system) tests for {@link Snippets}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class SnippetsIT {
@@ -47,30 +43,26 @@ public class SnippetsIT {
private static final String LOCATION_ID = "global";
private static final String KEY_RING_ID = "test-key-ring-" + UUID.randomUUID().toString();
private static final String CRYPTO_KEY_ID = UUID.randomUUID().toString();
- private static final String TEST_USER = "serviceAccount:"
- + "131304031188-compute@developer.gserviceaccount.com";
+ private static final String TEST_USER =
+ "serviceAccount:" + "131304031188-compute@developer.gserviceaccount.com";
private static final String TEST_ROLE = "roles/viewer";
- /**
- * Creates a CryptoKey for use during this test run.
- */
+ /** Creates a CryptoKey for use during this test run. */
@BeforeClass
public static void setUpClass() throws Exception {
KeyRing keyRing = Snippets.createKeyRing(PROJECT_ID, LOCATION_ID, KEY_RING_ID);
assertThat(keyRing.getName()).contains("keyRings/" + KEY_RING_ID);
- CryptoKey cryptoKey =
+ CryptoKey cryptoKey =
Snippets.createCryptoKey(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
- assertThat(cryptoKey.getName()).contains(String.format(
- "keyRings/%s/cryptoKeys/%s", KEY_RING_ID, CRYPTO_KEY_ID));
+ assertThat(cryptoKey.getName())
+ .contains(String.format("keyRings/%s/cryptoKeys/%s", KEY_RING_ID, CRYPTO_KEY_ID));
}
- /**
- * Destroys all the key versions created during this test run.
- */
+ /** Destroys all the key versions created during this test run. */
@AfterClass
public static void tearDownClass() throws Exception {
- List versions =
+ List versions =
Snippets.listCryptoKeyVersions(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
for (CryptoKeyVersion version : versions) {
@@ -92,18 +84,20 @@ public void listKeyRings_retrievesKeyRing() throws Exception {
public void listCryptoKeys_retrievesCryptoKeys() throws Exception {
List keys = Snippets.listCryptoKeys(PROJECT_ID, LOCATION_ID, KEY_RING_ID);
assertThat(keys).isNotEmpty();
- assertThat(keys.get(0).getName()).contains(
- String.format("keyRings/%s/cryptoKeys/%s", KEY_RING_ID, CRYPTO_KEY_ID));
+ assertThat(keys.get(0).getName())
+ .contains(String.format("keyRings/%s/cryptoKeys/%s", KEY_RING_ID, CRYPTO_KEY_ID));
}
@Test
public void listCryptoKeyVersions_retrievesVersions() throws Exception {
- List versions =
+ List versions =
Snippets.listCryptoKeyVersions(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
for (CryptoKeyVersion version : versions) {
- assertThat(version.getName()).contains(String.format(
- "keyRings/%s/cryptoKeys/%s/cryptoKeyVersions/", KEY_RING_ID, CRYPTO_KEY_ID));
+ assertThat(version.getName())
+ .contains(
+ String.format(
+ "keyRings/%s/cryptoKeys/%s/cryptoKeyVersions/", KEY_RING_ID, CRYPTO_KEY_ID));
if (version.getState().equals(CryptoKeyVersion.CryptoKeyVersionState.ENABLED)) {
return;
@@ -116,90 +110,94 @@ public void listCryptoKeyVersions_retrievesVersions() throws Exception {
@Test
public void disableCryptoKeyVersion_disables() throws Exception {
- CryptoKeyVersion version = Snippets.createCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
-
+ CryptoKeyVersion version =
+ Snippets.createCryptoKeyVersion(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
+
String versionId = parseVersionId(version.getName());
- CryptoKeyVersion disabled = Snippets.disableCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
+ CryptoKeyVersion disabled =
+ Snippets.disableCryptoKeyVersion(
+ PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
assertThat(disabled.getState()).isEqualTo(CryptoKeyVersion.CryptoKeyVersionState.DISABLED);
}
@Test
public void enableCryptoKeyVersion_enables() throws Exception {
- CryptoKeyVersion version = Snippets.createCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
-
+ CryptoKeyVersion version =
+ Snippets.createCryptoKeyVersion(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
+
String versionId = parseVersionId(version.getName());
// Disable the new key version
- CryptoKeyVersion disabled = Snippets.disableCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
+ CryptoKeyVersion disabled =
+ Snippets.disableCryptoKeyVersion(
+ PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
assertThat(disabled.getState()).isEqualTo(CryptoKeyVersion.CryptoKeyVersionState.DISABLED);
// Enable the now-disabled key version
- CryptoKeyVersion enabled = Snippets.enableCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
+ CryptoKeyVersion enabled =
+ Snippets.enableCryptoKeyVersion(
+ PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
assertThat(enabled.getState()).isEqualTo(CryptoKeyVersion.CryptoKeyVersionState.ENABLED);
}
@Test
public void destroyCryptoKeyVersion_destroys() throws Exception {
- CryptoKeyVersion version = Snippets.createCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
+ CryptoKeyVersion version =
+ Snippets.createCryptoKeyVersion(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
String versionId = parseVersionId(version.getName());
// Destroy the new key version
- CryptoKeyVersion destroyScheduled = Snippets.destroyCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
- assertThat(destroyScheduled.getState()).isEqualTo(
- CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED);
+ CryptoKeyVersion destroyScheduled =
+ Snippets.destroyCryptoKeyVersion(
+ PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
+ assertThat(destroyScheduled.getState())
+ .isEqualTo(CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED);
}
-
@Test
public void restoreCryptoKeyVersion_restores() throws Exception {
- CryptoKeyVersion version = Snippets.createCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
+ CryptoKeyVersion version =
+ Snippets.createCryptoKeyVersion(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
String versionId = parseVersionId(version.getName());
// Only key versions scheduled for destruction are restorable, so schedule this key
// version for destruction.
- CryptoKeyVersion destroyScheduled = Snippets.destroyCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
- assertThat(destroyScheduled.getState()).isEqualTo(
- CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED);
+ CryptoKeyVersion destroyScheduled =
+ Snippets.destroyCryptoKeyVersion(
+ PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
+ assertThat(destroyScheduled.getState())
+ .isEqualTo(CryptoKeyVersion.CryptoKeyVersionState.DESTROY_SCHEDULED);
// Now restore the key version.
- CryptoKeyVersion restored = Snippets.restoreCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
- assertThat(restored.getState()).isEqualTo(
- CryptoKeyVersion.CryptoKeyVersionState.DISABLED);
+ CryptoKeyVersion restored =
+ Snippets.restoreCryptoKeyVersion(
+ PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
+ assertThat(restored.getState()).isEqualTo(CryptoKeyVersion.CryptoKeyVersionState.DISABLED);
}
@Test
public void setPrimaryVersion_createKeyAndSetPrimaryVersion() throws Exception {
// We can't test that setPrimaryVersion actually took effect via a list call because of
// caching. So we test that the call was successful.
- CryptoKeyVersion version = Snippets.createCryptoKeyVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
+ CryptoKeyVersion version =
+ Snippets.createCryptoKeyVersion(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
assertThat(version.getState()).isEqualTo(CryptoKeyVersion.CryptoKeyVersionState.ENABLED);
String versionId = parseVersionId(version.getName());
- CryptoKey key = Snippets.setPrimaryVersion(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
+ CryptoKey key =
+ Snippets.setPrimaryVersion(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, versionId);
assertThat(key.getPrimary().getName()).isEqualTo(version.getName());
}
@Test
public void addAndRemoveMemberToCryptoKeyPolicy_addsDisplaysAndRemoves() throws Exception {
// Retrieve the current policy
- Policy policy = Snippets.getCryptoKeyPolicy(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
+ Policy policy =
+ Snippets.getCryptoKeyPolicy(PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID);
// Make sure the policy doesn't already have our test user
for (Binding binding : policy.getBindingsList()) {
@@ -210,8 +208,9 @@ public void addAndRemoveMemberToCryptoKeyPolicy_addsDisplaysAndRemoves() throws
try {
// Add the test user, and make sure the policy has it
- Policy added = Snippets.addMemberToCryptoKeyPolicy(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, TEST_USER, TEST_ROLE);
+ Policy added =
+ Snippets.addMemberToCryptoKeyPolicy(
+ PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, TEST_USER, TEST_ROLE);
for (Binding binding : added.getBindingsList()) {
for (String m : binding.getMembersList()) {
@@ -225,8 +224,9 @@ public void addAndRemoveMemberToCryptoKeyPolicy_addsDisplaysAndRemoves() throws
assertTrue("No policy binding containing TEST_USER exists", false);
} finally {
// Now remove the test user, and make sure the policy no longer has it
- Policy removed = Snippets.removeMemberFromCryptoKeyPolicy(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, TEST_USER, TEST_ROLE);
+ Policy removed =
+ Snippets.removeMemberFromCryptoKeyPolicy(
+ PROJECT_ID, LOCATION_ID, KEY_RING_ID, CRYPTO_KEY_ID, TEST_USER, TEST_ROLE);
for (Binding binding : removed.getBindingsList()) {
for (String m : binding.getMembersList()) {
assertThat(TEST_USER).isNotEqualTo(m);
@@ -249,8 +249,9 @@ public void addAndRemoveMemberToKeyRingPolicy_addsDisplaysAndRemoves() throws Ex
try {
// Add the test user, and make sure the policy has it
- Policy added = Snippets.addMemberToKeyRingPolicy(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, TEST_USER, TEST_ROLE);
+ Policy added =
+ Snippets.addMemberToKeyRingPolicy(
+ PROJECT_ID, LOCATION_ID, KEY_RING_ID, TEST_USER, TEST_ROLE);
for (Binding binding : added.getBindingsList()) {
for (String m : binding.getMembersList()) {
@@ -264,8 +265,9 @@ public void addAndRemoveMemberToKeyRingPolicy_addsDisplaysAndRemoves() throws Ex
assertTrue("No policy binding containing TEST_USER exists", false);
} finally {
// Now remove the test user, and make sure the policy no longer has it
- Policy removed = Snippets.removeMemberFromKeyRingPolicy(
- PROJECT_ID, LOCATION_ID, KEY_RING_ID, TEST_USER, TEST_ROLE);
+ Policy removed =
+ Snippets.removeMemberFromKeyRingPolicy(
+ PROJECT_ID, LOCATION_ID, KEY_RING_ID, TEST_USER, TEST_ROLE);
for (Binding binding : removed.getBindingsList()) {
for (String m : binding.getMembersList()) {
assertThat(TEST_USER).isNotEqualTo(m);
diff --git a/language/analysis/pom.xml b/language/analysis/pom.xml
index 5dd4c7b139a..a38b5440b1e 100644
--- a/language/analysis/pom.xml
+++ b/language/analysis/pom.xml
@@ -27,7 +27,7 @@ limitations under the License.
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
1.8
diff --git a/language/analysis/src/main/java/com/google/cloud/language/samples/Analyze.java b/language/analysis/src/main/java/com/google/cloud/language/samples/Analyze.java
index 29f037bf542..e340bcb7524 100644
--- a/language/analysis/src/main/java/com/google/cloud/language/samples/Analyze.java
+++ b/language/analysis/src/main/java/com/google/cloud/language/samples/Analyze.java
@@ -34,7 +34,6 @@
import com.google.cloud.language.v1.LanguageServiceClient;
import com.google.cloud.language.v1.Sentiment;
import com.google.cloud.language.v1.Token;
-
import java.util.List;
import java.util.Map;
@@ -44,15 +43,12 @@
*/
public class Analyze {
- /**
- * Detects entities,sentiment and syntax in a document using the Natural Language API.
- */
+ /** Detects entities,sentiment and syntax in a document using the Natural Language API. */
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("Usage:");
System.err.printf(
- "\tjava %s \"command\" \"text to analyze\"\n",
- Analyze.class.getCanonicalName());
+ "\tjava %s \"command\" \"text to analyze\"\n", Analyze.class.getCanonicalName());
System.exit(1);
}
String command = args[0];
@@ -91,21 +87,17 @@ public static void main(String[] args) throws Exception {
}
}
- /**
- * Identifies entities in the string {@code text}.
- */
+ /** Identifies entities in the string {@code text}. */
public static void analyzeEntitiesText(String text) throws Exception {
// [START language_entities_text]
// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
- Document doc = Document.newBuilder()
- .setContent(text)
- .setType(Type.PLAIN_TEXT)
- .build();
- AnalyzeEntitiesRequest request = AnalyzeEntitiesRequest.newBuilder()
- .setDocument(doc)
- .setEncodingType(EncodingType.UTF16)
- .build();
+ Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();
+ AnalyzeEntitiesRequest request =
+ AnalyzeEntitiesRequest.newBuilder()
+ .setDocument(doc)
+ .setEncodingType(EncodingType.UTF16)
+ .build();
AnalyzeEntitiesResponse response = language.analyzeEntities(request);
@@ -127,22 +119,19 @@ public static void analyzeEntitiesText(String text) throws Exception {
// [END language_entities_text]
}
- /**
- * Identifies entities in the contents of the object at the given GCS {@code path}.
- */
+ /** Identifies entities in the contents of the object at the given GCS {@code path}. */
public static void analyzeEntitiesFile(String gcsUri) throws Exception {
// [START language_entities_gcs]
// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
// set the GCS Content URI path to the file to be analyzed
- Document doc = Document.newBuilder()
- .setGcsContentUri(gcsUri)
- .setType(Type.PLAIN_TEXT)
- .build();
- AnalyzeEntitiesRequest request = AnalyzeEntitiesRequest.newBuilder()
- .setDocument(doc)
- .setEncodingType(EncodingType.UTF16)
- .build();
+ Document doc =
+ Document.newBuilder().setGcsContentUri(gcsUri).setType(Type.PLAIN_TEXT).build();
+ AnalyzeEntitiesRequest request =
+ AnalyzeEntitiesRequest.newBuilder()
+ .setDocument(doc)
+ .setEncodingType(EncodingType.UTF16)
+ .build();
AnalyzeEntitiesResponse response = language.analyzeEntities(request);
@@ -164,17 +153,12 @@ public static void analyzeEntitiesFile(String gcsUri) throws Exception {
// [END language_entities_gcs]
}
- /**
- * Identifies the sentiment in the string {@code text}.
- */
+ /** Identifies the sentiment in the string {@code text}. */
public static Sentiment analyzeSentimentText(String text) throws Exception {
// [START language_sentiment_text]
// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
- Document doc = Document.newBuilder()
- .setContent(text)
- .setType(Type.PLAIN_TEXT)
- .build();
+ Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();
AnalyzeSentimentResponse response = language.analyzeSentiment(doc);
Sentiment sentiment = response.getDocumentSentiment();
if (sentiment == null) {
@@ -188,17 +172,13 @@ public static Sentiment analyzeSentimentText(String text) throws Exception {
// [END language_sentiment_text]
}
- /**
- * Gets {@link Sentiment} from the contents of the GCS hosted file.
- */
+ /** Gets {@link Sentiment} from the contents of the GCS hosted file. */
public static Sentiment analyzeSentimentFile(String gcsUri) throws Exception {
// [START language_sentiment_gcs]
// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
- Document doc = Document.newBuilder()
- .setGcsContentUri(gcsUri)
- .setType(Type.PLAIN_TEXT)
- .build();
+ Document doc =
+ Document.newBuilder().setGcsContentUri(gcsUri).setType(Type.PLAIN_TEXT).build();
AnalyzeSentimentResponse response = language.analyzeSentiment(doc);
Sentiment sentiment = response.getDocumentSentiment();
if (sentiment == null) {
@@ -212,21 +192,17 @@ public static Sentiment analyzeSentimentFile(String gcsUri) throws Exception {
// [END language_sentiment_gcs]
}
- /**
- * from the string {@code text}.
- */
+ /** from the string {@code text}. */
public static List analyzeSyntaxText(String text) throws Exception {
// [START language_syntax_text]
// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
- Document doc = Document.newBuilder()
- .setContent(text)
- .setType(Type.PLAIN_TEXT)
- .build();
- AnalyzeSyntaxRequest request = AnalyzeSyntaxRequest.newBuilder()
- .setDocument(doc)
- .setEncodingType(EncodingType.UTF16)
- .build();
+ Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();
+ AnalyzeSyntaxRequest request =
+ AnalyzeSyntaxRequest.newBuilder()
+ .setDocument(doc)
+ .setEncodingType(EncodingType.UTF16)
+ .build();
// analyze the syntax in the given text
AnalyzeSyntaxResponse response = language.analyzeSyntax(request);
// print the response
@@ -255,21 +231,18 @@ public static List analyzeSyntaxText(String text) throws Exception {
// [END language_syntax_text]
}
- /**
- * Get the syntax of the GCS hosted file.
- */
+ /** Get the syntax of the GCS hosted file. */
public static List analyzeSyntaxFile(String gcsUri) throws Exception {
// [START language_syntax_gcs]
// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
- Document doc = Document.newBuilder()
- .setGcsContentUri(gcsUri)
- .setType(Type.PLAIN_TEXT)
- .build();
- AnalyzeSyntaxRequest request = AnalyzeSyntaxRequest.newBuilder()
- .setDocument(doc)
- .setEncodingType(EncodingType.UTF16)
- .build();
+ Document doc =
+ Document.newBuilder().setGcsContentUri(gcsUri).setType(Type.PLAIN_TEXT).build();
+ AnalyzeSyntaxRequest request =
+ AnalyzeSyntaxRequest.newBuilder()
+ .setDocument(doc)
+ .setEncodingType(EncodingType.UTF16)
+ .build();
// analyze the syntax in the given text
AnalyzeSyntaxResponse response = language.analyzeSyntax(request);
// print the response
@@ -299,70 +272,58 @@ public static List analyzeSyntaxFile(String gcsUri) throws Exception {
// [END language_syntax_gcs]
}
- /**
- * Detects categories in text using the Language Beta API.
- */
+ /** Detects categories in text using the Language Beta API. */
public static void classifyText(String text) throws Exception {
// [START language_classify_text]
// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
// set content to the text string
- Document doc = Document.newBuilder()
- .setContent(text)
- .setType(Type.PLAIN_TEXT)
- .build();
- ClassifyTextRequest request = ClassifyTextRequest.newBuilder()
- .setDocument(doc)
- .build();
+ Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();
+ ClassifyTextRequest request = ClassifyTextRequest.newBuilder().setDocument(doc).build();
// detect categories in the given text
ClassifyTextResponse response = language.classifyText(request);
for (ClassificationCategory category : response.getCategoriesList()) {
- System.out.printf("Category name : %s, Confidence : %.3f\n",
+ System.out.printf(
+ "Category name : %s, Confidence : %.3f\n",
category.getName(), category.getConfidence());
}
}
// [END language_classify_text]
}
- /**
- * Detects categories in a GCS hosted file using the Language Beta API.
- */
+ /** Detects categories in a GCS hosted file using the Language Beta API. */
public static void classifyFile(String gcsUri) throws Exception {
// [START language_classify_gcs]
// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
// set the GCS content URI path
- Document doc = Document.newBuilder()
- .setGcsContentUri(gcsUri)
- .setType(Type.PLAIN_TEXT)
- .build();
- ClassifyTextRequest request = ClassifyTextRequest.newBuilder()
- .setDocument(doc)
- .build();
+ Document doc =
+ Document.newBuilder().setGcsContentUri(gcsUri).setType(Type.PLAIN_TEXT).build();
+ ClassifyTextRequest request = ClassifyTextRequest.newBuilder().setDocument(doc).build();
// detect categories in the given file
ClassifyTextResponse response = language.classifyText(request);
for (ClassificationCategory category : response.getCategoriesList()) {
- System.out.printf("Category name : %s, Confidence : %.3f\n",
+ System.out.printf(
+ "Category name : %s, Confidence : %.3f\n",
category.getName(), category.getConfidence());
}
}
// [END language_classify_gcs]
}
- /**
- * Detects the entity sentiments in the string {@code text} using the Language Beta API.
- */
+ /** Detects the entity sentiments in the string {@code text} using the Language Beta API. */
public static void entitySentimentText(String text) throws Exception {
// [START language_entity_sentiment_text]
// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
- Document doc = Document.newBuilder()
- .setContent(text).setType(Type.PLAIN_TEXT).build();
- AnalyzeEntitySentimentRequest request = AnalyzeEntitySentimentRequest.newBuilder()
- .setDocument(doc)
- .setEncodingType(EncodingType.UTF16).build();
+ Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();
+ AnalyzeEntitySentimentRequest request =
+ AnalyzeEntitySentimentRequest.newBuilder()
+ .setDocument(doc)
+ .setEncodingType(EncodingType.UTF16)
+ .build();
// detect entity sentiments in the given string
AnalyzeEntitySentimentResponse response = language.analyzeEntitySentiment(request);
// Print the response
@@ -382,21 +343,18 @@ public static void entitySentimentText(String text) throws Exception {
// [END language_entity_sentiment_text]
}
- /**
- * Identifies the entity sentiments in the the GCS hosted file using the Language Beta API.
- */
+ /** Identifies the entity sentiments in the the GCS hosted file using the Language Beta API. */
public static void entitySentimentFile(String gcsUri) throws Exception {
// [START language_entity_sentiment_gcs]
// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
- Document doc = Document.newBuilder()
- .setGcsContentUri(gcsUri)
- .setType(Type.PLAIN_TEXT)
- .build();
- AnalyzeEntitySentimentRequest request = AnalyzeEntitySentimentRequest.newBuilder()
- .setDocument(doc)
- .setEncodingType(EncodingType.UTF16)
- .build();
+ Document doc =
+ Document.newBuilder().setGcsContentUri(gcsUri).setType(Type.PLAIN_TEXT).build();
+ AnalyzeEntitySentimentRequest request =
+ AnalyzeEntitySentimentRequest.newBuilder()
+ .setDocument(doc)
+ .setEncodingType(EncodingType.UTF16)
+ .build();
// Detect entity sentiments in the given file
AnalyzeEntitySentimentResponse response = language.analyzeEntitySentiment(request);
// Print the response
diff --git a/language/analysis/src/main/java/com/google/cloud/language/samples/AnalyzeBeta.java b/language/analysis/src/main/java/com/google/cloud/language/samples/AnalyzeBeta.java
index 268bcfd39ae..46366312896 100644
--- a/language/analysis/src/main/java/com/google/cloud/language/samples/AnalyzeBeta.java
+++ b/language/analysis/src/main/java/com/google/cloud/language/samples/AnalyzeBeta.java
@@ -16,29 +16,22 @@
package com.google.cloud.language.samples;
-import com.google.cloud.language.v1beta2.AnalyzeEntitySentimentRequest;
-import com.google.cloud.language.v1beta2.AnalyzeEntitySentimentResponse;
import com.google.cloud.language.v1beta2.AnalyzeSentimentResponse;
import com.google.cloud.language.v1beta2.ClassificationCategory;
import com.google.cloud.language.v1beta2.ClassifyTextRequest;
import com.google.cloud.language.v1beta2.ClassifyTextResponse;
import com.google.cloud.language.v1beta2.Document;
import com.google.cloud.language.v1beta2.Document.Type;
-import com.google.cloud.language.v1beta2.EncodingType;
-import com.google.cloud.language.v1beta2.Entity;
-import com.google.cloud.language.v1beta2.EntityMention;
import com.google.cloud.language.v1beta2.LanguageServiceClient;
import com.google.cloud.language.v1beta2.Sentiment;
/**
- * A sample application that uses the Natural Language API to perform
- * entity, sentiment and syntax analysis.
+ * A sample application that uses the Natural Language API to perform entity, sentiment and syntax
+ * analysis.
*/
public class AnalyzeBeta {
- /**
- * Detects entities,sentiment and syntax in a document using the Natural Language API.
- */
+ /** Detects entities,sentiment and syntax in a document using the Natural Language API. */
public static void main(String[] args) throws Exception {
if (args.length < 2 || args.length > 4) {
System.err.println("Usage:");
@@ -53,7 +46,7 @@ public static void main(String[] args) throws Exception {
if (args.length > 2) {
lang = args[2];
}
-
+
if (command.equals("classify")) {
if (text.startsWith("gs://")) {
classifyFile(text);
@@ -65,9 +58,7 @@ public static void main(String[] args) throws Exception {
}
}
- /**
- * Detects sentiments from the string {@code text}.
- */
+ /** Detects sentiments from the string {@code text}. */
public static Sentiment analyzeSentimentText(String text, String lang) throws Exception {
// [START beta_sentiment_text]
// Instantiate a beta client : com.google.cloud.language.v1beta2.LanguageServiceClient
@@ -75,14 +66,14 @@ public static Sentiment analyzeSentimentText(String text, String lang) throws Ex
// NL auto-detects the language, if not provided
Document doc;
if (lang != null) {
- doc = Document.newBuilder()
- .setLanguage(lang)
- .setContent(text).setType(Type.PLAIN_TEXT)
- .build();
+ doc =
+ Document.newBuilder()
+ .setLanguage(lang)
+ .setContent(text)
+ .setType(Type.PLAIN_TEXT)
+ .build();
} else {
- doc = Document.newBuilder()
- .setContent(text).setType(Type.PLAIN_TEXT)
- .build();
+ doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();
}
AnalyzeSentimentResponse response = language.analyzeSentiment(doc);
Sentiment sentiment = response.getDocumentSentiment();
@@ -98,53 +89,41 @@ public static Sentiment analyzeSentimentText(String text, String lang) throws Ex
// [END beta_sentiment_text]
}
-
- /**
- * Detects categories in text using the Language Beta API.
- */
+ /** Detects categories in text using the Language Beta API. */
public static void classifyText(String text) throws Exception {
// [START classify_text]
// Instantiate a beta client : com.google.cloud.language.v1beta2.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
// set content to the text string
- Document doc = Document.newBuilder()
- .setContent(text)
- .setType(Type.PLAIN_TEXT)
- .build();
- ClassifyTextRequest request = ClassifyTextRequest.newBuilder()
- .setDocument(doc)
- .build();
+ Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();
+ ClassifyTextRequest request = ClassifyTextRequest.newBuilder().setDocument(doc).build();
// detect categories in the given text
ClassifyTextResponse response = language.classifyText(request);
for (ClassificationCategory category : response.getCategoriesList()) {
- System.out.printf("Category name : %s, Confidence : %.3f\n",
+ System.out.printf(
+ "Category name : %s, Confidence : %.3f\n",
category.getName(), category.getConfidence());
}
}
// [END classify_text]
}
- /**
- * Detects categories in a GCS hosted file using the Language Beta API.
- */
+ /** Detects categories in a GCS hosted file using the Language Beta API. */
public static void classifyFile(String gcsUri) throws Exception {
// [START classify_file]
// Instantiate a beta client : com.google.cloud.language.v1beta2.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
// set the GCS content URI path
- Document doc = Document.newBuilder()
- .setGcsContentUri(gcsUri)
- .setType(Type.PLAIN_TEXT)
- .build();
- ClassifyTextRequest request = ClassifyTextRequest.newBuilder()
- .setDocument(doc)
- .build();
+ Document doc =
+ Document.newBuilder().setGcsContentUri(gcsUri).setType(Type.PLAIN_TEXT).build();
+ ClassifyTextRequest request = ClassifyTextRequest.newBuilder().setDocument(doc).build();
// detect categories in the given file
ClassifyTextResponse response = language.classifyText(request);
for (ClassificationCategory category : response.getCategoriesList()) {
- System.out.printf("Category name : %s, Confidence : %.3f\n",
+ System.out.printf(
+ "Category name : %s, Confidence : %.3f\n",
category.getName(), category.getConfidence());
}
}
diff --git a/language/analysis/src/test/java/com/google/cloud/language/samples/AnalyzeBetaIT.java b/language/analysis/src/test/java/com/google/cloud/language/samples/AnalyzeBetaIT.java
index 9e3f9aa611e..fb850102bf6 100644
--- a/language/analysis/src/test/java/com/google/cloud/language/samples/AnalyzeBetaIT.java
+++ b/language/analysis/src/test/java/com/google/cloud/language/samples/AnalyzeBetaIT.java
@@ -19,7 +19,6 @@
import static com.google.common.truth.Truth.assertThat;
import com.google.cloud.language.v1beta2.Sentiment;
-
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.Before;
@@ -27,9 +26,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Integration (system) tests for {@link Analyze}.
- */
+/** Integration (system) tests for {@link Analyze}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class AnalyzeBetaIT {
@@ -48,17 +45,18 @@ public void setUp() {
@Test
public void analyzeSentiment_returnPositiveGerman() throws Exception {
- Sentiment sentiment = AnalyzeBeta.analyzeSentimentText(
- "Ich hatte die schönste Erfahrung mit euch allen.", "DE");
+ Sentiment sentiment =
+ AnalyzeBeta.analyzeSentimentText("Ich hatte die schönste Erfahrung mit euch allen.", "DE");
assertThat(sentiment.getMagnitude()).isGreaterThan(0.0F);
assertThat(sentiment.getScore()).isGreaterThan(0.0F);
}
@Test
public void analyzeCategoriesInTextReturnsExpectedResult() throws Exception {
- AnalyzeBeta.classifyText("Android is a mobile operating system developed by Google, "
- + "based on the Linux kernel and designed primarily for touchscreen "
- + "mobile devices such as smartphones and tablets.");
+ AnalyzeBeta.classifyText(
+ "Android is a mobile operating system developed by Google, "
+ + "based on the Linux kernel and designed primarily for touchscreen "
+ + "mobile devices such as smartphones and tablets.");
String got = bout.toString();
assertThat(got).contains("Computers & Electronics");
}
diff --git a/language/analysis/src/test/java/com/google/cloud/language/samples/AnalyzeIT.java b/language/analysis/src/test/java/com/google/cloud/language/samples/AnalyzeIT.java
index f4863be0916..58d1426ea06 100644
--- a/language/analysis/src/test/java/com/google/cloud/language/samples/AnalyzeIT.java
+++ b/language/analysis/src/test/java/com/google/cloud/language/samples/AnalyzeIT.java
@@ -21,20 +21,16 @@
import com.google.cloud.language.v1.PartOfSpeech.Tag;
import com.google.cloud.language.v1.Sentiment;
import com.google.cloud.language.v1.Token;
-
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.stream.Collectors;
-
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Integration (system) tests for {@link Analyze}.
- */
+/** Integration (system) tests for {@link Analyze}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class AnalyzeIT {
@@ -54,9 +50,10 @@ public void setUp() {
@Test
public void analyzeCategoriesInTextReturnsExpectedResult() throws Exception {
- Analyze.classifyText("Android is a mobile operating system developed by Google, "
- + "based on the Linux kernel and designed primarily for touchscreen "
- + "mobile devices such as smartphones and tablets.");
+ Analyze.classifyText(
+ "Android is a mobile operating system developed by Google, "
+ + "based on the Linux kernel and designed primarily for touchscreen "
+ + "mobile devices such as smartphones and tablets.");
String got = bout.toString();
assertThat(got).contains("Computers & Electronics");
}
@@ -89,63 +86,70 @@ public void analyzeEntities_withEntitiesFile_containsCalifornia() throws Excepti
@Test
public void analyzeSentimentText_returnPositive() throws Exception {
- Sentiment sentiment = Analyze.analyzeSentimentText(
- "Tom Cruise is one of the finest actors in hollywood and a great star!");
+ Sentiment sentiment =
+ Analyze.analyzeSentimentText(
+ "Tom Cruise is one of the finest actors in hollywood and a great star!");
assertThat(sentiment.getMagnitude()).isGreaterThan(0.0F);
assertThat(sentiment.getScore()).isGreaterThan(0.0F);
}
@Test
public void analyzeSentimentFile_returnPositiveFile() throws Exception {
- Sentiment sentiment = Analyze.analyzeSentimentFile("gs://cloud-samples-data/language/"
- + "sentiment-positive.txt");
+ Sentiment sentiment =
+ Analyze.analyzeSentimentFile(
+ "gs://cloud-samples-data/language/" + "sentiment-positive.txt");
assertThat(sentiment.getMagnitude()).isGreaterThan(0.0F);
assertThat(sentiment.getScore()).isGreaterThan(0.0F);
}
@Test
public void analyzeSentimentText_returnNegative() throws Exception {
- Sentiment sentiment = Analyze.analyzeSentimentText(
- "That was the worst performance I've seen in a while.");
+ Sentiment sentiment =
+ Analyze.analyzeSentimentText("That was the worst performance I've seen in a while.");
assertThat(sentiment.getMagnitude()).isGreaterThan(0.0F);
assertThat(sentiment.getScore()).isLessThan(0.0F);
}
@Test
public void analyzeSentiment_returnNegative() throws Exception {
- Sentiment sentiment = Analyze.analyzeSentimentFile("gs://cloud-samples-data/language/"
- + "sentiment-negative.txt");
+ Sentiment sentiment =
+ Analyze.analyzeSentimentFile(
+ "gs://cloud-samples-data/language/" + "sentiment-negative.txt");
assertThat(sentiment.getMagnitude()).isGreaterThan(0.0F);
assertThat(sentiment.getScore()).isLessThan(0.0F);
}
@Test
public void analyzeSyntax_partOfSpeech() throws Exception {
- List tokens = Analyze
- .analyzeSyntaxText("President Obama was elected for the second term");
+ List tokens =
+ Analyze.analyzeSyntaxText("President Obama was elected for the second term");
- List got = tokens.stream().map(e -> e.getPartOfSpeech().getTag())
- .collect(Collectors.toList());
+ List got =
+ tokens.stream().map(e -> e.getPartOfSpeech().getTag()).collect(Collectors.toList());
- assertThat(got).containsExactly(Tag.NOUN, Tag.NOUN, Tag.VERB,
- Tag.VERB, Tag.ADP, Tag.DET, Tag.ADJ, Tag.NOUN).inOrder();
+ assertThat(got)
+ .containsExactly(
+ Tag.NOUN, Tag.NOUN, Tag.VERB, Tag.VERB, Tag.ADP, Tag.DET, Tag.ADJ, Tag.NOUN)
+ .inOrder();
}
@Test
public void analyzeSyntax_partOfSpeechFile() throws Exception {
- List token = Analyze.analyzeSyntaxFile("gs://cloud-samples-data/language/"
- + "syntax-sentence.txt");
-
- List got = token.stream().map(e -> e.getPartOfSpeech().getTag())
- .collect(Collectors.toList());
- assertThat(got).containsExactly(Tag.DET, Tag.VERB, Tag.DET, Tag.ADJ, Tag.NOUN,
- Tag.PUNCT).inOrder();
+ List token =
+ Analyze.analyzeSyntaxFile("gs://cloud-samples-data/language/" + "syntax-sentence.txt");
+
+ List got =
+ token.stream().map(e -> e.getPartOfSpeech().getTag()).collect(Collectors.toList());
+ assertThat(got)
+ .containsExactly(Tag.DET, Tag.VERB, Tag.DET, Tag.ADJ, Tag.NOUN, Tag.PUNCT)
+ .inOrder();
}
@Test
public void analyzeEntitySentimentTextReturnsExpectedResult() throws Exception {
- Analyze.entitySentimentText("Oranges, grapes, and apples can be "
- + "found in the cafeterias located in Mountain View, Seattle, and London.");
+ Analyze.entitySentimentText(
+ "Oranges, grapes, and apples can be "
+ + "found in the cafeterias located in Mountain View, Seattle, and London.");
String got = bout.toString();
assertThat(got).contains("Seattle");
}
@@ -163,5 +167,4 @@ public void analyzeEntitySentimenFileReturnsExpectedResult() throws Exception {
String got = bout.toString();
assertThat(got).contains("Kennedy");
}
-
}
diff --git a/language/automl/pom.xml b/language/automl/pom.xml
index 40012a4a52f..8caf27fe038 100644
--- a/language/automl/pom.xml
+++ b/language/automl/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/language/automl/src/main/java/com/google/cloud/language/samples/DatasetApi.java b/language/automl/src/main/java/com/google/cloud/language/samples/DatasetApi.java
index 5f44f95cf43..95d6525af0d 100644
--- a/language/automl/src/main/java/com/google/cloud/language/samples/DatasetApi.java
+++ b/language/automl/src/main/java/com/google/cloud/language/samples/DatasetApi.java
@@ -29,11 +29,9 @@
import com.google.cloud.automl.v1beta1.OutputConfig;
import com.google.cloud.automl.v1beta1.TextClassificationDatasetMetadata;
import com.google.protobuf.Empty;
-
import java.io.IOException;
import java.io.PrintStream;
import java.util.Arrays;
-
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
@@ -208,7 +206,7 @@ public static void importData(
// Get multiple training data files to be imported
GcsSource gcsSource =
- GcsSource.newBuilder().addAllInputUris(Arrays.asList(path.split(","))).build();
+ GcsSource.newBuilder().addAllInputUris(Arrays.asList(path.split(","))).build();
// Import data from the input URI
InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).build();
diff --git a/language/automl/src/main/java/com/google/cloud/language/samples/ModelApi.java b/language/automl/src/main/java/com/google/cloud/language/samples/ModelApi.java
index f827742ca2a..260d3d2a548 100644
--- a/language/automl/src/main/java/com/google/cloud/language/samples/ModelApi.java
+++ b/language/automl/src/main/java/com/google/cloud/language/samples/ModelApi.java
@@ -29,11 +29,9 @@
import com.google.cloud.automl.v1beta1.ModelEvaluationName;
import com.google.cloud.automl.v1beta1.ModelName;
import com.google.cloud.automl.v1beta1.OperationMetadata;
-
import com.google.cloud.automl.v1beta1.TextClassificationModelMetadata;
import com.google.longrunning.Operation;
import com.google.protobuf.Empty;
-
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
diff --git a/language/automl/src/main/java/com/google/cloud/language/samples/PredictionApi.java b/language/automl/src/main/java/com/google/cloud/language/samples/PredictionApi.java
index 6985470c312..fc8743521d1 100644
--- a/language/automl/src/main/java/com/google/cloud/language/samples/PredictionApi.java
+++ b/language/automl/src/main/java/com/google/cloud/language/samples/PredictionApi.java
@@ -23,15 +23,12 @@
import com.google.cloud.automl.v1beta1.PredictResponse;
import com.google.cloud.automl.v1beta1.PredictionServiceClient;
import com.google.cloud.automl.v1beta1.TextSnippet;
-
import java.io.IOException;
import java.io.PrintStream;
-
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
-
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
diff --git a/language/automl/src/test/java/com/google/cloud/language/samples/DatasetApiIT.java b/language/automl/src/test/java/com/google/cloud/language/samples/DatasetApiIT.java
index c10c9918cc1..5510e7edc56 100644
--- a/language/automl/src/test/java/com/google/cloud/language/samples/DatasetApiIT.java
+++ b/language/automl/src/test/java/com/google/cloud/language/samples/DatasetApiIT.java
@@ -21,7 +21,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/language/automl/src/test/java/com/google/cloud/language/samples/ModelApiIT.java b/language/automl/src/test/java/com/google/cloud/language/samples/ModelApiIT.java
index 49f93ebb089..9be28510451 100644
--- a/language/automl/src/test/java/com/google/cloud/language/samples/ModelApiIT.java
+++ b/language/automl/src/test/java/com/google/cloud/language/samples/ModelApiIT.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/language/automl/src/test/java/com/google/cloud/language/samples/PredictionApiIT.java b/language/automl/src/test/java/com/google/cloud/language/samples/PredictionApiIT.java
index ed5a115852a..c4925077e24 100644
--- a/language/automl/src/test/java/com/google/cloud/language/samples/PredictionApiIT.java
+++ b/language/automl/src/test/java/com/google/cloud/language/samples/PredictionApiIT.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/language/cloud-client/pom.xml b/language/cloud-client/pom.xml
index 913504ef899..124be00c2f5 100644
--- a/language/cloud-client/pom.xml
+++ b/language/cloud-client/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
1.8
diff --git a/language/cloud-client/src/main/java/com/example/language/QuickstartSample.java b/language/cloud-client/src/main/java/com/example/language/QuickstartSample.java
index 85f516bd1ef..c264dc96dd6 100644
--- a/language/cloud-client/src/main/java/com/example/language/QuickstartSample.java
+++ b/language/cloud-client/src/main/java/com/example/language/QuickstartSample.java
@@ -30,8 +30,7 @@ public static void main(String... args) throws Exception {
// The text to analyze
String text = "Hello, world!";
- Document doc = Document.newBuilder()
- .setContent(text).setType(Type.PLAIN_TEXT).build();
+ Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();
// Detects the sentiment of the text
Sentiment sentiment = language.analyzeSentiment(doc).getDocumentSentiment();
diff --git a/language/cloud-client/src/main/java/com/example/language/SetEndpoint.java b/language/cloud-client/src/main/java/com/example/language/SetEndpoint.java
index 618d91b4259..73ab525a4fb 100644
--- a/language/cloud-client/src/main/java/com/example/language/SetEndpoint.java
+++ b/language/cloud-client/src/main/java/com/example/language/SetEndpoint.java
@@ -20,7 +20,6 @@
import com.google.cloud.language.v1.LanguageServiceClient;
import com.google.cloud.language.v1.LanguageServiceSettings;
import com.google.cloud.language.v1.Sentiment;
-
import java.io.IOException;
class SetEndpoint {
@@ -28,9 +27,8 @@ class SetEndpoint {
// Change your endpoint
static void setEndpoint() throws IOException {
// [START language_set_endpoint]
- LanguageServiceSettings settings = LanguageServiceSettings.newBuilder()
- .setEndpoint("eu-language.googleapis.com:443")
- .build();
+ LanguageServiceSettings settings =
+ LanguageServiceSettings.newBuilder().setEndpoint("eu-language.googleapis.com:443").build();
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
@@ -40,8 +38,7 @@ static void setEndpoint() throws IOException {
// The text to analyze
String text = "Hello, world!";
- Document doc = Document.newBuilder()
- .setContent(text).setType(Document.Type.PLAIN_TEXT).build();
+ Document doc = Document.newBuilder().setContent(text).setType(Document.Type.PLAIN_TEXT).build();
// Detects the sentiment of the text
Sentiment sentiment = client.analyzeSentiment(doc).getDocumentSentiment();
diff --git a/language/cloud-client/src/test/java/com/example/language/QuickstartSampleIT.java b/language/cloud-client/src/test/java/com/example/language/QuickstartSampleIT.java
index 4fad6479404..9f335c78a5b 100644
--- a/language/cloud-client/src/test/java/com/example/language/QuickstartSampleIT.java
+++ b/language/cloud-client/src/test/java/com/example/language/QuickstartSampleIT.java
@@ -26,9 +26,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for quickstart sample.
- */
+/** Tests for quickstart sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class QuickstartSampleIT {
diff --git a/language/cloud-client/src/test/java/com/example/language/SetEndpointIT.java b/language/cloud-client/src/test/java/com/example/language/SetEndpointIT.java
index 1a8bbc50636..df570711337 100644
--- a/language/cloud-client/src/test/java/com/example/language/SetEndpointIT.java
+++ b/language/cloud-client/src/test/java/com/example/language/SetEndpointIT.java
@@ -21,7 +21,6 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -36,7 +35,6 @@ public class SetEndpointIT {
private ByteArrayOutputStream bout;
private PrintStream out;
-
@Before
public void setUp() {
bout = new ByteArrayOutputStream();
@@ -49,7 +47,6 @@ public void tearDown() {
System.setOut(null);
}
-
@Test
public void testSetEndpoint() throws IOException {
// Act
diff --git a/logging/cloud-client/pom.xml b/logging/cloud-client/pom.xml
index 1343dd23b88..37aa422f660 100644
--- a/logging/cloud-client/pom.xml
+++ b/logging/cloud-client/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/logging/jul/pom.xml b/logging/jul/pom.xml
index 964dc1e95e0..710247ed8cc 100644
--- a/logging/jul/pom.xml
+++ b/logging/jul/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/logging/logback/pom.xml b/logging/logback/pom.xml
index ae6b5214dfe..f64324c1c56 100644
--- a/logging/logback/pom.xml
+++ b/logging/logback/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/mlengine/online-prediction/pom.xml b/mlengine/online-prediction/pom.xml
index 04c35b9f8fd..883e6aef18d 100644
--- a/mlengine/online-prediction/pom.xml
+++ b/mlengine/online-prediction/pom.xml
@@ -24,7 +24,7 @@ limitations under the License.
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/monitoring/cloud-client/pom.xml b/monitoring/cloud-client/pom.xml
index f0ed8e14114..33edbfbc144 100644
--- a/monitoring/cloud-client/pom.xml
+++ b/monitoring/cloud-client/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/monitoring/cloud-client/src/main/java/com/example/monitoring/QuickstartSample.java b/monitoring/cloud-client/src/main/java/com/example/monitoring/QuickstartSample.java
index 151594b819b..fcfd392a43f 100644
--- a/monitoring/cloud-client/src/main/java/com/example/monitoring/QuickstartSample.java
+++ b/monitoring/cloud-client/src/main/java/com/example/monitoring/QuickstartSample.java
@@ -16,7 +16,7 @@
package com.example.monitoring;
-//CHECKSTYLE OFF: VariableDeclarationUsageDistance
+// CHECKSTYLE OFF: VariableDeclarationUsageDistance
// [START monitoring_quickstart]
import com.google.api.Metric;
@@ -51,16 +51,12 @@ public static void main(String... args) throws Exception {
MetricServiceClient metricServiceClient = MetricServiceClient.create();
// Prepares an individual data point
- TimeInterval interval = TimeInterval.newBuilder()
- .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
- .build();
- TypedValue value = TypedValue.newBuilder()
- .setDoubleValue(123.45)
- .build();
- Point point = Point.newBuilder()
- .setInterval(interval)
- .setValue(value)
- .build();
+ TimeInterval interval =
+ TimeInterval.newBuilder()
+ .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
+ .build();
+ TypedValue value = TypedValue.newBuilder().setDoubleValue(123.45).build();
+ Point point = Point.newBuilder().setInterval(interval).setValue(value).build();
List pointList = new ArrayList<>();
pointList.add(point);
@@ -70,32 +66,33 @@ public static void main(String... args) throws Exception {
// Prepares the metric descriptor
Map metricLabels = new HashMap();
metricLabels.put("store_id", "Pittsburg");
- Metric metric = Metric.newBuilder()
- .setType("custom.googleapis.com/stores/daily_sales")
- .putAllLabels(metricLabels)
- .build();
+ Metric metric =
+ Metric.newBuilder()
+ .setType("custom.googleapis.com/stores/daily_sales")
+ .putAllLabels(metricLabels)
+ .build();
// Prepares the monitored resource descriptor
Map resourceLabels = new HashMap();
resourceLabels.put("project_id", projectId);
- MonitoredResource resource = MonitoredResource.newBuilder()
- .setType("global")
- .putAllLabels(resourceLabels)
- .build();
+ MonitoredResource resource =
+ MonitoredResource.newBuilder().setType("global").putAllLabels(resourceLabels).build();
// Prepares the time series request
- TimeSeries timeSeries = TimeSeries.newBuilder()
- .setMetric(metric)
- .setResource(resource)
- .addAllPoints(pointList)
- .build();
+ TimeSeries timeSeries =
+ TimeSeries.newBuilder()
+ .setMetric(metric)
+ .setResource(resource)
+ .addAllPoints(pointList)
+ .build();
List timeSeriesList = new ArrayList<>();
timeSeriesList.add(timeSeries);
- CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder()
- .setName(name.toString())
- .addAllTimeSeries(timeSeriesList)
- .build();
+ CreateTimeSeriesRequest request =
+ CreateTimeSeriesRequest.newBuilder()
+ .setName(name.toString())
+ .addAllTimeSeries(timeSeriesList)
+ .build();
// Writes time series data
metricServiceClient.createTimeSeries(request);
@@ -106,4 +103,4 @@ public static void main(String... args) throws Exception {
}
}
// [END monitoring_quickstart]
-//CHECKSTYLE ON: VariableDeclarationUsageDistance
+// CHECKSTYLE ON: VariableDeclarationUsageDistance
diff --git a/monitoring/cloud-client/src/main/java/com/example/monitoring/Snippets.java b/monitoring/cloud-client/src/main/java/com/example/monitoring/Snippets.java
index a84d3df25cb..b2967ccd5eb 100644
--- a/monitoring/cloud-client/src/main/java/com/example/monitoring/Snippets.java
+++ b/monitoring/cloud-client/src/main/java/com/example/monitoring/Snippets.java
@@ -41,7 +41,6 @@
import com.google.monitoring.v3.TypedValue;
import com.google.protobuf.Duration;
import com.google.protobuf.util.Timestamps;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
@@ -50,16 +49,17 @@
// Imports the Google Cloud client library
-
public class Snippets {
private static final String CUSTOM_METRIC_DOMAIN = "custom.googleapis.com";
private static final Gson gson = new Gson();
/**
* Exercises the methods defined in this class.
+ *
*
- *
Assumes that you are authenticated using the Google Cloud SDK (using
- * {@code gcloud auth application-default-login}).
+ *
+ *
Assumes that you are authenticated using the Google Cloud SDK (using {@code gcloud auth
+ * application-default-login}).
*/
public static void main(String[] args) throws Exception {
@@ -85,8 +85,9 @@ public static void main(String[] args) throws Exception {
/**
* Creates a metric descriptor.
- *
- * See: https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create
+ *
+ *
See:
+ * https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors/create
*
* @param type The metric type
*/
@@ -99,21 +100,23 @@ void createMetricDescriptor(String type) throws IOException {
final MetricServiceClient client = MetricServiceClient.create();
ProjectName name = ProjectName.of(projectId);
- MetricDescriptor descriptor = MetricDescriptor.newBuilder()
- .setType(metricType)
- .addLabels(LabelDescriptor
- .newBuilder()
- .setKey("store_id")
- .setValueType(LabelDescriptor.ValueType.STRING))
- .setDescription("This is a simple example of a custom metric.")
- .setMetricKind(MetricDescriptor.MetricKind.GAUGE)
- .setValueType(MetricDescriptor.ValueType.DOUBLE)
- .build();
-
- CreateMetricDescriptorRequest request = CreateMetricDescriptorRequest.newBuilder()
- .setName(name.toString())
- .setMetricDescriptor(descriptor)
- .build();
+ MetricDescriptor descriptor =
+ MetricDescriptor.newBuilder()
+ .setType(metricType)
+ .addLabels(
+ LabelDescriptor.newBuilder()
+ .setKey("store_id")
+ .setValueType(LabelDescriptor.ValueType.STRING))
+ .setDescription("This is a simple example of a custom metric.")
+ .setMetricKind(MetricDescriptor.MetricKind.GAUGE)
+ .setValueType(MetricDescriptor.ValueType.DOUBLE)
+ .build();
+
+ CreateMetricDescriptorRequest request =
+ CreateMetricDescriptorRequest.newBuilder()
+ .setName(name.toString())
+ .setMetricDescriptor(descriptor)
+ .build();
client.createMetricDescriptor(request);
// [END monitoring_create_metric]
@@ -137,12 +140,11 @@ void deleteMetricDescriptor(String name) throws IOException {
/**
* Demonstrates writing a time series value for the metric type
* 'custom.google.apis.com/my_metric'.
- *
- * This method assumes `my_metric` descriptor has already been created as a
- * DOUBLE value_type and GAUGE metric kind. If the metric descriptor
- * doesn't exist, it will be auto-created.
+ *
+ *
This method assumes `my_metric` descriptor has already been created as a DOUBLE value_type
+ * and GAUGE metric kind. If the metric descriptor doesn't exist, it will be auto-created.
*/
- //CHECKSTYLE OFF: VariableDeclarationUsageDistance
+ // CHECKSTYLE OFF: VariableDeclarationUsageDistance
void writeTimeSeries() throws IOException {
// [START monitoring_write_timeseries]
String projectId = System.getProperty("projectId");
@@ -150,16 +152,12 @@ void writeTimeSeries() throws IOException {
MetricServiceClient metricServiceClient = MetricServiceClient.create();
// Prepares an individual data point
- TimeInterval interval = TimeInterval.newBuilder()
- .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
- .build();
- TypedValue value = TypedValue.newBuilder()
- .setDoubleValue(123.45)
- .build();
- Point point = Point.newBuilder()
- .setInterval(interval)
- .setValue(value)
- .build();
+ TimeInterval interval =
+ TimeInterval.newBuilder()
+ .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
+ .build();
+ TypedValue value = TypedValue.newBuilder().setDoubleValue(123.45).build();
+ Point point = Point.newBuilder().setInterval(interval).setValue(value).build();
List pointList = new ArrayList<>();
pointList.add(point);
@@ -168,46 +166,45 @@ void writeTimeSeries() throws IOException {
// Prepares the metric descriptor
Map metricLabels = new HashMap<>();
- Metric metric = Metric.newBuilder()
- .setType("custom.googleapis.com/my_metric")
- .putAllLabels(metricLabels)
- .build();
+ Metric metric =
+ Metric.newBuilder()
+ .setType("custom.googleapis.com/my_metric")
+ .putAllLabels(metricLabels)
+ .build();
// Prepares the monitored resource descriptor
Map resourceLabels = new HashMap<>();
resourceLabels.put("instance_id", "1234567890123456789");
resourceLabels.put("zone", "us-central1-f");
- MonitoredResource resource = MonitoredResource.newBuilder()
- .setType("gce_instance")
- .putAllLabels(resourceLabels)
- .build();
+ MonitoredResource resource =
+ MonitoredResource.newBuilder().setType("gce_instance").putAllLabels(resourceLabels).build();
// Prepares the time series request
- TimeSeries timeSeries = TimeSeries.newBuilder()
- .setMetric(metric)
- .setResource(resource)
- .addAllPoints(pointList)
- .build();
+ TimeSeries timeSeries =
+ TimeSeries.newBuilder()
+ .setMetric(metric)
+ .setResource(resource)
+ .addAllPoints(pointList)
+ .build();
List timeSeriesList = new ArrayList<>();
timeSeriesList.add(timeSeries);
- CreateTimeSeriesRequest request = CreateTimeSeriesRequest.newBuilder()
- .setName(name.toString())
- .addAllTimeSeries(timeSeriesList)
- .build();
+ CreateTimeSeriesRequest request =
+ CreateTimeSeriesRequest.newBuilder()
+ .setName(name.toString())
+ .addAllTimeSeries(timeSeriesList)
+ .build();
// Writes time series data
metricServiceClient.createTimeSeries(request);
System.out.println("Done writing time series value.");
// [END monitoring_write_timeseries]
}
- //CHECKSTYLE ON: VariableDeclarationUsageDistance
+ // CHECKSTYLE ON: VariableDeclarationUsageDistance
- /**
- * Demonstrates listing time series headers.
- */
+ /** Demonstrates listing time series headers. */
void listTimeSeriesHeaders() throws IOException {
// [START monitoring_read_timeseries_fields]
MetricServiceClient metricServiceClient = MetricServiceClient.create();
@@ -216,16 +213,18 @@ void listTimeSeriesHeaders() throws IOException {
// Restrict time to last 20 minutes
long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
- TimeInterval interval = TimeInterval.newBuilder()
- .setStartTime(Timestamps.fromMillis(startMillis))
- .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
- .build();
-
- ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder()
- .setName(name.toString())
- .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
- .setInterval(interval)
- .setView(ListTimeSeriesRequest.TimeSeriesView.HEADERS);
+ TimeInterval interval =
+ TimeInterval.newBuilder()
+ .setStartTime(Timestamps.fromMillis(startMillis))
+ .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
+ .build();
+
+ ListTimeSeriesRequest.Builder requestBuilder =
+ ListTimeSeriesRequest.newBuilder()
+ .setName(name.toString())
+ .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
+ .setInterval(interval)
+ .setView(ListTimeSeriesRequest.TimeSeriesView.HEADERS);
ListTimeSeriesRequest request = requestBuilder.build();
@@ -238,9 +237,7 @@ void listTimeSeriesHeaders() throws IOException {
// [END monitoring_read_timeseries_fields]
}
- /**
- * Demonstrates listing time series using a filter.
- */
+ /** Demonstrates listing time series using a filter. */
void listTimeSeries(String filter) throws IOException {
// [START monitoring_read_timeseries_simple]
MetricServiceClient metricServiceClient = MetricServiceClient.create();
@@ -249,15 +246,17 @@ void listTimeSeries(String filter) throws IOException {
// Restrict time to last 20 minutes
long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
- TimeInterval interval = TimeInterval.newBuilder()
- .setStartTime(Timestamps.fromMillis(startMillis))
- .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
- .build();
-
- ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder()
- .setName(name.toString())
- .setFilter(filter)
- .setInterval(interval);
+ TimeInterval interval =
+ TimeInterval.newBuilder()
+ .setStartTime(Timestamps.fromMillis(startMillis))
+ .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
+ .build();
+
+ ListTimeSeriesRequest.Builder requestBuilder =
+ ListTimeSeriesRequest.newBuilder()
+ .setName(name.toString())
+ .setFilter(filter)
+ .setInterval(interval);
ListTimeSeriesRequest request = requestBuilder.build();
@@ -270,9 +269,7 @@ void listTimeSeries(String filter) throws IOException {
// [END monitoring_read_timeseries_simple]
}
- /**
- * Demonstrates listing time series and aggregating them.
- */
+ /** Demonstrates listing time series and aggregating them. */
void listTimeSeriesAggregrate() throws IOException {
// [START monitoring_read_timeseries_align]
MetricServiceClient metricServiceClient = MetricServiceClient.create();
@@ -281,21 +278,24 @@ void listTimeSeriesAggregrate() throws IOException {
// Restrict time to last 20 minutes
long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
- TimeInterval interval = TimeInterval.newBuilder()
- .setStartTime(Timestamps.fromMillis(startMillis))
- .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
- .build();
-
- Aggregation aggregation = Aggregation.newBuilder()
- .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
- .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
- .build();
-
- ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder()
- .setName(name.toString())
- .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
- .setInterval(interval)
- .setAggregation(aggregation);
+ TimeInterval interval =
+ TimeInterval.newBuilder()
+ .setStartTime(Timestamps.fromMillis(startMillis))
+ .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
+ .build();
+
+ Aggregation aggregation =
+ Aggregation.newBuilder()
+ .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
+ .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
+ .build();
+
+ ListTimeSeriesRequest.Builder requestBuilder =
+ ListTimeSeriesRequest.newBuilder()
+ .setName(name.toString())
+ .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
+ .setInterval(interval)
+ .setAggregation(aggregation);
ListTimeSeriesRequest request = requestBuilder.build();
@@ -308,9 +308,7 @@ void listTimeSeriesAggregrate() throws IOException {
// [END monitoring_read_timeseries_align]
}
- /**
- * Demonstrates listing time series and aggregating and reducing them.
- */
+ /** Demonstrates listing time series and aggregating and reducing them. */
void listTimeSeriesReduce() throws IOException {
// [START monitoring_read_timeseries_reduce]
MetricServiceClient metricServiceClient = MetricServiceClient.create();
@@ -319,22 +317,25 @@ void listTimeSeriesReduce() throws IOException {
// Restrict time to last 20 minutes
long startMillis = System.currentTimeMillis() - ((60 * 20) * 1000);
- TimeInterval interval = TimeInterval.newBuilder()
- .setStartTime(Timestamps.fromMillis(startMillis))
- .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
- .build();
-
- Aggregation aggregation = Aggregation.newBuilder()
- .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
- .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
- .setCrossSeriesReducer(Aggregation.Reducer.REDUCE_MEAN)
- .build();
-
- ListTimeSeriesRequest.Builder requestBuilder = ListTimeSeriesRequest.newBuilder()
- .setName(name.toString())
- .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
- .setInterval(interval)
- .setAggregation(aggregation);
+ TimeInterval interval =
+ TimeInterval.newBuilder()
+ .setStartTime(Timestamps.fromMillis(startMillis))
+ .setEndTime(Timestamps.fromMillis(System.currentTimeMillis()))
+ .build();
+
+ Aggregation aggregation =
+ Aggregation.newBuilder()
+ .setAlignmentPeriod(Duration.newBuilder().setSeconds(600).build())
+ .setPerSeriesAligner(Aggregation.Aligner.ALIGN_MEAN)
+ .setCrossSeriesReducer(Aggregation.Reducer.REDUCE_MEAN)
+ .build();
+
+ ListTimeSeriesRequest.Builder requestBuilder =
+ ListTimeSeriesRequest.newBuilder()
+ .setName(name.toString())
+ .setFilter("metric.type=\"compute.googleapis.com/instance/cpu/utilization\"")
+ .setInterval(interval)
+ .setAggregation(aggregation);
ListTimeSeriesRequest request = requestBuilder.build();
@@ -347,9 +348,7 @@ void listTimeSeriesReduce() throws IOException {
// [END monitoring_read_timeseries_reduce]
}
- /**
- * Returns the first page of all metric descriptors.
- */
+ /** Returns the first page of all metric descriptors. */
void listMetricDescriptors() throws IOException {
// [START monitoring_list_descriptors]
// Your Google Cloud Platform project ID
@@ -358,10 +357,8 @@ void listMetricDescriptors() throws IOException {
final MetricServiceClient client = MetricServiceClient.create();
ProjectName name = ProjectName.of(projectId);
- ListMetricDescriptorsRequest request = ListMetricDescriptorsRequest
- .newBuilder()
- .setName(name.toString())
- .build();
+ ListMetricDescriptorsRequest request =
+ ListMetricDescriptorsRequest.newBuilder().setName(name.toString()).build();
ListMetricDescriptorsPagedResponse response = client.listMetricDescriptors(request);
System.out.println("Listing descriptors: ");
@@ -372,9 +369,7 @@ void listMetricDescriptors() throws IOException {
// [END monitoring_list_descriptors]
}
- /**
- * Gets all monitored resource descriptors.
- */
+ /** Gets all monitored resource descriptors. */
void listMonitoredResources() throws IOException {
// [START monitoring_list_resources]
// Your Google Cloud Platform project ID
@@ -383,15 +378,13 @@ void listMonitoredResources() throws IOException {
final MetricServiceClient client = MetricServiceClient.create();
ProjectName name = ProjectName.of(projectId);
- ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest
- .newBuilder()
- .setName(name.toString())
- .build();
+ ListMonitoredResourceDescriptorsRequest request =
+ ListMonitoredResourceDescriptorsRequest.newBuilder().setName(name.toString()).build();
System.out.println("Listing monitored resource descriptors: ");
- ListMonitoredResourceDescriptorsPagedResponse response = client
- .listMonitoredResourceDescriptors(request);
+ ListMonitoredResourceDescriptorsPagedResponse response =
+ client.listMonitoredResourceDescriptors(request);
for (MonitoredResourceDescriptor d : response.iterateAll()) {
System.out.println(d.getType());
@@ -429,7 +422,6 @@ void describeMonitoredResources(String type) throws IOException {
// [END monitoring_get_descriptor]
}
-
/**
* Handles a single command.
*
@@ -531,15 +523,18 @@ private static void printUsage() {
System.out.println(" get-resource Describes a monitored resource");
System.out.println(" delete-metric-descriptors Deletes a metric descriptor");
System.out.println(" write-time-series Writes a time series value to a metric");
- System.out.println(" list-headers List time series header of "
- + " 'compute.googleapis.com/instance/cpu/utilization'");
- System.out.println(" list-time-series-header List time series data that matches a "
- + "given filter");
- System.out.println(" list-aggregate `Aggregates time series data that matches"
- + "'compute.googleapis.com/instance/cpu/utilization");
- System.out.println(" list-reduce `Reduces time series data that matches"
- + " 'compute.googleapis.com/instance/cpu/utilization");
+ System.out.println(
+ " list-headers List time series header of "
+ + " 'compute.googleapis.com/instance/cpu/utilization'");
+ System.out.println(
+ " list-time-series-header List time series data that matches a "
+ + "given filter");
+ System.out.println(
+ " list-aggregate `Aggregates time series data that matches"
+ + "'compute.googleapis.com/instance/cpu/utilization");
+ System.out.println(
+ " list-reduce `Reduces time series data that matches"
+ + " 'compute.googleapis.com/instance/cpu/utilization");
System.out.println();
}
-
}
diff --git a/monitoring/cloud-client/src/test/java/com/example/monitoring/QuickstartSampleIT.java b/monitoring/cloud-client/src/test/java/com/example/monitoring/QuickstartSampleIT.java
index e118067e1d2..d4bd52c55a3 100644
--- a/monitoring/cloud-client/src/test/java/com/example/monitoring/QuickstartSampleIT.java
+++ b/monitoring/cloud-client/src/test/java/com/example/monitoring/QuickstartSampleIT.java
@@ -26,9 +26,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for quickstart sample.
- */
+/** Tests for quickstart sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class QuickstartSampleIT {
@@ -40,8 +38,8 @@ public class QuickstartSampleIT {
private static String getProjectId() {
String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME));
if (projectId == null) {
- projectId = System.getProperty(LEGACY_PROJECT_ENV_NAME,
- System.getenv(LEGACY_PROJECT_ENV_NAME));
+ projectId =
+ System.getProperty(LEGACY_PROJECT_ENV_NAME, System.getenv(LEGACY_PROJECT_ENV_NAME));
}
return projectId;
}
diff --git a/monitoring/cloud-client/src/test/java/com/example/monitoring/SnippetsIT.java b/monitoring/cloud-client/src/test/java/com/example/monitoring/SnippetsIT.java
index 5b4eb9beda9..9685926bbba 100644
--- a/monitoring/cloud-client/src/test/java/com/example/monitoring/SnippetsIT.java
+++ b/monitoring/cloud-client/src/test/java/com/example/monitoring/SnippetsIT.java
@@ -20,16 +20,13 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for quickstart sample.
- */
+/** Tests for quickstart sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class SnippetsIT {
@@ -41,8 +38,8 @@ public class SnippetsIT {
private static String getProjectId() {
String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME));
if (projectId == null) {
- projectId = System.getProperty(LEGACY_PROJECT_ENV_NAME,
- System.getenv(LEGACY_PROJECT_ENV_NAME));
+ projectId =
+ System.getProperty(LEGACY_PROJECT_ENV_NAME, System.getenv(LEGACY_PROJECT_ENV_NAME));
}
return projectId;
}
diff --git a/monitoring/v3/pom.xml b/monitoring/v3/pom.xml
index 715c0417d48..6c10364746d 100644
--- a/monitoring/v3/pom.xml
+++ b/monitoring/v3/pom.xml
@@ -27,7 +27,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/monitoring/v3/src/main/java/com/example/AlertSample.java b/monitoring/v3/src/main/java/com/example/AlertSample.java
index 163903a4e75..538d595fd32 100644
--- a/monitoring/v3/src/main/java/com/example/AlertSample.java
+++ b/monitoring/v3/src/main/java/com/example/AlertSample.java
@@ -37,7 +37,6 @@
import com.google.monitoring.v3.ProjectName;
import com.google.protobuf.BoolValue;
import com.google.protobuf.FieldMask;
-
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
@@ -45,7 +44,6 @@
import java.util.List;
import java.util.Map;
import java.util.Optional;
-
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
@@ -56,70 +54,73 @@
public class AlertSample {
- private static final Option PROJECT_ID_OPTION = Option.builder("p")
- .longOpt("projectid")
- .desc("Your Google project id.")
- .hasArg()
- .argName("PROJECT_ID")
- .build();
- private static final Option FILE_PATH_OPTION = Option.builder("j")
- .longOpt("jsonPath")
- .desc("Path to json file where alert polices are saved and restored.")
- .hasArg()
- .argName("JSON_PATH")
- .build();
- private static final Option ALERT_ID_OPTION = Option.builder("a")
- .required()
- .longOpt("alert-id")
- .desc("The id of the alert policy whose channels will be replaced.")
- .hasArg()
- .argName("ALERT_ID")
- .build();
- private static final Option CHANNEL_ID_OPTION = Option.builder("c")
- .longOpt("channel-id")
- .desc("A channel id. Repeat this option to set multiple channel ids.")
- .hasArg()
- .argName("CHANNEL_ID")
- .build();
- private static final Option FILTER_OPTION = Option.builder("d")
- .longOpt("filter")
- .desc("See https://cloud.google.com/monitoring/api/v3/filters.")
- .hasArg()
- .argName("FILTER")
- .build();
-
- private static final Options BASE_OPTIONS = new Options()
- .addOption(PROJECT_ID_OPTION);
- private static final Options BACKUP_OPTIONS = new Options()
- .addOption(PROJECT_ID_OPTION)
- .addOption(FILE_PATH_OPTION);
- private static final Options REPLACE_CHANNELS_OPTIONS = new Options()
- .addOption(PROJECT_ID_OPTION)
- .addOption(ALERT_ID_OPTION)
- .addOption(CHANNEL_ID_OPTION);
- private static final Options ENABLE_OPTIONS = new Options()
- .addOption(PROJECT_ID_OPTION)
- .addOption(FILTER_OPTION);
-
- private static Map COMMAND_OPTIONS = ImmutableMap.of(
- "backup", BACKUP_OPTIONS,
- "restore", BACKUP_OPTIONS,
- "replace-channels", REPLACE_CHANNELS_OPTIONS,
- "enable", ENABLE_OPTIONS,
- "disable", ENABLE_OPTIONS
- );
+ private static final Option PROJECT_ID_OPTION =
+ Option.builder("p")
+ .longOpt("projectid")
+ .desc("Your Google project id.")
+ .hasArg()
+ .argName("PROJECT_ID")
+ .build();
+ private static final Option FILE_PATH_OPTION =
+ Option.builder("j")
+ .longOpt("jsonPath")
+ .desc("Path to json file where alert polices are saved and restored.")
+ .hasArg()
+ .argName("JSON_PATH")
+ .build();
+ private static final Option ALERT_ID_OPTION =
+ Option.builder("a")
+ .required()
+ .longOpt("alert-id")
+ .desc("The id of the alert policy whose channels will be replaced.")
+ .hasArg()
+ .argName("ALERT_ID")
+ .build();
+ private static final Option CHANNEL_ID_OPTION =
+ Option.builder("c")
+ .longOpt("channel-id")
+ .desc("A channel id. Repeat this option to set multiple channel ids.")
+ .hasArg()
+ .argName("CHANNEL_ID")
+ .build();
+ private static final Option FILTER_OPTION =
+ Option.builder("d")
+ .longOpt("filter")
+ .desc("See https://cloud.google.com/monitoring/api/v3/filters.")
+ .hasArg()
+ .argName("FILTER")
+ .build();
+
+ private static final Options BASE_OPTIONS = new Options().addOption(PROJECT_ID_OPTION);
+ private static final Options BACKUP_OPTIONS =
+ new Options().addOption(PROJECT_ID_OPTION).addOption(FILE_PATH_OPTION);
+ private static final Options REPLACE_CHANNELS_OPTIONS =
+ new Options()
+ .addOption(PROJECT_ID_OPTION)
+ .addOption(ALERT_ID_OPTION)
+ .addOption(CHANNEL_ID_OPTION);
+ private static final Options ENABLE_OPTIONS =
+ new Options().addOption(PROJECT_ID_OPTION).addOption(FILTER_OPTION);
+
+ private static Map COMMAND_OPTIONS =
+ ImmutableMap.of(
+ "backup", BACKUP_OPTIONS,
+ "restore", BACKUP_OPTIONS,
+ "replace-channels", REPLACE_CHANNELS_OPTIONS,
+ "enable", ENABLE_OPTIONS,
+ "disable", ENABLE_OPTIONS);
private static final CommandLineParser PARSER = new DefaultParser();
- private static final FieldMask NOTIFICATION_CHANNEL_UPDATE_MASK = FieldMask
- .newBuilder()
- .addPaths("type")
- .addPaths("name")
- .addPaths("displayName")
- .addPaths("description")
- .addPaths("labels")
- .addPaths("userLabels")
- .build();
+ private static final FieldMask NOTIFICATION_CHANNEL_UPDATE_MASK =
+ FieldMask.newBuilder()
+ .addPaths("type")
+ .addPaths("name")
+ .addPaths("displayName")
+ .addPaths("description")
+ .addPaths("labels")
+ .addPaths("userLabels")
+ .build();
private static Gson gson = new Gson();
@@ -133,17 +134,19 @@ public static void main(String... args) throws IOException {
CommandLine cl = parseCommandLine(args, expectedOptions);
- String projectId = cl.hasOption(PROJECT_ID_OPTION.getOpt())
- ? cl.getOptionValue(PROJECT_ID_OPTION.getOpt())
- : System.getenv("GOOGLE_CLOUD_PROJECT");
+ String projectId =
+ cl.hasOption(PROJECT_ID_OPTION.getOpt())
+ ? cl.getOptionValue(PROJECT_ID_OPTION.getOpt())
+ : System.getenv("GOOGLE_CLOUD_PROJECT");
if (Strings.isNullOrEmpty(projectId)) {
projectId = System.getenv("DEVSHELL_PROJECT_ID");
}
if (Strings.isNullOrEmpty(projectId)) {
- usage("Error: --project-id arg required unless provided by the GOOGLE_CLOUD_PROJECT "
- + "or DEVSHELL_PROJECT_ID environment variables.");
+ usage(
+ "Error: --project-id arg required unless provided by the GOOGLE_CLOUD_PROJECT "
+ + "or DEVSHELL_PROJECT_ID environment variables.");
return;
}
@@ -248,7 +251,8 @@ private static void writePoliciesBackupFile(
String projectId,
String filePath,
List alertPolicies,
- List notificationChannels) throws IOException {
+ List notificationChannels)
+ throws IOException {
JsonObject backupContents = new JsonObject();
backupContents.add("project_id", new JsonPrimitive(projectId));
JsonArray policiesJson = new JsonArray();
@@ -280,9 +284,8 @@ private static void restorePolicies(String projectId, String filePath) throws IO
AlertPolicy[] policies = gson.fromJson(backupContent.get("policies"), AlertPolicy[].class);
List notificationChannels = readNotificationChannelsJson(backupContent);
- Map restoredChannelIds = restoreNotificationChannels(projectId,
- notificationChannels,
- isSameProject);
+ Map restoredChannelIds =
+ restoreNotificationChannels(projectId, notificationChannels, isSameProject);
List policiesToRestore =
reviseRestoredPolicies(policies, isSameProject, restoredChannelIds);
@@ -290,16 +293,15 @@ private static void restorePolicies(String projectId, String filePath) throws IO
}
private static List reviseRestoredPolicies(
- AlertPolicy[] policies,
- boolean isSameProject,
- Map restoredChannelIds) {
+ AlertPolicy[] policies, boolean isSameProject, Map restoredChannelIds) {
List newPolicies = Lists.newArrayListWithCapacity(policies.length);
for (AlertPolicy policy : policies) {
- AlertPolicy.Builder policyBuilder = policy
- .toBuilder()
- .clearNotificationChannels()
- .clearMutationRecord()
- .clearCreationRecord();
+ AlertPolicy.Builder policyBuilder =
+ policy
+ .toBuilder()
+ .clearNotificationChannels()
+ .clearMutationRecord()
+ .clearCreationRecord();
// Update restored notification channel names.
for (String channelName : policy.getNotificationChannelsList()) {
String newChannelName = restoredChannelIds.get(channelName);
@@ -321,9 +323,7 @@ private static List reviseRestoredPolicies(
// [START monitoring_alert_create_policy]
private static void restoreRevisedPolicies(
- String projectId,
- boolean isSameProject,
- List policies) throws IOException {
+ String projectId, boolean isSameProject, List policies) throws IOException {
try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
for (AlertPolicy policy : policies) {
if (!isSameProject) {
@@ -332,9 +332,9 @@ private static void restoreRevisedPolicies(
try {
client.updateAlertPolicy(null, policy);
} catch (Exception e) {
- policy = client.createAlertPolicy(
- ProjectName.of(projectId),
- policy.toBuilder().clearName().build());
+ policy =
+ client.createAlertPolicy(
+ ProjectName.of(projectId), policy.toBuilder().clearName().build());
}
}
System.out.println(String.format("Restored %s", policy.getName()));
@@ -345,8 +345,8 @@ private static void restoreRevisedPolicies(
private static List readNotificationChannelsJson(JsonObject backupContent) {
if (backupContent.has("notification_channels")) {
- NotificationChannel[] channels = gson.fromJson(backupContent.get("notification_channels"),
- NotificationChannel[].class);
+ NotificationChannel[] channels =
+ gson.fromJson(backupContent.get("notification_channels"), NotificationChannel[].class);
return Lists.newArrayList(channels);
}
return Lists.newArrayList();
@@ -355,9 +355,8 @@ private static List readNotificationChannelsJson(JsonObject
// [START monitoring_alert_create_channel]
// [START monitoring_alert_update_channel]
private static Map restoreNotificationChannels(
- String projectId,
- List channels,
- boolean isSameProject) throws IOException {
+ String projectId, List channels, boolean isSameProject)
+ throws IOException {
Map newChannelNames = Maps.newHashMap();
try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
for (NotificationChannel channel : channels) {
@@ -374,13 +373,10 @@ private static Map restoreNotificationChannels(
}
}
if (!channelUpdated) {
- NotificationChannel newChannel = client.createNotificationChannel(
- ProjectName.of(projectId),
- channel
- .toBuilder()
- .clearName()
- .clearVerificationStatus()
- .build());
+ NotificationChannel newChannel =
+ client.createNotificationChannel(
+ ProjectName.of(projectId),
+ channel.toBuilder().clearName().clearVerificationStatus().build());
newChannelNames.put(channel.getName(), newChannel.getName());
}
}
@@ -402,16 +398,17 @@ private static JsonObject getPolicyJsonContents(String filePath, BufferedReader
// [START monitoring_alert_replace_channels]
private static void replaceChannels(String projectId, String alertPolicyId, String[] channelIds)
throws IOException {
- AlertPolicy.Builder policyBuilder = AlertPolicy
- .newBuilder()
- .setName(AlertPolicyName.of(projectId, alertPolicyId).toString());
+ AlertPolicy.Builder policyBuilder =
+ AlertPolicy.newBuilder().setName(AlertPolicyName.of(projectId, alertPolicyId).toString());
for (String channelId : channelIds) {
policyBuilder.addNotificationChannels(
NotificationChannelName.of(projectId, channelId).toString());
}
try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
- AlertPolicy result = client.updateAlertPolicy(
- FieldMask.newBuilder().addPaths("notification_channels").build(), policyBuilder.build());
+ AlertPolicy result =
+ client.updateAlertPolicy(
+ FieldMask.newBuilder().addPaths("notification_channels").build(),
+ policyBuilder.build());
System.out.println(String.format("Updated %s", result.getName()));
}
}
@@ -422,29 +419,32 @@ private static void replaceChannels(String projectId, String alertPolicyId, Stri
private static void enablePolicies(String projectId, String filter, boolean enable)
throws IOException {
try (AlertPolicyServiceClient client = AlertPolicyServiceClient.create()) {
- ListAlertPoliciesPagedResponse response = client
- .listAlertPolicies(ListAlertPoliciesRequest.newBuilder()
- .setName(ProjectName.of(projectId).toString())
- .setFilter(filter)
- .build());
+ ListAlertPoliciesPagedResponse response =
+ client.listAlertPolicies(
+ ListAlertPoliciesRequest.newBuilder()
+ .setName(ProjectName.of(projectId).toString())
+ .setFilter(filter)
+ .build());
for (AlertPolicy policy : response.iterateAll()) {
if (policy.getEnabled().getValue() == enable) {
- System.out.println(String.format(
- "Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled"));
+ System.out.println(
+ String.format(
+ "Policy %s is already %b.", policy.getName(), enable ? "enabled" : "disabled"));
continue;
}
- AlertPolicy updatedPolicy = AlertPolicy
- .newBuilder()
- .setName(policy.getName())
- .setEnabled(BoolValue.newBuilder().setValue(enable))
- .build();
- AlertPolicy result = client.updateAlertPolicy(
- FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy);
- System.out.println(String.format(
- "%s %s",
- result.getDisplayName(),
- result.getEnabled().getValue() ? "enabled" : "disabled"));
+ AlertPolicy updatedPolicy =
+ AlertPolicy.newBuilder()
+ .setName(policy.getName())
+ .setEnabled(BoolValue.newBuilder().setValue(enable))
+ .build();
+ AlertPolicy result =
+ client.updateAlertPolicy(
+ FieldMask.newBuilder().addPaths("enabled").build(), updatedPolicy);
+ System.out.println(
+ String.format(
+ "%s %s",
+ result.getDisplayName(), result.getEnabled().getValue() ? "enabled" : "disabled"));
}
}
}
@@ -458,11 +458,7 @@ private static void usage(String message) {
formatter.printHelp("list", "Lists alert policies.", BASE_OPTIONS, "", true);
System.out.println();
formatter.printHelp(
- "[backup|restore]",
- "Backs up or restores alert policies.",
- BACKUP_OPTIONS,
- "",
- true);
+ "[backup|restore]", "Backs up or restores alert policies.", BACKUP_OPTIONS, "", true);
System.out.println();
formatter.printHelp(
"replace-channels",
@@ -472,10 +468,6 @@ private static void usage(String message) {
true);
System.out.println();
formatter.printHelp(
- "[enable|disable]",
- "Enables/disables alert policies.",
- ENABLE_OPTIONS,
- "",
- true);
+ "[enable|disable]", "Enables/disables alert policies.", ENABLE_OPTIONS, "", true);
}
}
diff --git a/monitoring/v3/src/main/java/com/example/DeleteNotificationChannel.java b/monitoring/v3/src/main/java/com/example/DeleteNotificationChannel.java
index 4cad86ffc31..751f8d2d732 100644
--- a/monitoring/v3/src/main/java/com/example/DeleteNotificationChannel.java
+++ b/monitoring/v3/src/main/java/com/example/DeleteNotificationChannel.java
@@ -18,12 +18,12 @@
import com.google.cloud.monitoring.v3.NotificationChannelServiceClient;
import com.google.monitoring.v3.NotificationChannelName;
-
import java.io.IOException;
public class DeleteNotificationChannel {
/**
* Demonstrates deleting a notification channel by name.
+ *
* @param channelName Name of the notification channel to delete.
*/
// [START monitoring_alert_delete_channel]
diff --git a/monitoring/v3/src/main/java/com/example/UptimeSample.java b/monitoring/v3/src/main/java/com/example/UptimeSample.java
index 77bd0769551..bc1c5bfde6c 100644
--- a/monitoring/v3/src/main/java/com/example/UptimeSample.java
+++ b/monitoring/v3/src/main/java/com/example/UptimeSample.java
@@ -32,10 +32,8 @@
import com.google.monitoring.v3.UptimeCheckIp;
import com.google.protobuf.Duration;
import com.google.protobuf.FieldMask;
-
import java.io.IOException;
import java.util.Optional;
-
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
@@ -46,39 +44,44 @@
public class UptimeSample {
- private static final Option PROJECT_ID_OPTION = Option.builder("p")
- .longOpt("projectid")
- .desc("Your Google project id.")
- .hasArg()
- .argName("PROJECT_ID")
- .build();
- private static final Option DISPLAY_NAME_OPTION = Option.builder("n")
- .longOpt("name")
- .desc("[create/get/delete]: Display name of uptime check.")
- .hasArg()
- .argName("DISPLAY_NAME")
- .required(false)
- .build();
- private static final Option HOST_NAME_OPTION = Option.builder("o")
- .longOpt("hostname")
- .desc("[create]: Host name of uptime check to create.")
- .hasArg()
- .argName("HOST_NAME")
- .required(false)
- .build();
- private static final Option PATH_NAME_OPTION = Option.builder("a")
- .longOpt("pathname")
- .desc("[create/update]: Path name of uptime check to create/update.")
- .hasArg()
- .argName("HOST_NAME")
- .required(false)
- .build();
+ private static final Option PROJECT_ID_OPTION =
+ Option.builder("p")
+ .longOpt("projectid")
+ .desc("Your Google project id.")
+ .hasArg()
+ .argName("PROJECT_ID")
+ .build();
+ private static final Option DISPLAY_NAME_OPTION =
+ Option.builder("n")
+ .longOpt("name")
+ .desc("[create/get/delete]: Display name of uptime check.")
+ .hasArg()
+ .argName("DISPLAY_NAME")
+ .required(false)
+ .build();
+ private static final Option HOST_NAME_OPTION =
+ Option.builder("o")
+ .longOpt("hostname")
+ .desc("[create]: Host name of uptime check to create.")
+ .hasArg()
+ .argName("HOST_NAME")
+ .required(false)
+ .build();
+ private static final Option PATH_NAME_OPTION =
+ Option.builder("a")
+ .longOpt("pathname")
+ .desc("[create/update]: Path name of uptime check to create/update.")
+ .hasArg()
+ .argName("HOST_NAME")
+ .required(false)
+ .build();
- private static final Options OPTIONS = new Options()
- .addOption(PROJECT_ID_OPTION)
- .addOption(DISPLAY_NAME_OPTION)
- .addOption(HOST_NAME_OPTION)
- .addOption(PATH_NAME_OPTION);
+ private static final Options OPTIONS =
+ new Options()
+ .addOption(PROJECT_ID_OPTION)
+ .addOption(DISPLAY_NAME_OPTION)
+ .addOption(HOST_NAME_OPTION)
+ .addOption(PATH_NAME_OPTION);
private static final CommandLineParser PARSER = new DefaultParser();
@@ -91,15 +94,14 @@ public static void main(String... args) throws IOException {
throw new RuntimeException("Exception parsing command line arguments.", pe);
}
- String projectId = cl.getOptionValue(
- PROJECT_ID_OPTION.getOpt(),
- System.getenv("GOOGLE_CLOUD_PROJECT"));
+ String projectId =
+ cl.getOptionValue(PROJECT_ID_OPTION.getOpt(), System.getenv("GOOGLE_CLOUD_PROJECT"));
- String command = Optional
- .of(cl.getArgList())
- .filter(l -> l.size() > 0)
- .map(l -> Strings.emptyToNull(l.get(0)))
- .orElse(null);
+ String command =
+ Optional.of(cl.getArgList())
+ .filter(l -> l.size() > 0)
+ .map(l -> Strings.emptyToNull(l.get(0)))
+ .orElse(null);
if (command == null) {
usage(null);
return;
@@ -111,16 +113,14 @@ public static void main(String... args) throws IOException {
projectId,
cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check"),
cl.getOptionValue(HOST_NAME_OPTION.getOpt(), "example.com"),
- cl.getOptionValue(PATH_NAME_OPTION.getOpt(), "/")
- );
+ cl.getOptionValue(PATH_NAME_OPTION.getOpt(), "/"));
break;
case "update":
updateUptimeCheck(
projectId,
cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check"),
cl.getOptionValue(HOST_NAME_OPTION.getOpt(), "example.com"),
- cl.getOptionValue(PATH_NAME_OPTION.getOpt(), "/")
- );
+ cl.getOptionValue(PATH_NAME_OPTION.getOpt(), "/"));
break;
case "list":
listUptimeChecks(projectId);
@@ -130,13 +130,11 @@ public static void main(String... args) throws IOException {
break;
case "get":
getUptimeCheckConfig(
- projectId,
- cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check"));
+ projectId, cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check"));
break;
case "delete":
deleteUptimeCheckConfig(
- projectId,
- cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check"));
+ projectId, cl.getOptionValue(DISPLAY_NAME_OPTION.getOpt(), "new uptime check"));
break;
default:
usage(null);
@@ -146,23 +144,20 @@ public static void main(String... args) throws IOException {
// [START monitoring_uptime_check_create]]
private static void createUptimeCheck(
String projectId, String displayName, String hostName, String pathName) throws IOException {
- CreateUptimeCheckConfigRequest request = CreateUptimeCheckConfigRequest
- .newBuilder()
- .setParent(ProjectName.format(projectId))
- .setUptimeCheckConfig(UptimeCheckConfig
- .newBuilder()
- .setDisplayName(displayName)
- .setMonitoredResource(MonitoredResource
- .newBuilder()
- .setType("uptime_url")
- .putLabels("host", hostName))
- .setHttpCheck(HttpCheck
- .newBuilder()
- .setPath(pathName)
- .setPort(80))
- .setTimeout(Duration.newBuilder().setSeconds(10))
- .setPeriod(Duration.newBuilder().setSeconds(300)))
- .build();
+ CreateUptimeCheckConfigRequest request =
+ CreateUptimeCheckConfigRequest.newBuilder()
+ .setParent(ProjectName.format(projectId))
+ .setUptimeCheckConfig(
+ UptimeCheckConfig.newBuilder()
+ .setDisplayName(displayName)
+ .setMonitoredResource(
+ MonitoredResource.newBuilder()
+ .setType("uptime_url")
+ .putLabels("host", hostName))
+ .setHttpCheck(HttpCheck.newBuilder().setPath(pathName).setPort(80))
+ .setTimeout(Duration.newBuilder().setSeconds(10))
+ .setPeriod(Duration.newBuilder().setSeconds(300)))
+ .build();
try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
UptimeCheckConfig config = client.createUptimeCheckConfig(request);
System.out.println("Uptime check created: " + config.getDisplayName());
@@ -178,25 +173,20 @@ private static void updateUptimeCheck(
String projectId, String displayName, String hostName, String pathName) throws IOException {
String fullCheckName = UptimeCheckConfigName.format(projectId, displayName);
- UpdateUptimeCheckConfigRequest request = UpdateUptimeCheckConfigRequest
- .newBuilder()
- .setUpdateMask(FieldMask
- .newBuilder()
- .addPaths("http_check.path"))
- .setUptimeCheckConfig(UptimeCheckConfig
- .newBuilder()
- .setName(fullCheckName)
- .setMonitoredResource(MonitoredResource
- .newBuilder()
- .setType("uptime_url")
- .putLabels("host", hostName))
- .setHttpCheck(HttpCheck
- .newBuilder()
- .setPath(pathName)
- .setPort(80))
- .setTimeout(Duration.newBuilder().setSeconds(10))
- .setPeriod(Duration.newBuilder().setSeconds(300)))
- .build();
+ UpdateUptimeCheckConfigRequest request =
+ UpdateUptimeCheckConfigRequest.newBuilder()
+ .setUpdateMask(FieldMask.newBuilder().addPaths("http_check.path"))
+ .setUptimeCheckConfig(
+ UptimeCheckConfig.newBuilder()
+ .setName(fullCheckName)
+ .setMonitoredResource(
+ MonitoredResource.newBuilder()
+ .setType("uptime_url")
+ .putLabels("host", hostName))
+ .setHttpCheck(HttpCheck.newBuilder().setPath(pathName).setPort(80))
+ .setTimeout(Duration.newBuilder().setSeconds(10))
+ .setPeriod(Duration.newBuilder().setSeconds(300)))
+ .build();
try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
UptimeCheckConfig config = client.updateUptimeCheckConfig(request);
System.out.println("Uptime check updated: \n" + config.toString());
@@ -209,10 +199,8 @@ private static void updateUptimeCheck(
// [START monitoring_uptime_check_list_configs]]
private static void listUptimeChecks(String projectId) throws IOException {
- ListUptimeCheckConfigsRequest request = ListUptimeCheckConfigsRequest
- .newBuilder()
- .setParent(ProjectName.format(projectId))
- .build();
+ ListUptimeCheckConfigsRequest request =
+ ListUptimeCheckConfigsRequest.newBuilder().setParent(ProjectName.format(projectId)).build();
try (UptimeCheckServiceClient client = UptimeCheckServiceClient.create()) {
ListUptimeCheckConfigsPagedResponse response = client.listUptimeCheckConfigs(request);
for (UptimeCheckConfig config : response.iterateAll()) {
@@ -273,7 +261,11 @@ private static void deleteUptimeCheckConfig(String projectId, String checkName)
private static void usage(String message) {
Optional.ofNullable(message).ifPresent(System.out::println);
HelpFormatter formatter = new HelpFormatter();
- formatter.printHelp("[create|list|listIPs|get|delete]",
- "Performs operations on monitoring uptime checks.", OPTIONS, "", true);
+ formatter.printHelp(
+ "[create|list|listIPs|get|delete]",
+ "Performs operations on monitoring uptime checks.",
+ OPTIONS,
+ "",
+ true);
}
}
diff --git a/monitoring/v3/src/test/java/com/example/AlertIT.java b/monitoring/v3/src/test/java/com/example/AlertIT.java
index 55015ff2806..bd648cd1cb3 100644
--- a/monitoring/v3/src/test/java/com/example/AlertIT.java
+++ b/monitoring/v3/src/test/java/com/example/AlertIT.java
@@ -20,7 +20,6 @@
import com.google.common.base.Strings;
import com.google.common.io.Files;
-
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
@@ -28,7 +27,6 @@
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@@ -37,16 +35,15 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for monitoring "AlertSample" sample.
- */
+/** Tests for monitoring "AlertSample" sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class AlertIT {
private static String testPolicyName = "test-policy";
private static String policyFileName = "target/policyBackup.json";
- private static Pattern policyNameRegex = Pattern.compile(
- "alertPolicies/(?.*)(?s).*(?!s)notificationChannels/(?[a-zA-Z0-9]*)$");
+ private static Pattern policyNameRegex =
+ Pattern.compile(
+ "alertPolicies/(?.*)(?s).*(?!s)notificationChannels/(?[a-zA-Z0-9]*)$");
private ByteArrayOutputStream bout;
private PrintStream out;
@@ -64,46 +61,43 @@ public void tearDown() {
@Test
public void testListPolicies() throws IOException {
- AlertSample.main(new String[]{"list"});
+ AlertSample.main(new String[] {"list"});
assertTrue(bout.toString().contains(testPolicyName));
}
@Test
public void testBackupPolicies() throws IOException {
- AlertSample.main(new String[]{"backup", "-j", policyFileName});
+ AlertSample.main(new String[] {"backup", "-j", policyFileName});
File backupFile = new File(policyFileName);
assertTrue(backupFile.exists());
- String fileContents =
- String.join("\n", Files.readLines(backupFile, StandardCharsets.UTF_8));
+ String fileContents = String.join("\n", Files.readLines(backupFile, StandardCharsets.UTF_8));
assertTrue(fileContents.contains("test-policy"));
}
// TODO(b/78293034): Complete restore backup test when parse/unparse issue is figured out.
@Test
@Ignore
- public void testRestoreBackup() throws IOException {
- }
+ public void testRestoreBackup() throws IOException {}
@Test
public void testReplaceChannels() throws IOException {
// Get a test policy name for the project.
- AlertSample.main(new String[]{"list"});
+ AlertSample.main(new String[] {"list"});
Matcher matcher = policyNameRegex.matcher(bout.toString());
assertTrue(matcher.find());
String alertId = matcher.group("alertid");
String channel = matcher.group("channel");
Assert.assertFalse(Strings.isNullOrEmpty(alertId));
- AlertSample.main(new String[]{"replace-channels", "-a", alertId, "-c", channel});
+ AlertSample.main(new String[] {"replace-channels", "-a", alertId, "-c", channel});
Pattern resultPattern = Pattern.compile("(?s).*Updated .*/alertPolicies/" + alertId);
assertTrue(resultPattern.matcher(bout.toString()).find());
}
@Test
public void testDisableEnablePolicies() throws IOException {
- AlertSample.main(new String[]{"disable", "-d", "display_name='test-policy'"});
+ AlertSample.main(new String[] {"disable", "-d", "display_name='test-policy'"});
assertTrue(bout.toString().contains("disabled"));
- AlertSample.main(new String[]{"enable", "-d", "display_name='test-policy'"});
+ AlertSample.main(new String[] {"enable", "-d", "display_name='test-policy'"});
assertTrue(bout.toString().contains("enabled"));
-
}
}
diff --git a/monitoring/v3/src/test/java/com/example/DeleteNotificationChannelIT.java b/monitoring/v3/src/test/java/com/example/DeleteNotificationChannelIT.java
index d3f0dad376d..5228b131b11 100644
--- a/monitoring/v3/src/test/java/com/example/DeleteNotificationChannelIT.java
+++ b/monitoring/v3/src/test/java/com/example/DeleteNotificationChannelIT.java
@@ -21,11 +21,9 @@
import com.google.cloud.monitoring.v3.NotificationChannelServiceClient;
import com.google.monitoring.v3.NotificationChannel;
import com.google.monitoring.v3.ProjectName;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -33,9 +31,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for delete notification channel sample.
- */
+/** Tests for delete notification channel sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class DeleteNotificationChannelIT {
@@ -49,8 +45,8 @@ public class DeleteNotificationChannelIT {
private static String getProjectId() {
String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME));
if (projectId == null) {
- projectId = System.getProperty(LEGACY_PROJECT_ENV_NAME,
- System.getenv(LEGACY_PROJECT_ENV_NAME));
+ projectId =
+ System.getProperty(LEGACY_PROJECT_ENV_NAME, System.getenv(LEGACY_PROJECT_ENV_NAME));
}
return projectId;
}
@@ -59,12 +55,13 @@ private static String getProjectId() {
public static void setupClass() throws IOException {
try (NotificationChannelServiceClient client = NotificationChannelServiceClient.create()) {
String projectId = getProjectId();
- NOTIFICATION_CHANNEL = NotificationChannel.newBuilder()
- .setType("email")
- .putLabels("email_address", "java-docs-samples-testing@google.com")
- .build();
- NotificationChannel channel = client.createNotificationChannel(ProjectName.of(projectId),
- NOTIFICATION_CHANNEL);
+ NOTIFICATION_CHANNEL =
+ NotificationChannel.newBuilder()
+ .setType("email")
+ .putLabels("email_address", "java-docs-samples-testing@google.com")
+ .build();
+ NotificationChannel channel =
+ client.createNotificationChannel(ProjectName.of(projectId), NOTIFICATION_CHANNEL);
NOTIFICATION_CHANNEL_NAME = channel.getName();
}
}
diff --git a/monitoring/v3/src/test/java/com/example/UptimeIT.java b/monitoring/v3/src/test/java/com/example/UptimeIT.java
index 3bed7dac123..41d5965099b 100644
--- a/monitoring/v3/src/test/java/com/example/UptimeIT.java
+++ b/monitoring/v3/src/test/java/com/example/UptimeIT.java
@@ -19,11 +19,9 @@
import static com.google.common.truth.Truth.assertThat;
import com.google.monitoring.v3.UptimeCheckConfig;
-
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.UUID;
-
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
@@ -32,9 +30,7 @@
import org.junit.runners.JUnit4;
import org.junit.runners.MethodSorters;
-/**
- * Integration (system) tests for {@link UptimeSample}.
- */
+/** Integration (system) tests for {@link UptimeSample}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@@ -42,10 +38,10 @@ public class UptimeIT {
private ByteArrayOutputStream bout;
private PrintStream out;
- private static UptimeCheckConfig config = UptimeCheckConfig
- .newBuilder()
- .setDisplayName("check-" + UUID.randomUUID().toString().substring(0, 6))
- .build();
+ private static UptimeCheckConfig config =
+ UptimeCheckConfig.newBuilder()
+ .setDisplayName("check-" + UUID.randomUUID().toString().substring(0, 6))
+ .build();
@BeforeClass
public static void setUpClass() {
@@ -63,10 +59,8 @@ public void setUp() {
@Test
public void test1_CreateUptimeCheck() throws Exception {
- UptimeSample.main(
- "create", "-n", config.getDisplayName(), "-o", "test.example.com", "-a", "/");
+ UptimeSample.main("create", "-n", config.getDisplayName(), "-o", "test.example.com", "-a", "/");
assertThat(bout.toString()).contains("Uptime check created: " + config.getDisplayName());
-
}
@Test
diff --git a/opencensus/pom.xml b/opencensus/pom.xml
index 96b63c2ef42..d29d470b38f 100644
--- a/opencensus/pom.xml
+++ b/opencensus/pom.xml
@@ -29,7 +29,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/opencensus/src/main/java/com/example/opencensus/Quickstart.java b/opencensus/src/main/java/com/example/opencensus/Quickstart.java
index 5a920cdb7cd..c304bf056dd 100644
--- a/opencensus/src/main/java/com/example/opencensus/Quickstart.java
+++ b/opencensus/src/main/java/com/example/opencensus/Quickstart.java
@@ -19,7 +19,6 @@
// [START monitoring_opencensus_metrics_quickstart]
import com.google.common.collect.Lists;
-
import io.opencensus.exporter.stats.stackdriver.StackdriverStatsExporter;
import io.opencensus.stats.Aggregation;
import io.opencensus.stats.BucketBoundaries;
@@ -29,7 +28,6 @@
import io.opencensus.stats.View;
import io.opencensus.stats.View.Name;
import io.opencensus.stats.ViewManager;
-
import java.io.IOException;
import java.util.Collections;
import java.util.Random;
@@ -37,25 +35,24 @@
public class Quickstart {
private static final int EXPORT_INTERVAL = 70;
- private static final MeasureLong LATENCY_MS = MeasureLong.create(
- "task_latency",
- "The task latency in milliseconds",
- "ms");
+ private static final MeasureLong LATENCY_MS =
+ MeasureLong.create("task_latency", "The task latency in milliseconds", "ms");
// Latency in buckets:
// [>=0ms, >=100ms, >=200ms, >=400ms, >=1s, >=2s, >=4s]
- private static final BucketBoundaries LATENCY_BOUNDARIES = BucketBoundaries.create(
- Lists.newArrayList(0d, 100d, 200d, 400d, 1000d, 2000d, 4000d));
+ private static final BucketBoundaries LATENCY_BOUNDARIES =
+ BucketBoundaries.create(Lists.newArrayList(0d, 100d, 200d, 400d, 1000d, 2000d, 4000d));
private static final StatsRecorder STATS_RECORDER = Stats.getStatsRecorder();
public static void main(String[] args) throws IOException, InterruptedException {
// Register the view. It is imperative that this step exists,
// otherwise recorded metrics will be dropped and never exported.
- View view = View.create(
- Name.create("task_latency_distribution"),
- "The distribution of the task latencies.",
- LATENCY_MS,
- Aggregation.Distribution.create(LATENCY_BOUNDARIES),
- Collections.emptyList());
+ View view =
+ View.create(
+ Name.create("task_latency_distribution"),
+ "The distribution of the task latencies.",
+ LATENCY_MS,
+ Aggregation.Distribution.create(LATENCY_BOUNDARIES),
+ Collections.emptyList());
ViewManager viewManager = Stats.getViewManager();
viewManager.registerView(view);
@@ -80,8 +77,10 @@ public static void main(String[] args) throws IOException, InterruptedException
// live for at least the interval past any metrics that must be collected, or some risk being
// lost if they are recorded after the last export.
- System.out.println(String.format(
- "Sleeping %d seconds before shutdown to ensure all records are flushed.", EXPORT_INTERVAL));
+ System.out.println(
+ String.format(
+ "Sleeping %d seconds before shutdown to ensure all records are flushed.",
+ EXPORT_INTERVAL));
Thread.sleep(TimeUnit.MILLISECONDS.convert(EXPORT_INTERVAL, TimeUnit.SECONDS));
}
}
diff --git a/pubsub/cloud-client/pom.xml b/pubsub/cloud-client/pom.xml
index 068548344b3..b5018720cf3 100644
--- a/pubsub/cloud-client/pom.xml
+++ b/pubsub/cloud-client/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/pubsub/cloud-client/src/main/java/com/example/pubsub/CreatePullSubscriptionExample.java b/pubsub/cloud-client/src/main/java/com/example/pubsub/CreatePullSubscriptionExample.java
index 06171a2971c..4de91bcbdfe 100644
--- a/pubsub/cloud-client/src/main/java/com/example/pubsub/CreatePullSubscriptionExample.java
+++ b/pubsub/cloud-client/src/main/java/com/example/pubsub/CreatePullSubscriptionExample.java
@@ -48,8 +48,8 @@ public static void main(String... args) throws Exception {
ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);
// Create a new subscription
- ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(
- projectId, subscriptionId);
+ ProjectSubscriptionName subscriptionName =
+ ProjectSubscriptionName.of(projectId, subscriptionId);
try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
// create a pull subscription with default acknowledgement deadline (= 10 seconds)
Subscription subscription =
@@ -63,7 +63,6 @@ public static void main(String... args) throws Exception {
System.out.print(e.getStatusCode().getCode());
System.out.print(e.isRetryable());
}
-
}
}
// [END pubsub_quickstart_create_subscription]
diff --git a/pubsub/cloud-client/src/main/java/com/example/pubsub/PublisherExample.java b/pubsub/cloud-client/src/main/java/com/example/pubsub/PublisherExample.java
index 95faf202902..1242eed6b23 100644
--- a/pubsub/cloud-client/src/main/java/com/example/pubsub/PublisherExample.java
+++ b/pubsub/cloud-client/src/main/java/com/example/pubsub/PublisherExample.java
@@ -24,7 +24,6 @@
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.ProjectTopicName;
import com.google.pubsub.v1.PubsubMessage;
-
import java.util.ArrayList;
import java.util.List;
@@ -33,7 +32,9 @@ public class PublisherExample {
// use the default project id
private static final String PROJECT_ID = ServiceOptions.getDefaultProjectId();
- /** Publish messages to a topic.
+ /**
+ * Publish messages to a topic.
+ *
* @param args topic name, number of messages
*/
public static void main(String... args) throws Exception {
@@ -53,9 +54,7 @@ public static void main(String... args) throws Exception {
// convert message to bytes
ByteString data = ByteString.copyFromUtf8(message);
- PubsubMessage pubsubMessage = PubsubMessage.newBuilder()
- .setData(data)
- .build();
+ PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
// Schedule a message to be published. Messages are automatically batched.
ApiFuture future = publisher.publish(pubsubMessage);
diff --git a/pubsub/cloud-client/src/main/java/com/example/pubsub/SubscriberExample.java b/pubsub/cloud-client/src/main/java/com/example/pubsub/SubscriberExample.java
index 3180644cb2c..e5bf2d831a0 100644
--- a/pubsub/cloud-client/src/main/java/com/example/pubsub/SubscriberExample.java
+++ b/pubsub/cloud-client/src/main/java/com/example/pubsub/SubscriberExample.java
@@ -44,13 +44,12 @@ public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
public static void main(String... args) throws Exception {
// set subscriber id, eg. my-sub
String subscriptionId = args[0];
- ProjectSubscriptionName subscriptionName = ProjectSubscriptionName.of(
- PROJECT_ID, subscriptionId);
+ ProjectSubscriptionName subscriptionName =
+ ProjectSubscriptionName.of(PROJECT_ID, subscriptionId);
Subscriber subscriber = null;
try {
// create a subscriber bound to the asynchronous message receiver
- subscriber =
- Subscriber.newBuilder(subscriptionName, new MessageReceiverExample()).build();
+ subscriber = Subscriber.newBuilder(subscriptionName, new MessageReceiverExample()).build();
subscriber.startAsync().awaitRunning();
// Allow the subscriber to run indefinitely unless an unrecoverable error occurs.
subscriber.awaitTerminated();
diff --git a/recommender/beta/cloud-client/pom.xml b/recommender/beta/cloud-client/pom.xml
index d9beeed3d39..6e7d54b0b3b 100644
--- a/recommender/beta/cloud-client/pom.xml
+++ b/recommender/beta/cloud-client/pom.xml
@@ -23,7 +23,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/run/hello-broken/pom.xml b/run/hello-broken/pom.xml
index 46f30dd3a9e..b5e26bcfb9f 100644
--- a/run/hello-broken/pom.xml
+++ b/run/hello-broken/pom.xml
@@ -23,7 +23,7 @@ limitations under the License.
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
UTF-8
diff --git a/run/helloworld/pom.xml b/run/helloworld/pom.xml
index 3afdba41993..70f7c660195 100644
--- a/run/helloworld/pom.xml
+++ b/run/helloworld/pom.xml
@@ -24,7 +24,7 @@ limitations under the License.
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/run/image-processing/pom.xml b/run/image-processing/pom.xml
index c6669c365a8..1e0eba09630 100644
--- a/run/image-processing/pom.xml
+++ b/run/image-processing/pom.xml
@@ -23,7 +23,7 @@ limitations under the License.
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
11
diff --git a/run/logging-manual/pom.xml b/run/logging-manual/pom.xml
index 2f766f847f9..ae5c6b8d37b 100644
--- a/run/logging-manual/pom.xml
+++ b/run/logging-manual/pom.xml
@@ -20,7 +20,7 @@ limitations under the License.
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
UTF-8
diff --git a/run/pubsub/pom.xml b/run/pubsub/pom.xml
index 60d49899380..46d30773fe1 100644
--- a/run/pubsub/pom.xml
+++ b/run/pubsub/pom.xml
@@ -21,7 +21,7 @@ limitations under the License.
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/run/system-package/pom.xml b/run/system-package/pom.xml
index 4f0c8c5afcc..090bf7067f6 100644
--- a/run/system-package/pom.xml
+++ b/run/system-package/pom.xml
@@ -25,7 +25,7 @@ limitations under the License.
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/secretmanager/pom.xml b/secretmanager/pom.xml
index 1052de57d5c..d941980e5ac 100644
--- a/secretmanager/pom.xml
+++ b/secretmanager/pom.xml
@@ -28,7 +28,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/securitycenter/pom.xml b/securitycenter/pom.xml
index 74795a9ad55..84c61aad1cb 100644
--- a/securitycenter/pom.xml
+++ b/securitycenter/pom.xml
@@ -23,7 +23,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/session-handling/pom.xml b/session-handling/pom.xml
index 006a06795d5..40e29353de8 100644
--- a/session-handling/pom.xml
+++ b/session-handling/pom.xml
@@ -25,7 +25,7 @@ Copyright 2019 Google LLC
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/session-handling/src/main/java/com/example/gettingstarted/actions/HelloWorldServlet.java b/session-handling/src/main/java/com/example/gettingstarted/actions/HelloWorldServlet.java
index 16902e0e470..df8c39b7082 100644
--- a/session-handling/src/main/java/com/example/gettingstarted/actions/HelloWorldServlet.java
+++ b/session-handling/src/main/java/com/example/gettingstarted/actions/HelloWorldServlet.java
@@ -20,7 +20,6 @@
import java.io.IOException;
import java.util.Random;
import java.util.logging.Logger;
-
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
diff --git a/session-handling/src/main/java/com/example/gettingstarted/util/FirestoreSessionFilter.java b/session-handling/src/main/java/com/example/gettingstarted/util/FirestoreSessionFilter.java
index 1eb95425afe..0fe4d4d78a8 100644
--- a/session-handling/src/main/java/com/example/gettingstarted/util/FirestoreSessionFilter.java
+++ b/session-handling/src/main/java/com/example/gettingstarted/util/FirestoreSessionFilter.java
@@ -34,7 +34,6 @@
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
-
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
@@ -127,9 +126,7 @@ public void doFilter(ServletRequest servletReq, ServletResponse servletResp, Fil
sessionMap.put(attrName, session.getAttribute(attrName));
}
-
- logger.info(
- "Saving data to " + sessionId + " with views: " + session.getAttribute("views"));
+ logger.info("Saving data to " + sessionId + " with views: " + session.getAttribute("views"));
firestore.runTransaction((ob) -> sessions.document(sessionId).set(sessionMap));
}
// [END sessions_handling_filter]
diff --git a/spanner/cloud-client/pom.xml b/spanner/cloud-client/pom.xml
index da1c33b395a..14b3b02c377 100644
--- a/spanner/cloud-client/pom.xml
+++ b/spanner/cloud-client/pom.xml
@@ -26,7 +26,7 @@ limitations under the License.
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/spanner/cloud-client/src/main/java/com/example/spanner/BatchSample.java b/spanner/cloud-client/src/main/java/com/example/spanner/BatchSample.java
index 1f44be61ae0..725f46d607f 100644
--- a/spanner/cloud-client/src/main/java/com/example/spanner/BatchSample.java
+++ b/spanner/cloud-client/src/main/java/com/example/spanner/BatchSample.java
@@ -26,16 +26,13 @@
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.TimestampBound;
-
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
-/**
- * Sample showing how to run a query using the Batch API.
- */
+/** Sample showing how to run a query using the Batch API. */
public class BatchSample {
/**
@@ -72,30 +69,33 @@ public static void main(String[] args) throws InterruptedException {
AtomicInteger totalRecords = new AtomicInteger(0);
try {
- BatchClient batchClient = spanner.getBatchClient(
- DatabaseId.of(options.getProjectId(), instanceId, databaseId));
+ BatchClient batchClient =
+ spanner.getBatchClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
final BatchReadOnlyTransaction txn =
batchClient.batchReadOnlyTransaction(TimestampBound.strong());
// A Partition object is serializable and can be used from a different process.
- List partitions = txn.partitionQuery(PartitionOptions.getDefaultInstance(),
- Statement.of("SELECT SingerId, FirstName, LastName FROM Singers"));
+ List partitions =
+ txn.partitionQuery(
+ PartitionOptions.getDefaultInstance(),
+ Statement.of("SELECT SingerId, FirstName, LastName FROM Singers"));
totalPartitions = partitions.size();
for (final Partition p : partitions) {
- executor.execute(() -> {
- try (ResultSet results = txn.execute(p)) {
- while (results.next()) {
- long singerId = results.getLong(0);
- String firstName = results.getString(1);
- String lastName = results.getString(2);
- System.out.println("[" + singerId + "] " + firstName + " " + lastName);
- totalRecords.getAndIncrement();
- }
- }
- });
+ executor.execute(
+ () -> {
+ try (ResultSet results = txn.execute(p)) {
+ while (results.next()) {
+ long singerId = results.getLong(0);
+ String firstName = results.getString(1);
+ String lastName = results.getString(2);
+ System.out.println("[" + singerId + "] " + firstName + " " + lastName);
+ totalRecords.getAndIncrement();
+ }
+ }
+ });
}
} finally {
executor.shutdown();
diff --git a/spanner/cloud-client/src/main/java/com/example/spanner/QuickstartSample.java b/spanner/cloud-client/src/main/java/com/example/spanner/QuickstartSample.java
index eaa64ed62aa..14aad267dd9 100644
--- a/spanner/cloud-client/src/main/java/com/example/spanner/QuickstartSample.java
+++ b/spanner/cloud-client/src/main/java/com/example/spanner/QuickstartSample.java
@@ -45,8 +45,8 @@ public static void main(String... args) throws Exception {
String databaseId = args[1];
try {
// Creates a database client
- DatabaseClient dbClient = spanner.getDatabaseClient(DatabaseId.of(
- options.getProjectId(), instanceId, databaseId));
+ DatabaseClient dbClient =
+ spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
// Queries the database
ResultSet resultSet = dbClient.singleUse().executeQuery(Statement.of("SELECT 1"));
diff --git a/spanner/cloud-client/src/main/java/com/example/spanner/SpannerSample.java b/spanner/cloud-client/src/main/java/com/example/spanner/SpannerSample.java
index 2db5d649a25..ffffeeac68b 100644
--- a/spanner/cloud-client/src/main/java/com/example/spanner/SpannerSample.java
+++ b/spanner/cloud-client/src/main/java/com/example/spanner/SpannerSample.java
@@ -128,8 +128,15 @@ static class Venue {
final boolean outdoorVenue;
final float popularityScore;
- Venue(long venueId, String venueName, String venueInfo, long capacity, Value availableDates,
- String lastContactDate, boolean outdoorVenue, float popularityScore) {
+ Venue(
+ long venueId,
+ String venueName,
+ String venueInfo,
+ long capacity,
+ Value availableDates,
+ String lastContactDate,
+ boolean outdoorVenue,
+ float popularityScore) {
this.venueId = venueId;
this.venueName = venueName;
this.venueInfo = venueInfo;
@@ -168,28 +175,31 @@ static class Venue {
// [END spanner_insert_data_with_timestamp_column]
// [START spanner_insert_datatypes_data]
- static Value availableDates1 = Value.dateArray(Arrays.asList(
- Date.parseDate("2020-12-01"),
- Date.parseDate("2020-12-02"),
- Date.parseDate("2020-12-03")));
- static Value availableDates2 = Value.dateArray(Arrays.asList(
- Date.parseDate("2020-11-01"),
- Date.parseDate("2020-11-05"),
- Date.parseDate("2020-11-15")));
- static Value availableDates3 = Value.dateArray(Arrays.asList(
- Date.parseDate("2020-10-01"),
- Date.parseDate("2020-10-07")));
+ static Value availableDates1 =
+ Value.dateArray(
+ Arrays.asList(
+ Date.parseDate("2020-12-01"),
+ Date.parseDate("2020-12-02"),
+ Date.parseDate("2020-12-03")));
+ static Value availableDates2 =
+ Value.dateArray(
+ Arrays.asList(
+ Date.parseDate("2020-11-01"),
+ Date.parseDate("2020-11-05"),
+ Date.parseDate("2020-11-15")));
+ static Value availableDates3 =
+ Value.dateArray(Arrays.asList(Date.parseDate("2020-10-01"), Date.parseDate("2020-10-07")));
static String exampleBytes1 = BaseEncoding.base64().encode("Hello World 1".getBytes());
static String exampleBytes2 = BaseEncoding.base64().encode("Hello World 2".getBytes());
static String exampleBytes3 = BaseEncoding.base64().encode("Hello World 3".getBytes());
static final List VENUES =
Arrays.asList(
- new Venue(4, "Venue 4", exampleBytes1, 1800,
- availableDates1, "2018-09-02", false, 0.85543f),
- new Venue(19, "Venue 19", exampleBytes2, 6300,
- availableDates2, "2019-01-15", true, 0.98716f),
- new Venue(42, "Venue 42", exampleBytes3, 3000,
- availableDates3, "2018-10-01", false, 0.72598f));
+ new Venue(
+ 4, "Venue 4", exampleBytes1, 1800, availableDates1, "2018-09-02", false, 0.85543f),
+ new Venue(
+ 19, "Venue 19", exampleBytes2, 6300, availableDates2, "2019-01-15", true, 0.98716f),
+ new Venue(
+ 42, "Venue 42", exampleBytes3, 3000, availableDates3, "2018-10-01", false, 0.72598f));
// [END spanner_insert_datatypes_data]
// [START spanner_create_database]
@@ -329,7 +339,8 @@ static void deleteExampleData(DatabaseClient dbClient) {
// [START spanner_query_data]
static void query(DatabaseClient dbClient) {
- try (ResultSet resultSet = dbClient
+ try (ResultSet resultSet =
+ dbClient
.singleUse() // Execute a single read or query against Cloud Spanner.
.executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))) {
while (resultSet.next()) {
@@ -342,7 +353,8 @@ static void query(DatabaseClient dbClient) {
// [START spanner_read_data]
static void read(DatabaseClient dbClient) {
- try (ResultSet resultSet = dbClient
+ try (ResultSet resultSet =
+ dbClient
.singleUse()
.read(
"Albums",
@@ -462,7 +474,8 @@ static void queryMarketingBudget(DatabaseClient dbClient) {
// Rows without an explicit value for MarketingBudget will have a MarketingBudget equal to
// null. A try-with-resource block is used to automatically release resources held by
// ResultSet.
- try (ResultSet resultSet = dbClient
+ try (ResultSet resultSet =
+ dbClient
.singleUse()
.executeQuery(Statement.of("SELECT SingerId, AlbumId, MarketingBudget FROM Albums"))) {
while (resultSet.next()) {
@@ -534,7 +547,8 @@ static void queryUsingIndex(DatabaseClient dbClient) {
// [START spanner_read_data_with_index]
static void readUsingIndex(DatabaseClient dbClient) {
- try (ResultSet resultSet = dbClient
+ try (ResultSet resultSet =
+ dbClient
.singleUse()
.readUsingIndex(
"Albums",
@@ -578,7 +592,8 @@ static void addStoringIndex(DatabaseAdminClient adminClient, DatabaseId dbId) {
// [START spanner_read_data_with_storing_index]
static void readStoringIndex(DatabaseClient dbClient) {
// We can read MarketingBudget also from the index since it stores a copy of MarketingBudget.
- try (ResultSet resultSet = dbClient
+ try (ResultSet resultSet =
+ dbClient
.singleUse()
.readUsingIndex(
"Albums",
@@ -624,10 +639,11 @@ static void readOnlyTransaction(DatabaseClient dbClient) {
// [START spanner_read_stale_data]
static void readStaleData(DatabaseClient dbClient) {
- try (ResultSet resultSet = dbClient
+ try (ResultSet resultSet =
+ dbClient
.singleUse(TimestampBound.ofExactStaleness(15, TimeUnit.SECONDS))
.read(
- "Albums", KeySet.all(), Arrays.asList("SingerId", "AlbumId", "MarketingBudget"))) {
+ "Albums", KeySet.all(), Arrays.asList("SingerId", "AlbumId", "MarketingBudget"))) {
while (resultSet.next()) {
System.out.printf(
"%d %d %s\n",
@@ -704,7 +720,8 @@ static void queryMarketingBudgetWithTimestamp(DatabaseClient dbClient) {
// Rows without an explicit value for MarketingBudget will have a MarketingBudget equal to
// null. A try-with-resource block is used to automatically release resources held by
// ResultSet.
- try (ResultSet resultSet = dbClient
+ try (ResultSet resultSet =
+ dbClient
.singleUse()
.executeQuery(
Statement.of(
@@ -725,7 +742,8 @@ static void queryMarketingBudgetWithTimestamp(DatabaseClient dbClient) {
// [END spanner_query_data_with_timestamp_column]
static void querySingersTable(DatabaseClient dbClient) {
- try (ResultSet resultSet = dbClient
+ try (ResultSet resultSet =
+ dbClient
.singleUse()
.executeQuery(Statement.of("SELECT SingerId, FirstName, LastName FROM Singers"))) {
while (resultSet.next()) {
@@ -742,7 +760,8 @@ static void queryPerformancesTable(DatabaseClient dbClient) {
// Rows without an explicit value for Revenue will have a Revenue equal to
// null. A try-with-resource block is used to automatically release resources held by
// ResultSet.
- try (ResultSet resultSet = dbClient
+ try (ResultSet resultSet =
+ dbClient
.singleUse()
.executeQuery(
Statement.of(
@@ -1012,8 +1031,7 @@ public Void run(TransactionContext transaction) throws Exception {
while (resultSet.next()) {
System.out.printf(
"%s %s\n",
- resultSet.getString("FirstName"),
- resultSet.getString("LastName"));
+ resultSet.getString("FirstName"), resultSet.getString("LastName"));
}
}
return null;
@@ -1239,15 +1257,24 @@ static void writeDatatypesData(DatabaseClient dbClient) {
for (Venue venue : VENUES) {
mutations.add(
Mutation.newInsertBuilder("Venues")
- .set("VenueId").to(venue.venueId)
- .set("VenueName").to(venue.venueName)
- .set("VenueInfo").to(venue.venueInfo)
- .set("Capacity").to(venue.capacity)
- .set("AvailableDates").to(venue.availableDates)
- .set("LastContactDate").to(venue.lastContactDate)
- .set("OutdoorVenue").to(venue.outdoorVenue)
- .set("PopularityScore").to(venue.popularityScore)
- .set("LastUpdateTime").to(Value.COMMIT_TIMESTAMP)
+ .set("VenueId")
+ .to(venue.venueId)
+ .set("VenueName")
+ .to(venue.venueName)
+ .set("VenueInfo")
+ .to(venue.venueInfo)
+ .set("Capacity")
+ .to(venue.capacity)
+ .set("AvailableDates")
+ .to(venue.availableDates)
+ .set("LastContactDate")
+ .to(venue.lastContactDate)
+ .set("OutdoorVenue")
+ .to(venue.outdoorVenue)
+ .set("PopularityScore")
+ .to(venue.popularityScore)
+ .set("LastUpdateTime")
+ .to(Value.COMMIT_TIMESTAMP)
.build());
}
dbClient.write(mutations);
@@ -1256,9 +1283,8 @@ static void writeDatatypesData(DatabaseClient dbClient) {
// [START spanner_query_with_array_parameter]
static void queryWithArray(DatabaseClient dbClient) {
- Value exampleArray = Value.dateArray(Arrays.asList(
- Date.parseDate("2020-10-01"),
- Date.parseDate("2020-11-01")));
+ Value exampleArray =
+ Value.dateArray(Arrays.asList(Date.parseDate("2020-10-01"), Date.parseDate("2020-11-01")));
Statement statement =
Statement.newBuilder(
@@ -1304,21 +1330,18 @@ static void queryWithBool(DatabaseClient dbClient) {
// [START spanner_query_with_bytes_parameter]
static void queryWithBytes(DatabaseClient dbClient) {
- ByteArray exampleBytes = ByteArray.fromBase64(
- BaseEncoding.base64().encode("Hello World 1".getBytes()));
+ ByteArray exampleBytes =
+ ByteArray.fromBase64(BaseEncoding.base64().encode("Hello World 1".getBytes()));
Statement statement =
Statement.newBuilder(
- "SELECT VenueId, VenueName FROM Venues "
- + "WHERE VenueInfo = @venueInfo")
+ "SELECT VenueId, VenueName FROM Venues " + "WHERE VenueInfo = @venueInfo")
.bind("venueInfo")
.to(exampleBytes)
.build();
try (ResultSet resultSet = dbClient.singleUse().executeQuery(statement)) {
while (resultSet.next()) {
System.out.printf(
- "%d %s\n",
- resultSet.getLong("VenueId"),
- resultSet.getString("VenueName"));
+ "%d %s\n", resultSet.getLong("VenueId"), resultSet.getString("VenueName"));
}
}
}
@@ -1373,8 +1396,7 @@ static void queryWithInt(DatabaseClient dbClient) {
long exampleInt = 3000;
Statement statement =
Statement.newBuilder(
- "SELECT VenueId, VenueName, Capacity FROM Venues "
- + "WHERE Capacity >= @capacity")
+ "SELECT VenueId, VenueName, Capacity FROM Venues " + "WHERE Capacity >= @capacity")
.bind("capacity")
.to(exampleInt)
.build();
@@ -1395,17 +1417,14 @@ static void queryWithString(DatabaseClient dbClient) {
String exampleString = "Venue 42";
Statement statement =
Statement.newBuilder(
- "SELECT VenueId, VenueName FROM Venues "
- + "WHERE VenueName = @venueName")
+ "SELECT VenueId, VenueName FROM Venues " + "WHERE VenueName = @venueName")
.bind("venueName")
.to(exampleString)
.build();
try (ResultSet resultSet = dbClient.singleUse().executeQuery(statement)) {
while (resultSet.next()) {
System.out.printf(
- "%d %s\n",
- resultSet.getLong("VenueId"),
- resultSet.getString("VenueName"));
+ "%d %s\n", resultSet.getLong("VenueId"), resultSet.getString("VenueName"));
}
}
}
@@ -1726,7 +1745,7 @@ public static void main(String[] args) throws Exception {
// Use client here...
// [END init_client]
run(dbClient, dbAdminClient, command, db);
- // [START init_client]
+ // [START init_client]
} finally {
spanner.close();
}
diff --git a/spanner/cloud-client/src/main/java/com/example/spanner/TracingSample.java b/spanner/cloud-client/src/main/java/com/example/spanner/TracingSample.java
index 4dfd5a1cb15..ddadf62a26e 100644
--- a/spanner/cloud-client/src/main/java/com/example/spanner/TracingSample.java
+++ b/spanner/cloud-client/src/main/java/com/example/spanner/TracingSample.java
@@ -22,7 +22,6 @@
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Statement;
-
import io.opencensus.common.Scope;
import io.opencensus.contrib.grpc.metrics.RpcViews;
import io.opencensus.contrib.zpages.ZPageHandlers;
@@ -30,14 +29,11 @@
import io.opencensus.exporter.trace.stackdriver.StackdriverExporter;
import io.opencensus.trace.Tracing;
import io.opencensus.trace.samplers.Samplers;
-
import java.util.Arrays;
-/**
- * This sample demonstrates how to enable opencensus tracing and stats in cloud spanner client.
- */
+/** This sample demonstrates how to enable opencensus tracing and stats in cloud spanner client. */
public class TracingSample {
-
+
private static final String SAMPLE_SPAN = "CloudSpannerSample";
public static void main(String[] args) throws Exception {
@@ -52,25 +48,27 @@ public static void main(String[] args) throws Exception {
ZPageHandlers.startHttpServerAndRegisterAll(8080);
// Installs an exporter for stack driver traces.
StackdriverExporter.createAndRegister();
- Tracing.getExportComponent().getSampledSpanStore().registerSpanNamesForCollection(
- Arrays.asList(SAMPLE_SPAN));
+ Tracing.getExportComponent()
+ .getSampledSpanStore()
+ .registerSpanNamesForCollection(Arrays.asList(SAMPLE_SPAN));
// Installs an exporter for stack driver stats.
StackdriverStatsExporter.createAndRegister();
RpcViews.registerAllCumulativeViews();
-
+
// Name of your instance & database.
String instanceId = args[0];
String databaseId = args[1];
try {
// Creates a database client
- DatabaseClient dbClient = spanner.getDatabaseClient(DatabaseId.of(
- options.getProjectId(), instanceId, databaseId));
+ DatabaseClient dbClient =
+ spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, databaseId));
// Queries the database
- try (Scope ss = Tracing.getTracer()
- .spanBuilderWithExplicitParent(SAMPLE_SPAN, null)
- .setSampler(Samplers.alwaysSample())
- .startScopedSpan()) {
+ try (Scope ss =
+ Tracing.getTracer()
+ .spanBuilderWithExplicitParent(SAMPLE_SPAN, null)
+ .setSampler(Samplers.alwaysSample())
+ .startScopedSpan()) {
ResultSet resultSet = dbClient.singleUse().executeQuery(Statement.of("SELECT 1"));
System.out.println("\n\nResults:");
@@ -84,5 +82,4 @@ public static void main(String[] args) throws Exception {
spanner.close();
}
}
-
}
diff --git a/spanner/hibernate/pom.xml b/spanner/hibernate/pom.xml
index aa2929d5162..97c08f0c854 100644
--- a/spanner/hibernate/pom.xml
+++ b/spanner/hibernate/pom.xml
@@ -17,7 +17,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
com.example.spanner
diff --git a/spanner/leaderboard/complete/pom.xml b/spanner/leaderboard/complete/pom.xml
index 1ac7be5a545..5b91989b26d 100644
--- a/spanner/leaderboard/complete/pom.xml
+++ b/spanner/leaderboard/complete/pom.xml
@@ -25,7 +25,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/spanner/leaderboard/complete/src/test/java/com/google/codelabs/AppTest.java b/spanner/leaderboard/complete/src/test/java/com/google/codelabs/AppTest.java
index 88ee60a17ef..64e8949ae91 100644
--- a/spanner/leaderboard/complete/src/test/java/com/google/codelabs/AppTest.java
+++ b/spanner/leaderboard/complete/src/test/java/com/google/codelabs/AppTest.java
@@ -22,30 +22,26 @@
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
-
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import java.util.UUID;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Unit tests for {@code Leaderboard}
- */
+/** Unit tests for {@code Leaderboard} */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class AppTest {
// The instance needs to exist for tests to pass.
private String defaultInstanceId = "default-instance";
private String systemInstanceId = System.getenv("SPANNER_TEST_INSTANCE");
- private final String instanceId =
+ private final String instanceId =
(systemInstanceId != null) ? systemInstanceId : defaultInstanceId;
private final String databaseId = formatForTest(System.getenv("SPANNER_TEST_DATABASE"));
DatabaseId dbId;
@@ -56,7 +52,7 @@ private String runSample(String command) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bout);
System.setOut(out);
- App.main(new String[]{command, instanceId, databaseId});
+ App.main(new String[] {command, instanceId, databaseId});
System.setOut(stdOut);
return bout.toString();
}
@@ -66,7 +62,7 @@ private String runSample(String command, String commandOption) throws Exception
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bout);
System.setOut(out);
- App.main(new String[]{command, instanceId, databaseId, commandOption});
+ App.main(new String[] {command, instanceId, databaseId, commandOption});
System.setOut(stdOut);
return bout.toString();
}
@@ -134,8 +130,6 @@ public void testSample() throws Exception {
// Test that Top Ten Players of the Week (within past 168 hours) runs successfully.
out = runSample("query", "168");
assertThat(out).contains("PlayerId: ");
-
-
}
private String formatForTest(String name) {
@@ -148,7 +142,7 @@ private String formatForTest(String name) {
char c = characters.charAt(random.nextInt(26));
name += c;
}
- }
+ }
return name + "-" + UUID.randomUUID().toString().substring(0, 20);
}
}
diff --git a/spanner/leaderboard/step4/pom.xml b/spanner/leaderboard/step4/pom.xml
index d74c76b4964..240f3694b12 100644
--- a/spanner/leaderboard/step4/pom.xml
+++ b/spanner/leaderboard/step4/pom.xml
@@ -25,7 +25,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/spanner/leaderboard/step5/pom.xml b/spanner/leaderboard/step5/pom.xml
index d74c76b4964..240f3694b12 100644
--- a/spanner/leaderboard/step5/pom.xml
+++ b/spanner/leaderboard/step5/pom.xml
@@ -25,7 +25,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/spanner/leaderboard/step6/pom.xml b/spanner/leaderboard/step6/pom.xml
index 2171b7ae907..c6a1fe3e388 100644
--- a/spanner/leaderboard/step6/pom.xml
+++ b/spanner/leaderboard/step6/pom.xml
@@ -25,7 +25,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/spanner/spring-data/pom.xml b/spanner/spring-data/pom.xml
index 7b85c8ecfa5..6aceaf0f942 100644
--- a/spanner/spring-data/pom.xml
+++ b/spanner/spring-data/pom.xml
@@ -28,7 +28,7 @@ limitations under the License.
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
com.example.spanner
diff --git a/spanner/spring-data/src/main/java/com/example/spanner/QuickStartSample.java b/spanner/spring-data/src/main/java/com/example/spanner/QuickStartSample.java
index a8849298a78..acb1c20f63a 100644
--- a/spanner/spring-data/src/main/java/com/example/spanner/QuickStartSample.java
+++ b/spanner/spring-data/src/main/java/com/example/spanner/QuickStartSample.java
@@ -17,7 +17,6 @@
package com.example.spanner;
import java.util.Arrays;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
@@ -33,14 +32,11 @@ public class QuickStartSample implements CommandLineRunner {
private static Logger LOG = LoggerFactory.getLogger(QuickStartSample.class);
- @Autowired
- SpannerSchemaToolsSample spannerSchemaToolsSample;
+ @Autowired SpannerSchemaToolsSample spannerSchemaToolsSample;
- @Autowired
- SpannerTemplateSample spannerTemplateSample;
+ @Autowired SpannerTemplateSample spannerTemplateSample;
- @Autowired
- SpannerRepositorySample spannerRepositorySample;
+ @Autowired SpannerRepositorySample spannerRepositorySample;
public static void main(String[] args) {
LOG.info("Starting Spring Data Cloud Spanner Sample.");
@@ -50,8 +46,8 @@ public static void main(String[] args) {
public void run(String... args) {
/*
- This call creates both the Singer and Album tables with an interleaved relationship.
- */
+ This call creates both the Singer and Album tables with an interleaved relationship.
+ */
LOG.info("(SpannerSchemaToolsSample): Creating database tables if they don't exist.");
spannerSchemaToolsSample.createTableIfNotExists();
@@ -59,28 +55,26 @@ public void run(String... args) {
singer.singerId = 1L;
singer.firstName = "John";
singer.lastName = "Doe";
- singer.albums = Arrays.asList(new Album(1L, 10L, "album1", 11L),
- new Album(1L, 20L, "album2", 12L));
+ singer.albums =
+ Arrays.asList(new Album(1L, 10L, "album1", 11L), new Album(1L, 20L, "album2", 12L));
/*
- This call inserts the singer and performs a read query using a SpannerTemplate instance.
- */
+ This call inserts the singer and performs a read query using a SpannerTemplate instance.
+ */
LOG.info("(SpannerTemplateSample): Saving one singer.");
spannerTemplateSample.runTemplateExample(singer);
/*
- This call uses queries defined in SingerRepository. The implementations of those queries
- are generated by Spring Data Cloud Spanner.
- */
+ This call uses queries defined in SingerRepository. The implementations of those queries
+ are generated by Spring Data Cloud Spanner.
+ */
LOG.info("(SpannerRepositorySample): Running queries.");
spannerRepositorySample.runRepositoryExample();
/*
- This call drops both the sample Singer and Album tables.
- */
+ This call drops both the sample Singer and Album tables.
+ */
LOG.info("(SpannerSchemaToolsSample): Dropping Singer and Album tables.");
spannerSchemaToolsSample.dropTables();
-
}
-
}
diff --git a/speech/beta/pom.xml b/speech/beta/pom.xml
index a293e5e3189..b0013d43a05 100644
--- a/speech/beta/pom.xml
+++ b/speech/beta/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/speech/beta/src/main/java/com/example/speech/Recognize.java b/speech/beta/src/main/java/com/example/speech/Recognize.java
index 8f0d1cd7059..a0cda2c8c71 100644
--- a/speech/beta/src/main/java/com/example/speech/Recognize.java
+++ b/speech/beta/src/main/java/com/example/speech/Recognize.java
@@ -29,12 +29,10 @@
import com.google.cloud.speech.v1p1beta1.RecognizeResponse;
import com.google.cloud.speech.v1p1beta1.SpeakerDiarizationConfig;
import com.google.cloud.speech.v1p1beta1.SpeechClient;
-
import com.google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1p1beta1.SpeechRecognitionResult;
import com.google.cloud.speech.v1p1beta1.WordInfo;
import com.google.protobuf.ByteString;
-
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -156,14 +154,16 @@ public static void transcribeDiarization(String fileName) throws Exception {
RecognitionAudio recognitionAudio =
RecognitionAudio.newBuilder().setContent(ByteString.copyFrom(content)).build();
- SpeakerDiarizationConfig speakerDiarizationConfig = SpeakerDiarizationConfig.newBuilder()
+ SpeakerDiarizationConfig speakerDiarizationConfig =
+ SpeakerDiarizationConfig.newBuilder()
.setEnableSpeakerDiarization(true)
.setMinSpeakerCount(2)
.setMaxSpeakerCount(2)
.build();
// Configure request to enable Speaker diarization
- RecognitionConfig config = RecognitionConfig.newBuilder()
+ RecognitionConfig config =
+ RecognitionConfig.newBuilder()
.setEncoding(AudioEncoding.LINEAR16)
.setLanguageCode("en-US")
.setSampleRateHertz(8000)
@@ -175,8 +175,7 @@ public static void transcribeDiarization(String fileName) throws Exception {
// Speaker Tags are only included in the last result object, which has only one alternative.
SpeechRecognitionAlternative alternative =
- recognizeResponse.getResults(
- recognizeResponse.getResultsCount() - 1).getAlternatives(0);
+ recognizeResponse.getResults(recognizeResponse.getResultsCount() - 1).getAlternatives(0);
// The alternative is made up of WordInfo objects that contain the speaker_tag.
WordInfo wordInfo = alternative.getWords(0);
@@ -184,7 +183,8 @@ public static void transcribeDiarization(String fileName) throws Exception {
// For each word, get all the words associated with one speaker, once the speaker changes,
// add a new line with the new speaker and their spoken words.
- StringBuilder speakerWords = new StringBuilder(
+ StringBuilder speakerWords =
+ new StringBuilder(
String.format("Speaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
for (int i = 1; i < alternative.getWordsCount(); i++) {
@@ -194,9 +194,7 @@ public static void transcribeDiarization(String fileName) throws Exception {
speakerWords.append(wordInfo.getWord());
} else {
speakerWords.append(
- String.format("\nSpeaker %d: %s",
- wordInfo.getSpeakerTag(),
- wordInfo.getWord()));
+ String.format("\nSpeaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
currentSpeakerTag = wordInfo.getSpeakerTag();
}
}
@@ -214,7 +212,8 @@ public static void transcribeDiarization(String fileName) throws Exception {
*/
public static void transcribeDiarizationGcs(String gcsUri) throws Exception {
try (SpeechClient speechClient = SpeechClient.create()) {
- SpeakerDiarizationConfig speakerDiarizationConfig = SpeakerDiarizationConfig.newBuilder()
+ SpeakerDiarizationConfig speakerDiarizationConfig =
+ SpeakerDiarizationConfig.newBuilder()
.setEnableSpeakerDiarization(true)
.setMinSpeakerCount(2)
.setMaxSpeakerCount(2)
@@ -244,9 +243,9 @@ public static void transcribeDiarizationGcs(String gcsUri) throws Exception {
// Speaker Tags are only included in the last result object, which has only one alternative.
LongRunningRecognizeResponse longRunningRecognizeResponse = response.get();
SpeechRecognitionAlternative alternative =
- longRunningRecognizeResponse.getResults(
- longRunningRecognizeResponse.getResultsCount() - 1)
- .getAlternatives(0);
+ longRunningRecognizeResponse
+ .getResults(longRunningRecognizeResponse.getResultsCount() - 1)
+ .getAlternatives(0);
// The alternative is made up of WordInfo objects that contain the speaker_tag.
WordInfo wordInfo = alternative.getWords(0);
@@ -254,7 +253,8 @@ public static void transcribeDiarizationGcs(String gcsUri) throws Exception {
// For each word, get all the words associated with one speaker, once the speaker changes,
// add a new line with the new speaker and their spoken words.
- StringBuilder speakerWords = new StringBuilder(
+ StringBuilder speakerWords =
+ new StringBuilder(
String.format("Speaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
for (int i = 1; i < alternative.getWordsCount(); i++) {
@@ -264,9 +264,7 @@ public static void transcribeDiarizationGcs(String gcsUri) throws Exception {
speakerWords.append(wordInfo.getWord());
} else {
speakerWords.append(
- String.format("\nSpeaker %d: %s",
- wordInfo.getSpeakerTag(),
- wordInfo.getWord()));
+ String.format("\nSpeaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
currentSpeakerTag = wordInfo.getSpeakerTag();
}
}
diff --git a/speech/beta/src/main/java/com/example/speech/SpeechAdaptation.java b/speech/beta/src/main/java/com/example/speech/SpeechAdaptation.java
index 54d15cffbc7..4c51672d134 100644
--- a/speech/beta/src/main/java/com/example/speech/SpeechAdaptation.java
+++ b/speech/beta/src/main/java/com/example/speech/SpeechAdaptation.java
@@ -25,7 +25,6 @@
import com.google.cloud.speech.v1p1beta1.SpeechContext;
import com.google.cloud.speech.v1p1beta1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1p1beta1.SpeechRecognitionResult;
-
import java.io.IOException;
public class SpeechAdaptation {
diff --git a/speech/beta/src/test/java/com/example/speech/SpeechAdaptationTest.java b/speech/beta/src/test/java/com/example/speech/SpeechAdaptationTest.java
index ed43b6a8436..a31b3637d5d 100644
--- a/speech/beta/src/test/java/com/example/speech/SpeechAdaptationTest.java
+++ b/speech/beta/src/test/java/com/example/speech/SpeechAdaptationTest.java
@@ -21,7 +21,6 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/speech/cloud-client/pom.xml b/speech/cloud-client/pom.xml
index b694f777128..c95b51248cd 100644
--- a/speech/cloud-client/pom.xml
+++ b/speech/cloud-client/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/speech/cloud-client/src/main/java/com/example/speech/InfiniteStreamRecognize.java b/speech/cloud-client/src/main/java/com/example/speech/InfiniteStreamRecognize.java
index fd4d460ddff..fa045ae0772 100644
--- a/speech/cloud-client/src/main/java/com/example/speech/InfiniteStreamRecognize.java
+++ b/speech/cloud-client/src/main/java/com/example/speech/InfiniteStreamRecognize.java
@@ -30,8 +30,6 @@
import com.google.cloud.speech.v1p1beta1.StreamingRecognizeResponse;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
-
-import java.lang.Math;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.concurrent.BlockingQueue;
@@ -87,11 +85,12 @@ public static String convertMillisToDate(double milliSeconds) {
long millis = (long) milliSeconds;
DecimalFormat format = new DecimalFormat();
format.setMinimumIntegerDigits(2);
- return String.format("%s:%s /",
- format.format(TimeUnit.MILLISECONDS.toMinutes(millis)),
- format.format(TimeUnit.MILLISECONDS.toSeconds(millis)
- - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)))
- );
+ return String.format(
+ "%s:%s /",
+ format.format(TimeUnit.MILLISECONDS.toMinutes(millis)),
+ format.format(
+ TimeUnit.MILLISECONDS.toSeconds(millis)
+ - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
}
/** Performs infinite streaming speech recognition */
@@ -139,37 +138,35 @@ public void onResponse(StreamingRecognizeResponse response) {
responses.add(response);
StreamingRecognitionResult result = response.getResultsList().get(0);
Duration resultEndTime = result.getResultEndTime();
- resultEndTimeInMS = (int) ((resultEndTime.getSeconds() * 1000)
- + (resultEndTime.getNanos() / 1000000));
- double correctedTime = resultEndTimeInMS - bridgingOffset
- + (STREAMING_LIMIT * restartCounter);
+ resultEndTimeInMS =
+ (int)
+ ((resultEndTime.getSeconds() * 1000) + (resultEndTime.getNanos() / 1000000));
+ double correctedTime =
+ resultEndTimeInMS - bridgingOffset + (STREAMING_LIMIT * restartCounter);
SpeechRecognitionAlternative alternative = result.getAlternativesList().get(0);
if (result.getIsFinal()) {
System.out.print(GREEN);
System.out.print("\033[2K\r");
- System.out.printf("%s: %s [confidence: %.2f]\n",
- convertMillisToDate(correctedTime),
- alternative.getTranscript(),
- alternative.getConfidence()
- );
+ System.out.printf(
+ "%s: %s [confidence: %.2f]\n",
+ convertMillisToDate(correctedTime),
+ alternative.getTranscript(),
+ alternative.getConfidence());
isFinalEndTime = resultEndTimeInMS;
lastTranscriptWasFinal = true;
} else {
System.out.print(RED);
System.out.print("\033[2K\r");
- System.out.printf("%s: %s", convertMillisToDate(correctedTime),
- alternative.getTranscript()
- );
+ System.out.printf(
+ "%s: %s", convertMillisToDate(correctedTime), alternative.getTranscript());
lastTranscriptWasFinal = false;
}
}
- public void onComplete() {
- }
+ public void onComplete() {}
- public void onError(Throwable t) {
- }
+ public void onError(Throwable t) {}
};
clientStream = client.streamingRecognizeCallable().splitCall(responseObserver);
@@ -244,8 +241,8 @@ public void onError(Throwable t) {
request =
StreamingRecognizeRequest.newBuilder()
- .setStreamingConfig(streamingRecognitionConfig)
- .build();
+ .setStreamingConfig(streamingRecognitionConfig)
+ .build();
System.out.println(YELLOW);
System.out.printf("%d: RESTARTING REQUEST\n", restartCounter * STREAMING_LIMIT);
@@ -269,11 +266,11 @@ public void onError(Throwable t) {
if (bridgingOffset > finalRequestEndTime) {
bridgingOffset = finalRequestEndTime;
}
- int chunksFromMS = (int) Math.floor((finalRequestEndTime
- - bridgingOffset) / chunkTime);
+ int chunksFromMS =
+ (int) Math.floor((finalRequestEndTime - bridgingOffset) / chunkTime);
// chunks from MS is number of chunks to resend
- bridgingOffset = (int) Math.floor((lastAudioInput.size()
- - chunksFromMS) * chunkTime);
+ bridgingOffset =
+ (int) Math.floor((lastAudioInput.size() - chunksFromMS) * chunkTime);
// set bridging offset for next request
for (int i = chunksFromMS; i < lastAudioInput.size(); i++) {
request =
@@ -289,12 +286,9 @@ public void onError(Throwable t) {
tempByteString = ByteString.copyFrom(sharedQueue.take());
request =
- StreamingRecognizeRequest.newBuilder()
- .setAudioContent(tempByteString)
- .build();
+ StreamingRecognizeRequest.newBuilder().setAudioContent(tempByteString).build();
audioInput.add(tempByteString);
-
}
clientStream.send(request);
@@ -304,6 +298,5 @@ public void onError(Throwable t) {
}
}
}
-
}
// [END speech_transcribe_infinite_streaming]
diff --git a/speech/cloud-client/src/main/java/com/example/speech/InfiniteStreamRecognizeOptions.java b/speech/cloud-client/src/main/java/com/example/speech/InfiniteStreamRecognizeOptions.java
index 5966c151b9e..909ff2be08c 100644
--- a/speech/cloud-client/src/main/java/com/example/speech/InfiniteStreamRecognizeOptions.java
+++ b/speech/cloud-client/src/main/java/com/example/speech/InfiniteStreamRecognizeOptions.java
@@ -24,18 +24,18 @@
import org.apache.commons.cli.ParseException;
public class InfiniteStreamRecognizeOptions {
- String langCode = "en-US"; //by default english US
+ String langCode = "en-US"; // by default english US
/** Construct an InfiniteStreamRecognizeOptions class from command line flags. */
public static InfiniteStreamRecognizeOptions fromFlags(String[] args) {
Options options = new Options();
options.addOption(
- Option.builder()
- .type(String.class)
- .longOpt("lang_code")
- .hasArg()
- .desc("Language code")
- .build());
+ Option.builder()
+ .type(String.class)
+ .longOpt("lang_code")
+ .hasArg()
+ .desc("Language code")
+ .build());
CommandLineParser parser = new DefaultParser();
CommandLine commandLine;
@@ -52,5 +52,4 @@ public static InfiniteStreamRecognizeOptions fromFlags(String[] args) {
return null;
}
}
-
}
diff --git a/speech/cloud-client/src/main/java/com/example/speech/QuickstartSample.java b/speech/cloud-client/src/main/java/com/example/speech/QuickstartSample.java
index 1b1a4ee820a..8c4c17af81b 100644
--- a/speech/cloud-client/src/main/java/com/example/speech/QuickstartSample.java
+++ b/speech/cloud-client/src/main/java/com/example/speech/QuickstartSample.java
@@ -33,9 +33,7 @@
public class QuickstartSample {
- /**
- * Demonstrates using the Speech API to transcribe an audio file.
- */
+ /** Demonstrates using the Speech API to transcribe an audio file. */
public static void main(String... args) throws Exception {
// Instantiates a client
try (SpeechClient speechClient = SpeechClient.create()) {
@@ -49,14 +47,13 @@ public static void main(String... args) throws Exception {
ByteString audioBytes = ByteString.copyFrom(data);
// Builds the sync recognize request
- RecognitionConfig config = RecognitionConfig.newBuilder()
- .setEncoding(AudioEncoding.LINEAR16)
- .setSampleRateHertz(16000)
- .setLanguageCode("en-US")
- .build();
- RecognitionAudio audio = RecognitionAudio.newBuilder()
- .setContent(audioBytes)
- .build();
+ RecognitionConfig config =
+ RecognitionConfig.newBuilder()
+ .setEncoding(AudioEncoding.LINEAR16)
+ .setSampleRateHertz(16000)
+ .setLanguageCode("en-US")
+ .build();
+ RecognitionAudio audio = RecognitionAudio.newBuilder().setContent(audioBytes).build();
// Performs speech recognition on the audio file
RecognizeResponse response = speechClient.recognize(config, audio);
diff --git a/speech/cloud-client/src/main/java/com/example/speech/Recognize.java b/speech/cloud-client/src/main/java/com/example/speech/Recognize.java
index 9c35e2b53ae..629974ad415 100644
--- a/speech/cloud-client/src/main/java/com/example/speech/Recognize.java
+++ b/speech/cloud-client/src/main/java/com/example/speech/Recognize.java
@@ -38,14 +38,12 @@
import com.google.cloud.speech.v1.WordInfo;
import com.google.common.util.concurrent.SettableFuture;
import com.google.protobuf.ByteString;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
-
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
diff --git a/speech/cloud-client/src/main/java/com/example/speech/TranscribeContextClasses.java b/speech/cloud-client/src/main/java/com/example/speech/TranscribeContextClasses.java
index 04cdfb80cdc..b75013ea358 100644
--- a/speech/cloud-client/src/main/java/com/example/speech/TranscribeContextClasses.java
+++ b/speech/cloud-client/src/main/java/com/example/speech/TranscribeContextClasses.java
@@ -25,7 +25,6 @@
import com.google.cloud.speech.v1.SpeechContext;
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1.SpeechRecognitionResult;
-
import java.io.IOException;
class TranscribeContextClasses {
diff --git a/speech/cloud-client/src/main/java/com/example/speech/TranscribeDiarization.java b/speech/cloud-client/src/main/java/com/example/speech/TranscribeDiarization.java
index 5a590d132d6..6778f4c5907 100644
--- a/speech/cloud-client/src/main/java/com/example/speech/TranscribeDiarization.java
+++ b/speech/cloud-client/src/main/java/com/example/speech/TranscribeDiarization.java
@@ -26,7 +26,6 @@
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1.WordInfo;
import com.google.protobuf.ByteString;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -51,14 +50,16 @@ static void transcribeDiarization(String fileName) throws IOException {
try (SpeechClient client = SpeechClient.create()) {
// Get the contents of the local audio file
RecognitionAudio recognitionAudio =
- RecognitionAudio.newBuilder().setContent(ByteString.copyFrom(content)).build();
- SpeakerDiarizationConfig speakerDiarizationConfig = SpeakerDiarizationConfig.newBuilder()
+ RecognitionAudio.newBuilder().setContent(ByteString.copyFrom(content)).build();
+ SpeakerDiarizationConfig speakerDiarizationConfig =
+ SpeakerDiarizationConfig.newBuilder()
.setEnableSpeakerDiarization(true)
.setMinSpeakerCount(2)
.setMaxSpeakerCount(2)
.build();
// Configure request to enable Speaker diarization
- RecognitionConfig config = RecognitionConfig.newBuilder()
+ RecognitionConfig config =
+ RecognitionConfig.newBuilder()
.setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
.setLanguageCode("en-US")
.setSampleRateHertz(8000)
@@ -70,14 +71,14 @@ static void transcribeDiarization(String fileName) throws IOException {
// Speaker Tags are only included in the last result object, which has only one alternative.
SpeechRecognitionAlternative alternative =
- recognizeResponse.getResults(
- recognizeResponse.getResultsCount() - 1).getAlternatives(0);
+ recognizeResponse.getResults(recognizeResponse.getResultsCount() - 1).getAlternatives(0);
// The alternative is made up of WordInfo objects that contain the speaker_tag.
WordInfo wordInfo = alternative.getWords(0);
int currentSpeakerTag = wordInfo.getSpeakerTag();
// For each word, get all the words associated with one speaker, once the speaker changes,
// add a new line with the new speaker and their spoken words.
- StringBuilder speakerWords = new StringBuilder(
+ StringBuilder speakerWords =
+ new StringBuilder(
String.format("Speaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
for (int i = 1; i < alternative.getWordsCount(); i++) {
wordInfo = alternative.getWords(i);
@@ -86,9 +87,7 @@ static void transcribeDiarization(String fileName) throws IOException {
speakerWords.append(wordInfo.getWord());
} else {
speakerWords.append(
- String.format("\nSpeaker %d: %s",
- wordInfo.getSpeakerTag(),
- wordInfo.getWord()));
+ String.format("\nSpeaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
currentSpeakerTag = wordInfo.getSpeakerTag();
}
}
diff --git a/speech/cloud-client/src/main/java/com/example/speech/TranscribeDiarizationGcs.java b/speech/cloud-client/src/main/java/com/example/speech/TranscribeDiarizationGcs.java
index de55cc44ea6..de7245b9a21 100644
--- a/speech/cloud-client/src/main/java/com/example/speech/TranscribeDiarizationGcs.java
+++ b/speech/cloud-client/src/main/java/com/example/speech/TranscribeDiarizationGcs.java
@@ -27,59 +27,58 @@
import com.google.cloud.speech.v1.SpeechClient;
import com.google.cloud.speech.v1.SpeechRecognitionAlternative;
import com.google.cloud.speech.v1.WordInfo;
-
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class TranscribeDiarizationGcs {
- static void transcribeDiarizationGcs() throws IOException, ExecutionException,
- InterruptedException {
+ static void transcribeDiarizationGcs()
+ throws IOException, ExecutionException, InterruptedException {
// TODO(developer): Replace these variables before running the sample.
String gcsUri = "gs://cloud-samples-data/speech/commercial_mono.wav";
transcribeDiarizationGcs(gcsUri);
}
// Transcribe the give gcs file using speaker diarization
- public static void transcribeDiarizationGcs(String gcsUri) throws IOException,
- ExecutionException, InterruptedException {
+ public static void transcribeDiarizationGcs(String gcsUri)
+ throws IOException, ExecutionException, InterruptedException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (SpeechClient speechClient = SpeechClient.create()) {
- SpeakerDiarizationConfig speakerDiarizationConfig = SpeakerDiarizationConfig.newBuilder()
+ SpeakerDiarizationConfig speakerDiarizationConfig =
+ SpeakerDiarizationConfig.newBuilder()
.setEnableSpeakerDiarization(true)
.setMinSpeakerCount(2)
.setMaxSpeakerCount(2)
.build();
// Configure request to enable Speaker diarization
RecognitionConfig config =
- RecognitionConfig.newBuilder()
- .setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
- .setLanguageCode("en-US")
- .setSampleRateHertz(8000)
- .setDiarizationConfig(speakerDiarizationConfig)
- .build();
+ RecognitionConfig.newBuilder()
+ .setEncoding(RecognitionConfig.AudioEncoding.LINEAR16)
+ .setLanguageCode("en-US")
+ .setSampleRateHertz(8000)
+ .setDiarizationConfig(speakerDiarizationConfig)
+ .build();
// Set the remote path for the audio file
RecognitionAudio audio = RecognitionAudio.newBuilder().setUri(gcsUri).build();
// Use non-blocking call for getting file transcription
OperationFuture future =
- speechClient.longRunningRecognizeAsync(config, audio);
+ speechClient.longRunningRecognizeAsync(config, audio);
System.out.println("Waiting for response...");
// Speaker Tags are only included in the last result object, which has only one alternative.
LongRunningRecognizeResponse response = future.get();
SpeechRecognitionAlternative alternative =
- response.getResults(
- response.getResultsCount() - 1)
- .getAlternatives(0);
+ response.getResults(response.getResultsCount() - 1).getAlternatives(0);
// The alternative is made up of WordInfo objects that contain the speaker_tag.
WordInfo wordInfo = alternative.getWords(0);
int currentSpeakerTag = wordInfo.getSpeakerTag();
// For each word, get all the words associated with one speaker, once the speaker changes,
// add a new line with the new speaker and their spoken words.
- StringBuilder speakerWords = new StringBuilder(
+ StringBuilder speakerWords =
+ new StringBuilder(
String.format("Speaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
for (int i = 1; i < alternative.getWordsCount(); i++) {
wordInfo = alternative.getWords(i);
@@ -88,9 +87,7 @@ public static void transcribeDiarizationGcs(String gcsUri) throws IOException,
speakerWords.append(wordInfo.getWord());
} else {
speakerWords.append(
- String.format("\nSpeaker %d: %s",
- wordInfo.getSpeakerTag(),
- wordInfo.getWord()));
+ String.format("\nSpeaker %d: %s", wordInfo.getSpeakerTag(), wordInfo.getWord()));
currentSpeakerTag = wordInfo.getSpeakerTag();
}
}
diff --git a/speech/cloud-client/src/test/java/com/example/speech/QuickstartSampleIT.java b/speech/cloud-client/src/test/java/com/example/speech/QuickstartSampleIT.java
index 22be282b8e1..ed739930161 100644
--- a/speech/cloud-client/src/test/java/com/example/speech/QuickstartSampleIT.java
+++ b/speech/cloud-client/src/test/java/com/example/speech/QuickstartSampleIT.java
@@ -26,9 +26,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for quickstart sample.
- */
+/** Tests for quickstart sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class QuickstartSampleIT {
diff --git a/speech/cloud-client/src/test/java/com/example/speech/TranscribeContextClassesTests.java b/speech/cloud-client/src/test/java/com/example/speech/TranscribeContextClassesTests.java
index fc875ce2fea..1afd71d3517 100644
--- a/speech/cloud-client/src/test/java/com/example/speech/TranscribeContextClassesTests.java
+++ b/speech/cloud-client/src/test/java/com/example/speech/TranscribeContextClassesTests.java
@@ -21,7 +21,6 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/speech/cloud-client/src/test/java/com/example/speech/TranscribeDiarizationIT.java b/speech/cloud-client/src/test/java/com/example/speech/TranscribeDiarizationIT.java
index cf814c288d5..ce69cdd2286 100644
--- a/speech/cloud-client/src/test/java/com/example/speech/TranscribeDiarizationIT.java
+++ b/speech/cloud-client/src/test/java/com/example/speech/TranscribeDiarizationIT.java
@@ -23,7 +23,6 @@
import java.io.IOException;
import java.io.PrintStream;
import java.util.concurrent.ExecutionException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -43,9 +42,8 @@ public class TranscribeDiarizationIT {
private static void requireEnvVar(String varName) {
assertNotNull(
- System.getenv(varName),
- "Environment variable '%s' is required to perform these tests.".format(varName)
- );
+ System.getenv(varName),
+ "Environment variable '%s' is required to perform these tests.".format(varName));
}
@BeforeClass
@@ -75,7 +73,7 @@ public void testDiarization() throws IOException {
@Test
public void testDiarizationGcs() throws IOException, ExecutionException, InterruptedException {
TranscribeDiarizationGcs.transcribeDiarizationGcs(
- "gs://cloud-samples-data/speech/commercial_mono.wav");
+ "gs://cloud-samples-data/speech/commercial_mono.wav");
String got = bout.toString();
assertThat(got).contains("Speaker");
}
diff --git a/tasks/pom.xml b/tasks/pom.xml
index 4503e9768ee..26c34c97d62 100644
--- a/tasks/pom.xml
+++ b/tasks/pom.xml
@@ -29,7 +29,7 @@ Copyright 2018 Google LLC
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/texttospeech/beta/pom.xml b/texttospeech/beta/pom.xml
index 5a8431552e7..0509ccc3288 100644
--- a/texttospeech/beta/pom.xml
+++ b/texttospeech/beta/pom.xml
@@ -23,7 +23,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/texttospeech/beta/src/main/java/com/example/texttospeech/ListAllSupportedVoices.java b/texttospeech/beta/src/main/java/com/example/texttospeech/ListAllSupportedVoices.java
index da20617b81a..81f0cfab764 100644
--- a/texttospeech/beta/src/main/java/com/example/texttospeech/ListAllSupportedVoices.java
+++ b/texttospeech/beta/src/main/java/com/example/texttospeech/ListAllSupportedVoices.java
@@ -22,20 +22,18 @@
import com.google.cloud.texttospeech.v1beta1.TextToSpeechClient;
import com.google.cloud.texttospeech.v1beta1.Voice;
import com.google.protobuf.ByteString;
-
import java.util.List;
-
/**
- * Google Cloud TextToSpeech API sample application.
- * Example usage: mvn package exec:java
- * -Dexec.mainClass='com.example.texttospeech.ListAllSupportedVoices'
+ * Google Cloud TextToSpeech API sample application. Example usage: mvn package exec:java
+ * -Dexec.mainClass='com.example.texttospeech.ListAllSupportedVoices'
*/
public class ListAllSupportedVoices {
// [START tts_list_voices]
/**
* Demonstrates using the Text to Speech client to list the client's supported voices.
+ *
* @throws Exception on TextToSpeechClient Errors.
*/
public static void listAllSupportedVoices() throws Exception {
@@ -62,8 +60,7 @@ public static void listAllSupportedVoices() throws Exception {
System.out.format("SSML Voice Gender: %s\n", voice.getSsmlGender());
// Display the natural sample rate hertz for this voice. Example: 24000
- System.out.format("Natural Sample Rate Hertz: %s\n\n",
- voice.getNaturalSampleRateHertz());
+ System.out.format("Natural Sample Rate Hertz: %s\n\n", voice.getNaturalSampleRateHertz());
}
}
}
@@ -72,4 +69,4 @@ public static void listAllSupportedVoices() throws Exception {
public static void main(String[] args) throws Exception {
listAllSupportedVoices();
}
-}
\ No newline at end of file
+}
diff --git a/texttospeech/beta/src/main/java/com/example/texttospeech/QuickstartSample.java b/texttospeech/beta/src/main/java/com/example/texttospeech/QuickstartSample.java
index d05c05f2dc9..016985bf60b 100644
--- a/texttospeech/beta/src/main/java/com/example/texttospeech/QuickstartSample.java
+++ b/texttospeech/beta/src/main/java/com/example/texttospeech/QuickstartSample.java
@@ -30,39 +30,34 @@
import java.io.OutputStream;
/**
- * Google Cloud TextToSpeech API sample application.
- * Example usage: mvn package exec:java
- * -Dexec.mainClass='com.example.texttospeech.QuickstartSample'
+ * Google Cloud TextToSpeech API sample application. Example usage: mvn package exec:java
+ * -Dexec.mainClass='com.example.texttospeech.QuickstartSample'
*/
public class QuickstartSample {
- /**
- * Demonstrates using the Text-to-Speech API.
- */
+ /** Demonstrates using the Text-to-Speech API. */
public static void main(String... args) throws Exception {
// Instantiates a client
try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
// Set the text input to be synthesized
- SynthesisInput input = SynthesisInput.newBuilder()
- .setText("Hello, World!")
- .build();
+ SynthesisInput input = SynthesisInput.newBuilder().setText("Hello, World!").build();
// Build the voice request, select the language code ("en-US") and the ssml voice gender
// ("neutral")
- VoiceSelectionParams voice = VoiceSelectionParams.newBuilder()
- .setLanguageCode("en-US")
- .setSsmlGender(SsmlVoiceGender.NEUTRAL)
- .build();
+ VoiceSelectionParams voice =
+ VoiceSelectionParams.newBuilder()
+ .setLanguageCode("en-US")
+ .setSsmlGender(SsmlVoiceGender.NEUTRAL)
+ .build();
// Select the type of audio file you want returned
- AudioConfig audioConfig = AudioConfig.newBuilder()
- .setAudioEncoding(AudioEncoding.MP3)
- .build();
+ AudioConfig audioConfig =
+ AudioConfig.newBuilder().setAudioEncoding(AudioEncoding.MP3).build();
// Perform the text-to-speech request on the text input with the selected voice parameters and
// audio file type
- SynthesizeSpeechResponse response = textToSpeechClient.synthesizeSpeech(input, voice,
- audioConfig);
+ SynthesizeSpeechResponse response =
+ textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);
// Get the audio contents from the response
ByteString audioContents = response.getAudioContent();
diff --git a/texttospeech/beta/src/main/java/com/example/texttospeech/SynthesizeFile.java b/texttospeech/beta/src/main/java/com/example/texttospeech/SynthesizeFile.java
index 8e22a1b05e9..bea8c47748d 100644
--- a/texttospeech/beta/src/main/java/com/example/texttospeech/SynthesizeFile.java
+++ b/texttospeech/beta/src/main/java/com/example/texttospeech/SynthesizeFile.java
@@ -25,7 +25,6 @@
import com.google.cloud.texttospeech.v1beta1.TextToSpeechClient;
import com.google.cloud.texttospeech.v1beta1.VoiceSelectionParams;
import com.google.protobuf.ByteString;
-
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
@@ -36,45 +35,44 @@
import net.sourceforge.argparse4j.inf.MutuallyExclusiveGroup;
import net.sourceforge.argparse4j.inf.Namespace;
-
/**
- * Google Cloud TextToSpeech API sample application.
- * Example usage: mvn package exec:java -Dexec.mainClass='com.example.texttospeech.SynthesizeFile'
- * -Dexec.args='--text resources/hello.txt'
+ * Google Cloud TextToSpeech API sample application. Example usage: mvn package exec:java
+ * -Dexec.mainClass='com.example.texttospeech.SynthesizeFile' -Dexec.args='--text
+ * resources/hello.txt'
*/
public class SynthesizeFile {
// [START tts_synthesize_text_file]
/**
* Demonstrates using the Text to Speech client to synthesize a text file or ssml file.
+ *
* @param textFile the text file to be synthesized. (e.g., hello.txt)
* @throws Exception on TextToSpeechClient Errors.
*/
- public static void synthesizeTextFile(String textFile)
- throws Exception {
+ public static void synthesizeTextFile(String textFile) throws Exception {
// Instantiates a client
try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
// Read the file's contents
String contents = new String(Files.readAllBytes(Paths.get(textFile)));
// Set the text input to be synthesized
- SynthesisInput input = SynthesisInput.newBuilder()
- .setText(contents)
- .build();
+ SynthesisInput input = SynthesisInput.newBuilder().setText(contents).build();
// Build the voice request
- VoiceSelectionParams voice = VoiceSelectionParams.newBuilder()
- .setLanguageCode("en-US") // languageCode = "en_us"
- .setSsmlGender(SsmlVoiceGender.FEMALE) // ssmlVoiceGender = SsmlVoiceGender.FEMALE
- .build();
+ VoiceSelectionParams voice =
+ VoiceSelectionParams.newBuilder()
+ .setLanguageCode("en-US") // languageCode = "en_us"
+ .setSsmlGender(SsmlVoiceGender.FEMALE) // ssmlVoiceGender = SsmlVoiceGender.FEMALE
+ .build();
// Select the type of audio file you want returned
- AudioConfig audioConfig = AudioConfig.newBuilder()
- .setAudioEncoding(AudioEncoding.MP3) // MP3 audio.
- .build();
+ AudioConfig audioConfig =
+ AudioConfig.newBuilder()
+ .setAudioEncoding(AudioEncoding.MP3) // MP3 audio.
+ .build();
// Perform the text-to-speech request
- SynthesizeSpeechResponse response = textToSpeechClient.synthesizeSpeech(input, voice,
- audioConfig);
+ SynthesizeSpeechResponse response =
+ textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);
// Get the audio contents from the response
ByteString audioContents = response.getAudioContent();
@@ -88,38 +86,37 @@ public static void synthesizeTextFile(String textFile)
}
// [END tts_synthesize_text_file]
-
// [START tts_synthesize_ssml_file]
/**
* Demonstrates using the Text to Speech client to synthesize a text file or ssml file.
+ *
* @param ssmlFile the ssml document to be synthesized. (e.g., hello.ssml)
* @throws Exception on TextToSpeechClient Errors.
*/
- public static void synthesizeSsmlFile(String ssmlFile)
- throws Exception {
+ public static void synthesizeSsmlFile(String ssmlFile) throws Exception {
// Instantiates a client
try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
// Read the file's contents
String contents = new String(Files.readAllBytes(Paths.get(ssmlFile)));
// Set the ssml input to be synthesized
- SynthesisInput input = SynthesisInput.newBuilder()
- .setSsml(contents)
- .build();
+ SynthesisInput input = SynthesisInput.newBuilder().setSsml(contents).build();
// Build the voice request
- VoiceSelectionParams voice = VoiceSelectionParams.newBuilder()
- .setLanguageCode("en-US") // languageCode = "en_us"
- .setSsmlGender(SsmlVoiceGender.FEMALE) // ssmlVoiceGender = SsmlVoiceGender.FEMALE
- .build();
+ VoiceSelectionParams voice =
+ VoiceSelectionParams.newBuilder()
+ .setLanguageCode("en-US") // languageCode = "en_us"
+ .setSsmlGender(SsmlVoiceGender.FEMALE) // ssmlVoiceGender = SsmlVoiceGender.FEMALE
+ .build();
// Select the type of audio file you want returned
- AudioConfig audioConfig = AudioConfig.newBuilder()
- .setAudioEncoding(AudioEncoding.MP3) // MP3 audio.
- .build();
+ AudioConfig audioConfig =
+ AudioConfig.newBuilder()
+ .setAudioEncoding(AudioEncoding.MP3) // MP3 audio.
+ .build();
// Perform the text-to-speech request
- SynthesizeSpeechResponse response = textToSpeechClient.synthesizeSpeech(input, voice,
- audioConfig);
+ SynthesizeSpeechResponse response =
+ textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);
// Get the audio contents from the response
ByteString audioContents = response.getAudioContent();
@@ -134,9 +131,11 @@ public static void synthesizeSsmlFile(String ssmlFile)
// [END tts_synthesize_ssml_file]
public static void main(String... args) throws Exception {
- ArgumentParser parser = ArgumentParsers.newFor("SynthesizeFile").build()
- .defaultHelp(true)
- .description("Synthesize a text file or ssml file.");
+ ArgumentParser parser =
+ ArgumentParsers.newFor("SynthesizeFile")
+ .build()
+ .defaultHelp(true)
+ .description("Synthesize a text file or ssml file.");
MutuallyExclusiveGroup group = parser.addMutuallyExclusiveGroup().required(true);
group.addArgument("--text").help("The text file from which to synthesize speech.");
group.addArgument("--ssml").help("The ssml file from which to synthesize speech.");
@@ -153,4 +152,4 @@ public static void main(String... args) throws Exception {
parser.handleError(e);
}
}
-}
\ No newline at end of file
+}
diff --git a/texttospeech/beta/src/main/java/com/example/texttospeech/SynthesizeText.java b/texttospeech/beta/src/main/java/com/example/texttospeech/SynthesizeText.java
index 22cf40d2232..344900f0f00 100644
--- a/texttospeech/beta/src/main/java/com/example/texttospeech/SynthesizeText.java
+++ b/texttospeech/beta/src/main/java/com/example/texttospeech/SynthesizeText.java
@@ -25,7 +25,6 @@
import com.google.cloud.texttospeech.v1beta1.TextToSpeechClient;
import com.google.cloud.texttospeech.v1beta1.VoiceSelectionParams;
import com.google.protobuf.ByteString;
-
import java.io.FileOutputStream;
import java.io.OutputStream;
import net.sourceforge.argparse4j.ArgumentParsers;
@@ -35,9 +34,8 @@
import net.sourceforge.argparse4j.inf.Namespace;
/**
- * Google Cloud TextToSpeech API sample application.
- * Example usage: mvn package exec:java-Dexec.mainClass='com.example.texttospeech.SynthesizeText'
- * -Dexec.args='--text "hello"'
+ * Google Cloud TextToSpeech API sample application. Example usage: mvn package
+ * exec:java-Dexec.mainClass='com.example.texttospeech.SynthesizeText' -Dexec.args='--text "hello"'
*/
public class SynthesizeText {
diff --git a/texttospeech/beta/src/test/java/com/example/texttospeech/ListAllSupportedVoicesIT.java b/texttospeech/beta/src/test/java/com/example/texttospeech/ListAllSupportedVoicesIT.java
index d57427e5eaf..3f6b43b3e44 100644
--- a/texttospeech/beta/src/test/java/com/example/texttospeech/ListAllSupportedVoicesIT.java
+++ b/texttospeech/beta/src/test/java/com/example/texttospeech/ListAllSupportedVoicesIT.java
@@ -20,16 +20,13 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for ListAllSupportedVoices sample.
- */
+/** Tests for ListAllSupportedVoices sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class ListAllSupportedVoicesIT {
@@ -38,7 +35,6 @@ public class ListAllSupportedVoicesIT {
private PrintStream out;
private ListAllSupportedVoices listAllSupportedVoices;
-
@Before
public void setUp() {
bout = new ByteArrayOutputStream();
@@ -63,4 +59,4 @@ public void testListAllSupportedVoices() throws Exception {
assertThat(got).contains("SSML Voice Gender: MALE");
assertThat(got).contains("SSML Voice Gender: FEMALE");
}
-}
\ No newline at end of file
+}
diff --git a/texttospeech/beta/src/test/java/com/example/texttospeech/SynthesizeFileIT.java b/texttospeech/beta/src/test/java/com/example/texttospeech/SynthesizeFileIT.java
index d3b68b498da..eed608b1c18 100644
--- a/texttospeech/beta/src/test/java/com/example/texttospeech/SynthesizeFileIT.java
+++ b/texttospeech/beta/src/test/java/com/example/texttospeech/SynthesizeFileIT.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
-
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
@@ -28,9 +27,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for SynthesizeFile sample.
- */
+/** Tests for SynthesizeFile sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class SynthesizeFileIT {
@@ -78,4 +75,4 @@ public void testSynthesizeSsml() throws Exception {
String got = bout.toString();
assertThat(got).contains("Audio content written to file \"output.mp3\"");
}
-}
\ No newline at end of file
+}
diff --git a/texttospeech/beta/src/test/java/com/example/texttospeech/SynthesizeTextIT.java b/texttospeech/beta/src/test/java/com/example/texttospeech/SynthesizeTextIT.java
index 23872be35a9..806e7467949 100644
--- a/texttospeech/beta/src/test/java/com/example/texttospeech/SynthesizeTextIT.java
+++ b/texttospeech/beta/src/test/java/com/example/texttospeech/SynthesizeTextIT.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
-
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
diff --git a/texttospeech/cloud-client/pom.xml b/texttospeech/cloud-client/pom.xml
index f7af9027f43..a07de770634 100644
--- a/texttospeech/cloud-client/pom.xml
+++ b/texttospeech/cloud-client/pom.xml
@@ -23,7 +23,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/texttospeech/cloud-client/src/main/java/com/example/texttospeech/ListAllSupportedVoices.java b/texttospeech/cloud-client/src/main/java/com/example/texttospeech/ListAllSupportedVoices.java
index 690091731f8..fff4c7bbe59 100644
--- a/texttospeech/cloud-client/src/main/java/com/example/texttospeech/ListAllSupportedVoices.java
+++ b/texttospeech/cloud-client/src/main/java/com/example/texttospeech/ListAllSupportedVoices.java
@@ -22,20 +22,18 @@
import com.google.cloud.texttospeech.v1.TextToSpeechClient;
import com.google.cloud.texttospeech.v1.Voice;
import com.google.protobuf.ByteString;
-
import java.util.List;
-
/**
- * Google Cloud TextToSpeech API sample application.
- * Example usage: mvn package exec:java
- * -Dexec.mainClass='com.example.texttospeech.ListAllSupportedVoices'
+ * Google Cloud TextToSpeech API sample application. Example usage: mvn package exec:java
+ * -Dexec.mainClass='com.example.texttospeech.ListAllSupportedVoices'
*/
public class ListAllSupportedVoices {
// [START tts_list_voices]
/**
* Demonstrates using the Text to Speech client to list the client's supported voices.
+ *
* @throws Exception on TextToSpeechClient Errors.
*/
public static List listAllSupportedVoices() throws Exception {
@@ -62,11 +60,10 @@ public static List listAllSupportedVoices() throws Exception {
System.out.format("SSML Voice Gender: %s\n", voice.getSsmlGender());
// Display the natural sample rate hertz for this voice. Example: 24000
- System.out.format("Natural Sample Rate Hertz: %s\n\n",
- voice.getNaturalSampleRateHertz());
+ System.out.format("Natural Sample Rate Hertz: %s\n\n", voice.getNaturalSampleRateHertz());
}
return voices;
}
}
// [END tts_list_voices]
-}
\ No newline at end of file
+}
diff --git a/texttospeech/cloud-client/src/main/java/com/example/texttospeech/QuickstartSample.java b/texttospeech/cloud-client/src/main/java/com/example/texttospeech/QuickstartSample.java
index 542cab8af51..73841cb1e02 100644
--- a/texttospeech/cloud-client/src/main/java/com/example/texttospeech/QuickstartSample.java
+++ b/texttospeech/cloud-client/src/main/java/com/example/texttospeech/QuickstartSample.java
@@ -30,39 +30,34 @@
import java.io.OutputStream;
/**
- * Google Cloud TextToSpeech API sample application.
- * Example usage: mvn package exec:java
- * -Dexec.mainClass='com.example.texttospeech.QuickstartSample'
+ * Google Cloud TextToSpeech API sample application. Example usage: mvn package exec:java
+ * -Dexec.mainClass='com.example.texttospeech.QuickstartSample'
*/
public class QuickstartSample {
- /**
- * Demonstrates using the Text-to-Speech API.
- */
+ /** Demonstrates using the Text-to-Speech API. */
public static void main(String... args) throws Exception {
// Instantiates a client
try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
// Set the text input to be synthesized
- SynthesisInput input = SynthesisInput.newBuilder()
- .setText("Hello, World!")
- .build();
+ SynthesisInput input = SynthesisInput.newBuilder().setText("Hello, World!").build();
// Build the voice request, select the language code ("en-US") and the ssml voice gender
// ("neutral")
- VoiceSelectionParams voice = VoiceSelectionParams.newBuilder()
- .setLanguageCode("en-US")
- .setSsmlGender(SsmlVoiceGender.NEUTRAL)
- .build();
+ VoiceSelectionParams voice =
+ VoiceSelectionParams.newBuilder()
+ .setLanguageCode("en-US")
+ .setSsmlGender(SsmlVoiceGender.NEUTRAL)
+ .build();
// Select the type of audio file you want returned
- AudioConfig audioConfig = AudioConfig.newBuilder()
- .setAudioEncoding(AudioEncoding.MP3)
- .build();
+ AudioConfig audioConfig =
+ AudioConfig.newBuilder().setAudioEncoding(AudioEncoding.MP3).build();
// Perform the text-to-speech request on the text input with the selected voice parameters and
// audio file type
- SynthesizeSpeechResponse response = textToSpeechClient.synthesizeSpeech(input, voice,
- audioConfig);
+ SynthesizeSpeechResponse response =
+ textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);
// Get the audio contents from the response
ByteString audioContents = response.getAudioContent();
diff --git a/texttospeech/cloud-client/src/main/java/com/example/texttospeech/SsmlAddresses.java b/texttospeech/cloud-client/src/main/java/com/example/texttospeech/SsmlAddresses.java
index 1e75b408a15..d5192429148 100644
--- a/texttospeech/cloud-client/src/main/java/com/example/texttospeech/SsmlAddresses.java
+++ b/texttospeech/cloud-client/src/main/java/com/example/texttospeech/SsmlAddresses.java
@@ -32,6 +32,7 @@
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
+
// [END tts_ssml_address_imports]
/**
diff --git a/texttospeech/cloud-client/src/main/java/com/example/texttospeech/SynthesizeFile.java b/texttospeech/cloud-client/src/main/java/com/example/texttospeech/SynthesizeFile.java
index 16a8f3c811e..b67c04df69d 100644
--- a/texttospeech/cloud-client/src/main/java/com/example/texttospeech/SynthesizeFile.java
+++ b/texttospeech/cloud-client/src/main/java/com/example/texttospeech/SynthesizeFile.java
@@ -25,51 +25,49 @@
import com.google.cloud.texttospeech.v1.TextToSpeechClient;
import com.google.cloud.texttospeech.v1.VoiceSelectionParams;
import com.google.protobuf.ByteString;
-
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
-
/**
- * Google Cloud TextToSpeech API sample application.
- * Example usage: mvn package exec:java -Dexec.mainClass='com.example.texttospeech.SynthesizeFile'
- * -Dexec.args='--text resources/hello.txt'
+ * Google Cloud TextToSpeech API sample application. Example usage: mvn package exec:java
+ * -Dexec.mainClass='com.example.texttospeech.SynthesizeFile' -Dexec.args='--text
+ * resources/hello.txt'
*/
public class SynthesizeFile {
// [START tts_synthesize_text_file]
/**
* Demonstrates using the Text to Speech client to synthesize a text file or ssml file.
+ *
* @param textFile the text file to be synthesized. (e.g., hello.txt)
* @throws Exception on TextToSpeechClient Errors.
*/
- public static ByteString synthesizeTextFile(String textFile)
- throws Exception {
+ public static ByteString synthesizeTextFile(String textFile) throws Exception {
// Instantiates a client
try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
// Read the file's contents
String contents = new String(Files.readAllBytes(Paths.get(textFile)));
// Set the text input to be synthesized
- SynthesisInput input = SynthesisInput.newBuilder()
- .setText(contents)
- .build();
+ SynthesisInput input = SynthesisInput.newBuilder().setText(contents).build();
// Build the voice request
- VoiceSelectionParams voice = VoiceSelectionParams.newBuilder()
- .setLanguageCode("en-US") // languageCode = "en_us"
- .setSsmlGender(SsmlVoiceGender.FEMALE) // ssmlVoiceGender = SsmlVoiceGender.FEMALE
- .build();
+ VoiceSelectionParams voice =
+ VoiceSelectionParams.newBuilder()
+ .setLanguageCode("en-US") // languageCode = "en_us"
+ .setSsmlGender(SsmlVoiceGender.FEMALE) // ssmlVoiceGender = SsmlVoiceGender.FEMALE
+ .build();
// Select the type of audio file you want returned
- AudioConfig audioConfig = AudioConfig.newBuilder()
- .setAudioEncoding(AudioEncoding.MP3) // MP3 audio.
- .build();
+ AudioConfig audioConfig =
+ AudioConfig.newBuilder()
+ .setAudioEncoding(AudioEncoding.MP3) // MP3 audio.
+ .build();
// Perform the text-to-speech request
- SynthesizeSpeechResponse response = textToSpeechClient.synthesizeSpeech(input, voice,
- audioConfig);
+ SynthesizeSpeechResponse response =
+ textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);
// Get the audio contents from the response
ByteString audioContents = response.getAudioContent();
@@ -84,38 +82,37 @@ public static ByteString synthesizeTextFile(String textFile)
}
// [END tts_synthesize_text_file]
-
// [START tts_synthesize_ssml_file]
/**
* Demonstrates using the Text to Speech client to synthesize a text file or ssml file.
+ *
* @param ssmlFile the ssml document to be synthesized. (e.g., hello.ssml)
* @throws Exception on TextToSpeechClient Errors.
*/
- public static ByteString synthesizeSsmlFile(String ssmlFile)
- throws Exception {
+ public static ByteString synthesizeSsmlFile(String ssmlFile) throws Exception {
// Instantiates a client
try (TextToSpeechClient textToSpeechClient = TextToSpeechClient.create()) {
// Read the file's contents
String contents = new String(Files.readAllBytes(Paths.get(ssmlFile)));
// Set the ssml input to be synthesized
- SynthesisInput input = SynthesisInput.newBuilder()
- .setSsml(contents)
- .build();
+ SynthesisInput input = SynthesisInput.newBuilder().setSsml(contents).build();
// Build the voice request
- VoiceSelectionParams voice = VoiceSelectionParams.newBuilder()
- .setLanguageCode("en-US") // languageCode = "en_us"
- .setSsmlGender(SsmlVoiceGender.FEMALE) // ssmlVoiceGender = SsmlVoiceGender.FEMALE
- .build();
+ VoiceSelectionParams voice =
+ VoiceSelectionParams.newBuilder()
+ .setLanguageCode("en-US") // languageCode = "en_us"
+ .setSsmlGender(SsmlVoiceGender.FEMALE) // ssmlVoiceGender = SsmlVoiceGender.FEMALE
+ .build();
// Select the type of audio file you want returned
- AudioConfig audioConfig = AudioConfig.newBuilder()
- .setAudioEncoding(AudioEncoding.MP3) // MP3 audio.
- .build();
+ AudioConfig audioConfig =
+ AudioConfig.newBuilder()
+ .setAudioEncoding(AudioEncoding.MP3) // MP3 audio.
+ .build();
// Perform the text-to-speech request
- SynthesizeSpeechResponse response = textToSpeechClient.synthesizeSpeech(input, voice,
- audioConfig);
+ SynthesizeSpeechResponse response =
+ textToSpeechClient.synthesizeSpeech(input, voice, audioConfig);
// Get the audio contents from the response
ByteString audioContents = response.getAudioContent();
@@ -129,4 +126,4 @@ public static ByteString synthesizeSsmlFile(String ssmlFile)
}
}
// [END tts_synthesize_ssml_file]
-}
\ No newline at end of file
+}
diff --git a/texttospeech/cloud-client/src/main/java/com/example/texttospeech/SynthesizeText.java b/texttospeech/cloud-client/src/main/java/com/example/texttospeech/SynthesizeText.java
index 3c495ff15c7..9e5f00484dc 100644
--- a/texttospeech/cloud-client/src/main/java/com/example/texttospeech/SynthesizeText.java
+++ b/texttospeech/cloud-client/src/main/java/com/example/texttospeech/SynthesizeText.java
@@ -25,14 +25,12 @@
import com.google.cloud.texttospeech.v1.TextToSpeechClient;
import com.google.cloud.texttospeech.v1.VoiceSelectionParams;
import com.google.protobuf.ByteString;
-
import java.io.FileOutputStream;
import java.io.OutputStream;
/**
- * Google Cloud TextToSpeech API sample application.
- * Example usage: mvn package exec:java -Dexec.mainClass='com.example.texttospeech.SynthesizeText'
- * -Dexec.args='--text "hello"'
+ * Google Cloud TextToSpeech API sample application. Example usage: mvn package exec:java
+ * -Dexec.mainClass='com.example.texttospeech.SynthesizeText' -Dexec.args='--text "hello"'
*/
public class SynthesizeText {
diff --git a/texttospeech/cloud-client/src/test/java/com/example/texttospeech/ListAllSupportedVoicesIT.java b/texttospeech/cloud-client/src/test/java/com/example/texttospeech/ListAllSupportedVoicesIT.java
index 3702d0b21ac..73dc3753caa 100644
--- a/texttospeech/cloud-client/src/test/java/com/example/texttospeech/ListAllSupportedVoicesIT.java
+++ b/texttospeech/cloud-client/src/test/java/com/example/texttospeech/ListAllSupportedVoicesIT.java
@@ -21,7 +21,6 @@
import com.google.cloud.texttospeech.v1.Voice;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import java.util.List;
import org.junit.After;
import org.junit.Before;
@@ -29,9 +28,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for ListAllSupportedVoices sample.
- */
+/** Tests for ListAllSupportedVoices sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class ListAllSupportedVoicesIT {
@@ -40,7 +37,6 @@ public class ListAllSupportedVoicesIT {
private PrintStream out;
private ListAllSupportedVoices listAllSupportedVoices;
-
@Before
public void setUp() {
bout = new ByteArrayOutputStream();
@@ -66,4 +62,4 @@ public void testListAllSupportedVoices() throws Exception {
assertThat(got).contains("SSML Voice Gender: MALE");
assertThat(got).contains("SSML Voice Gender: FEMALE");
}
-}
\ No newline at end of file
+}
diff --git a/texttospeech/cloud-client/src/test/java/com/example/texttospeech/SsmlAddressesIT.java b/texttospeech/cloud-client/src/test/java/com/example/texttospeech/SsmlAddressesIT.java
index e9d0d34a4c4..cbe8ec85c12 100644
--- a/texttospeech/cloud-client/src/test/java/com/example/texttospeech/SsmlAddressesIT.java
+++ b/texttospeech/cloud-client/src/test/java/com/example/texttospeech/SsmlAddressesIT.java
@@ -18,21 +18,17 @@
import static com.google.common.truth.Truth.assertThat;
-import com.google.protobuf.ByteString;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Paths;
-import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for SsmlAddresses sample.
- */
+/** Tests for SsmlAddresses sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class SsmlAddressesIT {
@@ -77,4 +73,4 @@ public void testSsmlToAudio() throws Exception {
// After
outputFile.delete();
}
-}
\ No newline at end of file
+}
diff --git a/texttospeech/cloud-client/src/test/java/com/example/texttospeech/SynthesizeFileIT.java b/texttospeech/cloud-client/src/test/java/com/example/texttospeech/SynthesizeFileIT.java
index 7c232d15ee4..1737d220a5d 100644
--- a/texttospeech/cloud-client/src/test/java/com/example/texttospeech/SynthesizeFileIT.java
+++ b/texttospeech/cloud-client/src/test/java/com/example/texttospeech/SynthesizeFileIT.java
@@ -21,7 +21,6 @@
import com.google.protobuf.ByteString;
import java.io.ByteArrayOutputStream;
import java.io.File;
-
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
@@ -29,9 +28,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for SynthesizeFile sample.
- */
+/** Tests for SynthesizeFile sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class SynthesizeFileIT {
@@ -81,4 +78,4 @@ public void testSynthesizeSsml() throws Exception {
String got = bout.toString();
assertThat(got).contains("Audio content written to file \"output.mp3\"");
}
-}
\ No newline at end of file
+}
diff --git a/texttospeech/cloud-client/src/test/java/com/example/texttospeech/SynthesizeTextIT.java b/texttospeech/cloud-client/src/test/java/com/example/texttospeech/SynthesizeTextIT.java
index eb326afd6b3..826052d7177 100644
--- a/texttospeech/cloud-client/src/test/java/com/example/texttospeech/SynthesizeTextIT.java
+++ b/texttospeech/cloud-client/src/test/java/com/example/texttospeech/SynthesizeTextIT.java
@@ -21,7 +21,6 @@
import com.google.protobuf.ByteString;
import java.io.ByteArrayOutputStream;
import java.io.File;
-
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
@@ -29,9 +28,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for SynthesizeText sample.
- */
+/** Tests for SynthesizeText sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class SynthesizeTextIT {
@@ -95,4 +92,4 @@ public void testSynthesizeTextWithAudioProfile() throws Exception {
String got = bout.toString();
assertThat(got).contains("Audio content written to file \"output.mp3\"");
}
-}
\ No newline at end of file
+}
diff --git a/trace/pom.xml b/trace/pom.xml
index b2a4d126ea6..767634b965b 100644
--- a/trace/pom.xml
+++ b/trace/pom.xml
@@ -28,7 +28,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/trace/src/main/java/com/example/trace/TraceSample.java b/trace/src/main/java/com/example/trace/TraceSample.java
index 767c41c41da..8421c9366bb 100644
--- a/trace/src/main/java/com/example/trace/TraceSample.java
+++ b/trace/src/main/java/com/example/trace/TraceSample.java
@@ -18,17 +18,14 @@
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.GoogleCredentials;
-
import io.opencensus.common.Scope;
import io.opencensus.exporter.trace.stackdriver.StackdriverTraceConfiguration;
import io.opencensus.exporter.trace.stackdriver.StackdriverTraceExporter;
import io.opencensus.trace.Tracer;
import io.opencensus.trace.Tracing;
import io.opencensus.trace.samplers.Samplers;
-
import java.io.IOException;
import java.util.Date;
-
import org.joda.time.DateTime;
public class TraceSample {
@@ -60,10 +57,11 @@ private static void doFinalWork() {
// [START trace_setup_java_full_sampling]
public static void doWorkFullSampled() {
- try (
- Scope ss = tracer.spanBuilder("MyChildWorkSpan")
- .setSampler(Samplers.alwaysSample())
- .startScopedSpan()) {
+ try (Scope ss =
+ tracer
+ .spanBuilder("MyChildWorkSpan")
+ .setSampler(Samplers.alwaysSample())
+ .startScopedSpan()) {
doInitialWork();
tracer.getCurrentSpan().addAnnotation("Finished initial work");
doFinalWork();
@@ -73,8 +71,7 @@ public static void doWorkFullSampled() {
// [START trace_setup_java_create_and_register]
public static void createAndRegister() throws IOException {
- StackdriverTraceExporter.createAndRegister(
- StackdriverTraceConfiguration.builder().build());
+ StackdriverTraceExporter.createAndRegister(StackdriverTraceConfiguration.builder().build());
}
// [END trace_setup_java_create_and_register]
@@ -95,9 +92,7 @@ public static void createAndRegisterWithToken(String accessToken) throws IOExcep
// [START trace_setup_java_register_exporter]
public static void createAndRegisterGoogleCloudPlatform(String projectId) throws IOException {
StackdriverTraceExporter.createAndRegister(
- StackdriverTraceConfiguration.builder()
- .setProjectId(projectId)
- .build());
+ StackdriverTraceConfiguration.builder().setProjectId(projectId).build());
}
// [END trace_setup_java_register_exporter]
}
diff --git a/trace/src/test/java/com/example/trace/TraceSampleIT.java b/trace/src/test/java/com/example/trace/TraceSampleIT.java
index ae30f3ee083..b4a09bca316 100644
--- a/trace/src/test/java/com/example/trace/TraceSampleIT.java
+++ b/trace/src/test/java/com/example/trace/TraceSampleIT.java
@@ -17,11 +17,8 @@
package com.example.trace;
import com.google.common.base.Strings;
-
import io.opencensus.exporter.trace.stackdriver.StackdriverTraceExporter;
-
import java.io.IOException;
-
import org.junit.After;
import org.junit.Assert;
import org.junit.BeforeClass;
@@ -29,9 +26,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for stackdriver tracing sample.
- */
+/** Tests for stackdriver tracing sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class TraceSampleIT {
diff --git a/translate/automl/pom.xml b/translate/automl/pom.xml
index 6c58ab52158..86314011ee8 100644
--- a/translate/automl/pom.xml
+++ b/translate/automl/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/translate/automl/src/main/java/com/google/cloud/translate/automl/DatasetApi.java b/translate/automl/src/main/java/com/google/cloud/translate/automl/DatasetApi.java
index 8616e0c1bae..39352aab793 100644
--- a/translate/automl/src/main/java/com/google/cloud/translate/automl/DatasetApi.java
+++ b/translate/automl/src/main/java/com/google/cloud/translate/automl/DatasetApi.java
@@ -26,11 +26,9 @@
import com.google.cloud.automl.v1beta1.LocationName;
import com.google.cloud.automl.v1beta1.TranslationDatasetMetadata;
import com.google.protobuf.Empty;
-
import java.io.IOException;
import java.io.PrintStream;
import java.util.concurrent.ExecutionException;
-
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
diff --git a/translate/automl/src/main/java/com/google/cloud/translate/automl/ModelApi.java b/translate/automl/src/main/java/com/google/cloud/translate/automl/ModelApi.java
index 805aa0ab5f7..e309432fc43 100644
--- a/translate/automl/src/main/java/com/google/cloud/translate/automl/ModelApi.java
+++ b/translate/automl/src/main/java/com/google/cloud/translate/automl/ModelApi.java
@@ -30,11 +30,9 @@
import com.google.cloud.automl.v1beta1.TranslationModelMetadata;
import com.google.longrunning.Operation;
import com.google.protobuf.Empty;
-
import java.io.IOException;
import java.io.PrintStream;
import java.util.concurrent.ExecutionException;
-
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
diff --git a/translate/automl/src/main/java/com/google/cloud/translate/automl/PredictionApi.java b/translate/automl/src/main/java/com/google/cloud/translate/automl/PredictionApi.java
index 98bbbc03b40..cb0df49eb0a 100644
--- a/translate/automl/src/main/java/com/google/cloud/translate/automl/PredictionApi.java
+++ b/translate/automl/src/main/java/com/google/cloud/translate/automl/PredictionApi.java
@@ -36,7 +36,6 @@
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
-
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
diff --git a/translate/automl/src/test/java/com/google/cloud/translate/automl/DatasetApiIT.java b/translate/automl/src/test/java/com/google/cloud/translate/automl/DatasetApiIT.java
index 2bb697faa02..16370a99244 100644
--- a/translate/automl/src/test/java/com/google/cloud/translate/automl/DatasetApiIT.java
+++ b/translate/automl/src/test/java/com/google/cloud/translate/automl/DatasetApiIT.java
@@ -23,7 +23,6 @@
import java.io.PrintStream;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/translate/automl/src/test/java/com/google/cloud/translate/automl/ModelApiIT.java b/translate/automl/src/test/java/com/google/cloud/translate/automl/ModelApiIT.java
index fff8a1a1561..82c185ef9eb 100644
--- a/translate/automl/src/test/java/com/google/cloud/translate/automl/ModelApiIT.java
+++ b/translate/automl/src/test/java/com/google/cloud/translate/automl/ModelApiIT.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/translate/automl/src/test/java/com/google/cloud/translate/automl/PredictionApiIT.java b/translate/automl/src/test/java/com/google/cloud/translate/automl/PredictionApiIT.java
index 78e47eb3e8e..950ccd2d963 100644
--- a/translate/automl/src/test/java/com/google/cloud/translate/automl/PredictionApiIT.java
+++ b/translate/automl/src/test/java/com/google/cloud/translate/automl/PredictionApiIT.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/translate/cloud-client/pom.xml b/translate/cloud-client/pom.xml
index 7f0728d2ff3..55d5276d393 100644
--- a/translate/cloud-client/pom.xml
+++ b/translate/cloud-client/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateText.java b/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateText.java
index 466c3cd7fa0..118cf6bff97 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateText.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateText.java
@@ -27,7 +27,6 @@
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.OutputConfig;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@@ -54,7 +53,7 @@ public static void batchTranslateText(
String targetLanguage,
String inputUri,
String outputUri)
- throws IOException, ExecutionException, InterruptedException, TimeoutException {
+ throws IOException, ExecutionException, InterruptedException, TimeoutException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
diff --git a/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateTextWithGlossary.java b/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateTextWithGlossary.java
index f622c5f6f05..a839d500ac4 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateTextWithGlossary.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateTextWithGlossary.java
@@ -29,7 +29,6 @@
import com.google.cloud.translate.v3.OutputConfig;
import com.google.cloud.translate.v3.TranslateTextGlossaryConfig;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
diff --git a/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateTextWithGlossaryAndModel.java b/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateTextWithGlossaryAndModel.java
index e1a52b819a4..92615eb1b4c 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateTextWithGlossaryAndModel.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateTextWithGlossaryAndModel.java
@@ -29,7 +29,6 @@
import com.google.cloud.translate.v3.OutputConfig;
import com.google.cloud.translate.v3.TranslateTextGlossaryConfig;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
diff --git a/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateTextWithModel.java b/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateTextWithModel.java
index dbc70058586..acce714753a 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateTextWithModel.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/BatchTranslateTextWithModel.java
@@ -27,7 +27,6 @@
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.OutputConfig;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@@ -57,7 +56,7 @@ public static void batchTranslateTextWithModel(
String inputUri,
String outputUri,
String modelId)
- throws IOException, ExecutionException, InterruptedException, TimeoutException {
+ throws IOException, ExecutionException, InterruptedException, TimeoutException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
diff --git a/translate/cloud-client/src/main/java/com/example/translate/CreateGlossary.java b/translate/cloud-client/src/main/java/com/example/translate/CreateGlossary.java
index a99f10def6f..ab9f7de4f0e 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/CreateGlossary.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/CreateGlossary.java
@@ -26,7 +26,6 @@
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
diff --git a/translate/cloud-client/src/main/java/com/example/translate/DeleteGlossary.java b/translate/cloud-client/src/main/java/com/example/translate/DeleteGlossary.java
index 73fe577a303..78266cdb5e1 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/DeleteGlossary.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/DeleteGlossary.java
@@ -23,7 +23,6 @@
import com.google.cloud.translate.v3.DeleteGlossaryResponse;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
import java.util.concurrent.ExecutionException;
diff --git a/translate/cloud-client/src/main/java/com/example/translate/DetectLanguage.java b/translate/cloud-client/src/main/java/com/example/translate/DetectLanguage.java
index 945dad8f07e..a1b4c5fb19f 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/DetectLanguage.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/DetectLanguage.java
@@ -22,7 +22,6 @@
import com.google.cloud.translate.v3.DetectedLanguage;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
public class DetectLanguage {
diff --git a/translate/cloud-client/src/main/java/com/example/translate/GetGlossary.java b/translate/cloud-client/src/main/java/com/example/translate/GetGlossary.java
index e400f503ae0..c3e8283bd13 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/GetGlossary.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/GetGlossary.java
@@ -21,7 +21,6 @@
import com.google.cloud.translate.v3.Glossary;
import com.google.cloud.translate.v3.GlossaryName;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
public class GetGlossary {
diff --git a/translate/cloud-client/src/main/java/com/example/translate/GetSupportedLanguages.java b/translate/cloud-client/src/main/java/com/example/translate/GetSupportedLanguages.java
index 32963c406bf..08eb5d46b65 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/GetSupportedLanguages.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/GetSupportedLanguages.java
@@ -22,7 +22,6 @@
import com.google.cloud.translate.v3.SupportedLanguage;
import com.google.cloud.translate.v3.SupportedLanguages;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
public class GetSupportedLanguages {
diff --git a/translate/cloud-client/src/main/java/com/example/translate/GetSupportedLanguagesForTarget.java b/translate/cloud-client/src/main/java/com/example/translate/GetSupportedLanguagesForTarget.java
index 1001ae7a551..d3de319ad5c 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/GetSupportedLanguagesForTarget.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/GetSupportedLanguagesForTarget.java
@@ -22,7 +22,6 @@
import com.google.cloud.translate.v3.SupportedLanguage;
import com.google.cloud.translate.v3.SupportedLanguages;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
public class GetSupportedLanguagesForTarget {
diff --git a/translate/cloud-client/src/main/java/com/example/translate/ListGlossaries.java b/translate/cloud-client/src/main/java/com/example/translate/ListGlossaries.java
index 055c2d14058..129d58ec7b7 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/ListGlossaries.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/ListGlossaries.java
@@ -21,7 +21,6 @@
import com.google.cloud.translate.v3.ListGlossariesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
public class ListGlossaries {
diff --git a/translate/cloud-client/src/main/java/com/example/translate/QuickstartSample.java b/translate/cloud-client/src/main/java/com/example/translate/QuickstartSample.java
index bf3aad063e1..d946c13aada 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/QuickstartSample.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/QuickstartSample.java
@@ -34,10 +34,7 @@ public static void main(String... args) throws Exception {
// Translates some text into Russian
Translation translation =
translate.translate(
- text,
- TranslateOption.sourceLanguage("en"),
- TranslateOption.targetLanguage("ru"));
-
+ text, TranslateOption.sourceLanguage("en"), TranslateOption.targetLanguage("ru"));
System.out.printf("Text: %s%n", text);
System.out.printf("Translation: %s%n", translation.getTranslatedText());
diff --git a/translate/cloud-client/src/main/java/com/example/translate/TranslateText.java b/translate/cloud-client/src/main/java/com/example/translate/TranslateText.java
index 94989428218..a36b54a65b5 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/TranslateText.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/TranslateText.java
@@ -22,7 +22,6 @@
import com.google.cloud.translate.v3.TranslateTextResponse;
import com.google.cloud.translate.v3.Translation;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
public class TranslateText {
diff --git a/translate/cloud-client/src/main/java/com/example/translate/TranslateTextWithGlossary.java b/translate/cloud-client/src/main/java/com/example/translate/TranslateTextWithGlossary.java
index 07e0c6c7e03..78c35aa66e7 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/TranslateTextWithGlossary.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/TranslateTextWithGlossary.java
@@ -24,7 +24,6 @@
import com.google.cloud.translate.v3.TranslateTextResponse;
import com.google.cloud.translate.v3.Translation;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
public class TranslateTextWithGlossary {
diff --git a/translate/cloud-client/src/main/java/com/example/translate/TranslateTextWithGlossaryAndModel.java b/translate/cloud-client/src/main/java/com/example/translate/TranslateTextWithGlossaryAndModel.java
index 473d3042eba..a383689deec 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/TranslateTextWithGlossaryAndModel.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/TranslateTextWithGlossaryAndModel.java
@@ -24,7 +24,6 @@
import com.google.cloud.translate.v3.TranslateTextResponse;
import com.google.cloud.translate.v3.Translation;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
public class TranslateTextWithGlossaryAndModel {
diff --git a/translate/cloud-client/src/main/java/com/example/translate/TranslateTextWithModel.java b/translate/cloud-client/src/main/java/com/example/translate/TranslateTextWithModel.java
index ace54514837..9d81c7979d9 100644
--- a/translate/cloud-client/src/main/java/com/example/translate/TranslateTextWithModel.java
+++ b/translate/cloud-client/src/main/java/com/example/translate/TranslateTextWithModel.java
@@ -22,7 +22,6 @@
import com.google.cloud.translate.v3.TranslateTextResponse;
import com.google.cloud.translate.v3.Translation;
import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.IOException;
public class TranslateTextWithModel {
diff --git a/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextTests.java b/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextTests.java
index ccd20972474..2b41f00d9ac 100644
--- a/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextTests.java
+++ b/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextTests.java
@@ -23,14 +23,12 @@
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -46,7 +44,7 @@ public class BatchTranslateTextTests {
private static final String INPUT_URI = "gs://cloud-samples-data/translation/text.txt";
private static final String PREFIX = "BATCH_TRANSLATION_OUTPUT/";
private static final String OUTPUT_URI =
- String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID());
+ String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID());
private ByteArrayOutputStream bout;
private PrintStream out;
@@ -105,8 +103,7 @@ public void tearDown() {
@Test
public void testBatchTranslateText()
throws InterruptedException, ExecutionException, IOException, TimeoutException {
- BatchTranslateText.batchTranslateText(
- PROJECT_ID, "en", "es", INPUT_URI, OUTPUT_URI);
+ BatchTranslateText.batchTranslateText(PROJECT_ID, "en", "es", INPUT_URI, OUTPUT_URI);
String got = bout.toString();
assertThat(got).contains("Total Characters: 13");
}
diff --git a/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryAndModelTests.java b/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryAndModelTests.java
index e8fe25709a2..b88419d9d5f 100644
--- a/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryAndModelTests.java
+++ b/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryAndModelTests.java
@@ -19,23 +19,10 @@
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.assertNotNull;
-import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
-import com.google.cloud.translate.v3.CreateGlossaryMetadata;
-import com.google.cloud.translate.v3.CreateGlossaryRequest;
-import com.google.cloud.translate.v3.DeleteGlossaryMetadata;
-import com.google.cloud.translate.v3.DeleteGlossaryRequest;
-import com.google.cloud.translate.v3.DeleteGlossaryResponse;
-import com.google.cloud.translate.v3.GcsSource;
-import com.google.cloud.translate.v3.Glossary;
-import com.google.cloud.translate.v3.GlossaryInputConfig;
-import com.google.cloud.translate.v3.GlossaryName;
-import com.google.cloud.translate.v3.LocationName;
-import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -44,7 +31,6 @@
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -66,7 +52,7 @@ public class BatchTranslateTextWithGlossaryAndModelTests {
"gs://cloud-samples-data/translation/glossary_ja.csv";
private static final String PREFIX = "BATCH_TRANSLATION_OUTPUT/";
private static final String OUTPUT_URI =
- String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID());
+ String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID());
private ByteArrayOutputStream bout;
private PrintStream out;
@@ -136,13 +122,7 @@ public void tearDown() throws InterruptedException, ExecutionException, IOExcept
public void testBatchTranslateTextWithGlossaryAndModel()
throws InterruptedException, ExecutionException, IOException, TimeoutException {
BatchTranslateTextWithGlossaryAndModel.batchTranslateTextWithGlossaryAndModel(
- PROJECT_ID,
- "en",
- "ja",
- INPUT_URI,
- OUTPUT_URI,
- GLOSSARY_ID,
- MODEL_ID);
+ PROJECT_ID, "en", "ja", INPUT_URI, OUTPUT_URI, GLOSSARY_ID, MODEL_ID);
String got = bout.toString();
assertThat(got).contains("Total Characters: 25");
}
diff --git a/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryTests.java b/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryTests.java
index ebd61202233..92258d8ee89 100644
--- a/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryTests.java
+++ b/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextWithGlossaryTests.java
@@ -19,23 +19,10 @@
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.assertNotNull;
-import com.google.api.gax.longrunning.OperationFuture;
import com.google.api.gax.paging.Page;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
-import com.google.cloud.translate.v3.CreateGlossaryMetadata;
-import com.google.cloud.translate.v3.CreateGlossaryRequest;
-import com.google.cloud.translate.v3.DeleteGlossaryMetadata;
-import com.google.cloud.translate.v3.DeleteGlossaryRequest;
-import com.google.cloud.translate.v3.DeleteGlossaryResponse;
-import com.google.cloud.translate.v3.GcsSource;
-import com.google.cloud.translate.v3.Glossary;
-import com.google.cloud.translate.v3.GlossaryInputConfig;
-import com.google.cloud.translate.v3.GlossaryName;
-import com.google.cloud.translate.v3.LocationName;
-import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -44,7 +31,6 @@
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -65,7 +51,7 @@ public class BatchTranslateTextWithGlossaryTests {
String.format("test_%s", UUID.randomUUID().toString().replace("-", "_").substring(0, 26));
private static final String PREFIX = "BATCH_TRANSLATION_OUTPUT/";
private static final String OUTPUT_URI =
- String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID());
+ String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID());
private ByteArrayOutputStream bout;
private PrintStream out;
@@ -136,12 +122,7 @@ public void tearDown() throws InterruptedException, ExecutionException, IOExcept
public void testBatchTranslateTextWithGlossary()
throws InterruptedException, ExecutionException, IOException, TimeoutException {
BatchTranslateTextWithGlossary.batchTranslateTextWithGlossary(
- PROJECT_ID,
- "en",
- "ja",
- INPUT_URI,
- OUTPUT_URI,
- GLOSSARY_ID);
+ PROJECT_ID, "en", "ja", INPUT_URI, OUTPUT_URI, GLOSSARY_ID);
String got = bout.toString();
assertThat(got).contains("Total Characters: 9");
}
diff --git a/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextWithModelTests.java b/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextWithModelTests.java
index f81a0faa307..db7ef195c18 100644
--- a/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextWithModelTests.java
+++ b/translate/cloud-client/src/test/java/com/example/translate/BatchTranslateTextWithModelTests.java
@@ -20,7 +20,6 @@
import static junit.framework.TestCase.assertNotNull;
import com.google.api.gax.paging.Page;
-
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
@@ -30,7 +29,6 @@
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -48,7 +46,7 @@ public class BatchTranslateTextWithModelTests {
private static final String MODEL_ID = "TRL2188848820815848149";
private static final String PREFIX = "BATCH_TRANSLATION_OUTPUT/";
private static final String OUTPUT_URI =
- String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID());
+ String.format("gs://%s/%s%s/", PROJECT_ID, PREFIX, UUID.randomUUID());
private ByteArrayOutputStream bout;
private PrintStream out;
@@ -108,12 +106,7 @@ public void tearDown() {
public void testBatchTranslateTextWithModel()
throws InterruptedException, ExecutionException, IOException, TimeoutException {
BatchTranslateTextWithModel.batchTranslateTextWithModel(
- PROJECT_ID,
- "en",
- "ja",
- INPUT_URI,
- OUTPUT_URI,
- MODEL_ID);
+ PROJECT_ID, "en", "ja", INPUT_URI, OUTPUT_URI, MODEL_ID);
String got = bout.toString();
assertThat(got).contains("Total Characters: 15");
}
diff --git a/translate/cloud-client/src/test/java/com/example/translate/CreateGlossaryTests.java b/translate/cloud-client/src/test/java/com/example/translate/CreateGlossaryTests.java
index b3ccb01395e..258dd37813f 100644
--- a/translate/cloud-client/src/test/java/com/example/translate/CreateGlossaryTests.java
+++ b/translate/cloud-client/src/test/java/com/example/translate/CreateGlossaryTests.java
@@ -26,7 +26,6 @@
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
diff --git a/translate/cloud-client/src/test/java/com/example/translate/DeleteGlossaryTests.java b/translate/cloud-client/src/test/java/com/example/translate/DeleteGlossaryTests.java
index 8fe5fd660c4..800a32361c0 100644
--- a/translate/cloud-client/src/test/java/com/example/translate/DeleteGlossaryTests.java
+++ b/translate/cloud-client/src/test/java/com/example/translate/DeleteGlossaryTests.java
@@ -26,7 +26,6 @@
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -81,8 +80,7 @@ public void tearDown() {
}
@Test
- public void testDeleteGlossary()
- throws InterruptedException, ExecutionException, IOException {
+ public void testDeleteGlossary() throws InterruptedException, ExecutionException, IOException {
DeleteGlossary.deleteGlossary(PROJECT_ID, GLOSSARY_ID);
String got = bout.toString();
assertThat(got).contains("us-central1");
diff --git a/translate/cloud-client/src/test/java/com/example/translate/GetGlossaryTests.java b/translate/cloud-client/src/test/java/com/example/translate/GetGlossaryTests.java
index d082c4fddb0..b8ce2cdb99a 100644
--- a/translate/cloud-client/src/test/java/com/example/translate/GetGlossaryTests.java
+++ b/translate/cloud-client/src/test/java/com/example/translate/GetGlossaryTests.java
@@ -19,19 +19,6 @@
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.assertNotNull;
-import com.google.api.gax.longrunning.OperationFuture;
-import com.google.cloud.translate.v3.CreateGlossaryMetadata;
-import com.google.cloud.translate.v3.CreateGlossaryRequest;
-import com.google.cloud.translate.v3.DeleteGlossaryMetadata;
-import com.google.cloud.translate.v3.DeleteGlossaryRequest;
-import com.google.cloud.translate.v3.DeleteGlossaryResponse;
-import com.google.cloud.translate.v3.GcsSource;
-import com.google.cloud.translate.v3.Glossary;
-import com.google.cloud.translate.v3.GlossaryInputConfig;
-import com.google.cloud.translate.v3.GlossaryName;
-import com.google.cloud.translate.v3.LocationName;
-import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -39,7 +26,6 @@
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
diff --git a/translate/cloud-client/src/test/java/com/example/translate/ListGlossariesTests.java b/translate/cloud-client/src/test/java/com/example/translate/ListGlossariesTests.java
index ee87cfdf67f..55776b32805 100644
--- a/translate/cloud-client/src/test/java/com/example/translate/ListGlossariesTests.java
+++ b/translate/cloud-client/src/test/java/com/example/translate/ListGlossariesTests.java
@@ -19,19 +19,6 @@
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.assertNotNull;
-import com.google.api.gax.longrunning.OperationFuture;
-import com.google.cloud.translate.v3.CreateGlossaryMetadata;
-import com.google.cloud.translate.v3.CreateGlossaryRequest;
-import com.google.cloud.translate.v3.DeleteGlossaryMetadata;
-import com.google.cloud.translate.v3.DeleteGlossaryRequest;
-import com.google.cloud.translate.v3.DeleteGlossaryResponse;
-import com.google.cloud.translate.v3.GcsSource;
-import com.google.cloud.translate.v3.Glossary;
-import com.google.cloud.translate.v3.GlossaryInputConfig;
-import com.google.cloud.translate.v3.GlossaryName;
-import com.google.cloud.translate.v3.LocationName;
-import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -39,7 +26,6 @@
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
diff --git a/translate/cloud-client/src/test/java/com/example/translate/QuickstartSampleIT.java b/translate/cloud-client/src/test/java/com/example/translate/QuickstartSampleIT.java
index 78480b78fc3..a9a5fb8a42c 100644
--- a/translate/cloud-client/src/test/java/com/example/translate/QuickstartSampleIT.java
+++ b/translate/cloud-client/src/test/java/com/example/translate/QuickstartSampleIT.java
@@ -26,9 +26,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Tests for quickstart sample.
- */
+/** Tests for quickstart sample. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class QuickstartSampleIT {
diff --git a/translate/cloud-client/src/test/java/com/example/translate/TranslateTextWithGlossaryAndModelTests.java b/translate/cloud-client/src/test/java/com/example/translate/TranslateTextWithGlossaryAndModelTests.java
index dc68fa0fa92..80d269fcffe 100644
--- a/translate/cloud-client/src/test/java/com/example/translate/TranslateTextWithGlossaryAndModelTests.java
+++ b/translate/cloud-client/src/test/java/com/example/translate/TranslateTextWithGlossaryAndModelTests.java
@@ -19,19 +19,6 @@
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.assertNotNull;
-import com.google.api.gax.longrunning.OperationFuture;
-import com.google.cloud.translate.v3.CreateGlossaryMetadata;
-import com.google.cloud.translate.v3.CreateGlossaryRequest;
-import com.google.cloud.translate.v3.DeleteGlossaryMetadata;
-import com.google.cloud.translate.v3.DeleteGlossaryRequest;
-import com.google.cloud.translate.v3.DeleteGlossaryResponse;
-import com.google.cloud.translate.v3.GcsSource;
-import com.google.cloud.translate.v3.Glossary;
-import com.google.cloud.translate.v3.GlossaryInputConfig;
-import com.google.cloud.translate.v3.GlossaryName;
-import com.google.cloud.translate.v3.LocationName;
-import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -39,7 +26,6 @@
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
diff --git a/translate/cloud-client/src/test/java/com/example/translate/TranslateTextWithGlossaryTests.java b/translate/cloud-client/src/test/java/com/example/translate/TranslateTextWithGlossaryTests.java
index ad7f560195b..3b2be95994e 100644
--- a/translate/cloud-client/src/test/java/com/example/translate/TranslateTextWithGlossaryTests.java
+++ b/translate/cloud-client/src/test/java/com/example/translate/TranslateTextWithGlossaryTests.java
@@ -19,19 +19,6 @@
import static com.google.common.truth.Truth.assertThat;
import static junit.framework.TestCase.assertNotNull;
-import com.google.api.gax.longrunning.OperationFuture;
-import com.google.cloud.translate.v3.CreateGlossaryMetadata;
-import com.google.cloud.translate.v3.CreateGlossaryRequest;
-import com.google.cloud.translate.v3.DeleteGlossaryMetadata;
-import com.google.cloud.translate.v3.DeleteGlossaryRequest;
-import com.google.cloud.translate.v3.DeleteGlossaryResponse;
-import com.google.cloud.translate.v3.GcsSource;
-import com.google.cloud.translate.v3.Glossary;
-import com.google.cloud.translate.v3.GlossaryInputConfig;
-import com.google.cloud.translate.v3.GlossaryName;
-import com.google.cloud.translate.v3.LocationName;
-import com.google.cloud.translate.v3.TranslationServiceClient;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
@@ -39,7 +26,6 @@
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
diff --git a/video/beta/pom.xml b/video/beta/pom.xml
index 79f9c5cd856..52520c489d5 100644
--- a/video/beta/pom.xml
+++ b/video/beta/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/video/beta/src/main/java/com/example/video/Detect.java b/video/beta/src/main/java/com/example/video/Detect.java
index 500c6405f43..110136f1162 100644
--- a/video/beta/src/main/java/com/example/video/Detect.java
+++ b/video/beta/src/main/java/com/example/video/Detect.java
@@ -33,8 +33,8 @@
public class Detect {
/**
- * Detects video transcription using the Video Intelligence
- * API
+ * Detects video transcription using the Video Intelligence API
+ *
* @param args specifies features to detect and the path to the video on Google Cloud Storage.
*/
public static void main(String[] args) {
@@ -48,8 +48,8 @@ public static void main(String[] args) {
/**
* Helper that handles the input passed to the program.
- * @param args specifies features to detect and the path to the video on Google Cloud Storage.
*
+ * @param args specifies features to detect and the path to the video on Google Cloud Storage.
* @throws IOException on Input/Output errors.
*/
public static void argsHelper(String[] args) throws Exception {
@@ -82,22 +82,22 @@ public static void speechTranscription(String gcsUri) throws Exception {
// Instantiate a com.google.cloud.videointelligence.v1p1beta1.VideoIntelligenceServiceClient
try (VideoIntelligenceServiceClient client = VideoIntelligenceServiceClient.create()) {
// Set the language code
- SpeechTranscriptionConfig config = SpeechTranscriptionConfig.newBuilder()
- .setLanguageCode("en-US")
- .setEnableAutomaticPunctuation(true)
- .build();
+ SpeechTranscriptionConfig config =
+ SpeechTranscriptionConfig.newBuilder()
+ .setLanguageCode("en-US")
+ .setEnableAutomaticPunctuation(true)
+ .build();
// Set the video context with the above configuration
- VideoContext context = VideoContext.newBuilder()
- .setSpeechTranscriptionConfig(config)
- .build();
+ VideoContext context = VideoContext.newBuilder().setSpeechTranscriptionConfig(config).build();
// Create the request
- AnnotateVideoRequest request = AnnotateVideoRequest.newBuilder()
- .setInputUri(gcsUri)
- .addFeatures(Feature.SPEECH_TRANSCRIPTION)
- .setVideoContext(context)
- .build();
+ AnnotateVideoRequest request =
+ AnnotateVideoRequest.newBuilder()
+ .setInputUri(gcsUri)
+ .addFeatures(Feature.SPEECH_TRANSCRIPTION)
+ .setVideoContext(context)
+ .build();
// asynchronously perform speech transcription on videos
OperationFuture response =
@@ -105,8 +105,8 @@ public static void speechTranscription(String gcsUri) throws Exception {
System.out.println("Waiting for operation to complete...");
// Display the results
- for (VideoAnnotationResults results : response.get(300, TimeUnit.SECONDS)
- .getAnnotationResultsList()) {
+ for (VideoAnnotationResults results :
+ response.get(300, TimeUnit.SECONDS).getAnnotationResultsList()) {
for (SpeechTranscription speechTranscription : results.getSpeechTranscriptionsList()) {
try {
// Print the transcription
@@ -118,12 +118,12 @@ public static void speechTranscription(String gcsUri) throws Exception {
System.out.println("Word level information:");
for (WordInfo wordInfo : alternative.getWordsList()) {
- double startTime = wordInfo.getStartTime().getSeconds()
- + wordInfo.getStartTime().getNanos() / 1e9;
- double endTime = wordInfo.getEndTime().getSeconds()
- + wordInfo.getEndTime().getNanos() / 1e9;
- System.out.printf("\t%4.2fs - %4.2fs: %s\n",
- startTime, endTime, wordInfo.getWord());
+ double startTime =
+ wordInfo.getStartTime().getSeconds() + wordInfo.getStartTime().getNanos() / 1e9;
+ double endTime =
+ wordInfo.getEndTime().getSeconds() + wordInfo.getEndTime().getNanos() / 1e9;
+ System.out.printf(
+ "\t%4.2fs - %4.2fs: %s\n", startTime, endTime, wordInfo.getWord());
}
} else {
System.out.println("No transcription found");
diff --git a/video/beta/src/main/java/com/example/video/DetectFaces.java b/video/beta/src/main/java/com/example/video/DetectFaces.java
index 92e53b0f3ab..e9d84aa34cf 100644
--- a/video/beta/src/main/java/com/example/video/DetectFaces.java
+++ b/video/beta/src/main/java/com/example/video/DetectFaces.java
@@ -33,12 +33,9 @@
import com.google.cloud.videointelligence.v1p3beta1.VideoIntelligenceServiceClient;
import com.google.cloud.videointelligence.v1p3beta1.VideoSegment;
import com.google.protobuf.ByteString;
-
-import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.concurrent.ExecutionException;
public class DetectFaces {
@@ -51,31 +48,31 @@ public static void detectFaces() throws Exception {
// Detects faces in a video stored in a local file using the Cloud Video Intelligence API.
public static void detectFaces(String localFilePath) throws Exception {
try (VideoIntelligenceServiceClient videoIntelligenceServiceClient =
- VideoIntelligenceServiceClient.create()) {
+ VideoIntelligenceServiceClient.create()) {
// Reads a local video file and converts it to base64.
Path path = Paths.get(localFilePath);
byte[] data = Files.readAllBytes(path);
ByteString inputContent = ByteString.copyFrom(data);
FaceDetectionConfig faceDetectionConfig =
- FaceDetectionConfig.newBuilder()
- // Must set includeBoundingBoxes to true to get facial attributes.
- .setIncludeBoundingBoxes(true)
- .setIncludeAttributes(true)
- .build();
+ FaceDetectionConfig.newBuilder()
+ // Must set includeBoundingBoxes to true to get facial attributes.
+ .setIncludeBoundingBoxes(true)
+ .setIncludeAttributes(true)
+ .build();
VideoContext videoContext =
- VideoContext.newBuilder().setFaceDetectionConfig(faceDetectionConfig).build();
+ VideoContext.newBuilder().setFaceDetectionConfig(faceDetectionConfig).build();
AnnotateVideoRequest request =
- AnnotateVideoRequest.newBuilder()
- .setInputContent(inputContent)
- .addFeatures(Feature.FACE_DETECTION)
- .setVideoContext(videoContext)
- .build();
+ AnnotateVideoRequest.newBuilder()
+ .setInputContent(inputContent)
+ .addFeatures(Feature.FACE_DETECTION)
+ .setVideoContext(videoContext)
+ .build();
// Detects faces in a video
OperationFuture future =
- videoIntelligenceServiceClient.annotateVideoAsync(request);
+ videoIntelligenceServiceClient.annotateVideoAsync(request);
System.out.println("Waiting for operation to complete...");
AnnotateVideoResponse response = future.get();
@@ -85,18 +82,17 @@ public static void detectFaces(String localFilePath) throws Exception {
// Annotations for list of faces detected, tracked and recognized in video.
for (FaceDetectionAnnotation faceDetectionAnnotation :
- annotationResult.getFaceDetectionAnnotationsList()) {
+ annotationResult.getFaceDetectionAnnotationsList()) {
System.out.print("Face detected:\n");
for (Track track : faceDetectionAnnotation.getTracksList()) {
VideoSegment segment = track.getSegment();
System.out.printf(
- "\tStart: %d.%.0fs\n",
- segment.getStartTimeOffset().getSeconds(),
- segment.getStartTimeOffset().getNanos() / 1e6);
+ "\tStart: %d.%.0fs\n",
+ segment.getStartTimeOffset().getSeconds(),
+ segment.getStartTimeOffset().getNanos() / 1e6);
System.out.printf(
- "\tEnd: %d.%.0fs\n",
- segment.getEndTimeOffset().getSeconds(),
- segment.getEndTimeOffset().getNanos() / 1e6);
+ "\tEnd: %d.%.0fs\n",
+ segment.getEndTimeOffset().getSeconds(), segment.getEndTimeOffset().getNanos() / 1e6);
// Each segment includes timestamped objects that
// include characteristics of the face detected.
@@ -111,4 +107,4 @@ public static void detectFaces(String localFilePath) throws Exception {
}
}
}
-// [END video_detect_faces_beta]
\ No newline at end of file
+// [END video_detect_faces_beta]
diff --git a/video/beta/src/main/java/com/example/video/DetectFacesGcs.java b/video/beta/src/main/java/com/example/video/DetectFacesGcs.java
index 6caedba75ac..335cd0e5195 100644
--- a/video/beta/src/main/java/com/example/video/DetectFacesGcs.java
+++ b/video/beta/src/main/java/com/example/video/DetectFacesGcs.java
@@ -44,27 +44,27 @@ public static void detectFacesGcs() throws Exception {
// Detects faces in a video stored in Google Cloud Storage using the Cloud Video Intelligence API.
public static void detectFacesGcs(String gcsUri) throws Exception {
try (VideoIntelligenceServiceClient videoIntelligenceServiceClient =
- VideoIntelligenceServiceClient.create()) {
+ VideoIntelligenceServiceClient.create()) {
FaceDetectionConfig faceDetectionConfig =
- FaceDetectionConfig.newBuilder()
- // Must set includeBoundingBoxes to true to get facial attributes.
- .setIncludeBoundingBoxes(true)
- .setIncludeAttributes(true)
- .build();
+ FaceDetectionConfig.newBuilder()
+ // Must set includeBoundingBoxes to true to get facial attributes.
+ .setIncludeBoundingBoxes(true)
+ .setIncludeAttributes(true)
+ .build();
VideoContext videoContext =
- VideoContext.newBuilder().setFaceDetectionConfig(faceDetectionConfig).build();
+ VideoContext.newBuilder().setFaceDetectionConfig(faceDetectionConfig).build();
AnnotateVideoRequest request =
- AnnotateVideoRequest.newBuilder()
- .setInputUri(gcsUri)
- .addFeatures(Feature.FACE_DETECTION)
- .setVideoContext(videoContext)
- .build();
+ AnnotateVideoRequest.newBuilder()
+ .setInputUri(gcsUri)
+ .addFeatures(Feature.FACE_DETECTION)
+ .setVideoContext(videoContext)
+ .build();
// Detects faces in a video
OperationFuture future =
- videoIntelligenceServiceClient.annotateVideoAsync(request);
+ videoIntelligenceServiceClient.annotateVideoAsync(request);
System.out.println("Waiting for operation to complete...");
AnnotateVideoResponse response = future.get();
@@ -74,18 +74,17 @@ public static void detectFacesGcs(String gcsUri) throws Exception {
// Annotations for list of people detected, tracked and recognized in video.
for (FaceDetectionAnnotation faceDetectionAnnotation :
- annotationResult.getFaceDetectionAnnotationsList()) {
+ annotationResult.getFaceDetectionAnnotationsList()) {
System.out.print("Face detected:\n");
for (Track track : faceDetectionAnnotation.getTracksList()) {
VideoSegment segment = track.getSegment();
System.out.printf(
- "\tStart: %d.%.0fs\n",
- segment.getStartTimeOffset().getSeconds(),
- segment.getStartTimeOffset().getNanos() / 1e6);
+ "\tStart: %d.%.0fs\n",
+ segment.getStartTimeOffset().getSeconds(),
+ segment.getStartTimeOffset().getNanos() / 1e6);
System.out.printf(
- "\tEnd: %d.%.0fs\n",
- segment.getEndTimeOffset().getSeconds(),
- segment.getEndTimeOffset().getNanos() / 1e6);
+ "\tEnd: %d.%.0fs\n",
+ segment.getEndTimeOffset().getSeconds(), segment.getEndTimeOffset().getNanos() / 1e6);
// Each segment includes timestamped objects that
// include characteristics of the face detected.
diff --git a/video/beta/src/main/java/com/example/video/DetectLogo.java b/video/beta/src/main/java/com/example/video/DetectLogo.java
index d448e4a0c81..458fd7aae02 100644
--- a/video/beta/src/main/java/com/example/video/DetectLogo.java
+++ b/video/beta/src/main/java/com/example/video/DetectLogo.java
@@ -31,12 +31,10 @@
import com.google.cloud.videointelligence.v1p3beta1.VideoSegment;
import com.google.protobuf.ByteString;
import com.google.protobuf.Duration;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
-
import java.util.concurrent.ExecutionException;
public class DetectLogo {
diff --git a/video/beta/src/main/java/com/example/video/DetectLogoGcs.java b/video/beta/src/main/java/com/example/video/DetectLogoGcs.java
index 4a1d8191272..18410d636de 100644
--- a/video/beta/src/main/java/com/example/video/DetectLogoGcs.java
+++ b/video/beta/src/main/java/com/example/video/DetectLogoGcs.java
@@ -30,9 +30,7 @@
import com.google.cloud.videointelligence.v1p3beta1.VideoIntelligenceServiceClient;
import com.google.cloud.videointelligence.v1p3beta1.VideoSegment;
import com.google.protobuf.Duration;
-
import java.io.IOException;
-
import java.util.concurrent.ExecutionException;
public class DetectLogoGcs {
diff --git a/video/beta/src/main/java/com/example/video/DetectPerson.java b/video/beta/src/main/java/com/example/video/DetectPerson.java
index c35eabc802e..a7ff3d2c940 100644
--- a/video/beta/src/main/java/com/example/video/DetectPerson.java
+++ b/video/beta/src/main/java/com/example/video/DetectPerson.java
@@ -34,7 +34,6 @@
import com.google.cloud.videointelligence.v1p3beta1.VideoIntelligenceServiceClient;
import com.google.cloud.videointelligence.v1p3beta1.VideoSegment;
import com.google.protobuf.ByteString;
-
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -47,37 +46,36 @@ public static void detectPerson() throws Exception {
detectPerson(localFilePath);
}
-
// Detects people in a video stored in a local file using the Cloud Video Intelligence API.
public static void detectPerson(String localFilePath) throws Exception {
try (VideoIntelligenceServiceClient videoIntelligenceServiceClient =
- VideoIntelligenceServiceClient.create()) {
+ VideoIntelligenceServiceClient.create()) {
// Reads a local video file and converts it to base64.
Path path = Paths.get(localFilePath);
byte[] data = Files.readAllBytes(path);
ByteString inputContent = ByteString.copyFrom(data);
PersonDetectionConfig personDetectionConfig =
- PersonDetectionConfig.newBuilder()
- // Must set includeBoundingBoxes to true to get poses and attributes.
- .setIncludeBoundingBoxes(true)
- .setIncludePoseLandmarks(true)
- .setIncludeAttributes(true)
- .build();
+ PersonDetectionConfig.newBuilder()
+ // Must set includeBoundingBoxes to true to get poses and attributes.
+ .setIncludeBoundingBoxes(true)
+ .setIncludePoseLandmarks(true)
+ .setIncludeAttributes(true)
+ .build();
VideoContext videoContext =
- VideoContext.newBuilder().setPersonDetectionConfig(personDetectionConfig).build();
+ VideoContext.newBuilder().setPersonDetectionConfig(personDetectionConfig).build();
AnnotateVideoRequest request =
- AnnotateVideoRequest.newBuilder()
- .setInputContent(inputContent)
- .addFeatures(Feature.PERSON_DETECTION)
- .setVideoContext(videoContext)
- .build();
+ AnnotateVideoRequest.newBuilder()
+ .setInputContent(inputContent)
+ .addFeatures(Feature.PERSON_DETECTION)
+ .setVideoContext(videoContext)
+ .build();
// Detects people in a video
// We get the first result because only one video is processed.
OperationFuture future =
- videoIntelligenceServiceClient.annotateVideoAsync(request);
+ videoIntelligenceServiceClient.annotateVideoAsync(request);
System.out.println("Waiting for operation to complete...");
AnnotateVideoResponse response = future.get();
@@ -87,18 +85,17 @@ public static void detectPerson(String localFilePath) throws Exception {
// Annotations for list of people detected, tracked and recognized in video.
for (PersonDetectionAnnotation personDetectionAnnotation :
- annotationResult.getPersonDetectionAnnotationsList()) {
+ annotationResult.getPersonDetectionAnnotationsList()) {
System.out.print("Person detected:\n");
for (Track track : personDetectionAnnotation.getTracksList()) {
VideoSegment segment = track.getSegment();
System.out.printf(
- "\tStart: %d.%.0fs\n",
- segment.getStartTimeOffset().getSeconds(),
- segment.getStartTimeOffset().getNanos() / 1e6);
+ "\tStart: %d.%.0fs\n",
+ segment.getStartTimeOffset().getSeconds(),
+ segment.getStartTimeOffset().getNanos() / 1e6);
System.out.printf(
- "\tEnd: %d.%.0fs\n",
- segment.getEndTimeOffset().getSeconds(),
- segment.getEndTimeOffset().getNanos() / 1e6);
+ "\tEnd: %d.%.0fs\n",
+ segment.getEndTimeOffset().getSeconds(), segment.getEndTimeOffset().getNanos() / 1e6);
// Each segment includes timestamped objects that include characteristic--e.g. clothes,
// posture of the person detected.
@@ -107,18 +104,18 @@ public static void detectPerson(String localFilePath) throws Exception {
// Attributes include unique pieces of clothing, poses, or hair color.
for (DetectedAttribute attribute : firstTimestampedObject.getAttributesList()) {
System.out.printf(
- "\tAttribute: %s; Value: %s\n", attribute.getName(), attribute.getValue());
+ "\tAttribute: %s; Value: %s\n", attribute.getName(), attribute.getValue());
}
// Landmarks in person detection include body parts.
for (DetectedLandmark attribute : firstTimestampedObject.getLandmarksList()) {
System.out.printf(
- "\tLandmark: %s; Vertex: %f, %f\n",
- attribute.getName(), attribute.getPoint().getX(), attribute.getPoint().getY());
+ "\tLandmark: %s; Vertex: %f, %f\n",
+ attribute.getName(), attribute.getPoint().getX(), attribute.getPoint().getY());
}
}
}
}
}
}
-// [END video_detect_person_beta]
\ No newline at end of file
+// [END video_detect_person_beta]
diff --git a/video/beta/src/main/java/com/example/video/DetectPersonGcs.java b/video/beta/src/main/java/com/example/video/DetectPersonGcs.java
index 63e17c3dd6a..34122291d8b 100644
--- a/video/beta/src/main/java/com/example/video/DetectPersonGcs.java
+++ b/video/beta/src/main/java/com/example/video/DetectPersonGcs.java
@@ -46,29 +46,29 @@ public static void detectPersonGcs() throws Exception {
// the Cloud Video Intelligence API.
public static void detectPersonGcs(String gcsUri) throws Exception {
try (VideoIntelligenceServiceClient videoIntelligenceServiceClient =
- VideoIntelligenceServiceClient.create()) {
+ VideoIntelligenceServiceClient.create()) {
// Reads a local video file and converts it to base64.
PersonDetectionConfig personDetectionConfig =
- PersonDetectionConfig.newBuilder()
- // Must set includeBoundingBoxes to true to get poses and attributes.
- .setIncludeBoundingBoxes(true)
- .setIncludePoseLandmarks(true)
- .setIncludeAttributes(true)
- .build();
+ PersonDetectionConfig.newBuilder()
+ // Must set includeBoundingBoxes to true to get poses and attributes.
+ .setIncludeBoundingBoxes(true)
+ .setIncludePoseLandmarks(true)
+ .setIncludeAttributes(true)
+ .build();
VideoContext videoContext =
- VideoContext.newBuilder().setPersonDetectionConfig(personDetectionConfig).build();
+ VideoContext.newBuilder().setPersonDetectionConfig(personDetectionConfig).build();
AnnotateVideoRequest request =
- AnnotateVideoRequest.newBuilder()
- .setInputUri(gcsUri)
- .addFeatures(Feature.PERSON_DETECTION)
- .setVideoContext(videoContext)
- .build();
+ AnnotateVideoRequest.newBuilder()
+ .setInputUri(gcsUri)
+ .addFeatures(Feature.PERSON_DETECTION)
+ .setVideoContext(videoContext)
+ .build();
// Detects people in a video
OperationFuture future =
- videoIntelligenceServiceClient.annotateVideoAsync(request);
+ videoIntelligenceServiceClient.annotateVideoAsync(request);
System.out.println("Waiting for operation to complete...");
AnnotateVideoResponse response = future.get();
@@ -77,18 +77,17 @@ public static void detectPersonGcs(String gcsUri) throws Exception {
// Annotations for list of people detected, tracked and recognized in video.
for (PersonDetectionAnnotation personDetectionAnnotation :
- annotationResult.getPersonDetectionAnnotationsList()) {
+ annotationResult.getPersonDetectionAnnotationsList()) {
System.out.print("Person detected:\n");
for (Track track : personDetectionAnnotation.getTracksList()) {
VideoSegment segment = track.getSegment();
System.out.printf(
- "\tStart: %d.%.0fs\n",
- segment.getStartTimeOffset().getSeconds(),
- segment.getStartTimeOffset().getNanos() / 1e6);
+ "\tStart: %d.%.0fs\n",
+ segment.getStartTimeOffset().getSeconds(),
+ segment.getStartTimeOffset().getNanos() / 1e6);
System.out.printf(
- "\tEnd: %d.%.0fs\n",
- segment.getEndTimeOffset().getSeconds(),
- segment.getEndTimeOffset().getNanos() / 1e6);
+ "\tEnd: %d.%.0fs\n",
+ segment.getEndTimeOffset().getSeconds(), segment.getEndTimeOffset().getNanos() / 1e6);
// Each segment includes timestamped objects that include characteristic--e.g. clothes,
// posture of the person detected.
@@ -97,14 +96,14 @@ public static void detectPersonGcs(String gcsUri) throws Exception {
// Attributes include unique pieces of clothing, poses, or hair color.
for (DetectedAttribute attribute : firstTimestampedObject.getAttributesList()) {
System.out.printf(
- "\tAttribute: %s; Value: %s\n", attribute.getName(), attribute.getValue());
+ "\tAttribute: %s; Value: %s\n", attribute.getName(), attribute.getValue());
}
// Landmarks in person detection include body parts.
for (DetectedLandmark attribute : firstTimestampedObject.getLandmarksList()) {
System.out.printf(
- "\tLandmark: %s; Vertex: %f, %f\n",
- attribute.getName(), attribute.getPoint().getX(), attribute.getPoint().getY());
+ "\tLandmark: %s; Vertex: %f, %f\n",
+ attribute.getName(), attribute.getPoint().getX(), attribute.getPoint().getY());
}
}
}
diff --git a/video/beta/src/main/java/com/example/video/StreamingAnnotationToStorage.java b/video/beta/src/main/java/com/example/video/StreamingAnnotationToStorage.java
index 5598717e3af..16eba34b0f0 100644
--- a/video/beta/src/main/java/com/example/video/StreamingAnnotationToStorage.java
+++ b/video/beta/src/main/java/com/example/video/StreamingAnnotationToStorage.java
@@ -48,37 +48,37 @@ static void streamingAnnotationToStorage(String filePath, String gcsUri) {
int chunkSize = 5 * 1024 * 1024;
int numChunks = (int) Math.ceil((double) data.length / chunkSize);
- StreamingStorageConfig streamingStorageConfig = StreamingStorageConfig.newBuilder()
- .setEnableStorageAnnotationResult(true)
- .setAnnotationResultStorageDirectory(gcsUri)
- .build();
+ StreamingStorageConfig streamingStorageConfig =
+ StreamingStorageConfig.newBuilder()
+ .setEnableStorageAnnotationResult(true)
+ .setAnnotationResultStorageDirectory(gcsUri)
+ .build();
- StreamingLabelDetectionConfig labelConfig = StreamingLabelDetectionConfig.newBuilder()
- .setStationaryCamera(false)
- .build();
+ StreamingLabelDetectionConfig labelConfig =
+ StreamingLabelDetectionConfig.newBuilder().setStationaryCamera(false).build();
- StreamingVideoConfig streamingVideoConfig = StreamingVideoConfig.newBuilder()
- .setFeature(StreamingFeature.STREAMING_LABEL_DETECTION)
- .setLabelDetectionConfig(labelConfig)
- .setStorageConfig(streamingStorageConfig)
- .build();
+ StreamingVideoConfig streamingVideoConfig =
+ StreamingVideoConfig.newBuilder()
+ .setFeature(StreamingFeature.STREAMING_LABEL_DETECTION)
+ .setLabelDetectionConfig(labelConfig)
+ .setStorageConfig(streamingStorageConfig)
+ .build();
BidiStream call =
client.streamingAnnotateVideoCallable().call();
// The first request must **only** contain the audio configuration:
call.send(
- StreamingAnnotateVideoRequest.newBuilder()
- .setVideoConfig(streamingVideoConfig)
- .build());
+ StreamingAnnotateVideoRequest.newBuilder().setVideoConfig(streamingVideoConfig).build());
// Subsequent requests must **only** contain the audio data.
// Send the requests in chunks
for (int i = 0; i < numChunks; i++) {
call.send(
StreamingAnnotateVideoRequest.newBuilder()
- .setInputContent(ByteString.copyFrom(
- Arrays.copyOfRange(data, i * chunkSize, i * chunkSize + chunkSize)))
+ .setInputContent(
+ ByteString.copyFrom(
+ Arrays.copyOfRange(data, i * chunkSize, i * chunkSize + chunkSize)))
.build());
}
@@ -93,4 +93,4 @@ static void streamingAnnotationToStorage(String filePath, String gcsUri) {
}
}
}
-// [END video_streaming_annotation_to_storage_beta]
\ No newline at end of file
+// [END video_streaming_annotation_to_storage_beta]
diff --git a/video/beta/src/main/java/com/example/video/StreamingAutoMlClassification.java b/video/beta/src/main/java/com/example/video/StreamingAutoMlClassification.java
index b84672b77a3..1ba3ed7fad3 100644
--- a/video/beta/src/main/java/com/example/video/StreamingAutoMlClassification.java
+++ b/video/beta/src/main/java/com/example/video/StreamingAutoMlClassification.java
@@ -28,7 +28,6 @@
import com.google.cloud.videointelligence.v1p3beta1.StreamingVideoConfig;
import com.google.cloud.videointelligence.v1p3beta1.StreamingVideoIntelligenceServiceClient;
import com.google.protobuf.ByteString;
-
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -43,7 +42,7 @@ static void streamingAutoMlClassification(String filePath, String projectId, Str
// String modelId = "YOUR_AUTO_ML_CLASSIFICATION_MODEL_ID";
try (StreamingVideoIntelligenceServiceClient client =
- StreamingVideoIntelligenceServiceClient.create()) {
+ StreamingVideoIntelligenceServiceClient.create()) {
Path path = Paths.get(filePath);
byte[] data = Files.readAllBytes(path);
@@ -51,39 +50,36 @@ static void streamingAutoMlClassification(String filePath, String projectId, Str
int chunkSize = 5 * 1024 * 1024;
int numChunks = (int) Math.ceil((double) data.length / chunkSize);
- String modelPath = String.format("projects/%s/locations/us-central1/models/%s",
- projectId,
- modelId);
+ String modelPath =
+ String.format("projects/%s/locations/us-central1/models/%s", projectId, modelId);
System.out.println(modelPath);
StreamingAutomlClassificationConfig streamingAutomlClassificationConfig =
- StreamingAutomlClassificationConfig.newBuilder()
- .setModelName(modelPath)
- .build();
+ StreamingAutomlClassificationConfig.newBuilder().setModelName(modelPath).build();
- StreamingVideoConfig streamingVideoConfig = StreamingVideoConfig.newBuilder()
+ StreamingVideoConfig streamingVideoConfig =
+ StreamingVideoConfig.newBuilder()
.setFeature(StreamingFeature.STREAMING_AUTOML_CLASSIFICATION)
.setAutomlClassificationConfig(streamingAutomlClassificationConfig)
.build();
BidiStream call =
- client.streamingAnnotateVideoCallable().call();
+ client.streamingAnnotateVideoCallable().call();
// The first request must **only** contain the audio configuration:
call.send(
- StreamingAnnotateVideoRequest.newBuilder()
- .setVideoConfig(streamingVideoConfig)
- .build());
+ StreamingAnnotateVideoRequest.newBuilder().setVideoConfig(streamingVideoConfig).build());
// Subsequent requests must **only** contain the audio data.
// Send the requests in chunks
for (int i = 0; i < numChunks; i++) {
call.send(
- StreamingAnnotateVideoRequest.newBuilder()
- .setInputContent(ByteString.copyFrom(
- Arrays.copyOfRange(data, i * chunkSize, i * chunkSize + chunkSize)))
- .build());
+ StreamingAnnotateVideoRequest.newBuilder()
+ .setInputContent(
+ ByteString.copyFrom(
+ Arrays.copyOfRange(data, i * chunkSize, i * chunkSize + chunkSize)))
+ .build());
}
// Tell the service you are done sending data
@@ -102,8 +98,8 @@ static void streamingAutoMlClassification(String filePath, String projectId, Str
// There is only one frame per annotation
LabelFrame labelFrame = annotation.getFrames(0);
- double offset = labelFrame.getTimeOffset().getSeconds()
- + labelFrame.getTimeOffset().getNanos() / 1e9;
+ double offset =
+ labelFrame.getTimeOffset().getSeconds() + labelFrame.getTimeOffset().getNanos() / 1e9;
float confidence = labelFrame.getConfidence();
System.out.format("%fs: %s (%f)\n", offset, entity, confidence);
diff --git a/video/beta/src/main/java/com/example/video/StreamingExplicitContentDetection.java b/video/beta/src/main/java/com/example/video/StreamingExplicitContentDetection.java
index 5227bf1292b..5d4d9860f5a 100644
--- a/video/beta/src/main/java/com/example/video/StreamingExplicitContentDetection.java
+++ b/video/beta/src/main/java/com/example/video/StreamingExplicitContentDetection.java
@@ -48,31 +48,30 @@ static void streamingExplicitContentDetection(String filePath) {
int chunkSize = 5 * 1024 * 1024;
int numChunks = (int) Math.ceil((double) data.length / chunkSize);
- StreamingLabelDetectionConfig labelConfig = StreamingLabelDetectionConfig.newBuilder()
- .setStationaryCamera(false)
- .build();
+ StreamingLabelDetectionConfig labelConfig =
+ StreamingLabelDetectionConfig.newBuilder().setStationaryCamera(false).build();
- StreamingVideoConfig streamingVideoConfig = StreamingVideoConfig.newBuilder()
- .setFeature(StreamingFeature.STREAMING_EXPLICIT_CONTENT_DETECTION)
- .setLabelDetectionConfig(labelConfig)
- .build();
+ StreamingVideoConfig streamingVideoConfig =
+ StreamingVideoConfig.newBuilder()
+ .setFeature(StreamingFeature.STREAMING_EXPLICIT_CONTENT_DETECTION)
+ .setLabelDetectionConfig(labelConfig)
+ .build();
BidiStream call =
client.streamingAnnotateVideoCallable().call();
// The first request must **only** contain the audio configuration:
call.send(
- StreamingAnnotateVideoRequest.newBuilder()
- .setVideoConfig(streamingVideoConfig)
- .build());
+ StreamingAnnotateVideoRequest.newBuilder().setVideoConfig(streamingVideoConfig).build());
// Subsequent requests must **only** contain the audio data.
// Send the requests in chunks
for (int i = 0; i < numChunks; i++) {
call.send(
StreamingAnnotateVideoRequest.newBuilder()
- .setInputContent(ByteString.copyFrom(
- Arrays.copyOfRange(data, i * chunkSize, i * chunkSize + chunkSize)))
+ .setInputContent(
+ ByteString.copyFrom(
+ Arrays.copyOfRange(data, i * chunkSize, i * chunkSize + chunkSize)))
.build());
}
@@ -85,8 +84,8 @@ static void streamingExplicitContentDetection(String filePath) {
for (ExplicitContentFrame frame :
annotationResults.getExplicitAnnotation().getFramesList()) {
- double offset = frame.getTimeOffset().getSeconds()
- + frame.getTimeOffset().getNanos() / 1e9;
+ double offset =
+ frame.getTimeOffset().getSeconds() + frame.getTimeOffset().getNanos() / 1e9;
System.out.format("Offset: %f\n", offset);
System.out.format("\tPornography: %s", frame.getPornographyLikelihood());
diff --git a/video/beta/src/main/java/com/example/video/StreamingLabelDetection.java b/video/beta/src/main/java/com/example/video/StreamingLabelDetection.java
index 99afce5c5e9..6be8790e316 100644
--- a/video/beta/src/main/java/com/example/video/StreamingLabelDetection.java
+++ b/video/beta/src/main/java/com/example/video/StreamingLabelDetection.java
@@ -49,31 +49,30 @@ static void streamingLabelDetection(String filePath) {
int chunkSize = 5 * 1024 * 1024;
int numChunks = (int) Math.ceil((double) data.length / chunkSize);
- StreamingLabelDetectionConfig labelConfig = StreamingLabelDetectionConfig.newBuilder()
- .setStationaryCamera(false)
- .build();
+ StreamingLabelDetectionConfig labelConfig =
+ StreamingLabelDetectionConfig.newBuilder().setStationaryCamera(false).build();
- StreamingVideoConfig streamingVideoConfig = StreamingVideoConfig.newBuilder()
- .setFeature(StreamingFeature.STREAMING_LABEL_DETECTION)
- .setLabelDetectionConfig(labelConfig)
- .build();
+ StreamingVideoConfig streamingVideoConfig =
+ StreamingVideoConfig.newBuilder()
+ .setFeature(StreamingFeature.STREAMING_LABEL_DETECTION)
+ .setLabelDetectionConfig(labelConfig)
+ .build();
BidiStream call =
client.streamingAnnotateVideoCallable().call();
// The first request must **only** contain the audio configuration:
call.send(
- StreamingAnnotateVideoRequest.newBuilder()
- .setVideoConfig(streamingVideoConfig)
- .build());
+ StreamingAnnotateVideoRequest.newBuilder().setVideoConfig(streamingVideoConfig).build());
// Subsequent requests must **only** contain the audio data.
// Send the requests in chunks
for (int i = 0; i < numChunks; i++) {
call.send(
StreamingAnnotateVideoRequest.newBuilder()
- .setInputContent(ByteString.copyFrom(
- Arrays.copyOfRange(data, i * chunkSize, i * chunkSize + chunkSize)))
+ .setInputContent(
+ ByteString.copyFrom(
+ Arrays.copyOfRange(data, i * chunkSize, i * chunkSize + chunkSize)))
.build());
}
@@ -88,8 +87,8 @@ static void streamingLabelDetection(String filePath) {
// There is only one frame per annotation
LabelFrame labelFrame = annotation.getFrames(0);
- double offset = labelFrame.getTimeOffset().getSeconds()
- + labelFrame.getTimeOffset().getNanos() / 1e9;
+ double offset =
+ labelFrame.getTimeOffset().getSeconds() + labelFrame.getTimeOffset().getNanos() / 1e9;
float confidence = labelFrame.getConfidence();
System.out.format("%fs: %s (%f)\n", offset, entity, confidence);
@@ -100,4 +99,4 @@ static void streamingLabelDetection(String filePath) {
}
}
}
-// [END video_streaming_label_detection_beta]
\ No newline at end of file
+// [END video_streaming_label_detection_beta]
diff --git a/video/beta/src/main/java/com/example/video/StreamingObjectTracking.java b/video/beta/src/main/java/com/example/video/StreamingObjectTracking.java
index 2c2e0403b92..09e58fcfab3 100644
--- a/video/beta/src/main/java/com/example/video/StreamingObjectTracking.java
+++ b/video/beta/src/main/java/com/example/video/StreamingObjectTracking.java
@@ -49,31 +49,30 @@ static void streamingObjectTracking(String filePath) {
int chunkSize = 5 * 1024 * 1024;
int numChunks = (int) Math.ceil((double) data.length / chunkSize);
- StreamingLabelDetectionConfig labelConfig = StreamingLabelDetectionConfig.newBuilder()
- .setStationaryCamera(false)
- .build();
+ StreamingLabelDetectionConfig labelConfig =
+ StreamingLabelDetectionConfig.newBuilder().setStationaryCamera(false).build();
- StreamingVideoConfig streamingVideoConfig = StreamingVideoConfig.newBuilder()
- .setFeature(StreamingFeature.STREAMING_OBJECT_TRACKING)
- .setLabelDetectionConfig(labelConfig)
- .build();
+ StreamingVideoConfig streamingVideoConfig =
+ StreamingVideoConfig.newBuilder()
+ .setFeature(StreamingFeature.STREAMING_OBJECT_TRACKING)
+ .setLabelDetectionConfig(labelConfig)
+ .build();
BidiStream call =
client.streamingAnnotateVideoCallable().call();
// The first request must **only** contain the audio configuration:
call.send(
- StreamingAnnotateVideoRequest.newBuilder()
- .setVideoConfig(streamingVideoConfig)
- .build());
+ StreamingAnnotateVideoRequest.newBuilder().setVideoConfig(streamingVideoConfig).build());
// Subsequent requests must **only** contain the audio data.
// Send the requests in chunks
for (int i = 0; i < numChunks; i++) {
call.send(
StreamingAnnotateVideoRequest.newBuilder()
- .setInputContent(ByteString.copyFrom(
- Arrays.copyOfRange(data, i * chunkSize, i * chunkSize + chunkSize)))
+ .setInputContent(
+ ByteString.copyFrom(
+ Arrays.copyOfRange(data, i * chunkSize, i * chunkSize + chunkSize)))
.build());
}
@@ -93,8 +92,8 @@ static void streamingObjectTracking(String filePath) {
// In streaming, there is always one frame.
ObjectTrackingFrame frame = objectAnnotations.getFrames(0);
- double offset = frame.getTimeOffset().getSeconds()
- + frame.getTimeOffset().getNanos() / 1e9;
+ double offset =
+ frame.getTimeOffset().getSeconds() + frame.getTimeOffset().getNanos() / 1e9;
System.out.format("Offset: %f\n", offset);
System.out.println("Bounding Box:");
diff --git a/video/beta/src/main/java/com/example/video/StreamingShotChangeDetection.java b/video/beta/src/main/java/com/example/video/StreamingShotChangeDetection.java
index 374964d0ca1..170418912e4 100644
--- a/video/beta/src/main/java/com/example/video/StreamingShotChangeDetection.java
+++ b/video/beta/src/main/java/com/example/video/StreamingShotChangeDetection.java
@@ -48,31 +48,30 @@ static void streamingShotChangeDetection(String filePath) {
int chunkSize = 5 * 1024 * 1024;
int numChunks = (int) Math.ceil((double) data.length / chunkSize);
- StreamingLabelDetectionConfig labelConfig = StreamingLabelDetectionConfig.newBuilder()
- .setStationaryCamera(false)
- .build();
+ StreamingLabelDetectionConfig labelConfig =
+ StreamingLabelDetectionConfig.newBuilder().setStationaryCamera(false).build();
- StreamingVideoConfig streamingVideoConfig = StreamingVideoConfig.newBuilder()
- .setFeature(StreamingFeature.STREAMING_SHOT_CHANGE_DETECTION)
- .setLabelDetectionConfig(labelConfig)
- .build();
+ StreamingVideoConfig streamingVideoConfig =
+ StreamingVideoConfig.newBuilder()
+ .setFeature(StreamingFeature.STREAMING_SHOT_CHANGE_DETECTION)
+ .setLabelDetectionConfig(labelConfig)
+ .build();
BidiStream call =
client.streamingAnnotateVideoCallable().call();
// The first request must **only** contain the audio configuration:
call.send(
- StreamingAnnotateVideoRequest.newBuilder()
- .setVideoConfig(streamingVideoConfig)
- .build());
+ StreamingAnnotateVideoRequest.newBuilder().setVideoConfig(streamingVideoConfig).build());
// Subsequent requests must **only** contain the audio data.
// Send the requests in chunks
for (int i = 0; i < numChunks; i++) {
call.send(
StreamingAnnotateVideoRequest.newBuilder()
- .setInputContent(ByteString.copyFrom(
- Arrays.copyOfRange(data, i * chunkSize, i * chunkSize + chunkSize)))
+ .setInputContent(
+ ByteString.copyFrom(
+ Arrays.copyOfRange(data, i * chunkSize, i * chunkSize + chunkSize)))
.build());
}
@@ -83,10 +82,11 @@ static void streamingShotChangeDetection(String filePath) {
StreamingVideoAnnotationResults annotationResults = response.getAnnotationResults();
for (VideoSegment segment : annotationResults.getShotAnnotationsList()) {
- double startTimeOffset = segment.getStartTimeOffset().getSeconds()
- + segment.getStartTimeOffset().getNanos() / 1e9;
- double endTimeOffset = segment.getEndTimeOffset().getSeconds()
- + segment.getEndTimeOffset().getNanos() / 1e9;
+ double startTimeOffset =
+ segment.getStartTimeOffset().getSeconds()
+ + segment.getStartTimeOffset().getNanos() / 1e9;
+ double endTimeOffset =
+ segment.getEndTimeOffset().getSeconds() + segment.getEndTimeOffset().getNanos() / 1e9;
System.out.format("Shot: %fs to %fs\n", startTimeOffset, endTimeOffset);
}
@@ -97,4 +97,3 @@ static void streamingShotChangeDetection(String filePath) {
}
}
// [END video_streaming_shot_change_detection_beta]
-
diff --git a/video/beta/src/main/java/com/example/video/TextDetection.java b/video/beta/src/main/java/com/example/video/TextDetection.java
index c095be6b7b5..e3726686e38 100644
--- a/video/beta/src/main/java/com/example/video/TextDetection.java
+++ b/video/beta/src/main/java/com/example/video/TextDetection.java
@@ -29,7 +29,6 @@
import com.google.cloud.videointelligence.v1p2beta1.VideoIntelligenceServiceClient;
import com.google.cloud.videointelligence.v1p2beta1.VideoSegment;
import com.google.protobuf.ByteString;
-
import com.google.protobuf.Duration;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -52,10 +51,11 @@ public static VideoAnnotationResults detectText(String filePath) throws Exceptio
byte[] data = Files.readAllBytes(path);
// Create the request
- AnnotateVideoRequest request = AnnotateVideoRequest.newBuilder()
- .setInputContent(ByteString.copyFrom(data))
- .addFeatures(Feature.TEXT_DETECTION)
- .build();
+ AnnotateVideoRequest request =
+ AnnotateVideoRequest.newBuilder()
+ .setInputContent(ByteString.copyFrom(data))
+ .addFeatures(Feature.TEXT_DETECTION)
+ .build();
// asynchronously perform object tracking on videos
OperationFuture future =
@@ -78,25 +78,29 @@ public static VideoAnnotationResults detectText(String filePath) throws Exceptio
Duration startTimeOffset = videoSegment.getStartTimeOffset();
Duration endTimeOffset = videoSegment.getEndTimeOffset();
// Display the offset times in seconds, 1e9 is part of the formula to convert nanos to seconds
- System.out.println(String.format("Start time: %.2f",
- startTimeOffset.getSeconds() + startTimeOffset.getNanos() / 1e9));
- System.out.println(String.format("End time: %.2f",
- endTimeOffset.getSeconds() + endTimeOffset.getNanos() / 1e9));
+ System.out.println(
+ String.format(
+ "Start time: %.2f", startTimeOffset.getSeconds() + startTimeOffset.getNanos() / 1e9));
+ System.out.println(
+ String.format(
+ "End time: %.2f", endTimeOffset.getSeconds() + endTimeOffset.getNanos() / 1e9));
// Show the first result for the first frame in the segment.
TextFrame textFrame = textSegment.getFrames(0);
Duration timeOffset = textFrame.getTimeOffset();
- System.out.println(String.format("Time offset for the first frame: %.2f",
- timeOffset.getSeconds() + timeOffset.getNanos() / 1e9));
+ System.out.println(
+ String.format(
+ "Time offset for the first frame: %.2f",
+ timeOffset.getSeconds() + timeOffset.getNanos() / 1e9));
// Display the rotated bounding box for where the text is on the frame.
System.out.println("Rotated Bounding Box Vertices:");
List vertices = textFrame.getRotatedBoundingBox().getVerticesList();
for (NormalizedVertex normalizedVertex : vertices) {
- System.out.println(String.format(
- "\tVertex.x: %.2f, Vertex.y: %.2f",
- normalizedVertex.getX(),
- normalizedVertex.getY()));
+ System.out.println(
+ String.format(
+ "\tVertex.x: %.2f, Vertex.y: %.2f",
+ normalizedVertex.getX(), normalizedVertex.getY()));
}
return results;
}
@@ -112,10 +116,11 @@ public static VideoAnnotationResults detectText(String filePath) throws Exceptio
public static VideoAnnotationResults detectTextGcs(String gcsUri) throws Exception {
try (VideoIntelligenceServiceClient client = VideoIntelligenceServiceClient.create()) {
// Create the request
- AnnotateVideoRequest request = AnnotateVideoRequest.newBuilder()
- .setInputUri(gcsUri)
- .addFeatures(Feature.TEXT_DETECTION)
- .build();
+ AnnotateVideoRequest request =
+ AnnotateVideoRequest.newBuilder()
+ .setInputUri(gcsUri)
+ .addFeatures(Feature.TEXT_DETECTION)
+ .build();
// asynchronously perform object tracking on videos
OperationFuture future =
@@ -138,25 +143,29 @@ public static VideoAnnotationResults detectTextGcs(String gcsUri) throws Excepti
Duration startTimeOffset = videoSegment.getStartTimeOffset();
Duration endTimeOffset = videoSegment.getEndTimeOffset();
// Display the offset times in seconds, 1e9 is part of the formula to convert nanos to seconds
- System.out.println(String.format("Start time: %.2f",
- startTimeOffset.getSeconds() + startTimeOffset.getNanos() / 1e9));
- System.out.println(String.format("End time: %.2f",
- endTimeOffset.getSeconds() + endTimeOffset.getNanos() / 1e9));
+ System.out.println(
+ String.format(
+ "Start time: %.2f", startTimeOffset.getSeconds() + startTimeOffset.getNanos() / 1e9));
+ System.out.println(
+ String.format(
+ "End time: %.2f", endTimeOffset.getSeconds() + endTimeOffset.getNanos() / 1e9));
// Show the first result for the first frame in the segment.
TextFrame textFrame = textSegment.getFrames(0);
Duration timeOffset = textFrame.getTimeOffset();
- System.out.println(String.format("Time offset for the first frame: %.2f",
- timeOffset.getSeconds() + timeOffset.getNanos() / 1e9));
+ System.out.println(
+ String.format(
+ "Time offset for the first frame: %.2f",
+ timeOffset.getSeconds() + timeOffset.getNanos() / 1e9));
// Display the rotated bounding box for where the text is on the frame.
System.out.println("Rotated Bounding Box Vertices:");
List vertices = textFrame.getRotatedBoundingBox().getVerticesList();
for (NormalizedVertex normalizedVertex : vertices) {
- System.out.println(String.format(
- "\tVertex.x: %.2f, Vertex.y: %.2f",
- normalizedVertex.getX(),
- normalizedVertex.getY()));
+ System.out.println(
+ String.format(
+ "\tVertex.x: %.2f, Vertex.y: %.2f",
+ normalizedVertex.getX(), normalizedVertex.getY()));
}
return results;
}
diff --git a/video/beta/src/main/java/com/example/video/TrackObjects.java b/video/beta/src/main/java/com/example/video/TrackObjects.java
index 7a5a52f0f27..1ae044572b6 100644
--- a/video/beta/src/main/java/com/example/video/TrackObjects.java
+++ b/video/beta/src/main/java/com/example/video/TrackObjects.java
@@ -29,7 +29,6 @@
import com.google.cloud.videointelligence.v1p2beta1.VideoIntelligenceServiceClient;
import com.google.cloud.videointelligence.v1p2beta1.VideoSegment;
import com.google.protobuf.ByteString;
-
import com.google.protobuf.Duration;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -51,11 +50,12 @@ public static VideoAnnotationResults trackObjects(String filePath) throws Except
byte[] data = Files.readAllBytes(path);
// Create the request
- AnnotateVideoRequest request = AnnotateVideoRequest.newBuilder()
- .setInputContent(ByteString.copyFrom(data))
- .addFeatures(Feature.OBJECT_TRACKING)
- .setLocationId("us-east1")
- .build();
+ AnnotateVideoRequest request =
+ AnnotateVideoRequest.newBuilder()
+ .setInputContent(ByteString.copyFrom(data))
+ .addFeatures(Feature.OBJECT_TRACKING)
+ .setLocationId("us-east1")
+ .build();
// asynchronously perform object tracking on videos
OperationFuture future =
@@ -81,19 +81,21 @@ public static VideoAnnotationResults trackObjects(String filePath) throws Except
Duration startTimeOffset = videoSegment.getStartTimeOffset();
Duration endTimeOffset = videoSegment.getEndTimeOffset();
// Display the segment time in seconds, 1e9 converts nanos to seconds
- System.out.println(String.format(
- "Segment: %.2fs to %.2fs",
- startTimeOffset.getSeconds() + startTimeOffset.getNanos() / 1e9,
- endTimeOffset.getSeconds() + endTimeOffset.getNanos() / 1e9));
+ System.out.println(
+ String.format(
+ "Segment: %.2fs to %.2fs",
+ startTimeOffset.getSeconds() + startTimeOffset.getNanos() / 1e9,
+ endTimeOffset.getSeconds() + endTimeOffset.getNanos() / 1e9));
}
// Here we print only the bounding box of the first frame in this segment.
ObjectTrackingFrame frame = annotation.getFrames(0);
// Display the offset time in seconds, 1e9 converts nanos to seconds
Duration timeOffset = frame.getTimeOffset();
- System.out.println(String.format(
- "Time offset of the first frame: %.2fs",
- timeOffset.getSeconds() + timeOffset.getNanos() / 1e9));
+ System.out.println(
+ String.format(
+ "Time offset of the first frame: %.2fs",
+ timeOffset.getSeconds() + timeOffset.getNanos() / 1e9));
// Display the bounding box of the detected object
NormalizedBoundingBox normalizedBoundingBox = frame.getNormalizedBoundingBox();
@@ -116,11 +118,12 @@ public static VideoAnnotationResults trackObjects(String filePath) throws Except
public static VideoAnnotationResults trackObjectsGcs(String gcsUri) throws Exception {
try (VideoIntelligenceServiceClient client = VideoIntelligenceServiceClient.create()) {
// Create the request
- AnnotateVideoRequest request = AnnotateVideoRequest.newBuilder()
- .setInputUri(gcsUri)
- .addFeatures(Feature.OBJECT_TRACKING)
- .setLocationId("us-east1")
- .build();
+ AnnotateVideoRequest request =
+ AnnotateVideoRequest.newBuilder()
+ .setInputUri(gcsUri)
+ .addFeatures(Feature.OBJECT_TRACKING)
+ .setLocationId("us-east1")
+ .build();
// asynchronously perform object tracking on videos
OperationFuture future =
@@ -146,19 +149,21 @@ public static VideoAnnotationResults trackObjectsGcs(String gcsUri) throws Excep
Duration startTimeOffset = videoSegment.getStartTimeOffset();
Duration endTimeOffset = videoSegment.getEndTimeOffset();
// Display the segment time in seconds, 1e9 converts nanos to seconds
- System.out.println(String.format(
- "Segment: %.2fs to %.2fs",
- startTimeOffset.getSeconds() + startTimeOffset.getNanos() / 1e9,
- endTimeOffset.getSeconds() + endTimeOffset.getNanos() / 1e9));
+ System.out.println(
+ String.format(
+ "Segment: %.2fs to %.2fs",
+ startTimeOffset.getSeconds() + startTimeOffset.getNanos() / 1e9,
+ endTimeOffset.getSeconds() + endTimeOffset.getNanos() / 1e9));
}
// Here we print only the bounding box of the first frame in this segment.
ObjectTrackingFrame frame = annotation.getFrames(0);
// Display the offset time in seconds, 1e9 converts nanos to seconds
Duration timeOffset = frame.getTimeOffset();
- System.out.println(String.format(
- "Time offset of the first frame: %.2fs",
- timeOffset.getSeconds() + timeOffset.getNanos() / 1e9));
+ System.out.println(
+ String.format(
+ "Time offset of the first frame: %.2fs",
+ timeOffset.getSeconds() + timeOffset.getNanos() / 1e9));
// Display the bounding box of the detected object
NormalizedBoundingBox normalizedBoundingBox = frame.getNormalizedBoundingBox();
@@ -172,4 +177,3 @@ public static VideoAnnotationResults trackObjectsGcs(String gcsUri) throws Excep
}
// [END video_object_tracking_gcs_beta]
}
-
diff --git a/video/beta/src/test/java/com/example/video/DetectFacesGcsIT.java b/video/beta/src/test/java/com/example/video/DetectFacesGcsIT.java
index c2bfb9b53e6..5d27191f8c3 100644
--- a/video/beta/src/test/java/com/example/video/DetectFacesGcsIT.java
+++ b/video/beta/src/test/java/com/example/video/DetectFacesGcsIT.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/video/beta/src/test/java/com/example/video/DetectFacesIT.java b/video/beta/src/test/java/com/example/video/DetectFacesIT.java
index 3993b463439..8869227df7f 100644
--- a/video/beta/src/test/java/com/example/video/DetectFacesIT.java
+++ b/video/beta/src/test/java/com/example/video/DetectFacesIT.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/video/beta/src/test/java/com/example/video/DetectIT.java b/video/beta/src/test/java/com/example/video/DetectIT.java
index e1c6d943427..c9cdf5c4d00 100644
--- a/video/beta/src/test/java/com/example/video/DetectIT.java
+++ b/video/beta/src/test/java/com/example/video/DetectIT.java
@@ -39,12 +39,22 @@ public class DetectIT {
private ByteArrayOutputStream bout;
private PrintStream out;
- static final String FILE_LOCATION =
- "gs://java-docs-samples-testing/video/googlework_short.mp4";
-
- private static final List POSSIBLE_TEXTS = Arrays.asList(
- "Google", "SUR", "SUR", "ROTO", "Vice President", "58oo9", "LONDRES", "OMAR", "PARIS",
- "METRO", "RUE", "CARLO");
+ static final String FILE_LOCATION = "gs://java-docs-samples-testing/video/googlework_short.mp4";
+
+ private static final List POSSIBLE_TEXTS =
+ Arrays.asList(
+ "Google",
+ "SUR",
+ "SUR",
+ "ROTO",
+ "Vice President",
+ "58oo9",
+ "LONDRES",
+ "OMAR",
+ "PARIS",
+ "METRO",
+ "RUE",
+ "CARLO");
@Before
public void setUp() {
@@ -84,8 +94,8 @@ public void testTrackObjects() throws Exception {
@Test
public void testTrackObjectsGcs() throws Exception {
- VideoAnnotationResults result = TrackObjects.trackObjectsGcs(
- "gs://cloud-samples-data/video/cat.mp4");
+ VideoAnnotationResults result =
+ TrackObjects.trackObjectsGcs("gs://cloud-samples-data/video/cat.mp4");
boolean textExists = false;
for (ObjectTrackingAnnotation objectTrackingAnnotation : result.getObjectAnnotationsList()) {
diff --git a/video/beta/src/test/java/com/example/video/DetectLogoGcsTest.java b/video/beta/src/test/java/com/example/video/DetectLogoGcsTest.java
index 41477f743e1..b333b706dbf 100644
--- a/video/beta/src/test/java/com/example/video/DetectLogoGcsTest.java
+++ b/video/beta/src/test/java/com/example/video/DetectLogoGcsTest.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/video/beta/src/test/java/com/example/video/DetectLogoTest.java b/video/beta/src/test/java/com/example/video/DetectLogoTest.java
index 3915ae63ca7..d4e832c2140 100644
--- a/video/beta/src/test/java/com/example/video/DetectLogoTest.java
+++ b/video/beta/src/test/java/com/example/video/DetectLogoTest.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/video/beta/src/test/java/com/example/video/DetectPersonGcsIT.java b/video/beta/src/test/java/com/example/video/DetectPersonGcsIT.java
index b0ede697de0..8709dc4e296 100644
--- a/video/beta/src/test/java/com/example/video/DetectPersonGcsIT.java
+++ b/video/beta/src/test/java/com/example/video/DetectPersonGcsIT.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/video/beta/src/test/java/com/example/video/DetectPersonIT.java b/video/beta/src/test/java/com/example/video/DetectPersonIT.java
index 6d8599a7a2f..5c8325732c9 100644
--- a/video/beta/src/test/java/com/example/video/DetectPersonIT.java
+++ b/video/beta/src/test/java/com/example/video/DetectPersonIT.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/video/beta/src/test/java/com/example/video/StreamingAnnotationToStorageIT.java b/video/beta/src/test/java/com/example/video/StreamingAnnotationToStorageIT.java
index 05698811fd2..2893ae2f25d 100644
--- a/video/beta/src/test/java/com/example/video/StreamingAnnotationToStorageIT.java
+++ b/video/beta/src/test/java/com/example/video/StreamingAnnotationToStorageIT.java
@@ -31,9 +31,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Integration (system) tests for {@link StreamingAnnotationToStorage}.
- */
+/** Integration (system) tests for {@link StreamingAnnotationToStorage}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class StreamingAnnotationToStorageIT {
@@ -65,8 +63,11 @@ public void testStreamingAnnotationToStorage() {
Storage storage = StorageOptions.getDefaultInstance().getService();
- Page blobs = storage.list(PROJECT_ID, BlobListOption.currentDirectory(),
- BlobListOption.prefix(OUTPUT_PREFIX + "/"));
+ Page blobs =
+ storage.list(
+ PROJECT_ID,
+ BlobListOption.currentDirectory(),
+ BlobListOption.prefix(OUTPUT_PREFIX + "/"));
deleteDirectory(storage, blobs);
}
@@ -75,8 +76,11 @@ private void deleteDirectory(Storage storage, Page blobs) {
for (Blob blob : blobs.iterateAll()) {
System.out.println(blob.getName());
if (!blob.delete()) {
- Page subBlobs = storage.list(PROJECT_ID, BlobListOption.currentDirectory(),
- BlobListOption.prefix(blob.getName()));
+ Page subBlobs =
+ storage.list(
+ PROJECT_ID,
+ BlobListOption.currentDirectory(),
+ BlobListOption.prefix(blob.getName()));
deleteDirectory(storage, subBlobs);
}
diff --git a/video/beta/src/test/java/com/example/video/StreamingAutoMlClassificationIT.java b/video/beta/src/test/java/com/example/video/StreamingAutoMlClassificationIT.java
index 1a37bbd539c..37dbe0bfe4c 100644
--- a/video/beta/src/test/java/com/example/video/StreamingAutoMlClassificationIT.java
+++ b/video/beta/src/test/java/com/example/video/StreamingAutoMlClassificationIT.java
@@ -14,24 +14,19 @@
* limitations under the License.
*/
-
package com.example.video;
import static com.google.common.truth.Truth.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-
-/**
- * Integration (system) tests for {@link StreamingAutoMlClassification}.
- */
+/** Integration (system) tests for {@link StreamingAutoMlClassification}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class StreamingAutoMlClassificationIT {
@@ -57,9 +52,7 @@ public void tearDown() {
@Test
public void testStreamingAutoMlClassification() {
StreamingAutoMlClassification.streamingAutoMlClassification(
- "resources/cat.mp4",
- PROJECT_ID,
- MODEL_ID);
+ "resources/cat.mp4", PROJECT_ID, MODEL_ID);
String got = bout.toString();
assertThat(got).contains("brush_hair");
diff --git a/video/beta/src/test/java/com/example/video/StreamingExplicitContentDetectionIT.java b/video/beta/src/test/java/com/example/video/StreamingExplicitContentDetectionIT.java
index 324414db3f7..d40000ad959 100644
--- a/video/beta/src/test/java/com/example/video/StreamingExplicitContentDetectionIT.java
+++ b/video/beta/src/test/java/com/example/video/StreamingExplicitContentDetectionIT.java
@@ -26,9 +26,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Integration (system) tests for {@link StreamingExplicitContentDetection}.
- */
+/** Integration (system) tests for {@link StreamingExplicitContentDetection}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class StreamingExplicitContentDetectionIT {
diff --git a/video/beta/src/test/java/com/example/video/StreamingLabelDetectionIT.java b/video/beta/src/test/java/com/example/video/StreamingLabelDetectionIT.java
index 70f7affd126..21fd5dc07ce 100644
--- a/video/beta/src/test/java/com/example/video/StreamingLabelDetectionIT.java
+++ b/video/beta/src/test/java/com/example/video/StreamingLabelDetectionIT.java
@@ -26,9 +26,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Integration (system) tests for {@link StreamingLabelDetection}.
- */
+/** Integration (system) tests for {@link StreamingLabelDetection}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class StreamingLabelDetectionIT {
diff --git a/video/beta/src/test/java/com/example/video/StreamingObjectTrackingIT.java b/video/beta/src/test/java/com/example/video/StreamingObjectTrackingIT.java
index c1097e1403d..21318774c2b 100644
--- a/video/beta/src/test/java/com/example/video/StreamingObjectTrackingIT.java
+++ b/video/beta/src/test/java/com/example/video/StreamingObjectTrackingIT.java
@@ -26,9 +26,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Integration (system) tests for {@link StreamingObjectTracking}.
- */
+/** Integration (system) tests for {@link StreamingObjectTracking}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class StreamingObjectTrackingIT {
diff --git a/video/beta/src/test/java/com/example/video/StreamingShotChangeDetectionIT.java b/video/beta/src/test/java/com/example/video/StreamingShotChangeDetectionIT.java
index 00b0787418c..a2eea83b804 100644
--- a/video/beta/src/test/java/com/example/video/StreamingShotChangeDetectionIT.java
+++ b/video/beta/src/test/java/com/example/video/StreamingShotChangeDetectionIT.java
@@ -26,9 +26,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Integration (system) tests for {@link StreamingShotChangeDetection}.
- */
+/** Integration (system) tests for {@link StreamingShotChangeDetection}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class StreamingShotChangeDetectionIT {
diff --git a/video/cloud-client/pom.xml b/video/cloud-client/pom.xml
index 5abaac81405..9bc49d0fdc3 100644
--- a/video/cloud-client/pom.xml
+++ b/video/cloud-client/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/video/cloud-client/src/main/java/com/example/video/TextDetection.java b/video/cloud-client/src/main/java/com/example/video/TextDetection.java
index f21b3c9e832..ef50641848c 100644
--- a/video/cloud-client/src/main/java/com/example/video/TextDetection.java
+++ b/video/cloud-client/src/main/java/com/example/video/TextDetection.java
@@ -29,7 +29,6 @@
import com.google.cloud.videointelligence.v1.VideoIntelligenceServiceClient;
import com.google.cloud.videointelligence.v1.VideoSegment;
import com.google.protobuf.ByteString;
-
import com.google.protobuf.Duration;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -163,4 +162,3 @@ public static VideoAnnotationResults detectTextGcs(String gcsUri) throws Excepti
}
// [END video_detect_text_gcs]
}
-
diff --git a/video/cloud-client/src/main/java/com/example/video/TrackObjects.java b/video/cloud-client/src/main/java/com/example/video/TrackObjects.java
index 61fc6434c7f..eea1db6f2ff 100644
--- a/video/cloud-client/src/main/java/com/example/video/TrackObjects.java
+++ b/video/cloud-client/src/main/java/com/example/video/TrackObjects.java
@@ -29,7 +29,6 @@
import com.google.cloud.videointelligence.v1.VideoIntelligenceServiceClient;
import com.google.cloud.videointelligence.v1.VideoSegment;
import com.google.protobuf.ByteString;
-
import com.google.protobuf.Duration;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -172,5 +171,3 @@ public static VideoAnnotationResults trackObjectsGcs(String gcsUri) throws Excep
}
// [END video_object_tracking_gcs]
}
-
-
diff --git a/video/cloud-client/src/test/java/com/example/video/DetectIT.java b/video/cloud-client/src/test/java/com/example/video/DetectIT.java
index a9710548b80..fafb471d3f3 100644
--- a/video/cloud-client/src/test/java/com/example/video/DetectIT.java
+++ b/video/cloud-client/src/test/java/com/example/video/DetectIT.java
@@ -21,12 +21,10 @@
import com.google.cloud.videointelligence.v1.ObjectTrackingAnnotation;
import com.google.cloud.videointelligence.v1.TextAnnotation;
import com.google.cloud.videointelligence.v1.VideoAnnotationResults;
-
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.List;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/vision/automl/pom.xml b/vision/automl/pom.xml
index c13c9a57eda..2b32f70ebf1 100644
--- a/vision/automl/pom.xml
+++ b/vision/automl/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModel.java b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModel.java
index 6b533c44a4d..63da52ead0d 100644
--- a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModel.java
+++ b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModel.java
@@ -23,7 +23,6 @@
import com.google.cloud.automl.v1beta1.ModelName;
import com.google.cloud.automl.v1beta1.OperationMetadata;
import com.google.protobuf.Empty;
-
import java.io.IOException;
import java.util.concurrent.ExecutionException;
@@ -31,7 +30,7 @@ class ClassificationDeployModel {
// Deploy a model
static void classificationDeployModel(String projectId, String modelId)
- throws IOException, ExecutionException, InterruptedException {
+ throws IOException, ExecutionException, InterruptedException {
// String projectId = "YOUR_PROJECT_ID";
// String modelId = "YOUR_MODEL_ID";
diff --git a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelNodeCount.java b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelNodeCount.java
index 22eb247e626..655cd7218c9 100644
--- a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelNodeCount.java
+++ b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelNodeCount.java
@@ -24,7 +24,6 @@
import com.google.cloud.automl.v1beta1.ModelName;
import com.google.cloud.automl.v1beta1.OperationMetadata;
import com.google.protobuf.Empty;
-
import java.io.IOException;
import java.util.concurrent.ExecutionException;
@@ -32,7 +31,7 @@ class ClassificationDeployModelNodeCount {
// Deploy a model with a specified node count
static void classificationDeployModelNodeCount(String projectId, String modelId)
- throws IOException, ExecutionException, InterruptedException {
+ throws IOException, ExecutionException, InterruptedException {
// String projectId = "YOUR_PROJECT_ID";
// String modelId = "YOUR_MODEL_ID";
@@ -45,9 +44,10 @@ static void classificationDeployModelNodeCount(String projectId, String modelId)
// Set how many nodes the model is deployed on
ImageClassificationModelDeploymentMetadata deploymentMetadata =
- ImageClassificationModelDeploymentMetadata.newBuilder().setNodeCount(2).build();
+ ImageClassificationModelDeploymentMetadata.newBuilder().setNodeCount(2).build();
- DeployModelRequest request = DeployModelRequest.newBuilder()
+ DeployModelRequest request =
+ DeployModelRequest.newBuilder()
.setName(modelFullId.toString())
.setImageClassificationModelDeploymentMetadata(deploymentMetadata)
.build();
@@ -58,4 +58,4 @@ static void classificationDeployModelNodeCount(String projectId, String modelId)
}
}
}
-// [END automl_vision_classification_deploy_model_node_count]
\ No newline at end of file
+// [END automl_vision_classification_deploy_model_node_count]
diff --git a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ClassificationUndeployModel.java b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ClassificationUndeployModel.java
index dd55e8f523c..33e75cdb876 100644
--- a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ClassificationUndeployModel.java
+++ b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ClassificationUndeployModel.java
@@ -23,7 +23,6 @@
import com.google.cloud.automl.v1beta1.OperationMetadata;
import com.google.cloud.automl.v1beta1.UndeployModelRequest;
import com.google.protobuf.Empty;
-
import java.io.IOException;
import java.util.concurrent.ExecutionException;
@@ -31,7 +30,7 @@ class ClassificationUndeployModel {
// Deploy a model
static void classificationUndeployModel(String projectId, String modelId)
- throws IOException, ExecutionException, InterruptedException {
+ throws IOException, ExecutionException, InterruptedException {
// String projectId = "YOUR_PROJECT_ID";
// String modelId = "YOUR_MODEL_ID";
@@ -45,11 +44,11 @@ static void classificationUndeployModel(String projectId, String modelId)
// Build deploy model request.
UndeployModelRequest undeployModelRequest =
- UndeployModelRequest.newBuilder().setName(modelFullId.toString()).build();
+ UndeployModelRequest.newBuilder().setName(modelFullId.toString()).build();
// Deploy a model with the deploy model request.
OperationFuture future =
- client.undeployModelAsync(undeployModelRequest);
+ client.undeployModelAsync(undeployModelRequest);
future.get();
diff --git a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/DatasetApi.java b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/DatasetApi.java
index e9c4f6422f3..bcf5ec74614 100644
--- a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/DatasetApi.java
+++ b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/DatasetApi.java
@@ -29,9 +29,7 @@
import com.google.cloud.automl.v1beta1.LocationName;
import com.google.cloud.automl.v1beta1.OutputConfig;
import com.google.protobuf.Empty;
-
import java.io.IOException;
-
import java.util.concurrent.ExecutionException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
@@ -195,8 +193,7 @@ static void getDataset(String projectId, String computeRegion, String datasetId)
* @param datasetId the Id of the dataset to which the training data will be imported.
* @param path the Google Cloud Storage URIs. Target files must be in AutoML vision CSV format.
*/
- static void importData(
- String projectId, String computeRegion, String datasetId, String path) {
+ static void importData(String projectId, String computeRegion, String datasetId, String path) {
// Instantiates a client
try (AutoMlClient client = AutoMlClient.create()) {
@@ -231,8 +228,7 @@ static void importData(
* @param datasetId the Id of the dataset.
* @param gcsUri the Destination URI (Google Cloud Storage)
*/
- static void exportData(
- String projectId, String computeRegion, String datasetId, String gcsUri) {
+ static void exportData(String projectId, String computeRegion, String datasetId, String gcsUri) {
// Instantiates a client
try (AutoMlClient client = AutoMlClient.create()) {
@@ -240,12 +236,12 @@ static void exportData(
DatasetName datasetFullId = DatasetName.of(projectId, computeRegion, datasetId);
// Set the output URI
- GcsDestination gcsDestination = GcsDestination.newBuilder().setOutputUriPrefix(gcsUri)
- .build();
+ GcsDestination gcsDestination =
+ GcsDestination.newBuilder().setOutputUriPrefix(gcsUri).build();
// Export the dataset to the output URI.
- OutputConfig outputConfig = OutputConfig.newBuilder().setGcsDestination(gcsDestination)
- .build();
+ OutputConfig outputConfig =
+ OutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
System.out.println("Processing export...");
Empty response = client.exportDataAsync(datasetFullId, outputConfig).get();
diff --git a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ModelApi.java b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ModelApi.java
index 913b2551472..9a89c215d40 100644
--- a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ModelApi.java
+++ b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ModelApi.java
@@ -30,13 +30,10 @@
import com.google.cloud.automl.v1beta1.ModelEvaluationName;
import com.google.cloud.automl.v1beta1.ModelName;
import com.google.cloud.automl.v1beta1.OperationMetadata;
-
import com.google.longrunning.Operation;
import com.google.protobuf.Empty;
-
import java.io.IOException;
import java.util.List;
-
import java.util.concurrent.ExecutionException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
@@ -62,8 +59,12 @@ public class ModelApi {
* @param modelName the Name of the model.
* @param trainBudget the Budget for training the model.
*/
- static void createModel(String projectId, String computeRegion, String dataSetId,
- String modelName, String trainBudget) {
+ static void createModel(
+ String projectId,
+ String computeRegion,
+ String dataSetId,
+ String modelName,
+ String trainBudget) {
// Instantiates a client
try (AutoMlClient client = AutoMlClient.create()) {
@@ -91,8 +92,8 @@ static void createModel(String projectId, String computeRegion, String dataSetId
client.createModelAsync(projectLocation, myModel);
System.out.println(
- String
- .format("Training operation name: %s", response.getInitialFuture().get().getName()));
+ String.format(
+ "Training operation name: %s", response.getInitialFuture().get().getName()));
System.out.println("Training started...");
} catch (IOException | ExecutionException | InterruptedException e) {
e.printStackTrace();
@@ -340,7 +341,7 @@ static void displayEvaluation(
+ '%');
System.out.println(
String.format(
- "Model Precision@1: %.2f ", confidenceMetricsEntry.getPrecisionAt1() * 100)
+ "Model Precision@1: %.2f ", confidenceMetricsEntry.getPrecisionAt1() * 100)
+ '%');
System.out.println(
String.format("Model Recall@1: %.2f ", confidenceMetricsEntry.getRecallAt1() * 100)
diff --git a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCount.java b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCount.java
index 927b3d299f0..cd6de5c5bcc 100644
--- a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCount.java
+++ b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCount.java
@@ -24,17 +24,16 @@
import com.google.cloud.automl.v1beta1.ModelName;
import com.google.cloud.automl.v1beta1.OperationMetadata;
import com.google.protobuf.Empty;
-
import java.io.IOException;
import java.util.concurrent.ExecutionException;
class ObjectDetectionDeployModelNodeCount {
static void objectDetectionDeployModelNodeCount(String projectId, String modelId)
- throws IOException, ExecutionException, InterruptedException {
+ throws IOException, ExecutionException, InterruptedException {
// String projectId = "YOUR_PROJECT_ID";
// String modelId = "YOUR_MODEL_ID";
-
+
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
@@ -44,9 +43,10 @@ static void objectDetectionDeployModelNodeCount(String projectId, String modelId
// Set how many nodes the model is deployed on
ImageObjectDetectionModelDeploymentMetadata deploymentMetadata =
- ImageObjectDetectionModelDeploymentMetadata.newBuilder().setNodeCount(2).build();
+ ImageObjectDetectionModelDeploymentMetadata.newBuilder().setNodeCount(2).build();
- DeployModelRequest request = DeployModelRequest.newBuilder()
+ DeployModelRequest request =
+ DeployModelRequest.newBuilder()
.setName(modelFullId.toString())
.setImageObjectDetectionModelDeploymentMetadata(deploymentMetadata)
.build();
diff --git a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/PredictionApi.java b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/PredictionApi.java
index 27328effae0..224c9a6db44 100644
--- a/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/PredictionApi.java
+++ b/vision/automl/src/main/java/com/google/cloud/vision/samples/automl/PredictionApi.java
@@ -32,13 +32,11 @@
import com.google.cloud.automl.v1beta1.PredictResponse;
import com.google.cloud.automl.v1beta1.PredictionServiceClient;
import com.google.protobuf.ByteString;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
-
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
diff --git a/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelIT.java b/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelIT.java
index 7612fe89f2f..fa49c779fce 100644
--- a/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelIT.java
+++ b/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/ClassificationDeployModelIT.java
@@ -22,7 +22,6 @@
import java.io.IOException;
import java.io.PrintStream;
import java.util.concurrent.ExecutionException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -71,7 +70,6 @@ public void testClassificationUndeployModelApi() {
} catch (IOException | ExecutionException | InterruptedException e) {
assertThat(e.getMessage()).contains("The model does not exist");
}
-
}
@Test
diff --git a/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/DatasetApiIT.java b/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/DatasetApiIT.java
index c9cf9f34133..04cc0a6f4d2 100644
--- a/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/DatasetApiIT.java
+++ b/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/DatasetApiIT.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import java.util.UUID;
import org.junit.After;
import org.junit.Before;
@@ -57,8 +56,8 @@ public void testCreateImportDeleteDataset() {
// Create a random dataset name with a length of 32 characters (max allowed by AutoML)
// To prevent name collisions when running tests in multiple java versions at once.
// AutoML doesn't allow "-", but accepts "_"
- String datasetName = String.format("test_%s",
- UUID.randomUUID().toString().replace("-", "_").substring(0, 26));
+ String datasetName =
+ String.format("test_%s", UUID.randomUUID().toString().replace("-", "_").substring(0, 26));
// Act
DatasetApi.createDataset(PROJECT_ID, COMPUTE_REGION, datasetName, false);
diff --git a/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/ModelApiIT.java b/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/ModelApiIT.java
index 133e56c4cfa..164c5e9586e 100644
--- a/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/ModelApiIT.java
+++ b/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/ModelApiIT.java
@@ -20,7 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -82,6 +81,5 @@ public void testModelApi() {
// Assert
got = bout.toString();
assertThat(got).contains("name:");
-
}
}
diff --git a/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCountIT.java b/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCountIT.java
index b2487783d23..54a7f48dd85 100644
--- a/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCountIT.java
+++ b/vision/automl/src/test/java/com/google/cloud/vision/samples/automl/ObjectDetectionDeployModelNodeCountIT.java
@@ -18,17 +18,10 @@
import static com.google.common.truth.Truth.assertThat;
-import com.google.api.gax.longrunning.OperationFuture;
-import com.google.cloud.automl.v1beta1.AutoMlClient;
-import com.google.cloud.automl.v1beta1.ModelName;
-import com.google.cloud.automl.v1beta1.OperationMetadata;
-import com.google.protobuf.Empty;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.concurrent.ExecutionException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/vision/beta/cloud-client/pom.xml b/vision/beta/cloud-client/pom.xml
index c2eb6e68560..f0614af9485 100644
--- a/vision/beta/cloud-client/pom.xml
+++ b/vision/beta/cloud-client/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/vision/beta/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImagesGcs.java b/vision/beta/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImagesGcs.java
index 5fc863ffde3..c63d8a2993b 100644
--- a/vision/beta/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImagesGcs.java
+++ b/vision/beta/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImagesGcs.java
@@ -86,9 +86,8 @@ public static void asyncBatchAnnotateImagesGcs(String gcsSourcePath, String gcsD
.setOutputConfig(outputConfig)
.build();
-
OperationFuture response =
- client.asyncBatchAnnotateImagesAsync(request);
+ client.asyncBatchAnnotateImagesAsync(request);
System.out.println("Waiting for the operation to finish.");
// we're not processing the response, since we'll be reading the output from GCS.
diff --git a/vision/beta/cloud-client/src/main/java/com/example/vision/Detect.java b/vision/beta/cloud-client/src/main/java/com/example/vision/Detect.java
index ed449981a59..7be90b63499 100644
--- a/vision/beta/cloud-client/src/main/java/com/example/vision/Detect.java
+++ b/vision/beta/cloud-client/src/main/java/com/example/vision/Detect.java
@@ -33,7 +33,6 @@
import com.google.cloud.vision.v1p3beta1.TextAnnotation;
import com.google.cloud.vision.v1p3beta1.Word;
import com.google.protobuf.ByteString;
-
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
diff --git a/vision/beta/cloud-client/src/main/java/com/example/vision/DetectBatchAnnotateFiles.java b/vision/beta/cloud-client/src/main/java/com/example/vision/DetectBatchAnnotateFiles.java
index 34fc8bfec8c..7ef3ac6f74d 100644
--- a/vision/beta/cloud-client/src/main/java/com/example/vision/DetectBatchAnnotateFiles.java
+++ b/vision/beta/cloud-client/src/main/java/com/example/vision/DetectBatchAnnotateFiles.java
@@ -33,7 +33,6 @@
import com.google.cloud.vision.v1p4beta1.TextAnnotation;
import com.google.cloud.vision.v1p4beta1.Word;
import com.google.protobuf.ByteString;
-
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
diff --git a/vision/beta/cloud-client/src/main/java/com/example/vision/DetectBatchAnnotateFilesGcs.java b/vision/beta/cloud-client/src/main/java/com/example/vision/DetectBatchAnnotateFilesGcs.java
index 5b8de5880ae..3f8b9582018 100644
--- a/vision/beta/cloud-client/src/main/java/com/example/vision/DetectBatchAnnotateFilesGcs.java
+++ b/vision/beta/cloud-client/src/main/java/com/example/vision/DetectBatchAnnotateFilesGcs.java
@@ -33,7 +33,6 @@
import com.google.cloud.vision.v1p4beta1.Symbol;
import com.google.cloud.vision.v1p4beta1.TextAnnotation;
import com.google.cloud.vision.v1p4beta1.Word;
-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -50,7 +49,7 @@ public static void detectBatchAnnotateFilesGcs(String gcsPath) {
List pages = Arrays.asList(1, 2, -1);
GcsSource gcsSource = GcsSource.newBuilder().setUri(gcsPath).build();
Feature feat = Feature.newBuilder().setType(Type.DOCUMENT_TEXT_DETECTION).build();
- //Other supported mime types : 'image/tiff' or 'image/gif'
+ // Other supported mime types : 'image/tiff' or 'image/gif'
InputConfig inputConfig =
InputConfig.newBuilder().setMimeType("application/pdf").setGcsSource(gcsSource).build();
AnnotateFileRequest request =
diff --git a/vision/beta/cloud-client/src/test/java/com/example/vision/DetectIT.java b/vision/beta/cloud-client/src/test/java/com/example/vision/DetectIT.java
index 333c6c7fe31..71a96ac52e5 100644
--- a/vision/beta/cloud-client/src/test/java/com/example/vision/DetectIT.java
+++ b/vision/beta/cloud-client/src/test/java/com/example/vision/DetectIT.java
@@ -27,7 +27,6 @@
import java.io.IOException;
import java.io.PrintStream;
import java.util.UUID;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -41,7 +40,7 @@ public class DetectIT {
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
private static final String BUCKET = "java-docs-samples-testing";
private static final String OUTPUT_BUCKET = PROJECT_ID;
- private static final String OUTPUT_PREFIX = "OUTPUT_VISION_BETA_" + UUID.randomUUID().toString();
+ private static final String OUTPUT_PREFIX = "OUTPUT_VISION_BETA_" + UUID.randomUUID().toString();
private ByteArrayOutputStream bout;
private PrintStream out;
private Detect app;
diff --git a/vision/cloud-client/pom.xml b/vision/cloud-client/pom.xml
index 86cdc8b0288..8504d70772a 100644
--- a/vision/cloud-client/pom.xml
+++ b/vision/cloud-client/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/vision/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImages.java b/vision/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImages.java
index 4ebb999388d..e9b31582051 100644
--- a/vision/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImages.java
+++ b/vision/cloud-client/src/main/java/com/example/vision/AsyncBatchAnnotateImages.java
@@ -26,7 +26,6 @@
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageSource;
import com.google.cloud.vision.v1.OutputConfig;
-
import java.io.IOException;
import java.util.concurrent.ExecutionException;
diff --git a/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFiles.java b/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFiles.java
index e2cf370d9da..0895ca7aa00 100644
--- a/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFiles.java
+++ b/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFiles.java
@@ -30,7 +30,6 @@
import com.google.cloud.vision.v1.Symbol;
import com.google.cloud.vision.v1.Word;
import com.google.protobuf.ByteString;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
diff --git a/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFilesGcs.java b/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFilesGcs.java
index 488cefbfbc7..dce825fd025 100644
--- a/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFilesGcs.java
+++ b/vision/cloud-client/src/main/java/com/example/vision/BatchAnnotateFilesGcs.java
@@ -30,7 +30,6 @@
import com.google.cloud.vision.v1.Paragraph;
import com.google.cloud.vision.v1.Symbol;
import com.google.cloud.vision.v1.Word;
-
import java.io.IOException;
public class BatchAnnotateFilesGcs {
diff --git a/vision/cloud-client/src/main/java/com/example/vision/Detect.java b/vision/cloud-client/src/main/java/com/example/vision/Detect.java
index 5e004c16b1a..ae84a53ed70 100644
--- a/vision/cloud-client/src/main/java/com/example/vision/Detect.java
+++ b/vision/cloud-client/src/main/java/com/example/vision/Detect.java
@@ -62,9 +62,7 @@
import com.google.cloud.vision.v1.WebDetection.WebPage;
import com.google.cloud.vision.v1.WebDetectionParams;
import com.google.cloud.vision.v1.Word;
-
import com.google.protobuf.ByteString;
-
import com.google.protobuf.util.JsonFormat;
import java.io.FileInputStream;
import java.io.IOException;
@@ -249,14 +247,13 @@ public static void detectFaces(String filePath, PrintStream out) throws Exceptio
* Detects faces in the specified remote image on Google Cloud Storage.
*
* @param gcsPath The path to the remote file on Google Cloud Storage to perform face detection
- * on.
+ * on.
* @param out A {@link PrintStream} to write detected features to.
* @throws Exception on errors while closing the client.
* @throws IOException on Input/Output errors.
*/
// [START vision_face_detection_gcs]
- public static void detectFacesGcs(String gcsPath, PrintStream out) throws Exception,
- IOException {
+ public static void detectFacesGcs(String gcsPath, PrintStream out) throws Exception, IOException {
List requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
@@ -334,14 +331,14 @@ public static void detectLabels(String filePath, PrintStream out) throws Excepti
* Detects labels in the specified remote image on Google Cloud Storage.
*
* @param gcsPath The path to the remote file on Google Cloud Storage to perform label detection
- * on.
+ * on.
* @param out A {@link PrintStream} to write detected features to.
* @throws Exception on errors while closing the client.
* @throws IOException on Input/Output errors.
*/
// [START vision_label_detection_gcs]
- public static void detectLabelsGcs(String gcsPath, PrintStream out) throws Exception,
- IOException {
+ public static void detectLabelsGcs(String gcsPath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
@@ -363,8 +360,7 @@ public static void detectLabelsGcs(String gcsPath, PrintStream out) throws Excep
// For full list of available annotations, see http://g.co/cloud/vision/docs
for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
- annotation.getAllFields().forEach((k, v) ->
- out.printf("%s : %s\n", k, v.toString()));
+ annotation.getAllFields().forEach((k, v) -> out.printf("%s : %s\n", k, v.toString()));
}
}
}
@@ -380,8 +376,8 @@ public static void detectLabelsGcs(String gcsPath, PrintStream out) throws Excep
* @throws IOException on Input/Output errors.
*/
// [START vision_landmark_detection]
- public static void detectLandmarks(String filePath, PrintStream out) throws Exception,
- IOException {
+ public static void detectLandmarks(String filePath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));
@@ -419,8 +415,7 @@ public static void detectLandmarks(String filePath, PrintStream out) throws Exce
* @throws Exception on errors while closing the client.
* @throws IOException on Input/Output errors.
*/
- public static void detectLandmarksUrl(String uri, PrintStream out) throws Exception,
- IOException {
+ public static void detectLandmarksUrl(String uri, PrintStream out) throws Exception, IOException {
List requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setImageUri(uri).build();
@@ -453,14 +448,14 @@ public static void detectLandmarksUrl(String uri, PrintStream out) throws Except
* Detects landmarks in the specified remote image on Google Cloud Storage.
*
* @param gcsPath The path to the remote file on Google Cloud Storage to perform landmark
- * detection on.
+ * detection on.
* @param out A {@link PrintStream} to write detected landmarks to.
* @throws Exception on errors while closing the client.
* @throws IOException on Input/Output errors.
*/
// [START vision_landmark_detection_gcs]
- public static void detectLandmarksGcs(String gcsPath, PrintStream out) throws Exception,
- IOException {
+ public static void detectLandmarksGcs(String gcsPath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
@@ -533,14 +528,13 @@ public static void detectLogos(String filePath, PrintStream out) throws Exceptio
* Detects logos in the specified remote image on Google Cloud Storage.
*
* @param gcsPath The path to the remote file on Google Cloud Storage to perform logo detection
- * on.
+ * on.
* @param out A {@link PrintStream} to write detected logos to.
* @throws Exception on errors while closing the client.
* @throws IOException on Input/Output errors.
*/
// [START vision_logo_detection_gcs]
- public static void detectLogosGcs(String gcsPath, PrintStream out) throws Exception,
- IOException {
+ public static void detectLogosGcs(String gcsPath, PrintStream out) throws Exception, IOException {
List requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
@@ -657,8 +651,8 @@ public static void detectTextGcs(String gcsPath, PrintStream out) throws Excepti
* @throws IOException on Input/Output errors.
*/
// [START vision_image_property_detection]
- public static void detectProperties(String filePath, PrintStream out) throws Exception,
- IOException {
+ public static void detectProperties(String filePath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));
@@ -704,8 +698,8 @@ public static void detectProperties(String filePath, PrintStream out) throws Exc
* @throws IOException on Input/Output errors.
*/
// [START vision_image_property_detection_gcs]
- public static void detectPropertiesGcs(String gcsPath, PrintStream out) throws Exception,
- IOException {
+ public static void detectPropertiesGcs(String gcsPath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
@@ -749,8 +743,8 @@ public static void detectPropertiesGcs(String gcsPath, PrintStream out) throws E
* @throws IOException on Input/Output errors.
*/
// [START vision_safe_search_detection]
- public static void detectSafeSearch(String filePath, PrintStream out) throws Exception,
- IOException {
+ public static void detectSafeSearch(String filePath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));
@@ -786,8 +780,8 @@ public static void detectSafeSearch(String filePath, PrintStream out) throws Exc
// [END vision_safe_search_detection]
/**
- * Detects whether the specified image on Google Cloud Storage has features you would want
- * to moderate.
+ * Detects whether the specified image on Google Cloud Storage has features you would want to
+ * moderate.
*
* @param gcsPath The path to the remote file on Google Cloud Storage to detect safe-search on.
* @param out A {@link PrintStream} to write the results to.
@@ -795,8 +789,8 @@ public static void detectSafeSearch(String filePath, PrintStream out) throws Exc
* @throws IOException on Input/Output errors.
*/
// [START vision_safe_search_detection_gcs]
- public static void detectSafeSearchGcs(String gcsPath, PrintStream out) throws Exception,
- IOException {
+ public static void detectSafeSearchGcs(String gcsPath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
@@ -839,8 +833,8 @@ public static void detectSafeSearchGcs(String gcsPath, PrintStream out) throws E
* @throws Exception on errors while closing the client.
* @throws IOException on Input/Output errors.
*/
- public static void detectWebDetections(String filePath, PrintStream out) throws Exception,
- IOException {
+ public static void detectWebDetections(String filePath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));
@@ -868,8 +862,8 @@ public static void detectWebDetections(String filePath, PrintStream out) throws
out.println("Entity:Id:Score");
out.println("===============");
for (WebEntity entity : annotation.getWebEntitiesList()) {
- out.println(entity.getDescription() + " : " + entity.getEntityId() + " : "
- + entity.getScore());
+ out.println(
+ entity.getDescription() + " : " + entity.getEntityId() + " : " + entity.getScore());
}
for (WebLabel label : annotation.getBestGuessLabelsList()) {
out.format("\nBest guess label: %s", label.getLabel());
@@ -905,8 +899,8 @@ public static void detectWebDetections(String filePath, PrintStream out) throws
* @throws Exception on errors while closing the client.
* @throws IOException on Input/Output errors.
*/
- public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) throws Exception,
- IOException {
+ public static void detectWebDetectionsGcs(String gcsPath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
@@ -933,8 +927,8 @@ public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) throw
out.println("Entity:Id:Score");
out.println("===============");
for (WebEntity entity : annotation.getWebEntitiesList()) {
- out.println(entity.getDescription() + " : " + entity.getEntityId() + " : "
- + entity.getScore());
+ out.println(
+ entity.getDescription() + " : " + entity.getEntityId() + " : " + entity.getScore());
}
for (WebLabel label : annotation.getBestGuessLabelsList()) {
out.format("\nBest guess label: %s", label.getLabel());
@@ -962,13 +956,14 @@ public static void detectWebDetectionsGcs(String gcsPath, PrintStream out) throw
/**
* Find web entities given a local image.
+ *
* @param filePath The path of the image to detect.
* @param out A {@link PrintStream} to write the results to.
* @throws Exception on errors while closing the client.
* @throws IOException on Input/Output errors.
*/
- public static void detectWebEntities(String filePath, PrintStream out) throws Exception,
- IOException {
+ public static void detectWebEntities(String filePath, PrintStream out)
+ throws Exception, IOException {
// Instantiates a client
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
// Read in the local image
@@ -978,71 +973,87 @@ public static void detectWebEntities(String filePath, PrintStream out) throws Ex
Image image = Image.newBuilder().setContent(contents).build();
// Create the request with the image and the specified feature: web detection
- AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
- .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION))
- .setImage(image)
- .build();
+ AnnotateImageRequest request =
+ AnnotateImageRequest.newBuilder()
+ .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION))
+ .setImage(image)
+ .build();
// Perform the request
BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request));
// Display the results
- response.getResponsesList().stream()
- .forEach(r -> r.getWebDetection().getWebEntitiesList().stream()
- .forEach(entity -> {
- out.format("Description: %s\n", entity.getDescription());
- out.format("Score: %f\n", entity.getScore());
- }));
+ response
+ .getResponsesList()
+ .stream()
+ .forEach(
+ r ->
+ r.getWebDetection()
+ .getWebEntitiesList()
+ .stream()
+ .forEach(
+ entity -> {
+ out.format("Description: %s\n", entity.getDescription());
+ out.format("Score: %f\n", entity.getScore());
+ }));
}
}
/**
* Find web entities given the remote image on Google Cloud Storage.
+ *
* @param gcsPath The path to the remote file on Google Cloud Storage to detect web entities.
* @param out A {@link PrintStream} to write the results to.
* @throws Exception on errors while closing the client.
* @throws IOException on Input/Output errors.
*/
- public static void detectWebEntitiesGcs(String gcsPath, PrintStream out) throws Exception,
- IOException {
+ public static void detectWebEntitiesGcs(String gcsPath, PrintStream out)
+ throws Exception, IOException {
// Instantiates a client
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
// Set the image source to the given gs uri
- ImageSource imageSource = ImageSource.newBuilder()
- .setGcsImageUri(gcsPath)
- .build();
+ ImageSource imageSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
// Build the image
Image image = Image.newBuilder().setSource(imageSource).build();
// Create the request with the image and the specified feature: web detection
- AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
- .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION))
- .setImage(image)
- .build();
+ AnnotateImageRequest request =
+ AnnotateImageRequest.newBuilder()
+ .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION))
+ .setImage(image)
+ .build();
// Perform the request
BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request));
// Display the results
- response.getResponsesList().stream()
- .forEach(r -> r.getWebDetection().getWebEntitiesList().stream()
- .forEach(entity -> {
- System.out.format("Description: %s\n", entity.getDescription());
- System.out.format("Score: %f\n", entity.getScore());
- }));
+ response
+ .getResponsesList()
+ .stream()
+ .forEach(
+ r ->
+ r.getWebDetection()
+ .getWebEntitiesList()
+ .stream()
+ .forEach(
+ entity -> {
+ System.out.format("Description: %s\n", entity.getDescription());
+ System.out.format("Score: %f\n", entity.getScore());
+ }));
}
}
// [START vision_web_detection_include_geo]
/**
* Find web entities given a local image.
+ *
* @param filePath The path of the image to detect.
* @param out A {@link PrintStream} to write the results to.
* @throws Exception on errors while closing the client.
* @throws IOException on Input/Output errors.
*/
- public static void detectWebEntitiesIncludeGeoResults(String filePath, PrintStream out) throws
- Exception, IOException {
+ public static void detectWebEntitiesIncludeGeoResults(String filePath, PrintStream out)
+ throws Exception, IOException {
// Instantiates a client
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
// Read in the local image
@@ -1052,32 +1063,38 @@ public static void detectWebEntitiesIncludeGeoResults(String filePath, PrintStre
Image image = Image.newBuilder().setContent(contents).build();
// Enable `IncludeGeoResults`
- WebDetectionParams webDetectionParams = WebDetectionParams.newBuilder()
- .setIncludeGeoResults(true)
- .build();
+ WebDetectionParams webDetectionParams =
+ WebDetectionParams.newBuilder().setIncludeGeoResults(true).build();
// Set the parameters for the image
- ImageContext imageContext = ImageContext.newBuilder()
- .setWebDetectionParams(webDetectionParams)
- .build();
+ ImageContext imageContext =
+ ImageContext.newBuilder().setWebDetectionParams(webDetectionParams).build();
// Create the request with the image, imageContext, and the specified feature: web detection
- AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
- .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION))
- .setImage(image)
- .setImageContext(imageContext)
- .build();
+ AnnotateImageRequest request =
+ AnnotateImageRequest.newBuilder()
+ .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION))
+ .setImage(image)
+ .setImageContext(imageContext)
+ .build();
// Perform the request
BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request));
// Display the results
- response.getResponsesList().stream()
- .forEach(r -> r.getWebDetection().getWebEntitiesList().stream()
- .forEach(entity -> {
- out.format("Description: %s\n", entity.getDescription());
- out.format("Score: %f\n", entity.getScore());
- }));
+ response
+ .getResponsesList()
+ .stream()
+ .forEach(
+ r ->
+ r.getWebDetection()
+ .getWebEntitiesList()
+ .stream()
+ .forEach(
+ entity -> {
+ out.format("Description: %s\n", entity.getDescription());
+ out.format("Score: %f\n", entity.getScore());
+ }));
}
}
// [END vision_web_detection_include_geo]
@@ -1085,50 +1102,55 @@ public static void detectWebEntitiesIncludeGeoResults(String filePath, PrintStre
// [START vision_web_detection_include_geo_gcs]
/**
* Find web entities given the remote image on Google Cloud Storage.
+ *
* @param gcsPath The path to the remote file on Google Cloud Storage to detect web entities with
- * geo results.
+ * geo results.
* @param out A {@link PrintStream} to write the results to.
* @throws Exception on errors while closing the client.
* @throws IOException on Input/Output errors.
*/
- public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath, PrintStream out) throws
- Exception, IOException {
+ public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath, PrintStream out)
+ throws Exception, IOException {
// Instantiates a client
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
// Set the image source to the given gs uri
- ImageSource imageSource = ImageSource.newBuilder()
- .setGcsImageUri(gcsPath)
- .build();
+ ImageSource imageSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
// Build the image
Image image = Image.newBuilder().setSource(imageSource).build();
// Enable `IncludeGeoResults`
- WebDetectionParams webDetectionParams = WebDetectionParams.newBuilder()
- .setIncludeGeoResults(true)
- .build();
+ WebDetectionParams webDetectionParams =
+ WebDetectionParams.newBuilder().setIncludeGeoResults(true).build();
// Set the parameters for the image
- ImageContext imageContext = ImageContext.newBuilder()
- .setWebDetectionParams(webDetectionParams)
- .build();
+ ImageContext imageContext =
+ ImageContext.newBuilder().setWebDetectionParams(webDetectionParams).build();
// Create the request with the image, imageContext, and the specified feature: web detection
- AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
- .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION))
- .setImage(image)
- .setImageContext(imageContext)
- .build();
+ AnnotateImageRequest request =
+ AnnotateImageRequest.newBuilder()
+ .addFeatures(Feature.newBuilder().setType(Type.WEB_DETECTION))
+ .setImage(image)
+ .setImageContext(imageContext)
+ .build();
// Perform the request
BatchAnnotateImagesResponse response = client.batchAnnotateImages(Arrays.asList(request));
// Display the results
- response.getResponsesList().stream()
- .forEach(r -> r.getWebDetection().getWebEntitiesList().stream()
- .forEach(entity -> {
- out.format("Description: %s\n", entity.getDescription());
- out.format("Score: %f\n", entity.getScore());
- }));
+ response
+ .getResponsesList()
+ .stream()
+ .forEach(
+ r ->
+ r.getWebDetection()
+ .getWebEntitiesList()
+ .stream()
+ .forEach(
+ entity -> {
+ out.format("Description: %s\n", entity.getDescription());
+ out.format("Score: %f\n", entity.getScore());
+ }));
}
}
// [END vision_web_detection_include_geo_gcs]
@@ -1142,8 +1164,8 @@ public static void detectWebEntitiesIncludeGeoResultsGcs(String gcsPath, PrintSt
* @throws IOException on Input/Output errors.
*/
// [START vision_crop_hint_detection]
- public static void detectCropHints(String filePath, PrintStream out) throws Exception,
- IOException {
+ public static void detectCropHints(String filePath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));
@@ -1183,8 +1205,8 @@ public static void detectCropHints(String filePath, PrintStream out) throws Exce
* @throws IOException on Input/Output errors.
*/
// [START vision_crop_hint_detection_gcs]
- public static void detectCropHintsGcs(String gcsPath, PrintStream out) throws Exception,
- IOException {
+ public static void detectCropHintsGcs(String gcsPath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
@@ -1223,8 +1245,8 @@ public static void detectCropHintsGcs(String gcsPath, PrintStream out) throws Ex
* @throws IOException on Input/Output errors.
*/
// [START vision_fulltext_detection]
- public static void detectDocumentText(String filePath, PrintStream out) throws Exception,
- IOException {
+ public static void detectDocumentText(String filePath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));
@@ -1248,18 +1270,19 @@ public static void detectDocumentText(String filePath, PrintStream out) throws E
// For full list of available annotations, see http://g.co/cloud/vision/docs
TextAnnotation annotation = res.getFullTextAnnotation();
- for (Page page: annotation.getPagesList()) {
+ for (Page page : annotation.getPagesList()) {
String pageText = "";
for (Block block : page.getBlocksList()) {
String blockText = "";
for (Paragraph para : block.getParagraphsList()) {
String paraText = "";
- for (Word word: para.getWordsList()) {
+ for (Word word : para.getWordsList()) {
String wordText = "";
- for (Symbol symbol: word.getSymbolsList()) {
+ for (Symbol symbol : word.getSymbolsList()) {
wordText = wordText + symbol.getText();
- out.format("Symbol text: %s (confidence: %f)\n", symbol.getText(),
- symbol.getConfidence());
+ out.format(
+ "Symbol text: %s (confidence: %f)\n",
+ symbol.getText(), symbol.getConfidence());
}
out.format("Word text: %s (confidence: %f)\n\n", wordText, word.getConfidence());
paraText = String.format("%s %s", paraText, wordText);
@@ -1288,8 +1311,8 @@ public static void detectDocumentText(String filePath, PrintStream out) throws E
* @throws IOException on Input/Output errors.
*/
// [START vision_fulltext_detection_gcs]
- public static void detectDocumentTextGcs(String gcsPath, PrintStream out) throws Exception,
- IOException {
+ public static void detectDocumentTextGcs(String gcsPath, PrintStream out)
+ throws Exception, IOException {
List requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
@@ -1311,18 +1334,19 @@ public static void detectDocumentTextGcs(String gcsPath, PrintStream out) throws
}
// For full list of available annotations, see http://g.co/cloud/vision/docs
TextAnnotation annotation = res.getFullTextAnnotation();
- for (Page page: annotation.getPagesList()) {
+ for (Page page : annotation.getPagesList()) {
String pageText = "";
for (Block block : page.getBlocksList()) {
String blockText = "";
for (Paragraph para : block.getParagraphsList()) {
String paraText = "";
- for (Word word: para.getWordsList()) {
+ for (Word word : para.getWordsList()) {
String wordText = "";
- for (Symbol symbol: word.getSymbolsList()) {
+ for (Symbol symbol : word.getSymbolsList()) {
wordText = wordText + symbol.getText();
- out.format("Symbol text: %s (confidence: %f)\n", symbol.getText(),
- symbol.getConfidence());
+ out.format(
+ "Symbol text: %s (confidence: %f)\n",
+ symbol.getText(), symbol.getConfidence());
}
out.format("Word text: %s (confidence: %f)\n\n", wordText, word.getConfidence());
paraText = String.format("%s %s", paraText, wordText);
@@ -1347,49 +1371,47 @@ public static void detectDocumentTextGcs(String gcsPath, PrintStream out) throws
* Performs document text OCR with PDF/TIFF as source files on Google Cloud Storage.
*
* @param gcsSourcePath The path to the remote file on Google Cloud Storage to detect document
- * text on.
+ * text on.
* @param gcsDestinationPath The path to the remote file on Google Cloud Storage to store the
- * results on.
+ * results on.
* @throws Exception on errors while closing the client.
*/
- public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinationPath) throws
- Exception {
+ public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinationPath)
+ throws Exception {
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
List requests = new ArrayList<>();
// Set the GCS source path for the remote file.
- GcsSource gcsSource = GcsSource.newBuilder()
- .setUri(gcsSourcePath)
- .build();
+ GcsSource gcsSource = GcsSource.newBuilder().setUri(gcsSourcePath).build();
// Create the configuration with the specified MIME (Multipurpose Internet Mail Extensions)
// types
- InputConfig inputConfig = InputConfig.newBuilder()
- .setMimeType("application/pdf") // Supported MimeTypes: "application/pdf", "image/tiff"
- .setGcsSource(gcsSource)
- .build();
+ InputConfig inputConfig =
+ InputConfig.newBuilder()
+ .setMimeType(
+ "application/pdf") // Supported MimeTypes: "application/pdf", "image/tiff"
+ .setGcsSource(gcsSource)
+ .build();
// Set the GCS destination path for where to save the results.
- GcsDestination gcsDestination = GcsDestination.newBuilder()
- .setUri(gcsDestinationPath)
- .build();
+ GcsDestination gcsDestination =
+ GcsDestination.newBuilder().setUri(gcsDestinationPath).build();
// Create the configuration for the output with the batch size.
// The batch size sets how many pages should be grouped into each json output file.
- OutputConfig outputConfig = OutputConfig.newBuilder()
- .setBatchSize(2)
- .setGcsDestination(gcsDestination)
- .build();
+ OutputConfig outputConfig =
+ OutputConfig.newBuilder().setBatchSize(2).setGcsDestination(gcsDestination).build();
// Select the Feature required by the vision API
Feature feature = Feature.newBuilder().setType(Feature.Type.DOCUMENT_TEXT_DETECTION).build();
// Build the OCR request
- AsyncAnnotateFileRequest request = AsyncAnnotateFileRequest.newBuilder()
- .addFeatures(feature)
- .setInputConfig(inputConfig)
- .setOutputConfig(outputConfig)
- .build();
+ AsyncAnnotateFileRequest request =
+ AsyncAnnotateFileRequest.newBuilder()
+ .addFeatures(feature)
+ .setInputConfig(inputConfig)
+ .setOutputConfig(outputConfig)
+ .build();
requests.add(request);
@@ -1401,8 +1423,8 @@ public static void detectDocumentsGcs(String gcsSourcePath, String gcsDestinatio
// Wait for the request to finish. (The result is not used, since the API saves the result to
// the specified location on GCS.)
- List result = response.get(180, TimeUnit.SECONDS)
- .getResponsesList();
+ List result =
+ response.get(180, TimeUnit.SECONDS).getResponsesList();
// Once the request has completed and the output has been
// written to GCS, we can list all the output files.
diff --git a/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java b/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java
index c7d5bd2ec6f..b88233612d9 100644
--- a/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java
+++ b/vision/cloud-client/src/main/java/com/example/vision/QuickstartSample.java
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-
package com.example.vision;
// [START vision_quickstart]
@@ -52,10 +51,8 @@ public static void main(String... args) throws Exception {
List requests = new ArrayList<>();
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
- AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
- .addFeatures(feat)
- .setImage(img)
- .build();
+ AnnotateImageRequest request =
+ AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
// Performs label detection on the image file
@@ -69,8 +66,9 @@ public static void main(String... args) throws Exception {
}
for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
- annotation.getAllFields().forEach((k, v) ->
- System.out.printf("%s : %s\n", k, v.toString()));
+ annotation
+ .getAllFields()
+ .forEach((k, v) -> System.out.printf("%s : %s\n", k, v.toString()));
}
}
}
diff --git a/vision/cloud-client/src/main/java/com/example/vision/SetEndpoint.java b/vision/cloud-client/src/main/java/com/example/vision/SetEndpoint.java
index a08a0d084ac..22eed6813d4 100644
--- a/vision/cloud-client/src/main/java/com/example/vision/SetEndpoint.java
+++ b/vision/cloud-client/src/main/java/com/example/vision/SetEndpoint.java
@@ -25,7 +25,6 @@
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageAnnotatorSettings;
import com.google.cloud.vision.v1.ImageSource;
-
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
diff --git a/vision/cloud-client/src/test/java/com/example/vision/AsyncBatchAnnotateImagesTest.java b/vision/cloud-client/src/test/java/com/example/vision/AsyncBatchAnnotateImagesTest.java
index b770d3fb57b..8edc89828fb 100644
--- a/vision/cloud-client/src/test/java/com/example/vision/AsyncBatchAnnotateImagesTest.java
+++ b/vision/cloud-client/src/test/java/com/example/vision/AsyncBatchAnnotateImagesTest.java
@@ -23,13 +23,11 @@
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
-
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
@@ -50,8 +48,8 @@ public class AsyncBatchAnnotateImagesTest {
private static void requireEnvVar(String varName) {
assertNotNull(
- System.getenv(varName),
- "Environment variable '%s' is required to perform these tests.".format(varName));
+ System.getenv(varName),
+ "Environment variable '%s' is required to perform these tests.".format(varName));
}
@BeforeClass
@@ -72,7 +70,10 @@ public void tearDown() {
Storage storage = StorageOptions.getDefaultInstance().getService();
- Page blobs = storage.list(PROJECT_ID, Storage.BlobListOption.currentDirectory(),
+ Page blobs =
+ storage.list(
+ PROJECT_ID,
+ Storage.BlobListOption.currentDirectory(),
Storage.BlobListOption.prefix(PREFIX));
for (Blob blob : blobs.iterateAll()) {
blob.delete();
diff --git a/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesGcsTest.java b/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesGcsTest.java
index ff73d717469..5f1c1e043a3 100644
--- a/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesGcsTest.java
+++ b/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesGcsTest.java
@@ -21,7 +21,6 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesTest.java b/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesTest.java
index e6dfc9dee0b..621aba76798 100644
--- a/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesTest.java
+++ b/vision/cloud-client/src/test/java/com/example/vision/BatchAnnotateFilesTest.java
@@ -21,7 +21,6 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/vision/cloud-client/src/test/java/com/example/vision/DetectIT.java b/vision/cloud-client/src/test/java/com/example/vision/DetectIT.java
index 4ec885e99b9..ad3c19d85a5 100644
--- a/vision/cloud-client/src/test/java/com/example/vision/DetectIT.java
+++ b/vision/cloud-client/src/test/java/com/example/vision/DetectIT.java
@@ -24,11 +24,9 @@
import com.google.cloud.storage.Storage.BlobListOption;
import com.google.cloud.storage.StorageOptions;
import java.io.ByteArrayOutputStream;
-import java.io.IOException;
import java.io.PrintStream;
import java.util.UUID;
import java.util.regex.Pattern;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -61,7 +59,7 @@ public void tearDown() {
@Test
public void testFaces() throws Exception {
// Act
- String[] args = { "faces", "./resources/face_no_surprise.jpg" };
+ String[] args = {"faces", "./resources/face_no_surprise.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -74,7 +72,7 @@ public void testFaces() throws Exception {
@Test
public void testFacesGcs() throws Exception {
// Act
- String[] args = { "faces", "gs://" + ASSET_BUCKET + "/vision/face/face_no_surprise.jpg" };
+ String[] args = {"faces", "gs://" + ASSET_BUCKET + "/vision/face/face_no_surprise.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -87,7 +85,7 @@ public void testFacesGcs() throws Exception {
@Test
public void testLabels() throws Exception {
// Act
- String[] args = { "labels", "./resources/wakeupcat.jpg" };
+ String[] args = {"labels", "./resources/wakeupcat.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -98,7 +96,7 @@ public void testLabels() throws Exception {
@Test
public void testLabelsGcs() throws Exception {
// Act
- String[] args = { "labels", "gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg" };
+ String[] args = {"labels", "gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -109,7 +107,7 @@ public void testLabelsGcs() throws Exception {
@Test
public void testLandmarks() throws Exception {
// Act
- String[] args = { "landmarks", "./resources/landmark.jpg" };
+ String[] args = {"landmarks", "./resources/landmark.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -120,7 +118,7 @@ public void testLandmarks() throws Exception {
@Test
public void testLandmarksGcs() throws Exception {
// Act
- String[] args = { "landmarks", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg" };
+ String[] args = {"landmarks", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -131,8 +129,9 @@ public void testLandmarksGcs() throws Exception {
@Test
public void testLandmarksUrl() throws Exception {
// Act
- String uri = "https://storage-download.googleapis.com/" + ASSET_BUCKET + "/vision/landmark/pofa.jpg";
- String[] args = { "landmarks", uri };
+ String uri =
+ "https://storage-download.googleapis.com/" + ASSET_BUCKET + "/vision/landmark/pofa.jpg";
+ String[] args = {"landmarks", uri};
Detect.argsHelper(args, out);
// Assert
@@ -143,7 +142,7 @@ public void testLandmarksUrl() throws Exception {
@Test
public void testLogos() throws Exception {
// Act
- String[] args = { "logos", "./resources/logos.png" };
+ String[] args = {"logos", "./resources/logos.png"};
Detect.argsHelper(args, out);
// Assert
@@ -154,7 +153,7 @@ public void testLogos() throws Exception {
@Test
public void testLogosGcs() throws Exception {
// Act
- String[] args = { "logos", "gs://" + ASSET_BUCKET + "/vision/logo/logo_google.png" };
+ String[] args = {"logos", "gs://" + ASSET_BUCKET + "/vision/logo/logo_google.png"};
Detect.argsHelper(args, out);
// Assert
@@ -165,7 +164,7 @@ public void testLogosGcs() throws Exception {
@Test
public void testText() throws Exception {
// Act
- String[] args = { "text", "./resources/text.jpg" };
+ String[] args = {"text", "./resources/text.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -176,7 +175,7 @@ public void testText() throws Exception {
@Test
public void testTextGcs() throws Exception {
// Act
- String[] args = { "text", "gs://" + ASSET_BUCKET + "/vision/text/screen.jpg" };
+ String[] args = {"text", "gs://" + ASSET_BUCKET + "/vision/text/screen.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -187,7 +186,7 @@ public void testTextGcs() throws Exception {
@Test
public void testSafeSearch() throws Exception {
// Act
- String[] args = { "safe-search", "./resources/wakeupcat.jpg" };
+ String[] args = {"safe-search", "./resources/wakeupcat.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -199,7 +198,7 @@ public void testSafeSearch() throws Exception {
@Test
public void testSafeSearchGcs() throws Exception {
// Act
- String[] args = { "safe-search", "gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg" };
+ String[] args = {"safe-search", "gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -211,7 +210,7 @@ public void testSafeSearchGcs() throws Exception {
@Test
public void testProperties() throws Exception {
// Act
- String[] args = { "properties", "./resources/landmark.jpg" };
+ String[] args = {"properties", "./resources/landmark.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -225,7 +224,7 @@ public void testProperties() throws Exception {
@Test
public void testPropertiesGcs() throws Exception {
// Act
- String[] args = { "properties", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg" };
+ String[] args = {"properties", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -239,7 +238,7 @@ public void testPropertiesGcs() throws Exception {
@Test
public void detectWebAnnotations() throws Exception {
// Act
- String[] args = { "web", "./resources/landmark.jpg" };
+ String[] args = {"web", "./resources/landmark.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -251,7 +250,7 @@ public void detectWebAnnotations() throws Exception {
@Test
public void detectWebAnnotationsGcs() throws Exception {
// Act
- String[] args = { "web", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg" };
+ String[] args = {"web", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -263,7 +262,7 @@ public void detectWebAnnotationsGcs() throws Exception {
@Test
public void testDetectWebEntities() throws Exception {
// Act
- String[] args = { "web-entities", "./resources/city.jpg" };
+ String[] args = {"web-entities", "./resources/city.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -274,7 +273,7 @@ public void testDetectWebEntities() throws Exception {
@Test
public void testDetectWebEntitiesGcs() throws Exception {
// Act
- String[] args = { "web-entities", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg" };
+ String[] args = {"web-entities", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"};
Detect.argsHelper(args, out);
String got = bout.toString().toLowerCase();
@@ -284,7 +283,7 @@ public void testDetectWebEntitiesGcs() throws Exception {
@Test
public void testDetectWebEntitiesIncludeGeoResults() throws Exception {
// Act
- String[] args = { "web-entities-include-geo", "./resources/city.jpg" };
+ String[] args = {"web-entities-include-geo", "./resources/city.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -296,8 +295,9 @@ public void testDetectWebEntitiesIncludeGeoResults() throws Exception {
@Test
public void testDetectWebEntitiesIncludeGeoResultsGcs() throws Exception {
// Act
- String[] args = { "web-entities-include-geo",
- "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg" };
+ String[] args = {
+ "web-entities-include-geo", "gs://" + ASSET_BUCKET + "/vision/landmark/pofa.jpg"
+ };
Detect.argsHelper(args, out);
String got = bout.toString().toLowerCase();
@@ -307,7 +307,7 @@ public void testDetectWebEntitiesIncludeGeoResultsGcs() throws Exception {
@Test
public void testCropHints() throws Exception {
// Act
- String[] args = { "crop", "./resources/wakeupcat.jpg" };
+ String[] args = {"crop", "./resources/wakeupcat.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -320,7 +320,7 @@ public void testCropHints() throws Exception {
@Test
public void testCropHintsGcs() throws Exception {
// Act
- String[] args = { "crop", "gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg" };
+ String[] args = {"crop", "gs://" + ASSET_BUCKET + "/vision/label/wakeupcat.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -333,7 +333,7 @@ public void testCropHintsGcs() throws Exception {
@Test
public void testDocumentText() throws Exception {
// Act
- String[] args = { "fulltext", "./resources/text.jpg" };
+ String[] args = {"fulltext", "./resources/text.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -346,7 +346,7 @@ public void testDocumentText() throws Exception {
@Test
public void testDocumentTextGcs() throws Exception {
// Act
- String[] args = { "fulltext", "gs://" + ASSET_BUCKET + "/vision/text/screen.jpg" };
+ String[] args = {"fulltext", "gs://" + ASSET_BUCKET + "/vision/text/screen.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -359,8 +359,11 @@ public void testDocumentTextGcs() throws Exception {
@Test
public void testDetectDocumentsGcs() throws Exception {
// Act
- String[] args = { "ocr", "gs://" + ASSET_BUCKET + "/vision/document/custom_0773375000.pdf",
- "gs://" + OUTPUT_BUCKET + "/" + OUTPUT_PREFIX + "/" };
+ String[] args = {
+ "ocr",
+ "gs://" + ASSET_BUCKET + "/vision/document/custom_0773375000.pdf",
+ "gs://" + OUTPUT_BUCKET + "/" + OUTPUT_PREFIX + "/"
+ };
Detect.argsHelper(args, out);
// Assert
@@ -370,8 +373,11 @@ public void testDetectDocumentsGcs() throws Exception {
Storage storage = StorageOptions.getDefaultInstance().getService();
- Page blobs = storage.list(OUTPUT_BUCKET, BlobListOption.currentDirectory(),
- BlobListOption.prefix(OUTPUT_PREFIX + "/"));
+ Page blobs =
+ storage.list(
+ OUTPUT_BUCKET,
+ BlobListOption.currentDirectory(),
+ BlobListOption.prefix(OUTPUT_PREFIX + "/"));
for (Blob blob : blobs.iterateAll()) {
blob.delete();
}
@@ -380,7 +386,7 @@ public void testDetectDocumentsGcs() throws Exception {
@Test
public void testDetectLocalizedObjects() throws Exception {
// Act
- String[] args = { "object-localization", "./resources/puppies.jpg" };
+ String[] args = {"object-localization", "./resources/puppies.jpg"};
Detect.argsHelper(args, out);
// Assert
@@ -391,8 +397,9 @@ public void testDetectLocalizedObjects() throws Exception {
@Test
public void testDetectLocalizedObjectsGcs() throws Exception {
// Act
- String[] args = { "object-localization",
- "gs://cloud-samples-data/vision/object_localization/puppies.jpg" };
+ String[] args = {
+ "object-localization", "gs://cloud-samples-data/vision/object_localization/puppies.jpg"
+ };
Detect.argsHelper(args, out);
// Assert
diff --git a/vision/cloud-client/src/test/java/com/example/vision/SetEndpointIT.java b/vision/cloud-client/src/test/java/com/example/vision/SetEndpointIT.java
index 5aac338ae51..9b27ea7d7de 100644
--- a/vision/cloud-client/src/test/java/com/example/vision/SetEndpointIT.java
+++ b/vision/cloud-client/src/test/java/com/example/vision/SetEndpointIT.java
@@ -21,7 +21,6 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/vision/face-detection/pom.xml b/vision/face-detection/pom.xml
index e13f43fcbaf..537446fa70a 100644
--- a/vision/face-detection/pom.xml
+++ b/vision/face-detection/pom.xml
@@ -28,7 +28,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/vision/face-detection/src/main/java/com/google/cloud/vision/samples/facedetect/FaceDetectApp.java b/vision/face-detection/src/main/java/com/google/cloud/vision/samples/facedetect/FaceDetectApp.java
index 3ebf525bf3a..d3bc08e3f1c 100644
--- a/vision/face-detection/src/main/java/com/google/cloud/vision/samples/facedetect/FaceDetectApp.java
+++ b/vision/face-detection/src/main/java/com/google/cloud/vision/samples/facedetect/FaceDetectApp.java
@@ -44,11 +44,10 @@
import java.security.GeneralSecurityException;
import java.util.List;
import javax.imageio.ImageIO;
+
// [END vision_face_detection_tutorial_imports]
-/**
- * A sample application that uses the Vision API to detect faces in an image.
- */
+/** A sample application that uses the Vision API to detect faces in an image. */
@SuppressWarnings("serial")
public class FaceDetectApp {
/**
@@ -60,15 +59,12 @@ public class FaceDetectApp {
private static final int MAX_RESULTS = 4;
// [START vision_face_detection_tutorial_run_application]
- /**
- * Annotates an image using the Vision API.
- */
+ /** Annotates an image using the Vision API. */
public static void main(String[] args) throws IOException, GeneralSecurityException {
if (args.length != 2) {
System.err.println("Usage:");
System.err.printf(
- "\tjava %s inputImagePath outputImagePath\n",
- FaceDetectApp.class.getCanonicalName());
+ "\tjava %s inputImagePath outputImagePath\n", FaceDetectApp.class.getCanonicalName());
System.exit(1);
}
Path inputPath = Paths.get(args[0]);
@@ -87,44 +83,38 @@ public static void main(String[] args) throws IOException, GeneralSecurityExcept
// [END vision_face_detection_tutorial_run_application]
// [START vision_face_detection_tutorial_client]
- /**
- * Connects to the Vision API using Application Default Credentials.
- */
+ /** Connects to the Vision API using Application Default Credentials. */
public static Vision getVisionService() throws IOException, GeneralSecurityException {
GoogleCredential credential =
GoogleCredential.getApplicationDefault().createScoped(VisionScopes.all());
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
return new Vision.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, credential)
- .setApplicationName(APPLICATION_NAME)
- .build();
+ .setApplicationName(APPLICATION_NAME)
+ .build();
}
// [END vision_face_detection_tutorial_client]
private final Vision vision;
- /**
- * Constructs a {@link FaceDetectApp} which connects to the Vision API.
- */
+ /** Constructs a {@link FaceDetectApp} which connects to the Vision API. */
public FaceDetectApp(Vision vision) {
this.vision = vision;
}
// [START vision_face_detection_tutorial_send_request]
- /**
- * Gets up to {@code maxResults} faces for an image stored at {@code path}.
- */
+ /** Gets up to {@code maxResults} faces for an image stored at {@code path}. */
public List detectFaces(Path path, int maxResults) throws IOException {
byte[] data = Files.readAllBytes(path);
AnnotateImageRequest request =
new AnnotateImageRequest()
.setImage(new Image().encodeContent(data))
- .setFeatures(ImmutableList.of(
- new Feature()
- .setType("FACE_DETECTION")
- .setMaxResults(maxResults)));
+ .setFeatures(
+ ImmutableList.of(
+ new Feature().setType("FACE_DETECTION").setMaxResults(maxResults)));
Vision.Images.Annotate annotate =
- vision.images()
+ vision
+ .images()
.annotate(new BatchAnnotateImagesRequest().setRequests(ImmutableList.of(request)));
// Due to a bug: requests to Vision API containing large images fail when GZipped.
annotate.setDisableGZipContent(true);
@@ -143,9 +133,7 @@ public List detectFaces(Path path, int maxResults) throws IOExce
// [END vision_face_detection_tutorial_send_request]
// [START vision_face_detection_tutorial_process_response]
- /**
- * Reads image {@code inputPath} and writes {@code outputPath} with {@code faces} outlined.
- */
+ /** Reads image {@code inputPath} and writes {@code outputPath} with {@code faces} outlined. */
private static void writeWithFaces(Path inputPath, Path outputPath, List faces)
throws IOException {
BufferedImage img = ImageIO.read(inputPath.toFile());
@@ -153,18 +141,14 @@ private static void writeWithFaces(Path inputPath, Path outputPath, List faces) {
for (FaceAnnotation face : faces) {
annotateWithFace(img, face);
}
}
- /**
- * Annotates an image {@code img} with a polygon defined by {@code face}.
- */
+ /** Annotates an image {@code img} with a polygon defined by {@code face}. */
private static void annotateWithFace(BufferedImage img, FaceAnnotation face) {
Graphics2D gfx = img.createGraphics();
Polygon poly = new Polygon();
diff --git a/vision/face-detection/src/test/java/com/google/cloud/vision/samples/facedetect/FaceDetectAppIT.java b/vision/face-detection/src/test/java/com/google/cloud/vision/samples/facedetect/FaceDetectAppIT.java
index 6e7623e2fb9..ddabf90ee8e 100644
--- a/vision/face-detection/src/test/java/com/google/cloud/vision/samples/facedetect/FaceDetectAppIT.java
+++ b/vision/face-detection/src/test/java/com/google/cloud/vision/samples/facedetect/FaceDetectAppIT.java
@@ -29,9 +29,7 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Integration (system) tests for {@link FaceDetectApp}.
- */
+/** Integration (system) tests for {@link FaceDetectApp}. */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class FaceDetectAppIT {
@@ -39,20 +37,21 @@ public class FaceDetectAppIT {
private FaceDetectApp appUnderTest;
- @Before public void setUp() throws Exception {
+ @Before
+ public void setUp() throws Exception {
appUnderTest = new FaceDetectApp(FaceDetectApp.getVisionService());
}
- @Test public void detectFaces_withFace_returnsAtLeastOneFace() throws Exception {
- List faces =
- appUnderTest.detectFaces(Paths.get("data/face.jpg"), MAX_RESULTS);
+ @Test
+ public void detectFaces_withFace_returnsAtLeastOneFace() throws Exception {
+ List faces = appUnderTest.detectFaces(Paths.get("data/face.jpg"), MAX_RESULTS);
assertWithMessage("face.jpg faces").that(faces).isNotEmpty();
- assertThat(faces.get(0).getFdBoundingPoly().getVertices())
- .isNotEmpty();
+ assertThat(faces.get(0).getFdBoundingPoly().getVertices()).isNotEmpty();
}
- @Test public void detectFaces_badImage_throwsException() throws Exception {
+ @Test
+ public void detectFaces_badImage_throwsException() throws Exception {
try {
appUnderTest.detectFaces(Paths.get("data/bad.txt"), MAX_RESULTS);
fail("Expected IOException");
diff --git a/vision/face-detection/src/test/java/com/google/cloud/vision/samples/facedetect/FaceDetectAppTest.java b/vision/face-detection/src/test/java/com/google/cloud/vision/samples/facedetect/FaceDetectAppTest.java
index dbf2217d093..fbe91fc289c 100644
--- a/vision/face-detection/src/test/java/com/google/cloud/vision/samples/facedetect/FaceDetectAppTest.java
+++ b/vision/face-detection/src/test/java/com/google/cloud/vision/samples/facedetect/FaceDetectAppTest.java
@@ -27,28 +27,31 @@
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
-/**
- * Unit tests for {@link FaceDetectApp}.
- */
+/** Unit tests for {@link FaceDetectApp}. */
@RunWith(JUnit4.class)
public class FaceDetectAppTest {
- @Test public void annotateWithFaces_manyFaces_outlinesFaces() throws Exception {
+ @Test
+ public void annotateWithFaces_manyFaces_outlinesFaces() throws Exception {
// Arrange
ImmutableList faces =
ImmutableList.of(
new FaceAnnotation()
.setFdBoundingPoly(
- new BoundingPoly().setVertices(ImmutableList.of(
- new Vertex().setX(10).setY(5),
- new Vertex().setX(20).setY(5),
- new Vertex().setX(20).setY(25),
- new Vertex().setX(10).setY(25)))),
+ new BoundingPoly()
+ .setVertices(
+ ImmutableList.of(
+ new Vertex().setX(10).setY(5),
+ new Vertex().setX(20).setY(5),
+ new Vertex().setX(20).setY(25),
+ new Vertex().setX(10).setY(25)))),
new FaceAnnotation()
.setFdBoundingPoly(
- new BoundingPoly().setVertices(ImmutableList.of(
- new Vertex().setX(60).setY(50),
- new Vertex().setX(70).setY(60),
- new Vertex().setX(50).setY(60)))));
+ new BoundingPoly()
+ .setVertices(
+ ImmutableList.of(
+ new Vertex().setX(60).setY(50),
+ new Vertex().setX(70).setY(60),
+ new Vertex().setX(50).setY(60)))));
BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
// Act
diff --git a/vision/product-search/cloud-client/pom.xml b/vision/product-search/cloud-client/pom.xml
index d31491878ef..5f2074467d7 100644
--- a/vision/product-search/cloud-client/pom.xml
+++ b/vision/product-search/cloud-client/pom.xml
@@ -26,7 +26,7 @@
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
diff --git a/vision/product-search/cloud-client/src/main/java/com/example/vision/ImportProductSets.java b/vision/product-search/cloud-client/src/main/java/com/example/vision/ImportProductSets.java
index 76b8e172d95..53259474ebd 100644
--- a/vision/product-search/cloud-client/src/main/java/com/example/vision/ImportProductSets.java
+++ b/vision/product-search/cloud-client/src/main/java/com/example/vision/ImportProductSets.java
@@ -28,7 +28,6 @@
// [END vision_product_search_tutorial_import]
import java.io.PrintStream;
import javax.swing.JPanel;
-
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
diff --git a/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductInProductSetManagement.java b/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductInProductSetManagement.java
index cfd21998ec8..6173df12e8c 100644
--- a/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductInProductSetManagement.java
+++ b/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductInProductSetManagement.java
@@ -19,10 +19,8 @@
import com.google.cloud.vision.v1.Product;
import com.google.cloud.vision.v1.ProductName;
import com.google.cloud.vision.v1.ProductSearchClient;
-
import java.io.IOException;
import java.io.PrintStream;
-
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
@@ -172,7 +170,7 @@ public static void argsHelper(String[] args, PrintStream out) throws Exception {
}
if (ns.get("command").equals("remove_product_from_product_set")) {
removeProductFromProductSet(
- projectId, computeRegion, ns.getString("productId"), ns.getString("productSetId"));
+ projectId, computeRegion, ns.getString("productId"), ns.getString("productSetId"));
}
} catch (ArgumentParserException e) {
diff --git a/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductManagement.java b/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductManagement.java
index ce3cc9bb6f7..94fb411f42d 100644
--- a/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductManagement.java
+++ b/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductManagement.java
@@ -20,10 +20,8 @@
import com.google.cloud.vision.v1.Product.KeyValue;
import com.google.cloud.vision.v1.ProductSearchClient;
import com.google.protobuf.FieldMask;
-
import java.io.IOException;
import java.io.PrintStream;
-
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
diff --git a/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductSearch.java b/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductSearch.java
index 41a383161a6..9cd4bca0e67 100644
--- a/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductSearch.java
+++ b/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductSearch.java
@@ -29,14 +29,12 @@
import com.google.cloud.vision.v1.ProductSearchResults.Result;
import com.google.cloud.vision.v1.ProductSetName;
import com.google.protobuf.ByteString;
-
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
-
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
@@ -48,10 +46,9 @@
* This application demonstrates how to perform similar product search operation in Cloud Vision
* Product Search.
*
- * For more information, see the tutorial page at
+ * For more information, see the tutorial page at
* https://cloud.google.com/vision/product-search/docs/
*/
-
public class ProductSearch {
// [START vision_product_search_get_similar_products]
diff --git a/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductSetManagement.java b/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductSetManagement.java
index f54b5ae8fff..a6aa33f0d7e 100644
--- a/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductSetManagement.java
+++ b/vision/product-search/cloud-client/src/main/java/com/example/vision/ProductSetManagement.java
@@ -19,10 +19,8 @@
import com.google.cloud.vision.v1.CreateProductSetRequest;
import com.google.cloud.vision.v1.ProductSearchClient;
import com.google.cloud.vision.v1.ProductSet;
-
import java.io.IOException;
import java.io.PrintStream;
-
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
diff --git a/vision/product-search/cloud-client/src/main/java/com/example/vision/ReferenceImageManagement.java b/vision/product-search/cloud-client/src/main/java/com/example/vision/ReferenceImageManagement.java
index 7598950d5bb..9260d64aeba 100644
--- a/vision/product-search/cloud-client/src/main/java/com/example/vision/ReferenceImageManagement.java
+++ b/vision/product-search/cloud-client/src/main/java/com/example/vision/ReferenceImageManagement.java
@@ -16,14 +16,11 @@
package com.example.vision;
-import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageName;
import com.google.cloud.vision.v1.ProductSearchClient;
import com.google.cloud.vision.v1.ReferenceImage;
-
import java.io.IOException;
import java.io.PrintStream;
-
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
@@ -125,8 +122,7 @@ public static void getReferenceImage(
// Get the full path of the reference image.
String formattedName =
- ImageName.format(
- projectId, computeRegion, productId, referenceImageId);
+ ImageName.format(projectId, computeRegion, productId, referenceImageId);
// Get complete detail of the reference image.
ReferenceImage image = client.getReferenceImage(formattedName);
// Display the reference image information.
@@ -160,8 +156,7 @@ public static void deleteReferenceImage(
// Get the full path of the reference image.
String formattedName =
- ImageName.format(
- projectId, computeRegion, productId, referenceImageId);
+ ImageName.format(projectId, computeRegion, productId, referenceImageId);
// Delete the reference image.
client.deleteReferenceImage(formattedName);
System.out.println("Reference image deleted from product.");
diff --git a/vision/product-search/cloud-client/src/main/java/com/example/vision/snippets/PurgeProducts.java b/vision/product-search/cloud-client/src/main/java/com/example/vision/snippets/PurgeProducts.java
index c01c41ec75c..dc0fd2d3c86 100644
--- a/vision/product-search/cloud-client/src/main/java/com/example/vision/snippets/PurgeProducts.java
+++ b/vision/product-search/cloud-client/src/main/java/com/example/vision/snippets/PurgeProducts.java
@@ -21,15 +21,12 @@
import com.google.cloud.vision.v1.LocationName;
import com.google.cloud.vision.v1.ProductSearchClient;
import com.google.cloud.vision.v1.PurgeProductsRequest;
-
import java.util.concurrent.TimeUnit;
-
public class PurgeProducts {
// Delete the product and all its reference images.
- public static void purgeOrphanProducts(String projectId, String computeRegion)
- throws Exception {
+ public static void purgeOrphanProducts(String projectId, String computeRegion) throws Exception {
// String projectId = "YOUR_PROJECT_ID";
// String computeRegion = "us-central1";
@@ -39,8 +36,8 @@ public static void purgeOrphanProducts(String projectId, String computeRegion)
String parent = LocationName.format(projectId, computeRegion);
// The purge operation is async.
- PurgeProductsRequest request = PurgeProductsRequest
- .newBuilder()
+ PurgeProductsRequest request =
+ PurgeProductsRequest.newBuilder()
.setDeleteOrphanProducts(true)
// The operation is irreversible and removes multiple products.
// The user is required to pass in force=True to actually perform the
@@ -57,4 +54,4 @@ public static void purgeOrphanProducts(String projectId, String computeRegion)
}
}
}
-// [END vision_product_search_purge_orphan_products]
\ No newline at end of file
+// [END vision_product_search_purge_orphan_products]
diff --git a/vision/product-search/cloud-client/src/main/java/com/example/vision/snippets/PurgeProductsInProductSet.java b/vision/product-search/cloud-client/src/main/java/com/example/vision/snippets/PurgeProductsInProductSet.java
index c632768ec80..8ed6906c2d3 100644
--- a/vision/product-search/cloud-client/src/main/java/com/example/vision/snippets/PurgeProductsInProductSet.java
+++ b/vision/product-search/cloud-client/src/main/java/com/example/vision/snippets/PurgeProductsInProductSet.java
@@ -24,15 +24,13 @@
import com.google.cloud.vision.v1.ProductSetPurgeConfig;
import com.google.cloud.vision.v1.PurgeProductsRequest;
import com.google.protobuf.Empty;
-
import java.util.concurrent.TimeUnit;
public class PurgeProductsInProductSet {
// Delete all products in a product set.
public static void purgeProductsInProductSet(
- String projectId, String location, String productSetId)
- throws Exception {
+ String projectId, String location, String productSetId) throws Exception {
// String projectId = "YOUR_PROJECT_ID";
// String location = "us-central1";
@@ -42,13 +40,11 @@ public static void purgeProductsInProductSet(
try (ProductSearchClient client = ProductSearchClient.create()) {
String parent = LocationName.format(projectId, location);
- ProductSetPurgeConfig productSetPurgeConfig = ProductSetPurgeConfig
- .newBuilder()
- .setProductSetId(productSetId)
- .build();
+ ProductSetPurgeConfig productSetPurgeConfig =
+ ProductSetPurgeConfig.newBuilder().setProductSetId(productSetId).build();
- PurgeProductsRequest request = PurgeProductsRequest
- .newBuilder()
+ PurgeProductsRequest request =
+ PurgeProductsRequest.newBuilder()
.setParent(parent)
.setProductSetPurgeConfig(productSetPurgeConfig)
// The operation is irreversible and removes multiple products.
diff --git a/vision/product-search/cloud-client/src/test/java/com/example/vision/ImportProductSetsIT.java b/vision/product-search/cloud-client/src/test/java/com/example/vision/ImportProductSetsIT.java
index 4b810283acc..1836c3bd067 100644
--- a/vision/product-search/cloud-client/src/test/java/com/example/vision/ImportProductSetsIT.java
+++ b/vision/product-search/cloud-client/src/test/java/com/example/vision/ImportProductSetsIT.java
@@ -23,12 +23,10 @@
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.UUID;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
diff --git a/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductInProductSetManagementIT.java b/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductInProductSetManagementIT.java
index b3a3185f1f1..350a75b1c82 100644
--- a/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductInProductSetManagementIT.java
+++ b/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductInProductSetManagementIT.java
@@ -22,7 +22,6 @@
import java.io.IOException;
import java.io.PrintStream;
import java.util.UUID;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -36,11 +35,11 @@ public class ProductInProductSetManagementIT {
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
private static final String COMPUTE_REGION = "us-west1";
private static final String PRODUCT_SET_DISPLAY_NAME =
- String.format("test_%s", UUID.randomUUID().toString());
+ String.format("test_%s", UUID.randomUUID().toString());
private static final String PRODUCT_SET_ID =
- String.format("test_%s", UUID.randomUUID().toString());
+ String.format("test_%s", UUID.randomUUID().toString());
private static final String PRODUCT_DISPLAY_NAME =
- String.format("test_%s", UUID.randomUUID().toString());
+ String.format("test_%s", UUID.randomUUID().toString());
private static final String PRODUCT_CATEGORY = "apparel";
private static final String PRODUCT_ID = String.format("test_%s", UUID.randomUUID().toString());
private ByteArrayOutputStream bout;
diff --git a/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductManagementIT.java b/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductManagementIT.java
index 89c31e11e9b..b0f07e392f9 100644
--- a/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductManagementIT.java
+++ b/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductManagementIT.java
@@ -22,7 +22,6 @@
import java.io.IOException;
import java.io.PrintStream;
import java.util.UUID;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -36,7 +35,7 @@ public class ProductManagementIT {
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
private static final String COMPUTE_REGION = "us-west1";
private static final String PRODUCT_DISPLAY_NAME =
- String.format("test_%s", UUID.randomUUID().toString());
+ String.format("test_%s", UUID.randomUUID().toString());
private static final String PRODUCT_CATEGORY = "homegoods";
private static final String PRODUCT_ID = String.format("test_%s", UUID.randomUUID().toString());
private static final String KEY = String.format("test_%s", UUID.randomUUID().toString());
diff --git a/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductSearchIT.java b/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductSearchIT.java
index 1fa8792e0ac..aefc362dc46 100644
--- a/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductSearchIT.java
+++ b/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductSearchIT.java
@@ -20,8 +20,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import java.util.UUID;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -29,9 +27,9 @@
import org.junit.runners.JUnit4;
/**
- * Integration (system) tests for {@link ProductSearch}.Tests rely on pre-created product set
- * that has been indexed.
- **/
+ * Integration (system) tests for {@link ProductSearch}.Tests rely on pre-created product set that
+ * has been indexed.
+ */
@RunWith(JUnit4.class)
@SuppressWarnings("checkstyle:abbreviationaswordinname")
public class ProductSearchIT {
diff --git a/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductSetManagementIT.java b/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductSetManagementIT.java
index 445df96938c..12d7427c572 100644
--- a/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductSetManagementIT.java
+++ b/vision/product-search/cloud-client/src/test/java/com/example/vision/ProductSetManagementIT.java
@@ -21,7 +21,6 @@
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.UUID;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -35,9 +34,9 @@ public class ProductSetManagementIT {
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
private static final String COMPUTE_REGION = "us-west1";
private static final String PRODUCT_SET_ID =
- String.format("test_%s", UUID.randomUUID().toString());
+ String.format("test_%s", UUID.randomUUID().toString());
private static final String PRODUCT_SET_DISPLAY_NAME =
- String.format("test_%s", UUID.randomUUID().toString());
+ String.format("test_%s", UUID.randomUUID().toString());
private ByteArrayOutputStream bout;
private PrintStream out;
@@ -56,7 +55,7 @@ public void tearDown() {
@Test
public void testCreateDeleteProductSet() throws Exception {
ProductSetManagement.createProductSet(
- PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID, PRODUCT_SET_DISPLAY_NAME);
+ PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID, PRODUCT_SET_DISPLAY_NAME);
String got = bout.toString();
assertThat(got).contains(PRODUCT_SET_ID);
diff --git a/vision/product-search/cloud-client/src/test/java/com/example/vision/ReferenceImageManagementIT.java b/vision/product-search/cloud-client/src/test/java/com/example/vision/ReferenceImageManagementIT.java
index 9f49bb29491..4054ce6ca00 100644
--- a/vision/product-search/cloud-client/src/test/java/com/example/vision/ReferenceImageManagementIT.java
+++ b/vision/product-search/cloud-client/src/test/java/com/example/vision/ReferenceImageManagementIT.java
@@ -22,7 +22,6 @@
import java.io.IOException;
import java.io.PrintStream;
import java.util.UUID;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -36,13 +35,12 @@ public class ReferenceImageManagementIT {
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
private static final String COMPUTE_REGION = "us-west1";
private static final String PRODUCT_DISPLAY_NAME =
- String.format("test_%s", UUID.randomUUID().toString());
+ String.format("test_%s", UUID.randomUUID().toString());
private static final String PRODUCT_CATEGORY = "apparel";
private static final String PRODUCT_ID = String.format("test_%s", UUID.randomUUID().toString());
private static final String REFERENCE_IMAGE_ID =
- String.format("test_%s", UUID.randomUUID().toString());
- private static final String GCS_URI =
- "gs://java-docs-samples-testing/product-search/shoes_1.jpg";
+ String.format("test_%s", UUID.randomUUID().toString());
+ private static final String GCS_URI = "gs://java-docs-samples-testing/product-search/shoes_1.jpg";
private ByteArrayOutputStream bout;
private PrintStream out;
diff --git a/vision/product-search/cloud-client/src/test/java/vision/snippets/ProductInProductSetManagementTests.java b/vision/product-search/cloud-client/src/test/java/vision/snippets/ProductInProductSetManagementTests.java
index ff8aa163a8a..5af3d01c674 100644
--- a/vision/product-search/cloud-client/src/test/java/vision/snippets/ProductInProductSetManagementTests.java
+++ b/vision/product-search/cloud-client/src/test/java/vision/snippets/ProductInProductSetManagementTests.java
@@ -26,7 +26,6 @@
import java.io.IOException;
import java.io.PrintStream;
import java.util.UUID;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -35,11 +34,11 @@ public class ProductInProductSetManagementTests {
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
private static final String COMPUTE_REGION = "us-west1";
private static final String PRODUCT_SET_DISPLAY_NAME =
- String.format("test_%s", UUID.randomUUID().toString());
+ String.format("test_%s", UUID.randomUUID().toString());
private static final String PRODUCT_SET_ID =
- String.format("test_%s", UUID.randomUUID().toString());
+ String.format("test_%s", UUID.randomUUID().toString());
private static final String PRODUCT_DISPLAY_NAME =
- String.format("test_%s", UUID.randomUUID().toString());
+ String.format("test_%s", UUID.randomUUID().toString());
private static final String PRODUCT_CATEGORY = "apparel";
private static final String PRODUCT_ID = String.format("test_%s", UUID.randomUUID().toString());
private ByteArrayOutputStream bout;
@@ -51,9 +50,9 @@ public void setUp() throws IOException {
out = new PrintStream(bout);
System.setOut(out);
ProductSetManagement.createProductSet(
- PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID, PRODUCT_SET_DISPLAY_NAME);
+ PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID, PRODUCT_SET_DISPLAY_NAME);
ProductManagement.createProduct(
- PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY);
+ PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY);
bout.reset();
}
@@ -68,20 +67,17 @@ public void tearDown() throws IOException {
public void testPurgeProductsInProductSet() throws Exception {
// Act
ProductInProductSetManagement.addProductToProductSet(
- PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_SET_ID);
- ProductManagement.listProducts(
- PROJECT_ID, COMPUTE_REGION);
+ PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_SET_ID);
+ ProductManagement.listProducts(PROJECT_ID, COMPUTE_REGION);
// Assert
String got = bout.toString();
assertThat(got).contains(PRODUCT_ID);
bout.reset();
- PurgeProductsInProductSet.purgeProductsInProductSet(
- PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID);
+ PurgeProductsInProductSet.purgeProductsInProductSet(PROJECT_ID, COMPUTE_REGION, PRODUCT_SET_ID);
- ProductManagement.listProducts(
- PROJECT_ID, COMPUTE_REGION);
+ ProductManagement.listProducts(PROJECT_ID, COMPUTE_REGION);
// Assert
got = bout.toString();
diff --git a/vision/product-search/cloud-client/src/test/java/vision/snippets/ProductManagementTests.java b/vision/product-search/cloud-client/src/test/java/vision/snippets/ProductManagementTests.java
index 35049f4ded0..05c5a1cc291 100644
--- a/vision/product-search/cloud-client/src/test/java/vision/snippets/ProductManagementTests.java
+++ b/vision/product-search/cloud-client/src/test/java/vision/snippets/ProductManagementTests.java
@@ -24,7 +24,6 @@
import java.io.IOException;
import java.io.PrintStream;
import java.util.UUID;
-
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -37,7 +36,7 @@ public class ProductManagementTests {
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
private static final String COMPUTE_REGION = "us-west1";
private static final String PRODUCT_DISPLAY_NAME =
- String.format("test_%s", UUID.randomUUID().toString());
+ String.format("test_%s", UUID.randomUUID().toString());
private static final String PRODUCT_CATEGORY = "homegoods";
private static final String PRODUCT_ID = String.format("test_%s", UUID.randomUUID().toString());
private ByteArrayOutputStream bout;
@@ -60,7 +59,7 @@ public void tearDown() throws IOException {
public void testPurgeOrphanProducts() throws Exception {
// Act
ProductManagement.createProduct(
- PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY);
+ PROJECT_ID, COMPUTE_REGION, PRODUCT_ID, PRODUCT_DISPLAY_NAME, PRODUCT_CATEGORY);
ProductManagement.listProducts(PROJECT_ID, COMPUTE_REGION);
// Assert
diff --git a/vision/spring-framework/pom.xml b/vision/spring-framework/pom.xml
index c21bf804d3f..3b9a0cabbf5 100644
--- a/vision/spring-framework/pom.xml
+++ b/vision/spring-framework/pom.xml
@@ -29,7 +29,7 @@ limitations under the License.
com.google.cloud.samples
shared-configuration
- 1.0.11
+ 1.0.13
com.example.vision
diff --git a/vision/spring-framework/src/main/java/com/example/vision/Application.java b/vision/spring-framework/src/main/java/com/example/vision/Application.java
index bcbb69227c7..a3c4841f803 100644
--- a/vision/spring-framework/src/main/java/com/example/vision/Application.java
+++ b/vision/spring-framework/src/main/java/com/example/vision/Application.java
@@ -19,9 +19,7 @@
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
-/**
- * Entry point to running the Spring Boot application.
- */
+/** Entry point to running the Spring Boot application. */
@SpringBootApplication
public class Application {
diff --git a/vision/spring-framework/src/main/java/com/example/vision/VisionController.java b/vision/spring-framework/src/main/java/com/example/vision/VisionController.java
index f7326889d4b..35d48d3a71c 100644
--- a/vision/spring-framework/src/main/java/com/example/vision/VisionController.java
+++ b/vision/spring-framework/src/main/java/com/example/vision/VisionController.java
@@ -31,24 +31,22 @@
import org.springframework.web.servlet.ModelAndView;
/**
- * Code sample demonstrating Cloud Vision usage within the context of Spring Framework using
- * Spring Cloud GCP libraries. The sample is written as a Spring Boot application to demonstrate
- * a practical application of this usage.
+ * Code sample demonstrating Cloud Vision usage within the context of Spring Framework using Spring
+ * Cloud GCP libraries. The sample is written as a Spring Boot application to demonstrate a
+ * practical application of this usage.
*/
@RestController
public class VisionController {
- @Autowired
- private ResourceLoader resourceLoader;
+ @Autowired private ResourceLoader resourceLoader;
// [START spring_vision_autowire]
- @Autowired
- private CloudVisionTemplate cloudVisionTemplate;
+ @Autowired private CloudVisionTemplate cloudVisionTemplate;
// [END spring_vision_autowire]
/**
- * This method downloads an image from a URL and sends its contents
- * to the Vision API for label detection.
+ * This method downloads an image from a URL and sends its contents to the Vision API for label
+ * detection.
*
* @param imageUrl the URL of the image
* @param map the model map to use
@@ -56,12 +54,14 @@ public class VisionController {
*/
@GetMapping("/extractLabels")
public ModelAndView extractLabels(String imageUrl, ModelMap map) {
- //[START spring_vision_image_labelling]
- AnnotateImageResponse response = this.cloudVisionTemplate.analyzeImage(
- this.resourceLoader.getResource(imageUrl), Type.LABEL_DETECTION);
+ // [START spring_vision_image_labelling]
+ AnnotateImageResponse response =
+ this.cloudVisionTemplate.analyzeImage(
+ this.resourceLoader.getResource(imageUrl), Type.LABEL_DETECTION);
Map imageLabels =
- response.getLabelAnnotationsList()
+ response
+ .getLabelAnnotationsList()
.stream()
.collect(
Collectors.toMap(
@@ -71,7 +71,7 @@ public ModelAndView extractLabels(String imageUrl, ModelMap map) {
throw new IllegalStateException(String.format("Duplicate key %s", u));
},
LinkedHashMap::new));
- //[END spring_vision_image_labelling]
+ // [END spring_vision_image_labelling]
map.addAttribute("annotations", imageLabels);
map.addAttribute("imageUrl", imageUrl);
@@ -81,10 +81,10 @@ public ModelAndView extractLabels(String imageUrl, ModelMap map) {
@GetMapping("/extractText")
public String extractText(String imageUrl) {
- //[START spring_vision_text_extraction]
- String textFromImage = this.cloudVisionTemplate.extractTextFromImage(
- this.resourceLoader.getResource(imageUrl));
+ // [START spring_vision_text_extraction]
+ String textFromImage =
+ this.cloudVisionTemplate.extractTextFromImage(this.resourceLoader.getResource(imageUrl));
return "Text from image: " + textFromImage;
- //[END spring_vision_text_extraction]
+ // [END spring_vision_text_extraction]
}
}