repo_id
stringclasses 875
values | size
int64 974
38.9k
| file_path
stringlengths 10
308
| content
stringlengths 974
38.9k
|
|---|---|---|---|
oracle/nosql
| 38,280
|
kvtest/kvstore-IT/src/main/java/oracle/kv/impl/security/SecurityMetadataTest.java
|
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2011, 2025 Oracle and/or its affiliates. All rights reserved.
*
*/
package oracle.kv.impl.security;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import oracle.kv.TestBase;
import oracle.kv.impl.admin.SecurityStore;
import oracle.kv.impl.metadata.Metadata;
import oracle.kv.impl.metadata.Metadata.MetadataType;
import oracle.kv.impl.security.metadata.KVStoreUser;
import oracle.kv.impl.security.metadata.KVStoreUser.UserType;
import oracle.kv.impl.security.metadata.PasswordHashDigest;
import oracle.kv.impl.security.metadata.SecurityMDChange;
import oracle.kv.impl.security.metadata.SecurityMetadata;
import oracle.kv.impl.security.metadata.SecurityMetadata.KerberosInstance;
import oracle.kv.impl.security.metadata.SecurityMetadata.SecurityElement;
import oracle.kv.impl.security.metadata.SecurityMetadata.SecurityElementType;
import oracle.kv.impl.topo.StorageNodeId;
import oracle.kv.impl.util.SerializationUtil;
import oracle.kv.impl.util.TestUtils;
import oracle.kv.impl.util.server.LoggerUtils;
import oracle.nosql.common.json.JsonNode;
import oracle.nosql.common.json.JsonUtils;
import org.junit.Test;
import com.sleepycat.je.Environment;
import com.sleepycat.je.EnvironmentConfig;
import com.sleepycat.je.Transaction;
import com.sleepycat.je.TransactionConfig;
public class SecurityMetadataTest extends TestBase {
private static final String SEC_ID = "md-" + System.currentTimeMillis();
private static final String STORE_NAME = "foo";
private static final File TEST_DIR = TestUtils.getTestDir();
private static final SecureRandom random = new SecureRandom();
private final SecurityMetadata md =
new SecurityMetadata(STORE_NAME /* kvstorename */, SEC_ID /* id */);
@Override
public void setUp() throws Exception {
super.setUp();
}
@Override
public void tearDown() throws Exception {
super.tearDown();
LoggerUtils.closeAllHandlers();
}
@Test
public void testBasic() {
/* Test id, name and type */
assertEquals(SEC_ID, md.getId());
assertEquals(STORE_NAME, md.getKVStoreName());
assertEquals(MetadataType.SECURITY, md.getType());
/* Still empty now */
assertEquals(SecurityMetadata.EMPTY_SEQUENCE_NUMBER,
md.getSequenceNumber());
int expectedSeqNum = 3;
for (SecurityElementType type : SecurityElementType.values()) {
if (type.equals(SecurityElementType.KRBPRINCIPAL)) {
continue;
}
final SecurityElement e1 = addSecurityElement(type, "first");
final SecurityElement e2 = addSecurityElement(type, "second");
assertEquals(e1, getSecurityElement(type, "first"));
assertEquals(e2, getSecurityElement(type, "second"));
final Collection<? extends SecurityElement> elements =
getAllElements(type);
assertEquals(2, elements.size() /* should have two elements now */);
assertTrue(elements.contains(e1));
assertTrue(elements.contains(e2));
/* Add nobody */
assertNull(getSecurityElement(type, "nobody"));
/* Test element id related operations */
assertEquals(getSecurityElementId(type, 2), e2.getElementId());
assertEquals(e1, (getSecurityElementById(type, 1)));
/* Security elements with same names should have different ids. */
final SecurityElement repeatedE1 = addSecurityElement(type, "first");
assertFalse(e1.getElementId().equals(repeatedE1.getElementId()));
/* The sequence should have increased to 3 by now. */
assertEquals(expectedSeqNum, md.getSequenceNumber());
expectedSeqNum += 3;
}
}
@Test
public void testRemove() {
int initSeqNum = md.getSequenceNumber();
for (SecurityElementType type : SecurityElementType.values()) {
if (type.equals(SecurityElementType.KRBPRINCIPAL)) {
continue;
}
final int initElementNum = getAllElements(type).size();
final SecurityElement shortLived =
addSecurityElement(type, "shortLived");
assertEquals(shortLived, getSecurityElement(type, "shortLived"));
removeSecurityElement(type, shortLived.getElementId());
assertNull(getSecurityElement(type, "shortLived"));
assertNull(getSecurityElementById(type, 3));
assertFalse(getAllElements(type).contains(shortLived));
assertEquals(initElementNum, getAllElements(type).size());
/* Test removing a non-existing element */
try {
removeSecurityElement(type, "fooId");
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException iae) {
assertTrue(true); /* ignore */
}
/* The sequence should have increased by 2 now. */
assertEquals(initSeqNum += 2, md.getSequenceNumber());
}
}
@Test
public void testUpdate() {
int initSeqNum = md.getSequenceNumber();
for (SecurityElementType type : SecurityElementType.values()) {
if (type.equals(SecurityElementType.KRBPRINCIPAL)) {
continue;
}
/* Test updating an existing element */
final SecurityElement oldElement = addSecurityElement(type, "old");
final SecurityElement newElement =
updateSecurityElement(type, oldElement.getElementId(), "new");
assertEquals(newElement, getSecurityElement(type, "new"));
assertNull(getSecurityElement(type, "old"));
/* Test updating a non-existing element */
try {
updateSecurityElement(type, "fooId", null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException iae) {
assertTrue(true); /* ignore */
}
/* The sequence should have increased by 2 now. */
assertEquals(initSeqNum += 2, md.getSequenceNumber());
}
}
@Test
public void testChangeApply() {
for (SecurityElementType type : SecurityElementType.values()) {
if (type.equals(SecurityElementType.KRBPRINCIPAL)) {
continue;
}
/* Load some change data */
final SecurityElement toUpdate = addSecurityElement(type, "update");
final SecurityElement toRemove = addSecurityElement(type, "remove");
addSecurityElement(type, "remove");
updateSecurityElement(type, toUpdate.getElementId(), "newUpdate");
removeSecurityElement(type, toRemove.getElementId());
final SecurityMetadata newMd =
new SecurityMetadata(md.getKVStoreName(), md.getId());
/* Test applying null or empty changes */
assertFalse(newMd.apply(null));
assertFalse(newMd.apply(new ArrayList<SecurityMDChange>()));
/* Test applying non-continuous changes */
final List<SecurityMDChange> gappedChanges = md.getChanges(3);
try {
newMd.apply(gappedChanges);
fail("Expected IllegalStateException");
} catch (IllegalStateException ise) {
assertTrue(true); /* ignore */
}
/* Test applying non-overlapped and continuous changes */
final List<SecurityMDChange> appliableChanges = md.getChanges();
assertTrue(newMd.apply(appliableChanges));
assertSecurityMDEquals(newMd, md);
/* Test applying overlapped changes */
addSecurityElement(type, "oneMore");
/* overlapped SN: 3-5 */
final List<SecurityMDChange> overlappedChanges = md.getChanges(3);
assertTrue(newMd.apply(overlappedChanges));
assertSecurityMDEquals(newMd, md);
}
}
@Test
public void testBasicLogChanges() {
/* Empty tracker should return -1 as its first sequence number */
assertEquals(-1, md.getFirstChangeSeqNum());
int initialSeqNum = Metadata.EMPTY_SEQUENCE_NUMBER;
int totalChangesNum = 0;
for (SecurityElementType type : SecurityElementType.values()) {
if (type.equals(SecurityElementType.KRBPRINCIPAL)) {
continue;
}
/* Initial sequence number should be EMPTY_SEQUENCE_NUMBER */
assertEquals(initialSeqNum, md.getSequenceNumber());
/* No changes is saved */
if (initialSeqNum == Metadata.EMPTY_SEQUENCE_NUMBER) {
assertNull(md.getChanges(1));
} else {
assertNotNull(md.getChanges(1));
}
/* Test sequencing logged changes (3 changes will be logged)*/
md.logChange(new SecurityMDChange.Add(
newSecurityElement(type, "first")));
md.logChange(new SecurityMDChange.Remove("fooId", type,
newSecurityElement(type, "foo")));
md.logChange(new SecurityMDChange.Update(
newSecurityElement(type, "second")));
totalChangesNum += 3;
final int firstSeqNum = md.getFirstChangeSeqNum();
assertEquals(1, firstSeqNum);
assertEquals(initialSeqNum + 3, md.getSequenceNumber());
assertEquals(totalChangesNum, md.getChanges().size());
/* Test getting partial changes */
assertEquals(2, md.getChanges(initialSeqNum + 2).size());
assertNull(md.getChanges(firstSeqNum + totalChangesNum + 1));
initialSeqNum += 3;
}
}
@Test
public void testDiscardChanges() {
final int expectedSN = 2;
final int expectedSize = 5;
final int gap = 10;
testBasicLogChanges();
/* Test discarding changes in legal range */
md.pruneChanges(2, 0);
final int firstSeqNum = md.getFirstChangeSeqNum();
final int newSize = md.getChanges().size();
assertEquals(expectedSN, firstSeqNum);
assertEquals(expectedSize, newSize);
/* Test discarding changes with start SeqNum before first SeqNum */
md.pruneChanges(firstSeqNum - 1, Integer.MAX_VALUE);
assertEquals(expectedSN, firstSeqNum);
assertEquals(expectedSize, newSize);
/* Test discarding changes with start SeqNum before first SeqNum */
md.pruneChanges(md.getSequenceNumber() + gap, Integer.MAX_VALUE);
assertEquals(expectedSN, firstSeqNum);
assertEquals(expectedSize, newSize);
}
@Test
public void testSerialization() throws Exception {
testBasic();
/* Serialize the md */
final byte[] secMdByteArray = SerializationUtil.getBytes(md);
/* De-serialize the md */
final SecurityMetadata restoredMd =
SerializationUtil.getObject(secMdByteArray, md.getClass());
assertSecurityMDEquals(restoredMd, md);
/* Same check with FastExternalizable serialization */
assertSecurityMDEquals(
md, TestUtils.fastSerialize(md, SecurityMetadata::new));
}
@Test
public void testPersistence() {
testBasic();
final EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setTransactional(true);
envConfig.setAllowCreate(true);
final Environment env = new Environment(TEST_DIR, envConfig);
final TransactionConfig tconfig = new TransactionConfig();
final SecurityStore store = SecurityStore.getTestStore(env);
/* Persist the data */
Transaction txn = env.beginTransaction(null, tconfig);
store.putSecurityMetadata(txn, md, false);
txn.commit();
/* Retrieve the data */
txn = env.beginTransaction(null, tconfig);
final SecurityMetadata restoredMd = store.getSecurityMetadata(txn);
txn.commit();
assertSecurityMDEquals(restoredMd, md);
/* Test update and reload the persisted copy */
for (SecurityElementType type : SecurityElementType.values()) {
if (type.equals(SecurityElementType.KRBPRINCIPAL)) {
md.addKerberosInstanceName("instance", new StorageNodeId(1));
} else {
addSecurityElement(type, "newOne");
}
txn = env.beginTransaction(null, tconfig);
store.putSecurityMetadata(txn, md, false);
txn.commit();
txn = env.beginTransaction(null, tconfig);
final SecurityMetadata newReloadMd = store.getSecurityMetadata(txn);
txn.commit();
assertSecurityMDEquals(newReloadMd, md);
}
store.close();
env.close();
}
@Test
public void testPasswordVerification() {
final String userName = "test";
final KVStoreUser user = KVStoreUser.newInstance(userName);
user.setEnabled(true);
final char[] rightPass = "NoSql00__rightPass".toCharArray();
final char[] wrongPass = "wrongPass".toCharArray();
final char[] newPass = "NoSql00__newPass".toCharArray();
md.addUser(user);
user.setPassword(makeDefaultHashDigest(rightPass));
user.setPasswordLifetime(TimeUnit.DAYS.toMillis(1));
assertFalse(md.verifyUserPassword(userName, wrongPass));
assertTrue(md.verifyUserPassword(userName, rightPass));
/* Test retained password */
user.retainPassword();
user.getRetainedPassword().setLifetime(
TimeUnit.SECONDS.toMillis(1));
user.setPassword(makeDefaultHashDigest(newPass));
/* Both current and retained password work */
assertTrue(md.verifyUserPassword(userName, rightPass));
assertTrue(md.verifyUserPassword(userName, newPass));
assertTrue(user.retainedPasswordValid());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
/* Ignore */
assertTrue(true); /* ignore */
}
/* Time expired, current password works, retained password is gone */
assertTrue(md.verifyUserPassword(userName, newPass));
assertFalse(md.verifyUserPassword(userName, rightPass));
assertFalse(user.retainedPasswordValid());
/* Disabled user cannot login */
user.setEnabled(false);
assertFalse(md.verifyUserPassword(userName, newPass));
}
@Test
public void testPreviousPasswords() {
final String userName = "PrevPassUser";
KVStoreUser user = KVStoreUser.newInstance(userName);
user.setEnabled(true);
final char[] firstPass = "NoSql00__Pass1".toCharArray();
final char[] secondPass = "NoSql00__Pass2".toCharArray();
final char[] thirdPass = "NoSql00__Pass3".toCharArray();
final PasswordHashDigest firstPassPHD =
makeDefaultHashDigest(firstPass);
final PasswordHashDigest secondPassPHD =
makeDefaultHashDigest(secondPass);
final PasswordHashDigest thirdPassPHD =
makeDefaultHashDigest(thirdPass);
md.addUser(user);
user.setPassword(firstPassPHD);
user.setPassword(secondPassPHD);
user.setPassword(thirdPassPHD);
assertTrue(md.verifyUserPassword(userName, thirdPass));
SecurityMetadata secMd = persistAndRetrieve(md);
user = secMd.getUser(userName);
PasswordHashDigest[] previousPasswords = user.getRememberedPasswords(5);
assertEquals(previousPasswords.length, 3);
assertEquals(previousPasswords[0], thirdPassPHD);
assertEquals(previousPasswords[1], secondPassPHD);
assertEquals(previousPasswords[2], firstPassPHD);
previousPasswords = user.getRememberedPasswords(2);
assertEquals(previousPasswords.length, 2);
assertEquals(previousPasswords[0], thirdPassPHD);
assertEquals(previousPasswords[1], secondPassPHD);
}
@Test
public void testGrantRevokeRoles() {
final KVStoreUser user = KVStoreUser.newInstance("user1");
final Set<String> defaultRoles = buildRoleSet(RoleInstance.PUBLIC_NAME);
final Set<String> adminDefaultRoles =
buildRoleSet(RoleInstance.SYSADMIN_NAME, RoleInstance.PUBLIC_NAME);
final Set<String> grantedRoles = buildRoleSet(RoleInstance.READWRITE_NAME,
RoleInstance.SYSADMIN_NAME,
RoleInstance.PUBLIC_NAME);
/* Verify default roles of user and Admin user */
assertEquals(defaultRoles, user.getGrantedRoles());
user.setAdmin(true);
assertEquals(adminDefaultRoles, user.getGrantedRoles());
/* Grant READWRITE role to user and verify */
Set<String> roles = buildRoleSet(RoleInstance.READWRITE_NAME);
user.grantRoles(roles);
assertEquals(grantedRoles, user.getGrantedRoles());
/* Revoke READWRITE role */
user.revokeRoles(roles);
assertEquals(adminDefaultRoles, user.getGrantedRoles());
/* Revoke SYSADMIN role */
roles.remove(RoleInstance.READWRITE_NAME);
roles.add(RoleInstance.SYSADMIN_NAME);
user.revokeRoles(roles);
assertEquals(defaultRoles, user.getGrantedRoles());
}
@Test
public void testExternalUserType() {
final String externalUserName = "external/machine@external.com";
KVStoreUser user = KVStoreUser.newV1Instance(externalUserName);
user.setUserType(UserType.EXTERNAL);
md.addUser(user);
assertUserEquals(user, md.getUser(externalUserName));
assertEquals(
md.getUser(externalUserName).getUserType(), UserType.EXTERNAL);
final Collection<KVStoreUser> users = md.getAllUsers();
assertEquals(1, users.size());
assertEquals(1, md.getSequenceNumber());
}
@Test
public void testUserDescription() {
final char[] pwd = "NoSql00__Pass1".toCharArray();
final PasswordHashDigest pwdHash = makeDefaultHashDigest(pwd);
final char[] newPwd = "NoSql00__newPass".toCharArray();
final PasswordHashDigest newPwdHash = makeDefaultHashDigest(newPwd);
final KVStoreUser user = KVStoreUser.newInstance("user")
.setEnabled(true).setPassword(pwdHash);
JsonNode desc = JsonUtils.parseJsonNode(
user.getDescription().detailsAsJSON());
assertEquals(user.getName(), desc.get("name").asText());
assertEquals(user.isEnabled(), desc.get("enabled").asBoolean());
assertEquals(user.getUserType().toString(), desc.get("type").asText());
assertEquals("inactive", desc.get("retain-passwd").asText());
/* Test retain password expiration output */
user.retainPassword();
user.setPassword(newPwdHash);
desc = JsonUtils.parseJsonNode(user.getDescription().detailsAsJSON());
String expiryInfo = user.getRetainedPassword().getExpirationInfo();
assertEquals(
"active [expiration: " + expiryInfo +"]",
desc.get("retain-passwd").asText());
/* Test password expiration output */
expiryInfo = user.getPassword().getExpirationInfo();
desc = JsonUtils.parseJsonNode(user.getDescription().detailsAsJSON());
assertEquals(expiryInfo, desc.get("current-passwd-expiration").asText());
long lifetime = 360_000_000;
newPwdHash.setLifetime(lifetime);
user.setPassword(newPwdHash);
desc = JsonUtils.parseJsonNode(user.getDescription().detailsAsJSON());
final String expiry = desc.get("current-passwd-expiration").asText();
assertEquals(newPwdHash.getExpirationInfo(), expiry);
final String format = "yyyy-MM-dd HH:mm:ss z";
final SimpleDateFormat df = new SimpleDateFormat(format);
try {
df.parse(expiry);
} catch (ParseException e) {
fail("Expiration not in correct format, expect in format " + format +
", actual value " + expiry);
}
newPwdHash.setLifetime(-1);
user.setPassword(newPwdHash);
desc = JsonUtils.parseJsonNode(user.getDescription().detailsAsJSON());
assertEquals(newPwdHash.getExpirationInfo(),
desc.get("current-passwd-expiration").asText());
/* Test external user description output */
final KVStoreUser extUser = KVStoreUser.newInstance("user")
.setEnabled(true).setUserType(UserType.EXTERNAL);
desc = JsonUtils.parseJsonNode(extUser.getDescription().detailsAsJSON());
assertEquals(extUser.getName(), desc.get("name").asText());
assertEquals(extUser.isEnabled(), desc.get("enabled").asBoolean());
assertEquals(extUser.getUserType().toString(), desc.get("type").asText());
assertNull(desc.get("retain-passwd"));
assertNull(desc.get("current-passwd-expiration"));
}
@Test
public void testMDUpgrade() {
/* Test id, name and type */
assertEquals(SEC_ID, md.getId());
assertEquals(STORE_NAME, md.getKVStoreName());
assertEquals(MetadataType.SECURITY, md.getType());
/* Still empty now */
assertEquals(SecurityMetadata.EMPTY_SEQUENCE_NUMBER,
md.getSequenceNumber());
final String userName = "user";
final String adminUserName = "admin";
KVStoreUser user = KVStoreUser.newV1Instance(userName);
KVStoreUser admin =
KVStoreUser.newV1Instance(adminUserName).setAdmin(true);
md.addUser(user);
md.addUser(admin);
assertUserEquals(user, md.getUser(userName));
assertUserEquals(admin, md.getUser(adminUserName));
final Collection<KVStoreUser> users = md.getAllUsers();
assertEquals(2, users.size());
assertEquals(2, md.getSequenceNumber());
final EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setTransactional(true);
envConfig.setAllowCreate(true);
final Environment env = new Environment(TEST_DIR, envConfig);
final TransactionConfig tconfig = new TransactionConfig();
final SecurityStore store = SecurityStore.getTestStore(env);
/* Persist the data */
Transaction txn = env.beginTransaction(null, tconfig);
store.putSecurityMetadata(txn, md, false);
txn.commit();
/* Retrieve the data */
txn = env.beginTransaction(null, tconfig);
final SecurityMetadata md1 = store.getSecurityMetadata(txn);
txn.commit();
assertSecurityMDEquals(md1, md);
assertUserEquals(md.getUser(userName), md1.getUser(userName));
assertUserEquals(md.getUser(adminUserName), md1.getUser(adminUserName));
/* Check default roles of user */
assertEquals(user.getGrantedRoles(),
buildRoleSet(RoleInstance.PUBLIC_NAME,
RoleInstance.READWRITE_NAME));
/* Check default roles of admin user */
assertEquals(admin.getGrantedRoles(),
buildRoleSet(RoleInstance.PUBLIC_NAME,
RoleInstance.READWRITE_NAME,
RoleInstance.SYSADMIN_NAME));
/* Grant DBAADMIN role to user */
Set<String> dba = buildRoleSet(RoleInstance.DBADMIN_NAME);
user = user.grantRoles(dba);
/* Grant READONLY role to admin user */
admin = admin.grantRoles(
Collections.singleton(RoleInstance.READONLY_NAME));
md1.updateUser(user.getElementId(), user);
md1.updateUser(admin.getElementId(), admin);
txn = env.beginTransaction(null, tconfig);
store.putSecurityMetadata(txn, md1, false);
txn.commit();
txn = env.beginTransaction(null, tconfig);
final SecurityMetadata md2 = store.getSecurityMetadata(txn);
txn.commit();
assertSecurityMDEquals(md1, md2);
assertUserEquals(user, md2.getUser(userName));
assertUserEquals(admin, md2.getUser(adminUserName));
/* Revoke DBAADMIN role from user */
user.revokeRoles(dba);
/* Revoke READONLY role from admin user */
admin.revokeRoles(Collections.singleton(RoleInstance.READONLY_NAME));
md2.updateUser(user.getElementId(), user);
md2.updateUser(admin.getElementId(), admin);
txn = env.beginTransaction(null, tconfig);
store.putSecurityMetadata(txn, md2, false);
txn.commit();
txn = env.beginTransaction(null, tconfig);
final SecurityMetadata md3 = store.getSecurityMetadata(txn);
txn.commit();
assertSecurityMDEquals(md2, md3);
assertUserEquals(user, md3.getUser(userName));
assertUserEquals(admin, md3.getUser(adminUserName));
store.close();
env.close();
}
@Test
public void testUserDefinedRole() {
final RoleInstance manager = new RoleInstance("manager");
final RoleInstance employee = new RoleInstance("employee");
final Set<String> managerRoles = buildRoleSet(
RoleInstance.READWRITE_NAME, RoleInstance.SYSADMIN_NAME);
final Set<String> employeeRoles = buildRoleSet(
RoleInstance.READONLY_NAME, RoleInstance.SYSADMIN_NAME);
manager.grantRoles(managerRoles);
employee.grantRoles(employeeRoles);
assertEquals(managerRoles, manager.getGrantedRoles());
assertEquals(employeeRoles, employee.getGrantedRoles());
manager.grantRoles(Collections.singleton("employee"));
managerRoles.add("employee");
assertEquals(managerRoles, manager.getGrantedRoles());
}
@Test
public void testRoleIdLimit() {
int currentId = Integer.MAX_VALUE - 20;
md.setRoleMapId(currentId);
for (int i = 1; i <= 20; i++) {
currentId++;
md.addRole(new RoleInstance("old" + i));
assertEquals(md.getRole("old" + i).getElementId(), "r" + currentId);
}
assertEquals(currentId, Integer.MAX_VALUE);
currentId = 1;
for (int i = 0; i <= 20; i++) {
md.addRole(new RoleInstance("new" + i));
assertEquals(md.getRole("new" + i).getElementId(), "r" + currentId);
currentId++;
}
}
@Test
public void testKerberosPrincipal() {
/* Test id, name and type */
assertEquals(SEC_ID, md.getId());
assertEquals(STORE_NAME, md.getKVStoreName());
assertEquals(MetadataType.SECURITY, md.getType());
/* Still empty now */
assertEquals(SecurityMetadata.EMPTY_SEQUENCE_NUMBER,
md.getSequenceNumber());
int expectedSeqNum = 2;
final StorageNodeId sn1 = new StorageNodeId(1);
final StorageNodeId sn2 = new StorageNodeId(2);
final KerberosInstance i1 = md.addKerberosInstanceName("first", sn1);
final KerberosInstance i2 = md.addKerberosInstanceName("second", sn2);
assertEquals(i1, md.getKrbInstance(sn1));
assertEquals(i2, md.getKrbInstance(sn2));
final Collection<KerberosInstance> ins = md.getAllKrbInstanceNames();
assertEquals(2, ins.size());
assertTrue(ins.contains(i1));
assertTrue(ins.contains(i2));
/* Test element id related operations */
assertEquals(md.getKrbInstance(sn2).getElementId(), i2.getElementId());
assertEquals(i1, (md.getKrbInstanceById("k" + 1)));
/* Test adding principal for the same sn is not allowed */
assertEquals(expectedSeqNum, md.getSequenceNumber());
assertNull(md.addKerberosInstanceName("third", sn1));
assertEquals(expectedSeqNum, md.getSequenceNumber());
/* Test adding principal for invalid sn id is not allowed */
assertNull(md.addKerberosInstanceName("error", new StorageNodeId(0)));
/* Test new metadata apply Kerberos principal changes */
/* Create new metadata */
SecurityMetadata newMd = new SecurityMetadata(md.getKVStoreName(),
md.getId());
final StorageNodeId sn3 = new StorageNodeId(3);
final StorageNodeId sn4 = new StorageNodeId(4);
md.addKerberosInstanceName("thrid", sn3);
md.addUser(KVStoreUser.newInstance("user1"));
md.removeKrbInstanceName(sn1);
/* Test applying null or empty changes */
assertFalse(newMd.apply(null));
assertFalse(newMd.apply(new ArrayList<SecurityMDChange>()));
/* Test applying non-continuous changes */
final List<SecurityMDChange> gappedChanges = md.getChanges(3);
try {
newMd.apply(gappedChanges);
fail("Expected IllegalStateException");
} catch (IllegalStateException ise) {
assertTrue(true); /* ignore */
}
/* Test applying non-overlapped and continuous changes */
final List<SecurityMDChange> appliableChanges = md.getChanges();
assertTrue(newMd.apply(appliableChanges));
assertSecurityMDEquals(newMd, md);
/* Test applying overlapped changes */
md.addKerberosInstanceName("fourth", sn4);
/* overlapped SN: 3-5 */
final List<SecurityMDChange> overlappedChanges = md.getChanges(3);
assertTrue(newMd.apply(overlappedChanges));
assertSecurityMDEquals(newMd, md);
/* Test new metadata log Kerberos principal changes */
/* Initial sequence number should be EMPTY_SEQUENCE_NUMBER */
newMd = new SecurityMetadata(md.getKVStoreName(), md.getId());
assertEquals(0, newMd.getSequenceNumber());
assertNull(newMd.getChanges(1));
/* Test sequencing logged changes (3 changes will be logged)*/
newMd.logChange(
new SecurityMDChange.Add(new KerberosInstance("1", sn1)));
newMd.logChange(
new SecurityMDChange.Add(new KerberosInstance("2", sn2)));
newMd.logChange(new SecurityMDChange.Remove("fooId",
SecurityElementType.KRBPRINCIPAL, new KerberosInstance("3", sn3)));
final int firstSeqNum = newMd.getFirstChangeSeqNum();
assertEquals(1, firstSeqNum);
assertEquals(3, newMd.getSequenceNumber());
assertEquals(3, newMd.getChanges().size());
/* Test getting partial changes */
assertEquals(2, newMd.getChanges(2).size());
assertNull(newMd.getChanges(4));
}
/**
* Assert two security metadata copies are equal by comparing their ids,
* StoreName, sequenceNumbers and the internal security elements.
*/
public static void assertSecurityMDEquals(final SecurityMetadata expected,
final SecurityMetadata actual) {
assertEquals(expected.getId(), actual.getId());
assertEquals(expected.getSequenceNumber(), actual.getSequenceNumber());
assertEquals(expected.getKVStoreName(), actual.getKVStoreName());
assertEquals(expected.getKVStoreUserMap(), actual.getKVStoreUserMap());
}
private static PasswordHashDigest
makeDefaultHashDigest(final char[] plainPassword) {
final byte[] saltValue =
PasswordHash.generateSalt(random, PasswordHash.SUGG_SALT_BYTES);
return PasswordHashDigest.getHashDigest(PasswordHash.SUGG_ALGO,
PasswordHash.SUGG_HASH_ITERS,
PasswordHash.SUGG_SALT_BYTES,
saltValue, plainPassword);
}
private static void assertUserEquals(final KVStoreUser expected,
final KVStoreUser actual) {
assertEquals(expected, actual);
assertEquals(expected.getGrantedRoles(), actual.getGrantedRoles());
}
private static Set<String> buildRoleSet(final String... element) {
return new HashSet<>(Arrays.asList(element));
}
/**
* Format security element Id by given digital number.
*
* @param type security element type, KVStoreUser and RoleInstance
* @param id digital number of element id
* @return formatted element in string
*/
private String getSecurityElementId(SecurityElementType type, int id) {
if (type == SecurityElementType.KVSTOREUSER) {
return "u" + id;
}
return "r" + id;
}
/**
* Get security element by given name with its element type as prefix.
* - KVStoreUser, the actual name will be "user" + given string.
* - RoleInstance, the actual name will be "role" + given string.
*
* @param type security element type, KVStoreUser and RoleInstance
* @param name element name
* @return security element
*/
private SecurityElement getSecurityElement(SecurityElementType type,
String name) {
if (type == SecurityElementType.KVSTOREUSER) {
return md.getUser("user" + name);
}
return md.getRole("role" + name);
}
/**
* Add security element. The naming convention is as same as the
* getSecurityElement method.
*
* @param type security element type, KVStoreUser and RoleInstance
* @param name element name
* @return added security element
*/
private SecurityElement addSecurityElement(SecurityElementType type,
String name) {
if (type == SecurityElementType.KVSTOREUSER) {
return
md.addUser(KVStoreUser.newInstance("user" + name));
}
return md.addRole(new RoleInstance("role" + name));
}
/**
* Update security element associated with the given Id.
*
* @param type security element type, KVStoreUser and RoleInstance
* @param oldElementId update target element Id
* @param name element new name
* @return updated security element
*/
private SecurityElement updateSecurityElement(SecurityElementType type,
String oldElementId,
String newName) {
if (type == SecurityElementType.KVSTOREUSER) {
return md.updateUser(oldElementId,
KVStoreUser.newInstance("user" + newName));
}
return md.updateRole(oldElementId,
new RoleInstance("role" + newName));
}
/**
* Remove security element associated with the given Id.
*
* @param type security element type, KVStoreUser and RoleInstance
* @param elementId remove target element Id
*/
private void removeSecurityElement(SecurityElementType type,
String elementId) {
if (type == SecurityElementType.KVSTOREUSER) {
md.removeUser(elementId);
} else {
md.removeRole(elementId);
}
}
/**
* Get all element associated with given type.
*
* @param type security element type
* @return all element with specific type
*/
private Collection<? extends SecurityElement>
getAllElements(SecurityElementType type) {
if (type == SecurityElementType.KVSTOREUSER) {
return md.getAllUsers();
}
return md.getAllRoles();
}
/**
* Get security element by given digital Id.
* - KVStoreUser, the actual name will be "u" + given digital Id.
* - RoleInstance, the actual name will be "r" + given digital Id.
*
* @param type security element type
* @param elementId element digital id
* @return security element
*/
private SecurityElement getSecurityElementById(SecurityElementType type,
int elementId) {
if (type == SecurityElementType.KVSTOREUSER) {
return md.getUserById("u" + elementId);
}
return md.getRoleById("r" + elementId);
}
/**
* Build a new security element instance.
*
* @param type security element type
* @param name security element name
* @return the newly create security element
*/
private SecurityElement newSecurityElement(SecurityElementType type,
String name) {
if (type == SecurityElementType.KVSTOREUSER) {
return KVStoreUser.newInstance(name);
}
return new RoleInstance(name);
}
private SecurityMetadata persistAndRetrieve(SecurityMetadata metadata) {
final EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setTransactional(true);
envConfig.setAllowCreate(true);
final Environment env = new Environment(TEST_DIR, envConfig);
final TransactionConfig tconfig = new TransactionConfig();
final SecurityStore store = SecurityStore.getTestStore(env);
/* Persist the data */
Transaction txn = env.beginTransaction(null, tconfig);
store.putSecurityMetadata(txn, metadata, false);
txn.commit();
/* Retrieve the data */
txn = env.beginTransaction(null, tconfig);
final SecurityMetadata resultMd = store.getSecurityMetadata(txn);
txn.commit();
store.close();
env.close();
return resultMd;
}
}
|
apache/ofbiz
| 38,227
|
framework/common/src/main/java/org/apache/ofbiz/common/FindServices.java
|
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.apache.ofbiz.common;
import static org.apache.ofbiz.base.util.UtilGenerics.checkList;
import static org.apache.ofbiz.base.util.UtilGenerics.checkMap;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.ObjectType;
import org.apache.ofbiz.base.util.StringUtil;
import org.apache.ofbiz.base.util.UtilDateTime;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.base.util.UtilHttp;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilProperties;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntity;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.condition.EntityComparisonOperator;
import org.apache.ofbiz.entity.condition.EntityCondition;
import org.apache.ofbiz.entity.condition.EntityConditionList;
import org.apache.ofbiz.entity.condition.EntityFunction;
import org.apache.ofbiz.entity.condition.EntityOperator;
import org.apache.ofbiz.entity.model.ModelEntity;
import org.apache.ofbiz.entity.model.ModelField;
import org.apache.ofbiz.entity.util.EntityListIterator;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.entity.util.EntityUtil;
import org.apache.ofbiz.entity.util.EntityUtilProperties;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ServiceUtil;
/**
* FindServices Class
*/
public class FindServices {
public static final String module = FindServices.class.getName();
public static final String resource = "CommonUiLabels";
public static Map<String, EntityComparisonOperator<?, ?>> entityOperators;
static {
entityOperators = new LinkedHashMap<String, EntityComparisonOperator<?, ?>>();
entityOperators.put("between", EntityOperator.BETWEEN);
entityOperators.put("equals", EntityOperator.EQUALS);
entityOperators.put("greaterThan", EntityOperator.GREATER_THAN);
entityOperators.put("greaterThanEqualTo", EntityOperator.GREATER_THAN_EQUAL_TO);
entityOperators.put("in", EntityOperator.IN);
entityOperators.put("not-in", EntityOperator.NOT_IN);
entityOperators.put("lessThan", EntityOperator.LESS_THAN);
entityOperators.put("lessThanEqualTo", EntityOperator.LESS_THAN_EQUAL_TO);
entityOperators.put("like", EntityOperator.LIKE);
entityOperators.put("notLike", EntityOperator.NOT_LIKE);
entityOperators.put("not", EntityOperator.NOT);
entityOperators.put("notEqual", EntityOperator.NOT_EQUAL);
}
public FindServices() {}
/**
* prepareField, analyse inputFields to created normalizedFields a map with field name and operator.
*
* This is use to the generic method that expects entity data affixed with special suffixes
* to indicate their purpose in formulating an SQL query statement.
* @param inputFields Input parameters run thru UtilHttp.getParameterMap
* @return a map with field name and operator
*/
public static Map<String, Map<String, Map<String, Object>>> prepareField(Map<String, ?> inputFields, Map<String, Object> queryStringMap, Map<String, List<Object[]>> origValueMap) {
// Strip the "_suffix" off of the parameter name and
// build a three-level map of values keyed by fieldRoot name,
// fld0 or fld1, and, then, "op" or "value"
// ie. id
// - fld0
// - op:like
// - value:abc
// - fld1 (if there is a range)
// - op:lessThan
// - value:55 (note: these two "flds" wouldn't really go together)
// Also note that op/fld can be in any order. (eg. id_fld1_equals or id_equals_fld1)
// Note that "normalizedFields" will contain values other than those
// Contained in the associated entity.
// Those extra fields will be ignored in the second half of this method.
Map<String, Map<String, Map<String, Object>>> normalizedFields = new LinkedHashMap<String, Map<String, Map<String, Object>>>();
for (String fieldNameRaw: inputFields.keySet()) { // The name as it appeas in the HTML form
String fieldNameRoot = null; // The entity field name. Everything to the left of the first "_" if
// it exists, or the whole word, if not.
String fieldPair = null; // "fld0" or "fld1" - begin/end of range or just fld0 if no range.
Object fieldValue = null; // If it is a "value" field, it will be the value to be used in the query.
// If it is an "op" field, it will be "equals", "greaterThan", etc.
int iPos = -1;
int iPos2 = -1;
Map<String, Map<String, Object>> subMap = null;
Map<String, Object> subMap2 = null;
String fieldMode = null;
fieldValue = inputFields.get(fieldNameRaw);
if (ObjectType.isEmpty(fieldValue)) {
continue;
}
queryStringMap.put(fieldNameRaw, fieldValue);
iPos = fieldNameRaw.indexOf("_"); // Look for suffix
// This is a hack to skip fields from "multi" forms
// These would have the form "fieldName_o_1"
if (iPos >= 0) {
String suffix = fieldNameRaw.substring(iPos + 1);
iPos2 = suffix.indexOf("_");
if (iPos2 == 1) {
continue;
}
}
// If no suffix, assume no range (default to fld0) and operations of equals
// If no field op is present, it will assume "equals".
if (iPos < 0) {
fieldNameRoot = fieldNameRaw;
fieldPair = "fld0";
fieldMode = "value";
} else { // Must have at least "fld0/1" or "equals, greaterThan, etc."
// Some bogus fields will slip in, like "ENTITY_NAME", but they will be ignored
fieldNameRoot = fieldNameRaw.substring(0, iPos);
String suffix = fieldNameRaw.substring(iPos + 1);
iPos2 = suffix.indexOf("_");
if (iPos2 < 0) {
if (suffix.startsWith("fld")) {
// If only one token and it starts with "fld"
// assume it is a value field, not an op
fieldPair = suffix;
fieldMode = "value";
} else {
// if it does not start with fld, assume it is an op or the 'ignore case' (ic) field
fieldPair = "fld0";
fieldMode = suffix;
}
} else {
String tkn0 = suffix.substring(0, iPos2);
String tkn1 = suffix.substring(iPos2 + 1);
// If suffix has two parts, let them be in any order
// One will be "fld0/1" and the other will be the op (eg. equals, greaterThan_
if (tkn0.startsWith("fld")) {
fieldPair = tkn0;
fieldMode = tkn1;
} else {
fieldPair = tkn1;
fieldMode = tkn0;
}
}
}
subMap = normalizedFields.get(fieldNameRoot);
if (subMap == null) {
subMap = new LinkedHashMap<String, Map<String, Object>>();
normalizedFields.put(fieldNameRoot, subMap);
}
subMap2 = subMap.get(fieldPair);
if (subMap2 == null) {
subMap2 = new LinkedHashMap<String, Object>();
subMap.put(fieldPair, subMap2);
}
subMap2.put(fieldMode, fieldValue);
List<Object[]> origList = origValueMap.get(fieldNameRoot);
if (origList == null) {
origList = new LinkedList<Object[]>();
origValueMap.put(fieldNameRoot, origList);
}
Object [] origValues = {fieldNameRaw, fieldValue};
origList.add(origValues);
}
return normalizedFields;
}
/**
* Parses input parameters and returns an <code>EntityCondition</code> list.
*
* @param parameters
* @param fieldList
* @param queryStringMap
* @param delegator
* @param context
* @return returns an EntityCondition list
*/
public static List<EntityCondition> createConditionList(Map<String, ? extends Object> parameters, List<ModelField> fieldList, Map<String, Object> queryStringMap, Delegator delegator, Map<String, ?> context) {
Set<String> processed = new LinkedHashSet<String>();
Set<String> keys = new LinkedHashSet<String>();
Map<String, ModelField> fieldMap = new LinkedHashMap<String, ModelField>();
for (ModelField modelField : fieldList) {
fieldMap.put(modelField.getName(), modelField);
}
List<EntityCondition> result = new LinkedList<EntityCondition>();
for (Map.Entry<String, ? extends Object> entry : parameters.entrySet()) {
String parameterName = entry.getKey();
if (processed.contains(parameterName)) {
continue;
}
keys.clear();
String fieldName = parameterName;
Object fieldValue = null;
String operation = null;
boolean ignoreCase = false;
if (parameterName.endsWith("_ic") || parameterName.endsWith("_op")) {
fieldName = parameterName.substring(0, parameterName.length() - 3);
} else if (parameterName.endsWith("_value")) {
fieldName = parameterName.substring(0, parameterName.length() - 6);
}
String key = fieldName.concat("_ic");
if (parameters.containsKey(key)) {
keys.add(key);
ignoreCase = "Y".equals(parameters.get(key));
}
key = fieldName.concat("_op");
if (parameters.containsKey(key)) {
keys.add(key);
operation = (String) parameters.get(key);
}
key = fieldName.concat("_value");
if (parameters.containsKey(key)) {
keys.add(key);
fieldValue = parameters.get(key);
}
if (fieldName.endsWith("_fld0") || fieldName.endsWith("_fld1")) {
if (parameters.containsKey(fieldName)) {
keys.add(fieldName);
}
fieldName = fieldName.substring(0, fieldName.length() - 5);
}
if (parameters.containsKey(fieldName)) {
keys.add(fieldName);
}
processed.addAll(keys);
ModelField modelField = fieldMap.get(fieldName);
if (modelField == null) {
continue;
}
if (fieldValue == null) {
fieldValue = parameters.get(fieldName);
}
if (ObjectType.isEmpty(fieldValue) && !"empty".equals(operation)) {
continue;
}
result.add(createSingleCondition(modelField, operation, fieldValue, ignoreCase, delegator, context));
for (String mapKey : keys) {
queryStringMap.put(mapKey, parameters.get(mapKey));
}
}
return result;
}
/**
* Creates a single <code>EntityCondition</code> based on a set of parameters.
*
* @param modelField
* @param operation
* @param fieldValue
* @param ignoreCase
* @param delegator
* @param context
* @return return an EntityCondition
*/
public static EntityCondition createSingleCondition(ModelField modelField, String operation, Object fieldValue, boolean ignoreCase, Delegator delegator, Map<String, ?> context) {
EntityCondition cond = null;
String fieldName = modelField.getName();
Locale locale = (Locale) context.get("locale");
TimeZone timeZone = (TimeZone) context.get("timeZone");
EntityComparisonOperator<?, ?> fieldOp = null;
if (operation != null) {
if (operation.equals("contains")) {
fieldOp = EntityOperator.LIKE;
fieldValue = "%" + fieldValue + "%";
} else if ("not-contains".equals(operation) || "notContains".equals(operation)) {
fieldOp = EntityOperator.NOT_LIKE;
fieldValue = "%" + fieldValue + "%";
} else if (operation.equals("empty")) {
return EntityCondition.makeCondition(fieldName, EntityOperator.EQUALS, null);
} else if (operation.equals("like")) {
fieldOp = EntityOperator.LIKE;
fieldValue = fieldValue + "%";
} else if ("not-like".equals(operation) || "notLike".equals(operation)) {
fieldOp = EntityOperator.NOT_LIKE;
fieldValue = fieldValue + "%";
} else if ("opLessThan".equals(operation)) {
fieldOp = EntityOperator.LESS_THAN;
} else if ("upToDay".equals(operation)) {
fieldOp = EntityOperator.LESS_THAN;
} else if ("upThruDay".equals(operation)) {
fieldOp = EntityOperator.LESS_THAN_EQUAL_TO;
} else if (operation.equals("greaterThanFromDayStart")) {
String timeStampString = (String) fieldValue;
Object startValue = modelField.getModelEntity().convertFieldValue(modelField, dayStart(timeStampString, 0, timeZone, locale), delegator, context);
return EntityCondition.makeCondition(fieldName, EntityOperator.GREATER_THAN_EQUAL_TO, startValue);
} else if (operation.equals("sameDay")) {
String timeStampString = (String) fieldValue;
Object startValue = modelField.getModelEntity().convertFieldValue(modelField, dayStart(timeStampString, 0, timeZone, locale), delegator, context);
EntityCondition startCond = EntityCondition.makeCondition(fieldName, EntityOperator.GREATER_THAN_EQUAL_TO, startValue);
Object endValue = modelField.getModelEntity().convertFieldValue(modelField, dayStart(timeStampString, 1, timeZone, locale), delegator, context);
EntityCondition endCond = EntityCondition.makeCondition(fieldName, EntityOperator.LESS_THAN, endValue);
return EntityCondition.makeCondition(startCond, endCond);
} else {
fieldOp = entityOperators.get(operation);
}
} else {
if (UtilValidate.isNotEmpty(UtilGenerics.toList(fieldValue))) {
fieldOp = EntityOperator.IN;
} else {
fieldOp = EntityOperator.EQUALS;
}
}
Object fieldObject = fieldValue;
if ((fieldOp != EntityOperator.IN && fieldOp != EntityOperator.NOT_IN ) || !(fieldValue instanceof Collection<?>)) {
fieldObject = modelField.getModelEntity().convertFieldValue(modelField, fieldValue, delegator, context);
}
if (ignoreCase && fieldObject instanceof String) {
cond = EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(fieldName), fieldOp, EntityFunction.UPPER(((String)fieldValue).toUpperCase()));
} else {
if (fieldObject.equals(GenericEntity.NULL_FIELD.toString())) {
fieldObject = null;
}
cond = EntityCondition.makeCondition(fieldName, fieldOp, fieldObject);
}
if (EntityOperator.NOT_EQUAL.equals(fieldOp) && fieldObject != null) {
cond = EntityCondition.makeCondition(UtilMisc.toList(cond, EntityCondition.makeCondition(fieldName, null)), EntityOperator.OR);
}
return cond;
}
/**
* createCondition, comparing the normalizedFields with the list of keys, .
*
* This is use to the generic method that expects entity data affixed with special suffixes
* to indicate their purpose in formulating an SQL query statement.
* @param modelEntity the model entity object
* @param normalizedFields list of field the user have populated
* @return a arrayList usable to create an entityCondition
*/
public static List<EntityCondition> createCondition(ModelEntity modelEntity, Map<String, Map<String, Map<String, Object>>> normalizedFields, Map<String, Object> queryStringMap, Map<String, List<Object[]>> origValueMap, Delegator delegator, Map<String, ?> context) {
Map<String, Map<String, Object>> subMap = null;
Map<String, Object> subMap2 = null;
Object fieldValue = null; // If it is a "value" field, it will be the value to be used in the query.
// If it is an "op" field, it will be "equals", "greaterThan", etc.
EntityCondition cond = null;
List<EntityCondition> tmpList = new LinkedList<EntityCondition>();
String opString = null;
boolean ignoreCase = false;
List<ModelField> fields = modelEntity.getFieldsUnmodifiable();
for (ModelField modelField: fields) {
String fieldName = modelField.getName();
subMap = normalizedFields.get(fieldName);
if (subMap == null) {
continue;
}
subMap2 = subMap.get("fld0");
fieldValue = subMap2.get("value");
opString = (String) subMap2.get("op");
// null fieldValue is OK if operator is "empty"
if (fieldValue == null && !"empty".equals(opString)) {
continue;
}
ignoreCase = "Y".equals(subMap2.get("ic"));
cond = createSingleCondition(modelField, opString, fieldValue, ignoreCase, delegator, context);
tmpList.add(cond);
subMap2 = subMap.get("fld1");
if (subMap2 == null) {
continue;
}
fieldValue = subMap2.get("value");
opString = (String) subMap2.get("op");
if (fieldValue == null && !"empty".equals(opString)) {
continue;
}
ignoreCase = "Y".equals(subMap2.get("ic"));
cond = createSingleCondition(modelField, opString, fieldValue, ignoreCase, delegator, context);
tmpList.add(cond);
// add to queryStringMap
List<Object[]> origList = origValueMap.get(fieldName);
if (UtilValidate.isNotEmpty(origList)) {
for (Object[] arr: origList) {
queryStringMap.put((String) arr[0], arr[1]);
}
}
}
return tmpList;
}
/**
*
* same as performFind but now returning a list instead of an iterator
* Extra parameters viewIndex: startPage of the partial list (0 = first page)
* viewSize: the length of the page (number of records)
* Extra output parameter: listSize: size of the totallist
* list : the list itself.
*
* @param dctx
* @param context
* @return Map
*/
public static Map<String, Object> performFindList(DispatchContext dctx, Map<String, Object> context) {
Integer viewSize = (Integer) context.get("viewSize");
if (viewSize == null) viewSize = Integer.valueOf(20); // default
context.put("viewSize", viewSize);
Integer viewIndex = (Integer) context.get("viewIndex");
if (viewIndex == null) viewIndex = Integer.valueOf(0); // default
context.put("viewIndex", viewIndex);
Map<String, Object> result = performFind(dctx,context);
int start = viewIndex.intValue() * viewSize.intValue();
List<GenericValue> list = null;
Integer listSize = 0;
try {
EntityListIterator it = (EntityListIterator) result.get("listIt");
list = it.getPartialList(start+1, viewSize); // list starts at '1'
listSize = it.getResultsSizeAfterPartialList();
it.close();
} catch (Exception e) {
Debug.logInfo("Problem getting partial list" + e,module);
}
result.put("listSize", listSize);
result.put("list",list);
result.remove("listIt");
return result;
}
/**
* performFind
*
* This is a generic method that expects entity data affixed with special suffixes
* to indicate their purpose in formulating an SQL query statement.
*/
public static Map<String, Object> performFind(DispatchContext dctx, Map<String, ?> context) {
String entityName = (String) context.get("entityName");
String orderBy = (String) context.get("orderBy");
Map<String, ?> inputFields = checkMap(context.get("inputFields"), String.class, Object.class); // Input
String noConditionFind = (String) context.get("noConditionFind");
String distinct = (String) context.get("distinct");
List<String> fieldList = UtilGenerics.<String>checkList(context.get("fieldList"));
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
Delegator delegator = dctx.getDelegator();
if (UtilValidate.isEmpty(noConditionFind)) {
// try finding in inputFields Map
noConditionFind = (String) inputFields.get("noConditionFind");
}
if (UtilValidate.isEmpty(noConditionFind)) {
// Use configured default
noConditionFind = EntityUtilProperties.getPropertyValue("widget", "widget.defaultNoConditionFind", delegator);
}
String filterByDate = (String) context.get("filterByDate");
if (UtilValidate.isEmpty(filterByDate)) {
// try finding in inputFields Map
filterByDate = (String) inputFields.get("filterByDate");
}
Timestamp filterByDateValue = (Timestamp) context.get("filterByDateValue");
String fromDateName = (String) context.get("fromDateName");
if (UtilValidate.isEmpty(fromDateName)) {
// try finding in inputFields Map
fromDateName = (String) inputFields.get("fromDateName");
}
String thruDateName = (String) context.get("thruDateName");
if (UtilValidate.isEmpty(thruDateName)) {
// try finding in inputFields Map
thruDateName = (String) inputFields.get("thruDateName");
}
Integer viewSize = (Integer) context.get("viewSize");
Integer viewIndex = (Integer) context.get("viewIndex");
Integer maxRows = null;
if (viewSize != null && viewIndex != null) {
maxRows = viewSize * (viewIndex + 1);
}
LocalDispatcher dispatcher = dctx.getDispatcher();
Map<String, Object> prepareResult = null;
try {
prepareResult = dispatcher.runSync("prepareFind", UtilMisc.toMap("entityName", entityName, "orderBy", orderBy,
"inputFields", inputFields, "filterByDate", filterByDate, "noConditionFind", noConditionFind,
"filterByDateValue", filterByDateValue, "userLogin", userLogin, "fromDateName", fromDateName, "thruDateName", thruDateName,
"locale", context.get("locale"), "timeZone", context.get("timeZone")));
} catch (GenericServiceException gse) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonFindErrorPreparingConditions", UtilMisc.toMap("errorString", gse.getMessage()), locale));
}
EntityConditionList<EntityCondition> exprList = UtilGenerics.cast(prepareResult.get("entityConditionList"));
List<String> orderByList = checkList(prepareResult.get("orderByList"), String.class);
Map<String, Object> executeResult = null;
try {
executeResult = dispatcher.runSync("executeFind", UtilMisc.toMap("entityName", entityName, "orderByList", orderByList,
"fieldList", fieldList, "entityConditionList", exprList,
"noConditionFind", noConditionFind, "distinct", distinct,
"locale", context.get("locale"), "timeZone", context.get("timeZone"),
"maxRows", maxRows));
} catch (GenericServiceException gse) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonFindErrorRetrieveIterator", UtilMisc.toMap("errorString", gse.getMessage()), locale));
}
if (executeResult.get("listIt") == null) {
if (Debug.verboseOn()) Debug.logVerbose("No list iterator found for query string + [" + prepareResult.get("queryString") + "]", module);
}
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("listIt", executeResult.get("listIt"));
results.put("listSize", executeResult.get("listSize"));
results.put("queryString", prepareResult.get("queryString"));
results.put("queryStringMap", prepareResult.get("queryStringMap"));
return results;
}
/**
* prepareFind
*
* This is a generic method that expects entity data affixed with special suffixes
* to indicate their purpose in formulating an SQL query statement.
*/
public static Map<String, Object> prepareFind(DispatchContext dctx, Map<String, ?> context) {
String entityName = (String) context.get("entityName");
Delegator delegator = dctx.getDelegator();
String orderBy = (String) context.get("orderBy");
Map<String, ?> inputFields = checkMap(context.get("inputFields"), String.class, Object.class); // Input
String noConditionFind = (String) context.get("noConditionFind");
if (UtilValidate.isEmpty(noConditionFind)) {
// try finding in inputFields Map
noConditionFind = (String) inputFields.get("noConditionFind");
}
if (UtilValidate.isEmpty(noConditionFind)) {
// Use configured default
noConditionFind = EntityUtilProperties.getPropertyValue("widget", "widget.defaultNoConditionFind", delegator);
}
String filterByDate = (String) context.get("filterByDate");
if (UtilValidate.isEmpty(filterByDate)) {
// try finding in inputFields Map
filterByDate = (String) inputFields.get("filterByDate");
}
Timestamp filterByDateValue = (Timestamp) context.get("filterByDateValue");
String fromDateName = (String) context.get("fromDateName");
String thruDateName = (String) context.get("thruDateName");
Map<String, Object> queryStringMap = new LinkedHashMap<String, Object>();
ModelEntity modelEntity = delegator.getModelEntity(entityName);
List<EntityCondition> tmpList = createConditionList(inputFields, modelEntity.getFieldsUnmodifiable(), queryStringMap, delegator, context);
/* the filter by date condition should only be added when there are other conditions or when
* the user has specified a noConditionFind. Otherwise, specifying filterByDate will become
* its own condition.
*/
if (tmpList.size() > 0 || "Y".equals(noConditionFind)) {
if ("Y".equals(filterByDate)) {
queryStringMap.put("filterByDate", filterByDate);
if (UtilValidate.isEmpty(fromDateName)) fromDateName = "fromDate";
else queryStringMap.put("fromDateName", fromDateName);
if (UtilValidate.isEmpty(thruDateName)) thruDateName = "thruDate";
else queryStringMap.put("thruDateName", thruDateName);
if (UtilValidate.isEmpty(filterByDateValue)) {
EntityCondition filterByDateCondition = EntityUtil.getFilterByDateExpr(fromDateName, thruDateName);
tmpList.add(filterByDateCondition);
} else {
queryStringMap.put("filterByDateValue", filterByDateValue);
EntityCondition filterByDateCondition = EntityUtil.getFilterByDateExpr(filterByDateValue, fromDateName, thruDateName);
tmpList.add(filterByDateCondition);
}
}
}
EntityConditionList<EntityCondition> exprList = null;
if (tmpList.size() > 0) {
exprList = EntityCondition.makeCondition(tmpList);
}
List<String> orderByList = null;
if (UtilValidate.isNotEmpty(orderBy)) {
orderByList = StringUtil.split(orderBy,"|");
}
Map<String, Object> results = ServiceUtil.returnSuccess();
queryStringMap.put("noConditionFind", noConditionFind);
String queryString = UtilHttp.urlEncodeArgs(queryStringMap);
results.put("queryString", queryString);
results.put("queryStringMap", queryStringMap);
results.put("orderByList", orderByList);
results.put("entityConditionList", exprList);
return results;
}
/**
* executeFind
*
* This is a generic method that returns an EntityListIterator.
*/
public static Map<String, Object> executeFind(DispatchContext dctx, Map<String, ?> context) {
String entityName = (String) context.get("entityName");
EntityConditionList<EntityCondition> entityConditionList = UtilGenerics.cast(context.get("entityConditionList"));
List<String> orderByList = checkList(context.get("orderByList"), String.class);
boolean noConditionFind = "Y".equals(context.get("noConditionFind"));
boolean distinct = "Y".equals(context.get("distinct"));
List<String> fieldList = UtilGenerics.checkList(context.get("fieldList"));
Locale locale = (Locale) context.get("locale");
Set<String> fieldSet = null;
if (fieldList != null) {
fieldSet = UtilMisc.makeSetWritable(fieldList);
}
Integer maxRows = (Integer) context.get("maxRows");
maxRows = maxRows != null ? maxRows : -1;
Delegator delegator = dctx.getDelegator();
// Retrieve entities - an iterator over all the values
EntityListIterator listIt = null;
int listSize = 0;
try {
if (noConditionFind || (entityConditionList != null && entityConditionList.getConditionListSize() > 0)) {
listIt = EntityQuery.use(delegator)
.select(fieldSet)
.from(entityName)
.where(entityConditionList)
.orderBy(orderByList)
.cursorScrollInsensitive()
.maxRows(maxRows)
.distinct(distinct)
.queryIterator();
listSize = listIt.getResultsSizeAfterPartialList();
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "CommonFindErrorRunning", UtilMisc.toMap("entityName", entityName, "errorString", e.getMessage()), locale));
}
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("listIt", listIt);
results.put("listSize", listSize);
return results;
}
private static String dayStart(String timeStampString, int daysLater, TimeZone timeZone, Locale locale) {
String retValue = null;
Timestamp ts = null;
Timestamp startTs = null;
try {
ts = Timestamp.valueOf(timeStampString);
} catch (IllegalArgumentException e) {
timeStampString += " 00:00:00.000";
try {
ts = Timestamp.valueOf(timeStampString);
} catch (IllegalArgumentException e2) {
return retValue;
}
}
startTs = UtilDateTime.getDayStart(ts, daysLater, timeZone, locale);
retValue = startTs.toString();
return retValue;
}
public static Map<String, Object> buildReducedQueryString(Map<String, ?> inputFields, String entityName, Delegator delegator) {
// Strip the "_suffix" off of the parameter name and
// build a three-level map of values keyed by fieldRoot name,
// fld0 or fld1, and, then, "op" or "value"
// ie. id
// - fld0
// - op:like
// - value:abc
// - fld1 (if there is a range)
// - op:lessThan
// - value:55 (note: these two "flds" wouldn't really go together)
// Also note that op/fld can be in any order. (eg. id_fld1_equals or id_equals_fld1)
// Note that "normalizedFields" will contain values other than those
// Contained in the associated entity.
// Those extra fields will be ignored in the second half of this method.
ModelEntity modelEntity = delegator.getModelEntity(entityName);
Map<String, Object> normalizedFields = new LinkedHashMap<String, Object>();
//StringBuffer queryStringBuf = new StringBuffer();
for (String fieldNameRaw: inputFields.keySet()) { // The name as it appeas in the HTML form
String fieldNameRoot = null; // The entity field name. Everything to the left of the first "_" if
// it exists, or the whole word, if not.
Object fieldValue = null; // If it is a "value" field, it will be the value to be used in the query.
// If it is an "op" field, it will be "equals", "greaterThan", etc.
int iPos = -1;
int iPos2 = -1;
fieldValue = inputFields.get(fieldNameRaw);
if (ObjectType.isEmpty(fieldValue)) {
continue;
}
//queryStringBuffer.append(fieldNameRaw + "=" + fieldValue);
iPos = fieldNameRaw.indexOf("_"); // Look for suffix
// This is a hack to skip fields from "multi" forms
// These would have the form "fieldName_o_1"
if (iPos >= 0) {
String suffix = fieldNameRaw.substring(iPos + 1);
iPos2 = suffix.indexOf("_");
if (iPos2 == 1) {
continue;
}
}
// If no suffix, assume no range (default to fld0) and operations of equals
// If no field op is present, it will assume "equals".
if (iPos < 0) {
fieldNameRoot = fieldNameRaw;
} else { // Must have at least "fld0/1" or "equals, greaterThan, etc."
// Some bogus fields will slip in, like "ENTITY_NAME", but they will be ignored
fieldNameRoot = fieldNameRaw.substring(0, iPos);
}
if (modelEntity.isField(fieldNameRoot)) {
normalizedFields.put(fieldNameRaw, fieldValue);
}
}
return normalizedFields;
}
/**
* Returns the first generic item of the service 'performFind'
* Same parameters as performFind service but returns a single GenericValue
*
* @param dctx
* @param context
* @return returns the first item
*/
public static Map<String, Object> performFindItem(DispatchContext dctx, Map<String, Object> context) {
context.put("viewSize", 1);
context.put("viewIndex", 0);
Map<String, Object> result = org.apache.ofbiz.common.FindServices.performFind(dctx,context);
List<GenericValue> list = null;
GenericValue item= null;
try {
EntityListIterator it = (EntityListIterator) result.get("listIt");
list = it.getPartialList(1, 1); // list starts at '1'
if (UtilValidate.isNotEmpty(list)) {
item = list.get(0);
}
it.close();
} catch (Exception e) {
Debug.logInfo("Problem getting list Item" + e,module);
}
if (UtilValidate.isNotEmpty(item)) {
result.put("item",item);
}
result.remove("listIt");
if (result.containsKey("listSize")) {
result.remove("listSize");
}
return result;
}
}
|
googleapis/google-cloud-java
| 38,192
|
java-filestore/proto-google-cloud-filestore-v1/src/main/java/com/google/cloud/filestore/v1/CreateBackupRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/filestore/v1/cloud_filestore_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.filestore.v1;
/**
*
*
* <pre>
* CreateBackupRequest creates a backup.
* </pre>
*
* Protobuf type {@code google.cloud.filestore.v1.CreateBackupRequest}
*/
public final class CreateBackupRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.filestore.v1.CreateBackupRequest)
CreateBackupRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateBackupRequest.newBuilder() to construct.
private CreateBackupRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateBackupRequest() {
parent_ = "";
backupId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateBackupRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.filestore.v1.CloudFilestoreServiceProto
.internal_static_google_cloud_filestore_v1_CreateBackupRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.filestore.v1.CloudFilestoreServiceProto
.internal_static_google_cloud_filestore_v1_CreateBackupRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.filestore.v1.CreateBackupRequest.class,
com.google.cloud.filestore.v1.CreateBackupRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The backup's project and location, in the format
* `projects/{project_number}/locations/{location}`. In Filestore,
* backup locations map to Google Cloud regions, for example **us-west1**.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The backup's project and location, in the format
* `projects/{project_number}/locations/{location}`. In Filestore,
* backup locations map to Google Cloud regions, for example **us-west1**.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int BACKUP_FIELD_NUMBER = 2;
private com.google.cloud.filestore.v1.Backup backup_;
/**
*
*
* <pre>
* Required. A [backup resource][google.cloud.filestore.v1.Backup]
* </pre>
*
* <code>.google.cloud.filestore.v1.Backup backup = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the backup field is set.
*/
@java.lang.Override
public boolean hasBackup() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. A [backup resource][google.cloud.filestore.v1.Backup]
* </pre>
*
* <code>.google.cloud.filestore.v1.Backup backup = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The backup.
*/
@java.lang.Override
public com.google.cloud.filestore.v1.Backup getBackup() {
return backup_ == null ? com.google.cloud.filestore.v1.Backup.getDefaultInstance() : backup_;
}
/**
*
*
* <pre>
* Required. A [backup resource][google.cloud.filestore.v1.Backup]
* </pre>
*
* <code>.google.cloud.filestore.v1.Backup backup = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.filestore.v1.BackupOrBuilder getBackupOrBuilder() {
return backup_ == null ? com.google.cloud.filestore.v1.Backup.getDefaultInstance() : backup_;
}
public static final int BACKUP_ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object backupId_ = "";
/**
*
*
* <pre>
* Required. The ID to use for the backup.
* The ID must be unique within the specified project and location.
*
* This value must start with a lowercase letter followed by up to 62
* lowercase letters, numbers, or hyphens, and cannot end with a hyphen.
* Values that do not match this pattern will trigger an INVALID_ARGUMENT
* error.
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The backupId.
*/
@java.lang.Override
public java.lang.String getBackupId() {
java.lang.Object ref = backupId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
backupId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The ID to use for the backup.
* The ID must be unique within the specified project and location.
*
* This value must start with a lowercase letter followed by up to 62
* lowercase letters, numbers, or hyphens, and cannot end with a hyphen.
* Values that do not match this pattern will trigger an INVALID_ARGUMENT
* error.
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for backupId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getBackupIdBytes() {
java.lang.Object ref = backupId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
backupId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getBackup());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(backupId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, backupId_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getBackup());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(backupId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, backupId_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.filestore.v1.CreateBackupRequest)) {
return super.equals(obj);
}
com.google.cloud.filestore.v1.CreateBackupRequest other =
(com.google.cloud.filestore.v1.CreateBackupRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (hasBackup() != other.hasBackup()) return false;
if (hasBackup()) {
if (!getBackup().equals(other.getBackup())) return false;
}
if (!getBackupId().equals(other.getBackupId())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
if (hasBackup()) {
hash = (37 * hash) + BACKUP_FIELD_NUMBER;
hash = (53 * hash) + getBackup().hashCode();
}
hash = (37 * hash) + BACKUP_ID_FIELD_NUMBER;
hash = (53 * hash) + getBackupId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.filestore.v1.CreateBackupRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.filestore.v1.CreateBackupRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.filestore.v1.CreateBackupRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.filestore.v1.CreateBackupRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.filestore.v1.CreateBackupRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.filestore.v1.CreateBackupRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.filestore.v1.CreateBackupRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.filestore.v1.CreateBackupRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.filestore.v1.CreateBackupRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.filestore.v1.CreateBackupRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.filestore.v1.CreateBackupRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.filestore.v1.CreateBackupRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.filestore.v1.CreateBackupRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* CreateBackupRequest creates a backup.
* </pre>
*
* Protobuf type {@code google.cloud.filestore.v1.CreateBackupRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.filestore.v1.CreateBackupRequest)
com.google.cloud.filestore.v1.CreateBackupRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.filestore.v1.CloudFilestoreServiceProto
.internal_static_google_cloud_filestore_v1_CreateBackupRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.filestore.v1.CloudFilestoreServiceProto
.internal_static_google_cloud_filestore_v1_CreateBackupRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.filestore.v1.CreateBackupRequest.class,
com.google.cloud.filestore.v1.CreateBackupRequest.Builder.class);
}
// Construct using com.google.cloud.filestore.v1.CreateBackupRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getBackupFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
backup_ = null;
if (backupBuilder_ != null) {
backupBuilder_.dispose();
backupBuilder_ = null;
}
backupId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.filestore.v1.CloudFilestoreServiceProto
.internal_static_google_cloud_filestore_v1_CreateBackupRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.filestore.v1.CreateBackupRequest getDefaultInstanceForType() {
return com.google.cloud.filestore.v1.CreateBackupRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.filestore.v1.CreateBackupRequest build() {
com.google.cloud.filestore.v1.CreateBackupRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.filestore.v1.CreateBackupRequest buildPartial() {
com.google.cloud.filestore.v1.CreateBackupRequest result =
new com.google.cloud.filestore.v1.CreateBackupRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.filestore.v1.CreateBackupRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.backup_ = backupBuilder_ == null ? backup_ : backupBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.backupId_ = backupId_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.filestore.v1.CreateBackupRequest) {
return mergeFrom((com.google.cloud.filestore.v1.CreateBackupRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.filestore.v1.CreateBackupRequest other) {
if (other == com.google.cloud.filestore.v1.CreateBackupRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasBackup()) {
mergeBackup(other.getBackup());
}
if (!other.getBackupId().isEmpty()) {
backupId_ = other.backupId_;
bitField0_ |= 0x00000004;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getBackupFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
backupId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The backup's project and location, in the format
* `projects/{project_number}/locations/{location}`. In Filestore,
* backup locations map to Google Cloud regions, for example **us-west1**.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The backup's project and location, in the format
* `projects/{project_number}/locations/{location}`. In Filestore,
* backup locations map to Google Cloud regions, for example **us-west1**.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The backup's project and location, in the format
* `projects/{project_number}/locations/{location}`. In Filestore,
* backup locations map to Google Cloud regions, for example **us-west1**.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The backup's project and location, in the format
* `projects/{project_number}/locations/{location}`. In Filestore,
* backup locations map to Google Cloud regions, for example **us-west1**.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The backup's project and location, in the format
* `projects/{project_number}/locations/{location}`. In Filestore,
* backup locations map to Google Cloud regions, for example **us-west1**.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.cloud.filestore.v1.Backup backup_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.filestore.v1.Backup,
com.google.cloud.filestore.v1.Backup.Builder,
com.google.cloud.filestore.v1.BackupOrBuilder>
backupBuilder_;
/**
*
*
* <pre>
* Required. A [backup resource][google.cloud.filestore.v1.Backup]
* </pre>
*
* <code>.google.cloud.filestore.v1.Backup backup = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the backup field is set.
*/
public boolean hasBackup() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. A [backup resource][google.cloud.filestore.v1.Backup]
* </pre>
*
* <code>.google.cloud.filestore.v1.Backup backup = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The backup.
*/
public com.google.cloud.filestore.v1.Backup getBackup() {
if (backupBuilder_ == null) {
return backup_ == null
? com.google.cloud.filestore.v1.Backup.getDefaultInstance()
: backup_;
} else {
return backupBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. A [backup resource][google.cloud.filestore.v1.Backup]
* </pre>
*
* <code>.google.cloud.filestore.v1.Backup backup = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setBackup(com.google.cloud.filestore.v1.Backup value) {
if (backupBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
backup_ = value;
} else {
backupBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. A [backup resource][google.cloud.filestore.v1.Backup]
* </pre>
*
* <code>.google.cloud.filestore.v1.Backup backup = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setBackup(com.google.cloud.filestore.v1.Backup.Builder builderForValue) {
if (backupBuilder_ == null) {
backup_ = builderForValue.build();
} else {
backupBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. A [backup resource][google.cloud.filestore.v1.Backup]
* </pre>
*
* <code>.google.cloud.filestore.v1.Backup backup = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeBackup(com.google.cloud.filestore.v1.Backup value) {
if (backupBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& backup_ != null
&& backup_ != com.google.cloud.filestore.v1.Backup.getDefaultInstance()) {
getBackupBuilder().mergeFrom(value);
} else {
backup_ = value;
}
} else {
backupBuilder_.mergeFrom(value);
}
if (backup_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. A [backup resource][google.cloud.filestore.v1.Backup]
* </pre>
*
* <code>.google.cloud.filestore.v1.Backup backup = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearBackup() {
bitField0_ = (bitField0_ & ~0x00000002);
backup_ = null;
if (backupBuilder_ != null) {
backupBuilder_.dispose();
backupBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. A [backup resource][google.cloud.filestore.v1.Backup]
* </pre>
*
* <code>.google.cloud.filestore.v1.Backup backup = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.filestore.v1.Backup.Builder getBackupBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getBackupFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. A [backup resource][google.cloud.filestore.v1.Backup]
* </pre>
*
* <code>.google.cloud.filestore.v1.Backup backup = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.filestore.v1.BackupOrBuilder getBackupOrBuilder() {
if (backupBuilder_ != null) {
return backupBuilder_.getMessageOrBuilder();
} else {
return backup_ == null
? com.google.cloud.filestore.v1.Backup.getDefaultInstance()
: backup_;
}
}
/**
*
*
* <pre>
* Required. A [backup resource][google.cloud.filestore.v1.Backup]
* </pre>
*
* <code>.google.cloud.filestore.v1.Backup backup = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.filestore.v1.Backup,
com.google.cloud.filestore.v1.Backup.Builder,
com.google.cloud.filestore.v1.BackupOrBuilder>
getBackupFieldBuilder() {
if (backupBuilder_ == null) {
backupBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.filestore.v1.Backup,
com.google.cloud.filestore.v1.Backup.Builder,
com.google.cloud.filestore.v1.BackupOrBuilder>(
getBackup(), getParentForChildren(), isClean());
backup_ = null;
}
return backupBuilder_;
}
private java.lang.Object backupId_ = "";
/**
*
*
* <pre>
* Required. The ID to use for the backup.
* The ID must be unique within the specified project and location.
*
* This value must start with a lowercase letter followed by up to 62
* lowercase letters, numbers, or hyphens, and cannot end with a hyphen.
* Values that do not match this pattern will trigger an INVALID_ARGUMENT
* error.
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The backupId.
*/
public java.lang.String getBackupId() {
java.lang.Object ref = backupId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
backupId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The ID to use for the backup.
* The ID must be unique within the specified project and location.
*
* This value must start with a lowercase letter followed by up to 62
* lowercase letters, numbers, or hyphens, and cannot end with a hyphen.
* Values that do not match this pattern will trigger an INVALID_ARGUMENT
* error.
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for backupId.
*/
public com.google.protobuf.ByteString getBackupIdBytes() {
java.lang.Object ref = backupId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
backupId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The ID to use for the backup.
* The ID must be unique within the specified project and location.
*
* This value must start with a lowercase letter followed by up to 62
* lowercase letters, numbers, or hyphens, and cannot end with a hyphen.
* Values that do not match this pattern will trigger an INVALID_ARGUMENT
* error.
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The backupId to set.
* @return This builder for chaining.
*/
public Builder setBackupId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
backupId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ID to use for the backup.
* The ID must be unique within the specified project and location.
*
* This value must start with a lowercase letter followed by up to 62
* lowercase letters, numbers, or hyphens, and cannot end with a hyphen.
* Values that do not match this pattern will trigger an INVALID_ARGUMENT
* error.
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearBackupId() {
backupId_ = getDefaultInstance().getBackupId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ID to use for the backup.
* The ID must be unique within the specified project and location.
*
* This value must start with a lowercase letter followed by up to 62
* lowercase letters, numbers, or hyphens, and cannot end with a hyphen.
* Values that do not match this pattern will trigger an INVALID_ARGUMENT
* error.
* </pre>
*
* <code>string backup_id = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for backupId to set.
* @return This builder for chaining.
*/
public Builder setBackupIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
backupId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.filestore.v1.CreateBackupRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.filestore.v1.CreateBackupRequest)
private static final com.google.cloud.filestore.v1.CreateBackupRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.filestore.v1.CreateBackupRequest();
}
public static com.google.cloud.filestore.v1.CreateBackupRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateBackupRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateBackupRequest>() {
@java.lang.Override
public CreateBackupRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<CreateBackupRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateBackupRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.filestore.v1.CreateBackupRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/qpid-broker-j
| 38,172
|
systests/qpid-systests-jms_1.1/src/test/java/org/apache/qpid/systests/jms_1_1/topic/DurableSubscriptionTest.java
|
/* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.qpid.systests.jms_1_1.topic;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import java.util.Arrays;
import java.util.List;
import javax.jms.Connection;
import javax.jms.InvalidDestinationException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;
import javax.jms.TopicConnection;
import javax.jms.TopicPublisher;
import javax.jms.TopicSession;
import javax.jms.TopicSubscriber;
import org.junit.jupiter.api.Test;
import org.apache.qpid.server.model.Protocol;
import org.apache.qpid.systests.JmsTestBase;
public class DurableSubscriptionTest extends JmsTestBase
{
@Test
public void publishedMessagesAreSavedAfterSubscriberClose() throws Exception
{
Topic topic = createTopic(getTestName());
String subscriptionName = getTestName() + "_sub";
String clientId = "testClientId";
TopicConnection connection = (TopicConnection) getConnectionBuilder().setClientId(clientId).build();
try
{
Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(topic);
Session durableSubscriberSession = connection.createSession(true, Session.SESSION_TRANSACTED);
TopicSubscriber durableSubscriber =
durableSubscriberSession.createDurableSubscriber(topic, subscriptionName);
connection.start();
producer.send(producerSession.createTextMessage("A"));
Message message = durableSubscriber.receive(getReceiveTimeout());
assertTrue(message instanceof TextMessage);
assertEquals("A", ((TextMessage) message).getText());
durableSubscriberSession.commit();
producer.send(producerSession.createTextMessage("B"));
message = durableSubscriber.receive(getReceiveTimeout());
assertTrue(message instanceof TextMessage);
assertEquals("B", ((TextMessage) message).getText());
durableSubscriberSession.rollback();
durableSubscriber.close();
durableSubscriberSession.close();
producer.send(producerSession.createTextMessage("C"));
}
finally
{
connection.close();
}
if (getBrokerAdmin().supportsRestart())
{
getBrokerAdmin().restart();
}
TopicConnection connection2 = (TopicConnection) getConnectionBuilder().setClientId(clientId).build();
try
{
connection2.start();
final Session durableSubscriberSession = connection2.createSession(true, Session.SESSION_TRANSACTED);
final TopicSubscriber durableSubscriber =
durableSubscriberSession.createDurableSubscriber(topic, subscriptionName);
final List<String> expectedMessages = Arrays.asList("B", "C");
for (String expectedMessageText : expectedMessages)
{
final Message message = durableSubscriber.receive(getReceiveTimeout());
assertTrue(message instanceof TextMessage);
assertEquals(expectedMessageText, ((TextMessage) message).getText());
durableSubscriberSession.commit();
}
durableSubscriber.close();
durableSubscriberSession.unsubscribe(subscriptionName);
}
finally
{
connection2.close();
}
}
@Test
public void testUnsubscribe() throws Exception
{
Topic topic = createTopic(getTestName());
String subscriptionName = getTestName() + "_sub";
String clientId = "clientId";
int numberOfQueuesBeforeTest = getQueueCount();
Connection connection = getConnectionBuilder().setClientId(clientId).build();
try
{
Session durableSubscriberSession = connection.createSession(true, Session.SESSION_TRANSACTED);
Session nonDurableSubscriberSession = connection.createSession(true, Session.SESSION_TRANSACTED);
Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer subscriber = nonDurableSubscriberSession.createConsumer(topic);
MessageProducer producer = producerSession.createProducer(topic);
TopicSubscriber durableSubscriber =
durableSubscriberSession.createDurableSubscriber(topic, subscriptionName);
connection.start();
producer.send(nonDurableSubscriberSession.createTextMessage("A"));
Message message = subscriber.receive(getReceiveTimeout());
assertTrue(message instanceof TextMessage);
assertEquals("A", ((TextMessage) message).getText());
message = durableSubscriber.receive(getReceiveTimeout());
assertTrue(message instanceof TextMessage);
assertEquals("A", ((TextMessage) message).getText());
nonDurableSubscriberSession.commit();
durableSubscriberSession.commit();
durableSubscriber.close();
durableSubscriberSession.unsubscribe(subscriptionName);
producer.send(nonDurableSubscriberSession.createTextMessage("B"));
Session durableSubscriberSession2 = connection.createSession(true, Session.SESSION_TRANSACTED);
TopicSubscriber durableSubscriber2 =
durableSubscriberSession2.createDurableSubscriber(topic, subscriptionName);
producer.send(nonDurableSubscriberSession.createTextMessage("C"));
message = subscriber.receive(getReceiveTimeout());
assertTrue(message instanceof TextMessage);
assertEquals("B", ((TextMessage) message).getText());
message = subscriber.receive(getReceiveTimeout());
assertTrue(message instanceof TextMessage);
assertEquals("C", ((TextMessage) message).getText());
message = durableSubscriber2.receive(getReceiveTimeout());
assertTrue(message instanceof TextMessage);
assertEquals("C", ((TextMessage) message).getText());
nonDurableSubscriberSession.commit();
durableSubscriberSession2.commit();
assertEquals(0, getTotalDepthOfQueuesMessages(), "Message count should be 0");
durableSubscriber2.close();
durableSubscriberSession2.unsubscribe(subscriptionName);
}
finally
{
connection.close();
}
int numberOfQueuesAfterTest = getQueueCount();
assertEquals(numberOfQueuesBeforeTest, numberOfQueuesAfterTest, "Unexpected number of queues");
}
@Test
public void unsubscribeTwice() throws Exception
{
Topic topic = createTopic(getTestName());
Connection connection = getConnection();
String subscriptionName = getTestName() + "_sub";
try
{
Session subscriberSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
TopicSubscriber subscriber = subscriberSession.createDurableSubscriber(topic, subscriptionName);
MessageProducer publisher = subscriberSession.createProducer(topic);
connection.start();
publisher.send(subscriberSession.createTextMessage("Test"));
subscriberSession.commit();
Message message = subscriber.receive(getReceiveTimeout());
assertTrue(message instanceof TextMessage, "TextMessage should be received");
assertEquals("Test", ((TextMessage)message).getText(), "Unexpected message");
subscriberSession.commit();
subscriber.close();
subscriberSession.unsubscribe(subscriptionName);
try
{
subscriberSession.unsubscribe(subscriptionName);
fail("expected InvalidDestinationException when unsubscribing from unknown subscription");
}
catch (InvalidDestinationException e)
{
// PASS
}
catch (Exception e)
{
fail("expected InvalidDestinationException when unsubscribing from unknown subscription, got: " + e);
}
}
finally
{
connection.close();
}
}
/**
* <ul>
* <li>create and register a durable subscriber with no message selector
* <li>try to create another durable with the same name, should fail
* </ul>
* <p>
* QPID-2418
*/
@Test
public void multipleSubscribersWithTheSameName() throws Exception
{
String subscriptionName = getTestName() + "_sub";
Topic topic = createTopic(subscriptionName);
Connection conn = getConnection();
try
{
conn.start();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
// create and register a durable subscriber with no message selector
session.createDurableSubscriber(topic, subscriptionName, null, false);
// try to recreate the durable subscriber
try
{
session.createDurableSubscriber(topic, subscriptionName, null, false);
fail("Subscription should not have been created");
}
catch (JMSException e)
{
// pass
}
}
finally
{
conn.close();
}
}
@Test
public void testDurableSubscribeWithTemporaryTopic() throws Exception
{
assumeTrue(is(not(equalTo(Protocol.AMQP_1_0))).matches(getProtocol()), "Not investigated - fails on AMQP 1.0");
Connection connection = getConnection();
try
{
connection.start();
Session ssn = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = ssn.createTemporaryTopic();
try
{
ssn.createDurableSubscriber(topic, "test");
fail("expected InvalidDestinationException");
}
catch (InvalidDestinationException ex)
{
// this is expected
}
try
{
ssn.createDurableSubscriber(topic, "test", null, false);
fail("expected InvalidDestinationException");
}
catch (InvalidDestinationException ex)
{
// this is expected
}
}
finally
{
connection.close();
}
}
@Test
public void noLocalMessagesNotDelivered() throws Exception
{
String noLocalSubscriptionName = getTestName() + "_no_local_sub";
Topic topic = createTopic(getTestName());
String clientId = "testClientId";
Connection publishingConnection = getConnectionBuilder().setClientId("publishingConnection").build();
try
{
Session session = publishingConnection.createSession(true, Session.SESSION_TRANSACTED);
MessageProducer sessionProducer = session.createProducer(topic);
Connection noLocalConnection = getConnectionBuilder().setClientId(clientId).build();
try
{
Session noLocalSession = noLocalConnection.createSession(true, Session.SESSION_TRANSACTED);
MessageProducer noLocalSessionProducer = noLocalSession.createProducer(topic);
TopicSubscriber noLocalSubscriber =
noLocalSession.createDurableSubscriber(topic, noLocalSubscriptionName, null, true);
noLocalConnection.start();
publishingConnection.start();
noLocalSessionProducer.send(noLocalSession.createTextMessage("Message1"));
noLocalSession.commit();
sessionProducer.send(session.createTextMessage("Message2"));
session.commit();
Message durableSubscriberMessage = noLocalSubscriber.receive(getReceiveTimeout());
assertTrue(durableSubscriberMessage instanceof TextMessage);
assertEquals("Message2", ((TextMessage) durableSubscriberMessage).getText(),
"Unexpected local message received");
noLocalSession.commit();
}
finally
{
noLocalConnection.close();
}
Connection noLocalConnection2 = getConnectionBuilder().setClientId(clientId).build();
try
{
Session noLocalSession = noLocalConnection2.createSession(true, Session.SESSION_TRANSACTED);
noLocalConnection2.start();
TopicSubscriber noLocalSubscriber =
noLocalSession.createDurableSubscriber(topic, noLocalSubscriptionName, null, true);
try
{
sessionProducer.send(session.createTextMessage("Message3"));
session.commit();
final Message durableSubscriberMessage = noLocalSubscriber.receive(getReceiveTimeout());
assertTrue(durableSubscriberMessage instanceof TextMessage);
assertEquals("Message3", ((TextMessage) durableSubscriberMessage).getText(),
"Unexpected local message received");
noLocalSession.commit();
}
finally
{
noLocalSubscriber.close();
noLocalSession.unsubscribe(noLocalSubscriptionName);
}
}
finally
{
noLocalConnection2.close();
}
}
finally
{
publishingConnection.close();
}
}
/**
* Tests that messages are delivered normally to a subscriber on a separate connection despite
* the use of durable subscriber with no-local on the first connection.
*/
@Test
public void testNoLocalSubscriberAndSubscriberOnSeparateConnection() throws Exception
{
String noLocalSubscriptionName = getTestName() + "_no_local_sub";
String subscriobtionName = getTestName() + "_sub";
Topic topic = createTopic(getTestName());
final String clientId = "clientId";
Connection noLocalConnection = getConnectionBuilder().setClientId(clientId).build();
try
{
Connection connection = getConnection();
try
{
Session noLocalSession = noLocalConnection.createSession(true, Session.SESSION_TRANSACTED);
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
MessageProducer noLocalSessionProducer = noLocalSession.createProducer(topic);
MessageProducer sessionProducer = session.createProducer(topic);
try
{
TopicSubscriber noLocalSubscriber =
noLocalSession.createDurableSubscriber(topic, noLocalSubscriptionName, null, true);
TopicSubscriber subscriber = session.createDurableSubscriber(topic, subscriobtionName, null, false);
noLocalConnection.start();
connection.start();
noLocalSessionProducer.send(noLocalSession.createTextMessage("Message1"));
noLocalSession.commit();
sessionProducer.send(session.createTextMessage("Message2"));
sessionProducer.send(session.createTextMessage("Message3"));
session.commit();
Message durableSubscriberMessage = noLocalSubscriber.receive(getReceiveTimeout());
assertTrue(durableSubscriberMessage instanceof TextMessage);
assertEquals("Message2", ((TextMessage) durableSubscriberMessage).getText(),
"Unexpected local message received");
noLocalSession.commit();
Message nonDurableSubscriberMessage = subscriber.receive(getReceiveTimeout());
assertTrue(nonDurableSubscriberMessage instanceof TextMessage);
assertEquals("Message1", ((TextMessage) nonDurableSubscriberMessage).getText(),
"Unexpected message received");
session.commit();
noLocalSubscriber.close();
subscriber.close();
}
finally
{
noLocalSession.unsubscribe(noLocalSubscriptionName);
session.unsubscribe(subscriobtionName);
}
}
finally
{
connection.close();
}
}
finally
{
noLocalConnection.close();
}
}
@Test
public void testResubscribeWithChangedNoLocal() throws Exception
{
assumeTrue(is(equalTo(Protocol.AMQP_1_0)).matches(getProtocol()), "QPID-8068");
String subscriptionName = getTestName() + "_sub";
Topic topic = createTopic(getTestName());
String clientId = "testClientId";
Connection connection = getConnectionBuilder().setClientId(clientId).build();
try
{
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
TopicSubscriber durableSubscriber =
session.createDurableSubscriber(topic, subscriptionName, null, false);
MessageProducer producer = session.createProducer(topic);
producer.send(session.createTextMessage("A"));
producer.send(session.createTextMessage("B"));
session.commit();
connection.start();
Message receivedMessage = durableSubscriber.receive(getReceiveTimeout());
assertTrue(receivedMessage instanceof TextMessage, "TextMessage should be received");
assertEquals("A", ((TextMessage)receivedMessage).getText(), "Unexpected message received");
session.commit();
}
finally
{
connection.close();
}
connection = getConnectionBuilder().setClientId(clientId).build();
try
{
connection.start();
Session session2 = connection.createSession(true, Session.SESSION_TRANSACTED);
TopicSubscriber noLocalSubscriber2 = session2.createDurableSubscriber(topic, subscriptionName, null, true);
Connection secondConnection = getConnectionBuilder().setClientId("secondConnection").build();
try
{
Session secondSession = secondConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer secondProducer = secondSession.createProducer(topic);
secondProducer.send(secondSession.createTextMessage("C"));
}
finally
{
secondConnection.close();
}
Message noLocalSubscriberMessage = noLocalSubscriber2.receive(getReceiveTimeout());
assertTrue(noLocalSubscriberMessage instanceof TextMessage, "TextMessage should be received");
assertEquals("C", ((TextMessage)noLocalSubscriberMessage).getText(),
"Unexpected message received");
}
finally
{
connection.close();
}
}
/**
* create and register a durable subscriber with a message selector and then close it
* crash the broker
* create a publisher and send 5 right messages and 5 wrong messages
* recreate the durable subscriber and check we receive the 5 expected messages
*/
@Test
public void testMessageSelectorRecoveredOnBrokerRestart() throws Exception
{
assumeTrue(getBrokerAdmin().supportsRestart());
final Topic topic = createTopic(getTestName());
String clientId = "testClientId";
String subscriptionName = getTestName() + "_sub";
TopicConnection subscriberConnection =
(TopicConnection) getConnectionBuilder().setClientId(clientId).build();
try
{
TopicSession session = subscriberConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicSubscriber subscriber =
session.createDurableSubscriber(topic, subscriptionName, "testprop='true'", false);
subscriberConnection.start();
subscriber.close();
session.close();
}
finally
{
subscriberConnection.close();
}
getBrokerAdmin().restart();
TopicConnection connection = (TopicConnection) getConnectionBuilder().setClientId(clientId).build();
try
{
TopicSession session = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicPublisher publisher = session.createPublisher(topic);
for (int i = 0; i < 10; i++)
{
Message message = session.createMessage();
message.setStringProperty("testprop", String.valueOf(i % 2 == 0));
publisher.publish(message);
}
publisher.close();
session.close();
}
finally
{
connection.close();
}
TopicConnection subscriberConnection2 =
(TopicConnection) getConnectionBuilder().setClientId(clientId).build();
try
{
TopicSession session = subscriberConnection2.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicSubscriber subscriber =
session.createDurableSubscriber(topic, subscriptionName, "testprop='true'", false);
subscriberConnection2.start();
for (int i = 0; i < 5; i++)
{
Message message = subscriber.receive(1000);
if (message == null)
{
fail(String.format("Message '%d' was received", i));
}
else
{
assertEquals("true", message.getStringProperty("testprop"),
String.format("Received message %d with not matching selector", i));
}
}
subscriber.close();
session.unsubscribe(subscriptionName);
}
finally
{
subscriberConnection2.close();
}
}
/**
* create and register a durable subscriber without a message selector and then unsubscribe it
* create and register a durable subscriber with a message selector and then close it
* restart the broker
* send matching and non matching messages
* recreate and register the durable subscriber with a message selector
* verify only the matching messages are received
*/
@Test
public void testChangeSubscriberToHaveSelector() throws Exception
{
assumeTrue(getBrokerAdmin().supportsRestart());
final String subscriptionName = getTestName() + "_sub";
Topic topic = createTopic(getTestName());
String testClientId = "testClientId";
TopicConnection subscriberConnection =
(TopicConnection) getConnectionBuilder().setClientId(testClientId).build();
try
{
TopicSession session = subscriberConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicSubscriber subscriber = session.createDurableSubscriber(topic, subscriptionName);
TopicPublisher publisher = session.createPublisher(topic);
publisher.send(session.createTextMessage("Message1"));
publisher.send(session.createTextMessage("Message2"));
subscriberConnection.start();
Message receivedMessage = subscriber.receive(getReceiveTimeout());
assertTrue(receivedMessage instanceof TextMessage);
assertEquals("Message1", ((TextMessage) receivedMessage).getText(),
"Unexpected message content");
subscriber.close();
session.close();
}
finally
{
subscriberConnection.close();
}
//create and register a durable subscriber with a message selector and then close it
TopicConnection subscriberConnection2 =
(TopicConnection) getConnectionBuilder().setClientId(testClientId).build();
try
{
TopicSession session = subscriberConnection2.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicSubscriber subscriber =
session.createDurableSubscriber(topic, subscriptionName, "testprop='true'", false);
TopicPublisher publisher = session.createPublisher(topic);
TextMessage message = session.createTextMessage("Message3");
message.setStringProperty("testprop", "false");
publisher.send(message);
message = session.createTextMessage("Message4");
message.setStringProperty("testprop", "true");
publisher.send(message);
subscriberConnection2.start();
Message receivedMessage = subscriber.receive(getReceiveTimeout());
assertTrue(receivedMessage instanceof TextMessage);
assertEquals("Message4", ((TextMessage) receivedMessage).getText(),
"Unexpected message content");
subscriber.close();
session.close();
}
finally
{
subscriberConnection2.close();
}
getBrokerAdmin().restart();
TopicConnection publisherConnection = getTopicConnection();
try
{
TopicSession session = publisherConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicPublisher publisher = session.createPublisher(topic);
for (int i = 0; i < 10; i++)
{
Message message = session.createMessage();
message.setStringProperty("testprop", String.valueOf(i % 2 == 0));
publisher.publish(message);
}
publisher.close();
session.close();
}
finally
{
publisherConnection.close();
}
TopicConnection subscriberConnection3 =
(TopicConnection) getConnectionBuilder().setClientId(testClientId).build();
try
{
TopicSession session = (TopicSession) subscriberConnection3.createSession(false, Session.AUTO_ACKNOWLEDGE);
TopicSubscriber subscriber =
session.createDurableSubscriber(topic, subscriptionName, "testprop='true'", false);
subscriberConnection3.start();
for (int i = 0; i < 5; i++)
{
Message message = subscriber.receive(2000);
if (message == null)
{
fail(String.format("Message '%d' was not received", i));
}
else
{
assertEquals("true", message.getStringProperty("testprop"),
String.format("Received message %d with not matching selector", i));
}
}
subscriber.close();
session.unsubscribe(subscriptionName);
session.close();
}
finally
{
subscriberConnection3.close();
}
}
/**
* create and register a durable subscriber with a message selector and then unsubscribe it
* create and register a durable subscriber without a message selector and then close it
* restart the broker
* send matching and non matching messages
* recreate and register the durable subscriber without a message selector
* verify ALL the sent messages are received
*/
@Test
public void testChangeSubscriberToHaveNoSelector() throws Exception
{
assumeTrue(getBrokerAdmin().supportsRestart());
final String subscriptionName = getTestName() + "_sub";
Topic topic = createTopic(getTestName());
String clientId = "testClientId";
//create and register a durable subscriber with selector then unsubscribe it
TopicConnection durConnection = (TopicConnection) getConnectionBuilder().setClientId(clientId).build();
try
{
TopicSession session = durConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicSubscriber subscriber =
session.createDurableSubscriber(topic, subscriptionName, "testprop='true'", false);
TopicPublisher publisher = session.createPublisher(topic);
TextMessage message = session.createTextMessage("Messag1");
message.setStringProperty("testprop", "false");
publisher.send(message);
message = session.createTextMessage("Message2");
message.setStringProperty("testprop", "true");
publisher.send(message);
message = session.createTextMessage("Message3");
message.setStringProperty("testprop", "true");
publisher.send(message);
durConnection.start();
Message receivedMessage = subscriber.receive(getReceiveTimeout());
assertTrue(receivedMessage instanceof TextMessage);
assertEquals("Message2", ((TextMessage) receivedMessage).getText(),
"Unexpected message content");
subscriber.close();
session.close();
}
finally
{
durConnection.close();
}
//create and register a durable subscriber without the message selector and then close it
TopicConnection subscriberConnection2 =
(TopicConnection) getConnectionBuilder().setClientId(clientId).build();
try
{
TopicSession session = subscriberConnection2.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicSubscriber subscriber = session.createDurableSubscriber(topic, subscriptionName);
subscriberConnection2.start();
subscriber.close();
session.close();
}
finally
{
subscriberConnection2.close();
}
//send messages matching and not matching the original used selector
TopicConnection publisherConnection = getTopicConnection();
try
{
TopicSession session = publisherConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicPublisher publisher = session.createPublisher(topic);
for (int i = 1; i <= 10; i++)
{
Message message = session.createMessage();
message.setStringProperty("testprop", String.valueOf(i % 2 == 0));
publisher.publish(message);
}
publisher.close();
session.close();
}
finally
{
publisherConnection.close();
}
getBrokerAdmin().restart();
TopicConnection subscriberConnection3 =
(TopicConnection) getConnectionBuilder().setClientId(clientId).build();
try
{
TopicSession session = (TopicSession) subscriberConnection3.createSession(false, Session.AUTO_ACKNOWLEDGE);
TopicSubscriber subscriber = session.createDurableSubscriber(topic, subscriptionName);
subscriberConnection3.start();
for (int i = 1; i <= 10; i++)
{
Message message = subscriber.receive(2000);
if (message == null)
{
fail(String.format("Message %d was not received", i));
}
}
subscriber.close();
session.unsubscribe(subscriptionName);
session.close();
}
finally
{
subscriberConnection3.close();
}
}
@Test
public void testResubscribeWithChangedSelector() throws Exception
{
assumeTrue(getBrokerAdmin().supportsRestart());
String subscriptionName = getTestName() + "_sub";
Topic topic = createTopic(getTestName());
String clientId = "testClientId";
TopicConnection connection = (TopicConnection) getConnectionBuilder().setClientId(clientId).build();
try
{
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(topic);
// Create durable subscriber that matches A
TopicSubscriber subscriberA =
session.createDurableSubscriber(topic, subscriptionName, "Match = True", false);
// Send 1 non-matching message and 1 matching message
TextMessage message = session.createTextMessage("Message1");
message.setBooleanProperty("Match", false);
producer.send(message);
message = session.createTextMessage("Message2");
message.setBooleanProperty("Match", true);
producer.send(message);
Message receivedMessage = subscriberA.receive(getReceiveTimeout());
assertTrue(receivedMessage instanceof TextMessage);
assertEquals("Message2", ((TextMessage) receivedMessage).getText(), "Unexpected message content");
// Send another 1 matching message and 1 non-matching message
message = session.createTextMessage("Message3");
message.setBooleanProperty("Match", true);
producer.send(message);
message = session.createTextMessage("Message4");
message.setBooleanProperty("Match", false);
producer.send(message);
// Disconnect subscriber without receiving the message to
//leave it on the underlying queue
subscriberA.close();
// Reconnect with new selector that matches B
TopicSubscriber subscriberB = session.createDurableSubscriber(topic,
subscriptionName,
"Match = False", false);
// Check that new messages are received properly
message = session.createTextMessage("Message5");
message.setBooleanProperty("Match", true);
producer.send(message);
message = session.createTextMessage("Message6");
message.setBooleanProperty("Match", false);
producer.send(message);
// changing the selector should have cleared the queue so we expect message 6 instead of message 4
receivedMessage = subscriberB.receive(getReceiveTimeout());
assertTrue(receivedMessage instanceof TextMessage);
assertEquals("Message6", ((TextMessage) receivedMessage).getText(),
"Unexpected message content");
// publish a message to be consumed after restart
message = session.createTextMessage("Message7");
message.setBooleanProperty("Match", true);
producer.send(message);
message = session.createTextMessage("Message8");
message.setBooleanProperty("Match", false);
producer.send(message);
session.close();
}
finally
{
connection.close();
}
//now restart the server
getBrokerAdmin().restart();
// Reconnect to broker
TopicConnection connection2 = (TopicConnection) getConnectionBuilder().setClientId(clientId).build();
try
{
connection2.start();
Session session = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Reconnect with new selector that matches B
TopicSubscriber subscriberC =
session.createDurableSubscriber(topic, subscriptionName, "Match = False", false);
//check the dur sub's underlying queue now has msg count 1
Message receivedMessage = subscriberC.receive(getReceiveTimeout());
assertTrue(receivedMessage instanceof TextMessage);
assertEquals("Message8", ((TextMessage) receivedMessage).getText(), "Unexpected message content");
subscriberC.close();
session.unsubscribe(subscriptionName);
session.close();
}
finally
{
connection2.close();
}
}
}
|
apache/fineract
| 38,890
|
fineract-savings/src/main/java/org/apache/fineract/portfolio/savings/data/FixedDepositAccountData.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.fineract.portfolio.savings.data;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Collection;
import lombok.Getter;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.fineract.infrastructure.core.data.EnumOptionData;
import org.apache.fineract.organisation.monetary.data.CurrencyData;
import org.apache.fineract.organisation.staff.data.StaffData;
import org.apache.fineract.portfolio.account.data.PortfolioAccountData;
import org.apache.fineract.portfolio.charge.data.ChargeData;
import org.apache.fineract.portfolio.paymenttype.data.PaymentTypeData;
import org.apache.fineract.portfolio.savings.DepositAccountType;
import org.apache.fineract.portfolio.savings.service.SavingsEnumerations;
import org.apache.fineract.portfolio.tax.data.TaxGroupData;
/**
* Immutable data object representing a Fixed Deposit account.
*/
@Getter
public final class FixedDepositAccountData extends DepositAccountData {
private boolean preClosurePenalApplicable;
private BigDecimal preClosurePenalInterest;
private EnumOptionData preClosurePenalInterestOnType;
private Integer minDepositTerm;
private Integer maxDepositTerm;
private EnumOptionData minDepositTermType;
private EnumOptionData maxDepositTermType;
private Integer inMultiplesOfDepositTerm;
private EnumOptionData inMultiplesOfDepositTermType;
private BigDecimal depositAmount;
private BigDecimal maturityAmount;
private LocalDate maturityDate;
private Integer depositPeriod;
private EnumOptionData depositPeriodFrequency;
private BigDecimal activationCharge;
private Long transferToSavingsId;
// used for account close
private EnumOptionData onAccountClosure;
private final PortfolioAccountData linkedAccount;
private final Boolean transferInterestToSavings;
private final PortfolioAccountData transferToSavingsAccount;
private Collection<EnumOptionData> preClosurePenalInterestOnTypeOptions;
private Collection<EnumOptionData> periodFrequencyTypeOptions;
private Collection<SavingsAccountData> savingsAccounts;
// for account close
private Collection<EnumOptionData> onAccountClosureOptions;
private Collection<PaymentTypeData> paymentTypeOptions;
private final Collection<EnumOptionData> maturityInstructionOptions;
// import fields
private transient Integer rowIndex;
private String dateFormat;
private String locale;
private LocalDate submittedOnDate;
private Long depositPeriodFrequencyId;
public static FixedDepositAccountData importInstance(Long clientId, Long productId, Long fieldOfficerId, LocalDate submittedOnDate,
EnumOptionData interestCompoundingPeriodTypeEnum, EnumOptionData interestPostingPeriodTypeEnum,
EnumOptionData interestCalculationTypeEnum, EnumOptionData interestCalculationDaysInYearTypeEnum, Integer lockinPeriodFrequency,
EnumOptionData lockinPeriodFrequencyTypeEnum, BigDecimal depositAmount, Integer depositPeriod, Long depositPeriodFrequencyId,
String externalId, Collection<SavingsAccountChargeData> charges, Integer rowIndex, String locale, String dateFormat) {
return new FixedDepositAccountData(clientId, productId, fieldOfficerId, submittedOnDate, interestCompoundingPeriodTypeEnum,
interestPostingPeriodTypeEnum, interestCalculationTypeEnum, interestCalculationDaysInYearTypeEnum, lockinPeriodFrequency,
lockinPeriodFrequencyTypeEnum, depositAmount, depositPeriod, depositPeriodFrequencyId, externalId, charges, rowIndex,
locale, dateFormat);
}
private FixedDepositAccountData(Long clientId, Long productId, Long fieldofficerId, LocalDate submittedOnDate,
EnumOptionData interestCompoundingPeriodType, EnumOptionData interestPostingPeriodType, EnumOptionData interestCalculationType,
EnumOptionData interestCalculationDaysInYearType, Integer lockinPeriodFrequency, EnumOptionData lockinPeriodFrequencyType,
BigDecimal depositAmount, Integer depositPeriod, Long depositPeriodFrequencyId, String externalId,
Collection<SavingsAccountChargeData> charges, Integer rowIndex, String locale, String dateFormat) {
super(clientId, productId, fieldofficerId, interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType,
interestCalculationDaysInYearType, lockinPeriodFrequency, lockinPeriodFrequencyType, externalId, charges);
this.preClosurePenalApplicable = false;
this.preClosurePenalInterest = null;
this.preClosurePenalInterestOnType = null;
this.minDepositTerm = null;
this.maxDepositTerm = null;
this.minDepositTermType = null;
this.maxDepositTermType = null;
this.inMultiplesOfDepositTerm = null;
this.inMultiplesOfDepositTermType = null;
this.depositAmount = depositAmount;
this.maturityAmount = null;
this.maturityDate = null;
this.depositPeriod = depositPeriod;
this.depositPeriodFrequency = null;
this.activationCharge = null;
this.onAccountClosure = null;
this.linkedAccount = null;
this.transferToSavingsAccount = null;
this.transferInterestToSavings = null;
this.preClosurePenalInterestOnTypeOptions = null;
this.periodFrequencyTypeOptions = null;
this.savingsAccounts = null;
this.onAccountClosureOptions = null;
this.paymentTypeOptions = null;
this.rowIndex = rowIndex;
this.dateFormat = dateFormat;
this.locale = locale;
this.submittedOnDate = submittedOnDate;
this.depositPeriodFrequencyId = depositPeriodFrequencyId;
this.maturityInstructionOptions = null;
}
public static FixedDepositAccountData instance(final DepositAccountData depositAccountData, final boolean preClosurePenalApplicable,
final BigDecimal preClosurePenalInterest, final EnumOptionData preClosurePenalInterestOnType, final Integer minDepositTerm,
final Integer maxDepositTerm, final EnumOptionData minDepositTermType, final EnumOptionData maxDepositTermType,
final Integer inMultiplesOfDepositTerm, final EnumOptionData inMultiplesOfDepositTermType, final BigDecimal depositAmount,
final BigDecimal maturityAmount, final LocalDate maturityDate, final Integer depositPeriod,
final EnumOptionData depositPeriodFrequency, final EnumOptionData onAccountClosure, final Boolean transferInterestToSavings,
final Long transferToSavingsId) {
final PortfolioAccountData linkedAccount = null;
final PortfolioAccountData transferToSavingsAccount = null;
final Collection<EnumOptionData> preClosurePenalInterestOnTypeOptions = null;
final Collection<EnumOptionData> periodFrequencyTypeOptions = null;
final Collection<EnumOptionData> maturityInstructionOptions = null;
final EnumOptionData depositType = SavingsEnumerations.depositType(DepositAccountType.FIXED_DEPOSIT.getValue());
final Collection<EnumOptionData> onAccountClosureOptions = null;
final Collection<PaymentTypeData> paymentTypeOptions = null;
final Collection<SavingsAccountData> savingsAccountDatas = null;
return new FixedDepositAccountData(depositAccountData.id, depositAccountData.accountNo, depositAccountData.externalId,
depositAccountData.groupId, depositAccountData.groupName, depositAccountData.clientId, depositAccountData.clientName,
depositAccountData.depositProductId, depositAccountData.depositProductName, depositAccountData.fieldOfficerId,
depositAccountData.fieldOfficerName, depositAccountData.status, depositAccountData.timeline, depositAccountData.currency,
depositAccountData.nominalAnnualInterestRate, depositAccountData.interestCompoundingPeriodType,
depositAccountData.interestPostingPeriodType, depositAccountData.interestCalculationType,
depositAccountData.interestCalculationDaysInYearType, depositAccountData.minRequiredOpeningBalance,
depositAccountData.lockinPeriodFrequency, depositAccountData.lockinPeriodFrequencyType,
depositAccountData.withdrawalFeeForTransfers, depositAccountData.minBalanceForInterestCalculation,
depositAccountData.summary, depositAccountData.transactions, depositAccountData.productOptions,
depositAccountData.fieldOfficerOptions, depositAccountData.interestCompoundingPeriodTypeOptions,
depositAccountData.interestPostingPeriodTypeOptions, depositAccountData.interestCalculationTypeOptions,
depositAccountData.interestCalculationDaysInYearTypeOptions, depositAccountData.lockinPeriodFrequencyTypeOptions,
depositAccountData.withdrawalFeeTypeOptions, depositAccountData.charges, depositAccountData.chargeOptions,
depositAccountData.accountChart, depositAccountData.chartTemplate, preClosurePenalApplicable, preClosurePenalInterest,
preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm, maxDepositTerm, minDepositTermType,
maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType, depositAmount, maturityAmount, maturityDate,
depositPeriod, depositPeriodFrequency, periodFrequencyTypeOptions, depositType, onAccountClosure, onAccountClosureOptions,
paymentTypeOptions, savingsAccountDatas, linkedAccount, transferInterestToSavings, depositAccountData.withHoldTax,
depositAccountData.taxGroup, maturityInstructionOptions, transferToSavingsId, transferToSavingsAccount);
}
public static FixedDepositAccountData withInterestChart(final FixedDepositAccountData account,
final DepositAccountInterestRateChartData accountChart) {
return new FixedDepositAccountData(account.id, account.accountNo, account.externalId, account.groupId, account.groupName,
account.clientId, account.clientName, account.depositProductId, account.depositProductName, account.fieldOfficerId,
account.fieldOfficerName, account.status, account.timeline, account.currency, account.nominalAnnualInterestRate,
account.interestCompoundingPeriodType, account.interestPostingPeriodType, account.interestCalculationType,
account.interestCalculationDaysInYearType, account.minRequiredOpeningBalance, account.lockinPeriodFrequency,
account.lockinPeriodFrequencyType, account.withdrawalFeeForTransfers, account.minBalanceForInterestCalculation,
account.summary, account.transactions, account.productOptions, account.fieldOfficerOptions,
account.interestCompoundingPeriodTypeOptions, account.interestPostingPeriodTypeOptions,
account.interestCalculationTypeOptions, account.interestCalculationDaysInYearTypeOptions,
account.lockinPeriodFrequencyTypeOptions, account.withdrawalFeeTypeOptions, account.charges, account.chargeOptions,
accountChart, account.chartTemplate, account.preClosurePenalApplicable, account.preClosurePenalInterest,
account.preClosurePenalInterestOnType, account.preClosurePenalInterestOnTypeOptions, account.minDepositTerm,
account.maxDepositTerm, account.minDepositTermType, account.maxDepositTermType, account.inMultiplesOfDepositTerm,
account.inMultiplesOfDepositTermType, account.depositAmount, account.maturityAmount, account.maturityDate,
account.depositPeriod, account.depositPeriodFrequency, account.periodFrequencyTypeOptions, account.depositType,
account.onAccountClosure, account.onAccountClosureOptions, account.paymentTypeOptions, account.savingsAccounts,
account.linkedAccount, account.transferInterestToSavings, account.withHoldTax, account.taxGroup,
account.maturityInstructionOptions, account.transferToSavingsId, account.transferToSavingsAccount);
}
public static FixedDepositAccountData associationsAndTemplate(final FixedDepositAccountData account, FixedDepositAccountData template,
final Collection<SavingsAccountTransactionData> transactions, final Collection<SavingsAccountChargeData> charges,
final PortfolioAccountData linkedAccount, PortfolioAccountData transferToSavingsAccount) {
if (template == null) {
template = account;
}
return new FixedDepositAccountData(account.id, account.accountNo, account.externalId, account.groupId, account.groupName,
account.clientId, account.clientName, account.depositProductId, account.depositProductName, account.fieldOfficerId,
account.fieldOfficerName, account.status, account.timeline, account.currency, account.nominalAnnualInterestRate,
account.interestCompoundingPeriodType, account.interestPostingPeriodType, account.interestCalculationType,
account.interestCalculationDaysInYearType, account.minRequiredOpeningBalance, account.lockinPeriodFrequency,
account.lockinPeriodFrequencyType, account.withdrawalFeeForTransfers, account.minBalanceForInterestCalculation,
account.summary, transactions, template.productOptions, template.fieldOfficerOptions,
template.interestCompoundingPeriodTypeOptions, template.interestPostingPeriodTypeOptions,
template.interestCalculationTypeOptions, template.interestCalculationDaysInYearTypeOptions,
template.lockinPeriodFrequencyTypeOptions, template.withdrawalFeeTypeOptions, charges, template.chargeOptions,
account.accountChart, account.chartTemplate, account.preClosurePenalApplicable, account.preClosurePenalInterest,
account.preClosurePenalInterestOnType, template.preClosurePenalInterestOnTypeOptions, account.minDepositTerm,
account.maxDepositTerm, account.minDepositTermType, account.maxDepositTermType, account.inMultiplesOfDepositTerm,
account.inMultiplesOfDepositTermType, account.depositAmount, account.maturityAmount, account.maturityDate,
account.depositPeriod, account.depositPeriodFrequency, template.periodFrequencyTypeOptions, account.depositType,
account.onAccountClosure, account.onAccountClosureOptions, account.paymentTypeOptions, template.savingsAccounts,
linkedAccount, account.transferInterestToSavings, account.withHoldTax, account.taxGroup, account.maturityInstructionOptions,
account.transferToSavingsId, transferToSavingsAccount);
}
public static FixedDepositAccountData withTemplateOptions(final FixedDepositAccountData account,
final Collection<DepositProductData> productOptions, final Collection<StaffData> fieldOfficerOptions,
final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions,
final Collection<EnumOptionData> interestPostingPeriodTypeOptions,
final Collection<EnumOptionData> interestCalculationTypeOptions,
final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions,
final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions, final Collection<EnumOptionData> withdrawalFeeTypeOptions,
final Collection<SavingsAccountTransactionData> transactions, final Collection<SavingsAccountChargeData> charges,
final Collection<ChargeData> chargeOptions, final Collection<EnumOptionData> preClosurePenalInterestOnTypeOptions,
final Collection<EnumOptionData> periodFrequencyTypeOptions, final Collection<SavingsAccountData> savingsAccounts,
final Collection<EnumOptionData> maturityInstructionOptions) {
return new FixedDepositAccountData(account.id, account.accountNo, account.externalId, account.groupId, account.groupName,
account.clientId, account.clientName, account.depositProductId, account.depositProductName, account.fieldOfficerId,
account.fieldOfficerName, account.status, account.timeline, account.currency, account.nominalAnnualInterestRate,
account.interestCompoundingPeriodType, account.interestPostingPeriodType, account.interestCalculationType,
account.interestCalculationDaysInYearType, account.minRequiredOpeningBalance, account.lockinPeriodFrequency,
account.lockinPeriodFrequencyType, account.withdrawalFeeForTransfers, account.minBalanceForInterestCalculation,
account.summary, transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions,
interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions,
lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, account.accountChart,
account.chartTemplate, account.preClosurePenalApplicable, account.preClosurePenalInterest,
account.preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, account.minDepositTerm, account.maxDepositTerm,
account.minDepositTermType, account.maxDepositTermType, account.inMultiplesOfDepositTerm,
account.inMultiplesOfDepositTermType, account.depositAmount, account.maturityAmount, account.maturityDate,
account.depositPeriod, account.depositPeriodFrequency, periodFrequencyTypeOptions, account.depositType,
account.onAccountClosure, account.onAccountClosureOptions, account.paymentTypeOptions, savingsAccounts,
account.linkedAccount, account.transferInterestToSavings, account.withHoldTax, account.taxGroup, maturityInstructionOptions,
account.transferToSavingsId, account.transferToSavingsAccount);
}
public static FixedDepositAccountData withClientTemplate(final Long clientId, final String clientName, final Long groupId,
final String groupName) {
final Long id = null;
final String accountNo = null;
final String externalId = null;
final Long productId = null;
final String productName = null;
final Long fieldOfficerId = null;
final String fieldOfficerName = null;
final SavingsAccountStatusEnumData status = null;
final SavingsAccountApplicationTimelineData timeline = null;
final CurrencyData currency = null;
final BigDecimal nominalAnnualInterestRate = null;
final EnumOptionData interestPeriodType = null;
final EnumOptionData interestPostingPeriodType = null;
final EnumOptionData interestCalculationType = null;
final EnumOptionData interestCalculationDaysInYearType = null;
final BigDecimal minRequiredOpeningBalance = null;
final Integer lockinPeriodFrequency = null;
final EnumOptionData lockinPeriodFrequencyType = null;
final boolean withdrawalFeeForTransfers = false;
final BigDecimal minBalanceForInterestCalculation = null;
final SavingsAccountSummaryData summary = null;
final Collection<SavingsAccountTransactionData> transactions = null;
final boolean withHoldTax = false;
final TaxGroupData taxGroup = null;
final Collection<DepositProductData> productOptions = null;
final Collection<StaffData> fieldOfficerOptions = null;
final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions = null;
final Collection<EnumOptionData> interestPostingPeriodTypeOptions = null;
final Collection<EnumOptionData> interestCalculationTypeOptions = null;
final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions = null;
final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions = null;
final Collection<EnumOptionData> withdrawalFeeTypeOptions = null;
final Collection<SavingsAccountChargeData> charges = null;
final Collection<ChargeData> chargeOptions = null;
final DepositAccountInterestRateChartData accountChart = null;
final DepositAccountInterestRateChartData chartTemplate = null;
final boolean preClosurePenalApplicable = false;
final BigDecimal preClosurePenalInterest = null;
final EnumOptionData preClosurePenalInterestOnType = null;
final Integer minDepositTerm = null;
final Integer maxDepositTerm = null;
final EnumOptionData minDepositTermType = null;
final EnumOptionData maxDepositTermType = null;
final Integer inMultiplesOfDepositTerm = null;
final EnumOptionData inMultiplesOfDepositTermType = null;
final BigDecimal depositAmount = null;
final BigDecimal maturityAmount = null;
final LocalDate maturityDate = null;
final Integer depositPeriod = null;
final EnumOptionData depositPeriodFrequency = null;
final EnumOptionData onAccountClosure = null;
final PortfolioAccountData linkedAccount = null;
final PortfolioAccountData transferToSavingsAccount = null;
final Boolean transferInterestToSavings = null;
final Collection<EnumOptionData> preClosurePenalInterestOnTypeOptions = null;
final Collection<EnumOptionData> periodFrequencyTypeOptions = null;
final EnumOptionData depositType = SavingsEnumerations.depositType(DepositAccountType.FIXED_DEPOSIT.getValue());
final Collection<EnumOptionData> onAccountClosureOptions = null;
final Collection<PaymentTypeData> paymentTypeOptions = null;
final Collection<SavingsAccountData> savingsAccountDatas = null;
final Collection<EnumOptionData> maturityInstructionOptions = null;
final Long transferToSavingsId = null;
return new FixedDepositAccountData(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName,
fieldOfficerId, fieldOfficerName, status, timeline, currency, nominalAnnualInterestRate, interestPeriodType,
interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance,
lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, minBalanceForInterestCalculation, summary,
transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions,
interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions,
withdrawalFeeTypeOptions, charges, chargeOptions, accountChart, chartTemplate, preClosurePenalApplicable,
preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm,
maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType,
depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, periodFrequencyTypeOptions, depositType,
onAccountClosure, onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas, linkedAccount,
transferInterestToSavings, withHoldTax, taxGroup, maturityInstructionOptions, transferToSavingsId,
transferToSavingsAccount);
}
public static FixedDepositAccountData preClosureDetails(final Long accountId, BigDecimal maturityAmount,
final Collection<EnumOptionData> onAccountClosureOptions, final Collection<PaymentTypeData> paymentTypeOptions,
final Collection<SavingsAccountData> savingsAccountDatas) {
final Long groupId = null;
final String groupName = null;
final Long clientId = null;
final String clientName = null;
final String accountNo = null;
final String externalId = null;
final Long productId = null;
final String productName = null;
final Long fieldOfficerId = null;
final String fieldOfficerName = null;
final SavingsAccountStatusEnumData status = null;
final SavingsAccountApplicationTimelineData timeline = null;
final CurrencyData currency = null;
final BigDecimal nominalAnnualInterestRate = null;
final EnumOptionData interestPeriodType = null;
final EnumOptionData interestPostingPeriodType = null;
final EnumOptionData interestCalculationType = null;
final EnumOptionData interestCalculationDaysInYearType = null;
final BigDecimal minRequiredOpeningBalance = null;
final Integer lockinPeriodFrequency = null;
final EnumOptionData lockinPeriodFrequencyType = null;
final boolean withdrawalFeeForTransfers = false;
final BigDecimal minBalanceForInterestCalculation = null;
final SavingsAccountSummaryData summary = null;
final Collection<SavingsAccountTransactionData> transactions = null;
final Collection<DepositProductData> productOptions = null;
final Collection<StaffData> fieldOfficerOptions = null;
final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions = null;
final Collection<EnumOptionData> interestPostingPeriodTypeOptions = null;
final Collection<EnumOptionData> interestCalculationTypeOptions = null;
final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions = null;
final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions = null;
final Collection<EnumOptionData> withdrawalFeeTypeOptions = null;
final Collection<SavingsAccountChargeData> charges = null;
final Collection<ChargeData> chargeOptions = null;
final DepositAccountInterestRateChartData accountChart = null;
final DepositAccountInterestRateChartData chartTemplate = null;
final boolean preClosurePenalApplicable = false;
final BigDecimal preClosurePenalInterest = null;
final EnumOptionData preClosurePenalInterestOnType = null;
final Integer minDepositTerm = null;
final Integer maxDepositTerm = null;
final EnumOptionData minDepositTermType = null;
final EnumOptionData maxDepositTermType = null;
final Integer inMultiplesOfDepositTerm = null;
final EnumOptionData inMultiplesOfDepositTermType = null;
final BigDecimal depositAmount = null;
final LocalDate maturityDate = null;
final Integer depositPeriod = null;
final EnumOptionData depositPeriodFrequency = null;
final EnumOptionData onAccountClosure = null;
final Boolean transferInterestToSavings = null;
final Collection<EnumOptionData> preClosurePenalInterestOnTypeOptions = null;
final Collection<EnumOptionData> periodFrequencyTypeOptions = null;
final EnumOptionData depositType = SavingsEnumerations.depositType(DepositAccountType.FIXED_DEPOSIT.getValue());
final PortfolioAccountData linkedAccount = null;
final boolean withHoldTax = false;
final TaxGroupData taxGroup = null;
final Collection<EnumOptionData> maturityInstructionOptions = null;
final Long transferToSavingsId = null;
final PortfolioAccountData transferToSavingsAccount = null;
return new FixedDepositAccountData(accountId, accountNo, externalId, groupId, groupName, clientId, clientName, productId,
productName, fieldOfficerId, fieldOfficerName, status, timeline, currency, nominalAnnualInterestRate, interestPeriodType,
interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance,
lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, minBalanceForInterestCalculation, summary,
transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions,
interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions,
withdrawalFeeTypeOptions, charges, chargeOptions, accountChart, chartTemplate, preClosurePenalApplicable,
preClosurePenalInterest, preClosurePenalInterestOnType, preClosurePenalInterestOnTypeOptions, minDepositTerm,
maxDepositTerm, minDepositTermType, maxDepositTermType, inMultiplesOfDepositTerm, inMultiplesOfDepositTermType,
depositAmount, maturityAmount, maturityDate, depositPeriod, depositPeriodFrequency, periodFrequencyTypeOptions, depositType,
onAccountClosure, onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas, linkedAccount,
transferInterestToSavings, withHoldTax, taxGroup, maturityInstructionOptions, transferToSavingsId,
transferToSavingsAccount);
}
public static FixedDepositAccountData withClosureTemplateDetails(final FixedDepositAccountData account,
final Collection<EnumOptionData> onAccountClosureOptions, final Collection<PaymentTypeData> paymentTypeOptions,
final Collection<SavingsAccountData> savingsAccountDatas) {
return new FixedDepositAccountData(account.id, account.accountNo, account.externalId, account.groupId, account.groupName,
account.clientId, account.clientName, account.depositProductId, account.depositProductName, account.fieldOfficerId,
account.fieldOfficerName, account.status, account.timeline, account.currency, account.nominalAnnualInterestRate,
account.interestCompoundingPeriodType, account.interestPostingPeriodType, account.interestCalculationType,
account.interestCalculationDaysInYearType, account.minRequiredOpeningBalance, account.lockinPeriodFrequency,
account.lockinPeriodFrequencyType, account.withdrawalFeeForTransfers, account.minBalanceForInterestCalculation,
account.summary, account.transactions, account.productOptions, account.fieldOfficerOptions,
account.interestCompoundingPeriodTypeOptions, account.interestPostingPeriodTypeOptions,
account.interestCalculationTypeOptions, account.interestCalculationDaysInYearTypeOptions,
account.lockinPeriodFrequencyTypeOptions, account.withdrawalFeeTypeOptions, account.charges, account.chargeOptions,
account.accountChart, account.chartTemplate, account.preClosurePenalApplicable, account.preClosurePenalInterest,
account.preClosurePenalInterestOnType, account.preClosurePenalInterestOnTypeOptions, account.minDepositTerm,
account.maxDepositTerm, account.minDepositTermType, account.maxDepositTermType, account.inMultiplesOfDepositTerm,
account.inMultiplesOfDepositTermType, account.depositAmount, account.maturityAmount, account.maturityDate,
account.depositPeriod, account.depositPeriodFrequency, account.periodFrequencyTypeOptions, account.depositType,
account.onAccountClosure, onAccountClosureOptions, paymentTypeOptions, savingsAccountDatas, account.linkedAccount,
account.transferInterestToSavings, account.withHoldTax, account.taxGroup, account.maturityInstructionOptions,
account.transferToSavingsId, account.transferToSavingsAccount);
}
private FixedDepositAccountData(final Long id, final String accountNo, final String externalId, final Long groupId,
final String groupName, final Long clientId, final String clientName, final Long productId, final String productName,
final Long fieldofficerId, final String fieldofficerName, final SavingsAccountStatusEnumData status,
final SavingsAccountApplicationTimelineData timeline, final CurrencyData currency, final BigDecimal nominalAnnualInterestRate,
final EnumOptionData interestPeriodType, final EnumOptionData interestPostingPeriodType,
final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType,
final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType,
final boolean withdrawalFeeForTransfers, final BigDecimal minBalanceForInterestCalculation,
final SavingsAccountSummaryData summary, final Collection<SavingsAccountTransactionData> transactions,
final Collection<DepositProductData> productOptions, final Collection<StaffData> fieldOfficerOptions,
final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions,
final Collection<EnumOptionData> interestPostingPeriodTypeOptions,
final Collection<EnumOptionData> interestCalculationTypeOptions,
final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions,
final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions, final Collection<EnumOptionData> withdrawalFeeTypeOptions,
final Collection<SavingsAccountChargeData> charges, final Collection<ChargeData> chargeOptions,
final DepositAccountInterestRateChartData accountChart, final DepositAccountInterestRateChartData chartTemplate,
final boolean preClosurePenalApplicable, final BigDecimal preClosurePenalInterest,
final EnumOptionData preClosurePenalInterestOnType, final Collection<EnumOptionData> preClosurePenalInterestOnTypeOptions,
final Integer minDepositTerm, final Integer maxDepositTerm, final EnumOptionData minDepositTermType,
final EnumOptionData maxDepositTermType, final Integer inMultiplesOfDepositTerm,
final EnumOptionData inMultiplesOfDepositTermType, final BigDecimal depositAmount, final BigDecimal maturityAmount,
final LocalDate maturityDate, final Integer depositPeriod, final EnumOptionData depositPeriodFrequency,
final Collection<EnumOptionData> periodFrequencyTypeOptions, final EnumOptionData depositType,
final EnumOptionData onAccountClosure, final Collection<EnumOptionData> onAccountClosureOptions,
final Collection<PaymentTypeData> paymentTypeOptions, final Collection<SavingsAccountData> savingsAccountDatas,
final PortfolioAccountData linkedAccount, final Boolean transferInterestToSavings, final boolean withHoldTax,
final TaxGroupData taxGroup, final Collection<EnumOptionData> maturityInstructionOptions, final Long transferToSavingsId,
final PortfolioAccountData transferToSavingsAccount) {
super(id, accountNo, externalId, groupId, groupName, clientId, clientName, productId, productName, fieldofficerId, fieldofficerName,
status, timeline, currency, nominalAnnualInterestRate, interestPeriodType, interestPostingPeriodType,
interestCalculationType, interestCalculationDaysInYearType, minRequiredOpeningBalance, lockinPeriodFrequency,
lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions, productOptions, fieldOfficerOptions,
interestCompoundingPeriodTypeOptions, interestPostingPeriodTypeOptions, interestCalculationTypeOptions,
interestCalculationDaysInYearTypeOptions, lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges,
chargeOptions, accountChart, chartTemplate, depositType, minBalanceForInterestCalculation, withHoldTax, taxGroup);
this.preClosurePenalApplicable = preClosurePenalApplicable;
this.preClosurePenalInterest = preClosurePenalInterest;
this.preClosurePenalInterestOnType = preClosurePenalInterestOnType;
this.minDepositTerm = minDepositTerm;
this.maxDepositTerm = maxDepositTerm;
this.minDepositTermType = minDepositTermType;
this.maxDepositTermType = maxDepositTermType;
this.inMultiplesOfDepositTerm = inMultiplesOfDepositTerm;
this.inMultiplesOfDepositTermType = inMultiplesOfDepositTermType;
this.depositAmount = depositAmount;
this.maturityAmount = maturityAmount;
this.maturityDate = maturityDate;
this.depositPeriod = depositPeriod;
this.depositPeriodFrequency = depositPeriodFrequency;
this.onAccountClosure = onAccountClosure;
this.linkedAccount = linkedAccount;
this.transferToSavingsAccount = transferToSavingsAccount;
this.transferInterestToSavings = transferInterestToSavings;
// template
this.preClosurePenalInterestOnTypeOptions = preClosurePenalInterestOnTypeOptions;
this.periodFrequencyTypeOptions = periodFrequencyTypeOptions;
// account close template options
this.onAccountClosureOptions = onAccountClosureOptions;
this.paymentTypeOptions = paymentTypeOptions;
this.savingsAccounts = savingsAccountDatas;
this.maturityInstructionOptions = maturityInstructionOptions;
this.transferToSavingsId = transferToSavingsId;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof FixedDepositAccountData)) {
return false;
}
final FixedDepositAccountData rhs = (FixedDepositAccountData) obj;
return new EqualsBuilder().append(this.id, rhs.id).append(this.accountNo, rhs.accountNo).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37).append(this.id).append(this.accountNo).toHashCode();
}
public void setActivationCharge(BigDecimal activationCharge) {
this.activationCharge = activationCharge;
}
}
|
apache/seatunnel
| 37,746
|
seatunnel-e2e/seatunnel-connector-v2-e2e/connector-doris-e2e/src/test/java/org/apache/seatunnel/e2e/connector/doris/DorisIT.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.seatunnel.e2e.connector.doris;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
import org.apache.seatunnel.common.utils.ExceptionUtils;
import org.apache.seatunnel.common.utils.JsonUtils;
import org.apache.seatunnel.connectors.doris.util.DorisCatalogUtil;
import org.apache.seatunnel.e2e.common.container.ContainerExtendedFactory;
import org.apache.seatunnel.e2e.common.container.TestContainer;
import org.apache.seatunnel.e2e.common.junit.TestContainerExtension;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.TestTemplate;
import org.testcontainers.containers.Container;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Slf4j
public class DorisIT extends AbstractDorisIT {
private static final String UNIQUE_TABLE = "doris_e2e_unique_table";
private static final String DUPLICATE_TABLE = "doris_duplicate_table";
private static final String sourceDB = "e2e_source";
private static final String sinkDB = "e2e_sink";
private Connection conn;
private Map<String, String> checkColumnTypeMap = null;
private static final String INIT_UNIQUE_TABLE_DATA_SQL =
"insert into "
+ sourceDB
+ "."
+ UNIQUE_TABLE
+ " (\n"
+ " F_ID,\n"
+ " F_INT,\n"
+ " F_BIGINT,\n"
+ " F_TINYINT,\n"
+ " F_SMALLINT,\n"
+ " F_DECIMAL,\n"
+ " F_LARGEINT,\n"
+ " F_BOOLEAN,\n"
+ " F_DOUBLE,\n"
+ " F_FLOAT,\n"
+ " F_CHAR,\n"
+ " F_VARCHAR_11,\n"
+ " F_STRING,\n"
+ " F_DATETIME_P,\n"
+ " F_DATETIME,\n"
+ " F_DATE,\n"
+ " MAP_VARCHAR_BOOLEAN,\n"
+ " MAP_CHAR_TINYINT,\n"
+ " MAP_STRING_SMALLINT,\n"
+ " MAP_INT_INT,\n"
+ " MAP_TINYINT_BIGINT,\n"
+ " MAP_SMALLINT_LARGEINT,\n"
+ " MAP_BIGINT_FLOAT,\n"
+ " MAP_LARGEINT_DOUBLE,\n"
+ " MAP_STRING_DECIMAL,\n"
+ " MAP_DECIMAL_DATE,\n"
+ " MAP_DATE_DATETIME,\n"
+ " MAP_DATETIME_CHAR,\n"
+ " MAP_CHAR_VARCHAR,\n"
+ " MAP_VARCHAR_STRING\n"
+ ")values(\n"
+ "\t?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?\n"
+ ")";
private static final String INIT_DUPLICATE_TABLE_DATA_SQL =
"insert into "
+ sourceDB
+ "."
+ DUPLICATE_TABLE
+ " (\n"
+ " F_ID,\n"
+ " F_INT,\n"
+ " F_BIGINT,\n"
+ " F_TINYINT,\n"
+ " F_SMALLINT,\n"
+ " F_DECIMAL,\n"
+ " F_DECIMAL_V3,\n"
+ " F_LARGEINT,\n"
+ " F_BOOLEAN,\n"
+ " F_DOUBLE,\n"
+ " F_FLOAT,\n"
+ " F_CHAR,\n"
+ " F_VARCHAR_11,\n"
+ " F_STRING,\n"
+ " F_DATETIME_P,\n"
+ " F_DATETIME_V2,\n"
+ " F_DATETIME,\n"
+ " F_DATE,\n"
+ " F_DATE_V2,\n"
+ " F_JSON,\n"
+ " F_JSONB,\n"
+ " F_ARRAY_BOOLEAN,\n"
+ " F_ARRAY_BYTE,\n"
+ " F_ARRAY_SHOT,\n"
+ " F_ARRAY_INT,\n"
+ " F_ARRAY_BIGINT,\n"
+ " F_ARRAY_FLOAT,\n"
+ " F_ARRAY_DOUBLE,\n"
+ " F_ARRAY_STRING_CHAR,\n"
+ " F_ARRAY_STRING_VARCHAR,\n"
+ " F_ARRAY_STRING_LARGEINT,\n"
+ " F_ARRAY_STRING_STRING,\n"
+ " F_ARRAY_DECIMAL,\n"
+ " F_ARRAY_DATE,\n"
+ " F_ARRAY_DATETIME\n"
+ ")values(\n"
+ "\t?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?\n"
+ ")";
private final String DUPLICATE_TABLE_COLUMN_STRING =
"F_ID, F_INT, F_BIGINT, F_TINYINT, F_SMALLINT, F_DECIMAL, F_DECIMAL_V3, F_LARGEINT, F_BOOLEAN, F_DOUBLE, F_FLOAT, F_CHAR, F_VARCHAR_11, F_STRING, F_DATETIME_P, F_DATETIME_V2, F_DATETIME, F_DATE, F_DATE_V2, F_JSON, F_JSONB, F_ARRAY_BOOLEAN, F_ARRAY_BYTE, F_ARRAY_SHOT, F_ARRAY_INT, F_ARRAY_BIGINT, F_ARRAY_FLOAT, F_ARRAY_DOUBLE, F_ARRAY_STRING_CHAR, F_ARRAY_STRING_VARCHAR, F_ARRAY_STRING_LARGEINT, F_ARRAY_STRING_STRING, F_ARRAY_DECIMAL, F_ARRAY_DATE, F_ARRAY_DATETIME";
private final String UNIQUE_TABLE_COLUMN_STRING =
"F_ID, F_INT, F_BIGINT, F_TINYINT, F_SMALLINT, F_DECIMAL, F_LARGEINT, F_BOOLEAN, F_DOUBLE, F_FLOAT, F_CHAR, F_VARCHAR_11, F_STRING, F_DATETIME_P, F_DATETIME, F_DATE, MAP_VARCHAR_BOOLEAN, MAP_CHAR_TINYINT, MAP_STRING_SMALLINT, MAP_INT_INT, MAP_TINYINT_BIGINT, MAP_SMALLINT_LARGEINT, MAP_BIGINT_FLOAT, MAP_LARGEINT_DOUBLE, MAP_STRING_DECIMAL, MAP_DECIMAL_DATE, MAP_DATE_DATETIME, MAP_DATETIME_CHAR, MAP_CHAR_VARCHAR, MAP_VARCHAR_STRING";
@TestContainerExtension
protected final ContainerExtendedFactory extendedFactory =
container -> {
Container.ExecResult extraCommands =
container.execInContainer(
"bash",
"-c",
"mkdir -p /tmp/seatunnel/plugins/jdbc/lib && cd /tmp/seatunnel/plugins/jdbc/lib && wget "
+ DRIVER_JAR);
Assertions.assertEquals(0, extraCommands.getExitCode(), extraCommands.getStderr());
};
@TestTemplate
public void testCustomSql(TestContainer container) throws IOException, InterruptedException {
initializeJdbcTable();
Container.ExecResult execResult =
container.executeJob("/doris_source_and_sink_with_custom_sql.conf");
Assertions.assertEquals(0, execResult.getExitCode());
Assertions.assertEquals(101, tableCount(sinkDB, UNIQUE_TABLE));
clearUniqueTable();
}
@TestTemplate
public void testDoris(TestContainer container) throws IOException, InterruptedException {
initializeJdbcTable();
batchInsertUniqueTableData();
Container.ExecResult execResult = container.executeJob("/doris_source_and_sink.conf");
Assertions.assertEquals(0, execResult.getExitCode());
checkSinkData();
batchInsertUniqueTableData();
Container.ExecResult execResult2 =
container.executeJob("/doris_source_and_sink_2pc_false.conf");
Assertions.assertEquals(0, execResult2.getExitCode());
checkSinkData();
batchInsertDuplicateTableData();
Container.ExecResult execResult3 =
container.executeJob("/doris_source_to_doris_sink_type_convertor.conf");
Assertions.assertEquals(0, execResult3.getExitCode());
checkAllTypeSinkData();
}
@TestTemplate
public void testNoSchemaDoris(TestContainer container)
throws IOException, InterruptedException {
initializeJdbcTable();
batchInsertUniqueTableData();
Container.ExecResult execResult1 = container.executeJob("/doris_source_no_schema.conf");
Assertions.assertEquals(0, execResult1.getExitCode());
checkSinkData();
}
private void checkAllTypeSinkData() {
try {
assertHasData(sourceDB, DUPLICATE_TABLE);
try (PreparedStatement ps =
conn.prepareStatement(DorisCatalogUtil.TABLE_SCHEMA_QUERY)) {
ps.setString(1, sinkDB);
ps.setString(2, DUPLICATE_TABLE);
try (ResultSet resultSet = ps.executeQuery()) {
while (resultSet.next()) {
String columnName = resultSet.getString("COLUMN_NAME");
String columnType = resultSet.getString("COLUMN_TYPE");
Assertions.assertEquals(
checkColumnTypeMap.get(columnName).toUpperCase(Locale.ROOT),
columnType.toUpperCase(Locale.ROOT));
}
}
}
String sourceSql =
String.format("select * from %s.%s order by F_ID ", sourceDB, DUPLICATE_TABLE);
String sinkSql =
String.format("select * from %s.%s order by F_ID", sinkDB, DUPLICATE_TABLE);
checkSourceAndSinkTableDate(sourceSql, sinkSql, DUPLICATE_TABLE_COLUMN_STRING);
clearDuplicateTable();
} catch (Exception e) {
throw new RuntimeException("Doris connection error", e);
}
}
protected void checkSinkData() {
try {
assertHasData(sourceDB, UNIQUE_TABLE);
assertHasData(sinkDB, UNIQUE_TABLE);
PreparedStatement sourcePre =
conn.prepareStatement(DorisCatalogUtil.TABLE_SCHEMA_QUERY);
sourcePre.setString(1, sourceDB);
sourcePre.setString(2, UNIQUE_TABLE);
ResultSet sourceResultSet = sourcePre.executeQuery();
PreparedStatement sinkPre = conn.prepareStatement(DorisCatalogUtil.TABLE_SCHEMA_QUERY);
sinkPre.setString(1, sinkDB);
sinkPre.setString(2, UNIQUE_TABLE);
ResultSet sinkResultSet = sinkPre.executeQuery();
while (sourceResultSet.next()) {
if (sinkResultSet.next()) {
String sourceColumnType = sourceResultSet.getString("COLUMN_TYPE");
String sinkColumnType = sinkResultSet.getString("COLUMN_TYPE");
// because seatunnel type can not save the scale and length of the key type and
// value type in the MapType,
// so we use the longest scale on the doris sink to prevent data overflow.
if (sourceColumnType.equalsIgnoreCase("map<varchar(200),tinyint(1)>")) {
Assertions.assertEquals("map<string,tinyint(1)>", sinkColumnType);
continue;
}
if (sourceColumnType.equalsIgnoreCase("map<char(1),tinyint(4)>")) {
Assertions.assertEquals("map<string,tinyint(4)>", sinkColumnType);
continue;
}
if (sourceColumnType.equalsIgnoreCase("map<smallint(6),largeint>")) {
Assertions.assertEquals(
"map<smallint(6),decimalv3(20, 0)>", sinkColumnType);
continue;
}
if (sourceColumnType.equalsIgnoreCase("map<largeint,double>")) {
Assertions.assertEquals("map<decimalv3(20, 0),double>", sinkColumnType);
continue;
}
if (sourceColumnType.equalsIgnoreCase("map<date,datetime>")) {
Assertions.assertEquals("map<date,datetime(6)>", sinkColumnType);
continue;
}
if (sourceColumnType.equalsIgnoreCase("map<datetime,char(20)>")) {
Assertions.assertEquals("map<datetime(6),string>", sinkColumnType);
continue;
}
if (sourceColumnType.equalsIgnoreCase("map<char(20),varchar(255)>")) {
Assertions.assertEquals("map<string,string>", sinkColumnType);
continue;
}
if (sourceColumnType.equalsIgnoreCase("map<varchar(255),string>")) {
Assertions.assertEquals("map<string,string>", sinkColumnType);
continue;
}
Assertions.assertEquals(
sourceColumnType.toUpperCase(Locale.ROOT),
sinkColumnType.toUpperCase(Locale.ROOT));
}
}
String sourceSql =
String.format(
"select * from %s.%s where F_ID > 50 order by F_ID ",
sourceDB, UNIQUE_TABLE);
String sinkSql =
String.format("select * from %s.%s order by F_ID", sinkDB, UNIQUE_TABLE);
checkSourceAndSinkTableDate(sourceSql, sinkSql, UNIQUE_TABLE_COLUMN_STRING);
clearUniqueTable();
} catch (Exception e) {
throw new RuntimeException("Doris connection error", e);
}
}
private void checkSourceAndSinkTableDate(String sourceSql, String sinkSql, String columnsString)
throws Exception {
List<String> columnList =
Arrays.stream(columnsString.split(","))
.map(x -> x.trim())
.collect(Collectors.toList());
Statement sourceStatement =
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
Statement sinkStatement =
conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet sourceResultSet = sourceStatement.executeQuery(sourceSql);
ResultSet sinkResultSet = sinkStatement.executeQuery(sinkSql);
Assertions.assertEquals(
sourceResultSet.getMetaData().getColumnCount(),
sinkResultSet.getMetaData().getColumnCount());
while (sourceResultSet.next()) {
if (sinkResultSet.next()) {
for (String column : columnList) {
Object source = sourceResultSet.getObject(column);
Object sink = sinkResultSet.getObject(column);
if (!Objects.deepEquals(source, sink)) {
// source read map<xx,datetime> will create map<xx,datetime(6)> in doris
// sink, because seatunnel type can not save the scale in MapType
// so we use the longest scale on the doris sink to prevent data overflow.
String sinkStr = sink.toString().replaceAll(".000000", "");
Assertions.assertEquals(source, sinkStr);
}
}
}
}
// Check the row numbers is equal
sourceResultSet.last();
sinkResultSet.last();
Assertions.assertEquals(sourceResultSet.getRow(), sinkResultSet.getRow());
}
private Integer tableCount(String db, String table) {
try (Statement statement = conn.createStatement()) {
String sql = String.format("select count(*) from %s.%s", db, table);
ResultSet source = statement.executeQuery(sql);
if (source.next()) {
int rowCount = source.getInt(1);
return rowCount;
}
} catch (Exception e) {
throw new RuntimeException("Failed to check data in Doris server", e);
}
return -1;
}
private void assertHasData(String db, String table) {
try (Statement statement = conn.createStatement()) {
String sql = String.format("select * from %s.%s limit 1", db, table);
ResultSet source = statement.executeQuery(sql);
Assertions.assertTrue(source.next());
} catch (Exception e) {
throw new RuntimeException("test doris server image error", e);
}
}
private void clearUniqueTable() {
try (Statement statement = conn.createStatement()) {
statement.execute(String.format("TRUNCATE TABLE %s.%s", sourceDB, UNIQUE_TABLE));
statement.execute(String.format("TRUNCATE TABLE %s.%s", sinkDB, UNIQUE_TABLE));
} catch (SQLException e) {
throw new RuntimeException("test doris server image error", e);
}
}
private void clearDuplicateTable() {
try (Statement statement = conn.createStatement()) {
statement.execute(String.format("TRUNCATE TABLE %s.%s", sourceDB, DUPLICATE_TABLE));
statement.execute(String.format("TRUNCATE TABLE %s.%s", sinkDB, DUPLICATE_TABLE));
} catch (SQLException e) {
throw new RuntimeException("test doris server image error", e);
}
}
protected void initializeJdbcTable() {
try {
URLClassLoader urlClassLoader =
new URLClassLoader(
new URL[] {new URL(DRIVER_JAR)}, DorisIT.class.getClassLoader());
Thread.currentThread().setContextClassLoader(urlClassLoader);
Driver driver = (Driver) urlClassLoader.loadClass(DRIVER_CLASS).newInstance();
Properties props = new Properties();
props.put("user", USERNAME);
props.put("password", PASSWORD);
conn = driver.connect(String.format(URL, container.getHost()), props);
try (Statement statement = conn.createStatement()) {
// create test databases
statement.execute(createDatabase(sourceDB));
statement.execute(createDatabase(sinkDB));
log.info("create source and sink database succeed");
// create source and sink table
statement.execute(createUniqueTableForTest(sourceDB));
statement.execute(createDuplicateTableForTest(sourceDB));
log.info("create source and sink table succeed");
} catch (SQLException e) {
throw new RuntimeException("Initializing table failed!", e);
}
} catch (Exception e) {
throw new RuntimeException("Initializing jdbc failed!", e);
}
}
private String createDatabase(String db) {
return String.format("CREATE DATABASE IF NOT EXISTS %s ;", db);
}
private String createUniqueTableForTest(String db) {
String createTableSql =
"create table if not exists `%s`.`%s`(\n"
+ "F_ID bigint null,\n"
+ "F_INT int null,\n"
+ "F_BIGINT bigint null,\n"
+ "F_TINYINT tinyint null,\n"
+ "F_SMALLINT smallint null,\n"
+ "F_DECIMAL decimal(18,6) null,\n"
+ "F_LARGEINT largeint null,\n"
+ "F_BOOLEAN boolean null,\n"
+ "F_DOUBLE double null,\n"
+ "F_FLOAT float null,\n"
+ "F_CHAR char null,\n"
+ "F_VARCHAR_11 varchar(11) null,\n"
+ "F_STRING string null,\n"
+ "F_DATETIME_P datetime(6),\n"
+ "F_DATETIME datetime,\n"
+ "F_DATE date,\n"
+ "MAP_VARCHAR_BOOLEAN map<varchar(200),boolean>,\n"
+ "MAP_CHAR_TINYINT MAP<CHAR, TINYINT>,\n"
+ "MAP_STRING_SMALLINT MAP<STRING, SMALLINT>,\n"
+ "MAP_INT_INT MAP<INT, INT>,\n"
+ "MAP_TINYINT_BIGINT MAP<TINYINT, BIGINT>,\n"
+ "MAP_SMALLINT_LARGEINT MAP<SMALLINT, LARGEINT>,\n"
+ "MAP_BIGINT_FLOAT MAP<BIGINT, FLOAT>,\n"
+ "MAP_LARGEINT_DOUBLE MAP<LARGEINT, DOUBLE>,\n"
+ "MAP_STRING_DECIMAL MAP<STRING, DECIMAL(10,2)>,\n"
+ "MAP_DECIMAL_DATE MAP<DECIMAL(10,2), DATE>,\n"
+ "MAP_DATE_DATETIME MAP<DATE, DATETIME>,\n"
+ "MAP_DATETIME_CHAR MAP<DATETIME, CHAR(20)>,\n"
+ "MAP_CHAR_VARCHAR MAP<CHAR(20), VARCHAR(255)>,\n"
+ "MAP_VARCHAR_STRING MAP<VARCHAR(255), STRING>\n"
+ ")\n"
+ "UNIQUE KEY(`F_ID`)\n"
+ "DISTRIBUTED BY HASH(`F_ID`) BUCKETS 1\n"
+ "properties(\n"
+ "\"replication_allocation\" = \"tag.location.default: 1\""
+ ");";
return String.format(createTableSql, db, UNIQUE_TABLE);
}
private String createDuplicateTableForTest(String db) {
String createDuplicateTableSql =
"create table if not exists `%s`.`%s`(\n"
+ "F_ID bigint null,\n"
+ "F_INT int null,\n"
+ "F_BIGINT bigint null,\n"
+ "F_TINYINT tinyint null,\n"
+ "F_SMALLINT smallint null,\n"
+ "F_DECIMAL decimal(18,6) null,\n"
+ "F_DECIMAL_V3 decimalv3(28,10) null,\n"
+ "F_LARGEINT largeint null,\n"
+ "F_BOOLEAN boolean null,\n"
+ "F_DOUBLE double null,\n"
+ "F_FLOAT float null,\n"
+ "F_CHAR char null,\n"
+ "F_VARCHAR_11 varchar(11) null,\n"
+ "F_STRING string null,\n"
+ "F_DATETIME_P datetime(6),\n"
+ "F_DATETIME_V2 datetimev2(6),\n"
+ "F_DATETIME datetime,\n"
+ "F_DATE date,\n"
+ "F_DATE_V2 datev2,\n"
+ "F_JSON json,\n"
+ "F_JSONB jsonb,\n"
+ "F_ARRAY_BOOLEAN ARRAY<boolean>,\n"
+ "F_ARRAY_BYTE ARRAY<tinyint>,\n"
+ "F_ARRAY_SHOT ARRAY<smallint>,\n"
+ "F_ARRAY_INT ARRAY<int>,\n"
+ "F_ARRAY_BIGINT ARRAY<bigint>,\n"
+ "F_ARRAY_FLOAT ARRAY<float>,\n"
+ "F_ARRAY_DOUBLE ARRAY<double>,\n"
+ "F_ARRAY_STRING_CHAR ARRAY<char(10)>,\n"
+ "F_ARRAY_STRING_VARCHAR ARRAY<varchar(100)>,\n"
+ "F_ARRAY_STRING_LARGEINT ARRAY<largeint>,\n"
+ "F_ARRAY_STRING_STRING ARRAY<string>,\n"
+ "F_ARRAY_DECIMAL ARRAY<decimalv3(10,2)>,\n"
+ "F_ARRAY_DATE ARRAY<date>,\n"
+ "F_ARRAY_DATETIME ARRAY<datetime>\n"
+ ")\n"
+ "Duplicate KEY(`F_ID`)\n"
+ "DISTRIBUTED BY HASH(`F_ID`) BUCKETS 1\n"
+ "properties(\n"
+ "\"replication_allocation\" = \"tag.location.default: 1\""
+ ");";
checkColumnTypeMap = new HashMap<>();
checkColumnTypeMap.put("F_ID", "bigint(20)");
checkColumnTypeMap.put("F_INT", "int(11)");
checkColumnTypeMap.put("F_BIGINT", "bigint(20)");
checkColumnTypeMap.put("F_TINYINT", "tinyint(4)");
checkColumnTypeMap.put("F_SMALLINT", "smallint(6)");
checkColumnTypeMap.put("F_DECIMAL", "decimalv3(18, 6)");
checkColumnTypeMap.put("F_DECIMAL_V3", "decimalv3(28, 10)");
checkColumnTypeMap.put("F_LARGEINT", "largeint");
checkColumnTypeMap.put("F_BOOLEAN", "tinyint(1)");
checkColumnTypeMap.put("F_DOUBLE", "double");
checkColumnTypeMap.put("F_FLOAT", "float");
checkColumnTypeMap.put("F_CHAR", "char(1)");
checkColumnTypeMap.put("F_VARCHAR_11", "varchar(11)");
checkColumnTypeMap.put("F_STRING", "string");
checkColumnTypeMap.put("F_DATETIME_P", "datetime(6)");
checkColumnTypeMap.put("F_DATETIME_V2", "datetime(6)");
checkColumnTypeMap.put("F_DATETIME", "datetime");
checkColumnTypeMap.put("F_DATE", "date");
checkColumnTypeMap.put("F_DATE_V2", "date");
checkColumnTypeMap.put("F_JSON", "json");
checkColumnTypeMap.put("F_JSONB", "json");
checkColumnTypeMap.put("F_ARRAY_BOOLEAN", "ARRAY<tinyint(1)>");
checkColumnTypeMap.put("F_ARRAY_BYTE", "ARRAY<tinyint(4)>");
checkColumnTypeMap.put("F_ARRAY_SHOT", "ARRAY<smallint(6)>");
checkColumnTypeMap.put("F_ARRAY_INT", "ARRAY<int(11)>");
checkColumnTypeMap.put("F_ARRAY_BIGINT", "ARRAY<bigint(20)>");
checkColumnTypeMap.put("F_ARRAY_FLOAT", "ARRAY<float>");
checkColumnTypeMap.put("F_ARRAY_DOUBLE", "ARRAY<double>");
checkColumnTypeMap.put("F_ARRAY_STRING_CHAR", "ARRAY<string>");
checkColumnTypeMap.put("F_ARRAY_STRING_VARCHAR", "ARRAY<string>");
checkColumnTypeMap.put("F_ARRAY_STRING_LARGEINT", "ARRAY<decimalv3(20, 0)>");
checkColumnTypeMap.put("F_ARRAY_STRING_STRING", "ARRAY<string>");
checkColumnTypeMap.put("F_ARRAY_DECIMAL", "ARRAY<decimalv3(10, 2)>");
checkColumnTypeMap.put("F_ARRAY_DATE", "ARRAY<date>");
checkColumnTypeMap.put("F_ARRAY_DATETIME", "ARRAY<datetime>");
return String.format(createDuplicateTableSql, db, DUPLICATE_TABLE);
}
protected void batchInsertUniqueTableData() {
List<SeaTunnelRow> rows = genUniqueTableTestData(100L);
try {
conn.setAutoCommit(false);
try (PreparedStatement preparedStatement =
conn.prepareStatement(INIT_UNIQUE_TABLE_DATA_SQL)) {
for (int i = 0; i < rows.size(); i++) {
if (i % 10 == 0) {
for (int index = 0; index < rows.get(i).getFields().length; index++) {
preparedStatement.setObject(index + 1, null);
}
} else {
for (int index = 0; index < rows.get(i).getFields().length; index++) {
preparedStatement.setObject(index + 1, rows.get(i).getFields()[index]);
}
}
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
}
conn.commit();
} catch (Exception exception) {
log.error(ExceptionUtils.getMessage(exception));
String message = ExceptionUtils.getMessage(exception);
getErrorUrl(message);
throw new RuntimeException("get connection error", exception);
}
log.info("insert data succeed");
}
private void batchInsertDuplicateTableData() {
List<SeaTunnelRow> rows = genDuplicateTableTestData(100L);
try {
conn.setAutoCommit(false);
try (PreparedStatement preparedStatement =
conn.prepareStatement(INIT_DUPLICATE_TABLE_DATA_SQL)) {
for (int i = 0; i < rows.size(); i++) {
for (int index = 0; index < rows.get(i).getFields().length; index++) {
preparedStatement.setObject(index + 1, rows.get(i).getFields()[index]);
}
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
}
conn.commit();
} catch (Exception exception) {
log.error(ExceptionUtils.getMessage(exception));
throw new RuntimeException("get connection error", exception);
}
log.info("insert all type data succeed");
}
private List<SeaTunnelRow> genUniqueTableTestData(Long nums) {
List<SeaTunnelRow> datas = new ArrayList<>();
Map<String, Boolean> varcharBooleanMap = new HashMap<>();
varcharBooleanMap.put("aa", true);
Map<String, Byte> charTinyintMap = new HashMap<>();
charTinyintMap.put("a", (byte) 1);
Map<String, Short> stringSmallintMap = new HashMap<>();
stringSmallintMap.put("aa", Short.valueOf("1"));
Map<Integer, Integer> intIntMap = new HashMap<>();
intIntMap.put(1, 1);
Map<Byte, Long> tinyintBigintMap = new HashMap<>();
tinyintBigintMap.put((byte) 1, 1L);
Map<Short, Long> smallintLargeintMap = new HashMap<>();
smallintLargeintMap.put(Short.valueOf("1"), Long.valueOf("11"));
Map<Long, Float> bigintFloatMap = new HashMap<>();
bigintFloatMap.put(Long.valueOf("1"), Float.valueOf("11.1"));
Map<Long, Double> largeintDoubtMap = new HashMap<>();
largeintDoubtMap.put(11L, Double.valueOf("11.1"));
String stringDecimalMap = "{\"11\":\"10.2\"}";
String decimalDateMap = "{\"10.02\":\"2020-02-01\"}";
String dateDatetimeMap = "{\"2020-02-01\":\"2020-02-01 12:00:00\"}";
String datetimeCharMap = "{\"2020-02-01 12:00:00\":\"1\"}";
String charVarcharMap = "{\"1\":\"11\"}";
String varcharStringMap = "{\"11\":\"11\"}";
for (int i = 0; i < nums; i++) {
datas.add(
new SeaTunnelRow(
new Object[] {
Long.valueOf(i),
GenerateTestData.genInt(),
GenerateTestData.genBigint(),
GenerateTestData.genTinyint(),
GenerateTestData.genSmallint(),
GenerateTestData.genBigDecimal(18, 6),
GenerateTestData.genBigInteger(126),
GenerateTestData.genBoolean(),
GenerateTestData.genDouble(),
GenerateTestData.genFloat(0, 1000),
GenerateTestData.genString(1),
GenerateTestData.genString(11),
GenerateTestData.genString(12),
GenerateTestData.genDatetimeString(false),
GenerateTestData.genDatetimeString(true),
GenerateTestData.genDateString(),
JsonUtils.toJsonString(varcharBooleanMap),
JsonUtils.toJsonString(charTinyintMap),
JsonUtils.toJsonString(stringSmallintMap),
JsonUtils.toJsonString(intIntMap),
JsonUtils.toJsonString(tinyintBigintMap),
JsonUtils.toJsonString(smallintLargeintMap),
JsonUtils.toJsonString(bigintFloatMap),
JsonUtils.toJsonString(largeintDoubtMap),
stringDecimalMap,
decimalDateMap,
dateDatetimeMap,
datetimeCharMap,
charVarcharMap,
varcharStringMap
}));
}
log.info("generate test data succeed");
return datas;
}
private List<SeaTunnelRow> genDuplicateTableTestData(Long nums) {
List<SeaTunnelRow> datas = new ArrayList<>();
for (int i = 0; i < nums; i++) {
datas.add(
new SeaTunnelRow(
new Object[] {
Long.valueOf(i),
GenerateTestData.genInt(),
GenerateTestData.genBigint(),
GenerateTestData.genTinyint(),
GenerateTestData.genSmallint(),
GenerateTestData.genBigDecimal(18, 6),
GenerateTestData.genBigDecimal(28, 10),
GenerateTestData.genBigInteger(126),
GenerateTestData.genBoolean(),
GenerateTestData.genDouble(),
GenerateTestData.genFloat(0, 1000),
GenerateTestData.genString(1),
GenerateTestData.genString(11),
GenerateTestData.genString(12),
GenerateTestData.genDatetimeString(false),
GenerateTestData.genDatetimeString(false),
GenerateTestData.genDatetimeString(true),
GenerateTestData.genDateString(),
GenerateTestData.genDateString(),
GenerateTestData.genJsonString(),
GenerateTestData.genJsonString(),
(new boolean[] {true, true, false}).toString(),
(new int[] {1, 2, 3}).toString(),
(new int[] {1, 2, 3}).toString(),
(new int[] {1, 2, 3}).toString(),
(new long[] {1L, 2L, 3L}).toString(),
(new float[] {1.0F, 1.0F, 1.0F}).toString(),
(new double[] {1.0, 1.0, 1.0}).toString(),
(new String[] {"1", "1"}).toString(),
(new String[] {"1", "1"}).toString(),
(new String[] {"1", "1"}).toString(),
(new String[] {"1", "1"}).toString(),
(new BigDecimal[] {
new BigDecimal("10.02"), new BigDecimal("10.03")
})
.toString(),
(new String[] {"2020-06-09", "2020-06-10"}).toString(),
(new String[] {"2020-06-09 12:02:02", "2020-06-10 12:02:02"})
.toString()
}));
}
log.info("generate test data succeed");
return datas;
}
@AfterAll
public void close() throws SQLException {
if (conn != null) {
conn.close();
}
}
public void getErrorUrl(String message) {
// Using regular expressions to match URLs
Pattern pattern = Pattern.compile("http://[\\w./?=&-_]+");
Matcher matcher = pattern.matcher(message);
String urlString = null;
if (matcher.find()) {
log.error("Found URL: " + matcher.group());
urlString = matcher.group();
} else {
log.error("No URL found.");
return;
}
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method
connection.setRequestMethod("GET");
// Set the connection timeout
connection.setConnectTimeout(5000);
// Set the read timeout
connection.setReadTimeout(5000);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} else {
log.error("GET request not worked");
}
} catch (Exception e) {
log.error(ExceptionUtils.getMessage(e));
}
}
}
|
openjdk/jdk8
| 38,302
|
jdk/src/share/classes/com/sun/jndi/dns/DnsContext.java
|
/*
* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.jndi.dns;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.spi.DirectoryManager;
import com.sun.jndi.toolkit.ctx.*;
/**
* A DnsContext is a directory context representing a DNS node.
*
* @author Scott Seligman
*/
public class DnsContext extends ComponentDirContext {
DnsName domain; // fully-qualified domain name of this context,
// with a root (empty) label at position 0
Hashtable<Object,Object> environment;
private boolean envShared; // true if environment is possibly shared
// and so must be copied on write
private boolean parentIsDns; // was this DnsContext created by
// another? see composeName()
private String[] servers;
private Resolver resolver;
private boolean authoritative; // must all responses be authoritative?
private boolean recursion; // request recursion on queries?
private int timeout; // initial timeout on UDP queries in ms
private int retries; // number of UDP retries
static final NameParser nameParser = new DnsNameParser();
// Timeouts for UDP queries use exponential backoff: each retry
// is for twice as long as the last. The following constants set
// the defaults for the initial timeout (in ms) and the number of
// retries, and name the environment properties used to override
// these defaults.
private static final int DEFAULT_INIT_TIMEOUT = 1000;
private static final int DEFAULT_RETRIES = 4;
private static final String INIT_TIMEOUT =
"com.sun.jndi.dns.timeout.initial";
private static final String RETRIES = "com.sun.jndi.dns.timeout.retries";
// The resource record type and class to use for lookups, and the
// property used to modify them
private CT lookupCT;
private static final String LOOKUP_ATTR = "com.sun.jndi.dns.lookup.attr";
// Property used to disallow recursion on queries
private static final String RECURSION = "com.sun.jndi.dns.recursion";
// ANY == ResourceRecord.QCLASS_STAR == ResourceRecord.QTYPE_STAR
private static final int ANY = ResourceRecord.QTYPE_STAR;
// The zone tree used for list operations
private static final ZoneNode zoneTree = new ZoneNode(null);
/**
* Returns a DNS context for a given domain and servers.
* Each server is of the form "server[:port]".
* IPv6 literal host names include delimiting brackets.
* There must be at least one server.
* The environment must not be null; it is cloned before being stored.
*/
@SuppressWarnings("unchecked")
public DnsContext(String domain, String[] servers, Hashtable<?,?> environment)
throws NamingException {
this.domain = new DnsName(domain.endsWith(".")
? domain
: domain + ".");
this.servers = (servers == null) ? null : servers.clone();
this.environment = (Hashtable<Object,Object>) environment.clone();
envShared = false;
parentIsDns = false;
resolver = null;
initFromEnvironment();
}
/*
* Returns a clone of a DNS context, just like DnsContext(DnsContext)
* but with a different domain name and with parentIsDns set to true.
*/
DnsContext(DnsContext ctx, DnsName domain) {
this(ctx);
this.domain = domain;
parentIsDns = true;
}
/*
* Returns a clone of a DNS context. The context's modifiable
* private state is independent of the original's (so closing one
* context, for example, won't close the other). The two contexts
* share <tt>environment</tt>, but it's copy-on-write so there's
* no conflict.
*/
private DnsContext(DnsContext ctx) {
environment = ctx.environment; // shared environment, copy-on-write
envShared = ctx.envShared = true;
parentIsDns = ctx.parentIsDns;
domain = ctx.domain;
servers = ctx.servers; // shared servers, no write operation
resolver = ctx.resolver;
authoritative = ctx.authoritative;
recursion = ctx.recursion;
timeout = ctx.timeout;
retries = ctx.retries;
lookupCT = ctx.lookupCT;
}
public void close() {
if (resolver != null) {
resolver.close();
resolver = null;
}
}
//---------- Environment operations
/*
* Override default with a noncloning version.
*/
protected Hashtable<?,?> p_getEnvironment() {
return environment;
}
public Hashtable<?,?> getEnvironment() throws NamingException {
return (Hashtable<?,?>) environment.clone();
}
@SuppressWarnings("unchecked")
public Object addToEnvironment(String propName, Object propVal)
throws NamingException {
if (propName.equals(LOOKUP_ATTR)) {
lookupCT = getLookupCT((String) propVal);
} else if (propName.equals(Context.AUTHORITATIVE)) {
authoritative = "true".equalsIgnoreCase((String) propVal);
} else if (propName.equals(RECURSION)) {
recursion = "true".equalsIgnoreCase((String) propVal);
} else if (propName.equals(INIT_TIMEOUT)) {
int val = Integer.parseInt((String) propVal);
if (timeout != val) {
timeout = val;
resolver = null;
}
} else if (propName.equals(RETRIES)) {
int val = Integer.parseInt((String) propVal);
if (retries != val) {
retries = val;
resolver = null;
}
}
if (!envShared) {
return environment.put(propName, propVal);
} else if (environment.get(propName) != propVal) {
// copy on write
environment = (Hashtable<Object,Object>) environment.clone();
envShared = false;
return environment.put(propName, propVal);
} else {
return propVal;
}
}
@SuppressWarnings("unchecked")
public Object removeFromEnvironment(String propName)
throws NamingException {
if (propName.equals(LOOKUP_ATTR)) {
lookupCT = getLookupCT(null);
} else if (propName.equals(Context.AUTHORITATIVE)) {
authoritative = false;
} else if (propName.equals(RECURSION)) {
recursion = true;
} else if (propName.equals(INIT_TIMEOUT)) {
if (timeout != DEFAULT_INIT_TIMEOUT) {
timeout = DEFAULT_INIT_TIMEOUT;
resolver = null;
}
} else if (propName.equals(RETRIES)) {
if (retries != DEFAULT_RETRIES) {
retries = DEFAULT_RETRIES;
resolver = null;
}
}
if (!envShared) {
return environment.remove(propName);
} else if (environment.get(propName) != null) {
// copy-on-write
environment = (Hashtable<Object,Object>) environment.clone();
envShared = false;
return environment.remove(propName);
} else {
return null;
}
}
/*
* Update PROVIDER_URL property. Call this only when environment
* is not being shared.
*/
void setProviderUrl(String url) {
// assert !envShared;
environment.put(Context.PROVIDER_URL, url);
}
/*
* Read environment properties and set parameters.
*/
private void initFromEnvironment()
throws InvalidAttributeIdentifierException {
lookupCT = getLookupCT((String) environment.get(LOOKUP_ATTR));
authoritative = "true".equalsIgnoreCase((String)
environment.get(Context.AUTHORITATIVE));
String val = (String) environment.get(RECURSION);
recursion = ((val == null) ||
"true".equalsIgnoreCase(val));
val = (String) environment.get(INIT_TIMEOUT);
timeout = (val == null)
? DEFAULT_INIT_TIMEOUT
: Integer.parseInt(val);
val = (String) environment.get(RETRIES);
retries = (val == null)
? DEFAULT_RETRIES
: Integer.parseInt(val);
}
private CT getLookupCT(String attrId)
throws InvalidAttributeIdentifierException {
return (attrId == null)
? new CT(ResourceRecord.CLASS_INTERNET, ResourceRecord.TYPE_TXT)
: fromAttrId(attrId);
}
//---------- Naming operations
public Object c_lookup(Name name, Continuation cont)
throws NamingException {
cont.setSuccess();
if (name.isEmpty()) {
DnsContext ctx = new DnsContext(this);
ctx.resolver = new Resolver(servers, timeout, retries);
// clone for parallelism
return ctx;
}
try {
DnsName fqdn = fullyQualify(name);
ResourceRecords rrs =
getResolver().query(fqdn, lookupCT.rrclass, lookupCT.rrtype,
recursion, authoritative);
Attributes attrs = rrsToAttrs(rrs, null);
DnsContext ctx = new DnsContext(this, fqdn);
return DirectoryManager.getObjectInstance(ctx, name, this,
environment, attrs);
} catch (NamingException e) {
cont.setError(this, name);
throw cont.fillInException(e);
} catch (Exception e) {
cont.setError(this, name);
NamingException ne = new NamingException(
"Problem generating object using object factory");
ne.setRootCause(e);
throw cont.fillInException(ne);
}
}
public Object c_lookupLink(Name name, Continuation cont)
throws NamingException {
return c_lookup(name, cont);
}
public NamingEnumeration<NameClassPair> c_list(Name name, Continuation cont)
throws NamingException {
cont.setSuccess();
try {
DnsName fqdn = fullyQualify(name);
NameNode nnode = getNameNode(fqdn);
DnsContext ctx = new DnsContext(this, fqdn);
return new NameClassPairEnumeration(ctx, nnode.getChildren());
} catch (NamingException e) {
cont.setError(this, name);
throw cont.fillInException(e);
}
}
public NamingEnumeration<Binding> c_listBindings(Name name, Continuation cont)
throws NamingException {
cont.setSuccess();
try {
DnsName fqdn = fullyQualify(name);
NameNode nnode = getNameNode(fqdn);
DnsContext ctx = new DnsContext(this, fqdn);
return new BindingEnumeration(ctx, nnode.getChildren());
} catch (NamingException e) {
cont.setError(this, name);
throw cont.fillInException(e);
}
}
public void c_bind(Name name, Object obj, Continuation cont)
throws NamingException {
cont.setError(this, name);
throw cont.fillInException(
new OperationNotSupportedException());
}
public void c_rebind(Name name, Object obj, Continuation cont)
throws NamingException {
cont.setError(this, name);
throw cont.fillInException(
new OperationNotSupportedException());
}
public void c_unbind(Name name, Continuation cont)
throws NamingException {
cont.setError(this, name);
throw cont.fillInException(
new OperationNotSupportedException());
}
public void c_rename(Name oldname, Name newname, Continuation cont)
throws NamingException {
cont.setError(this, oldname);
throw cont.fillInException(
new OperationNotSupportedException());
}
public Context c_createSubcontext(Name name, Continuation cont)
throws NamingException {
cont.setError(this, name);
throw cont.fillInException(
new OperationNotSupportedException());
}
public void c_destroySubcontext(Name name, Continuation cont)
throws NamingException {
cont.setError(this, name);
throw cont.fillInException(
new OperationNotSupportedException());
}
public NameParser c_getNameParser(Name name, Continuation cont)
throws NamingException {
cont.setSuccess();
return nameParser;
}
//---------- Directory operations
public void c_bind(Name name,
Object obj,
Attributes attrs,
Continuation cont)
throws NamingException {
cont.setError(this, name);
throw cont.fillInException(
new OperationNotSupportedException());
}
public void c_rebind(Name name,
Object obj,
Attributes attrs,
Continuation cont)
throws NamingException {
cont.setError(this, name);
throw cont.fillInException(
new OperationNotSupportedException());
}
public DirContext c_createSubcontext(Name name,
Attributes attrs,
Continuation cont)
throws NamingException {
cont.setError(this, name);
throw cont.fillInException(
new OperationNotSupportedException());
}
public Attributes c_getAttributes(Name name,
String[] attrIds,
Continuation cont)
throws NamingException {
cont.setSuccess();
try {
DnsName fqdn = fullyQualify(name);
CT[] cts = attrIdsToClassesAndTypes(attrIds);
CT ct = getClassAndTypeToQuery(cts);
ResourceRecords rrs =
getResolver().query(fqdn, ct.rrclass, ct.rrtype,
recursion, authoritative);
return rrsToAttrs(rrs, cts);
} catch (NamingException e) {
cont.setError(this, name);
throw cont.fillInException(e);
}
}
public void c_modifyAttributes(Name name,
int mod_op,
Attributes attrs,
Continuation cont)
throws NamingException {
cont.setError(this, name);
throw cont.fillInException(
new OperationNotSupportedException());
}
public void c_modifyAttributes(Name name,
ModificationItem[] mods,
Continuation cont)
throws NamingException {
cont.setError(this, name);
throw cont.fillInException(
new OperationNotSupportedException());
}
public NamingEnumeration<SearchResult> c_search(Name name,
Attributes matchingAttributes,
String[] attributesToReturn,
Continuation cont)
throws NamingException {
throw new OperationNotSupportedException();
}
public NamingEnumeration<SearchResult> c_search(Name name,
String filter,
SearchControls cons,
Continuation cont)
throws NamingException {
throw new OperationNotSupportedException();
}
public NamingEnumeration<SearchResult> c_search(Name name,
String filterExpr,
Object[] filterArgs,
SearchControls cons,
Continuation cont)
throws NamingException {
throw new OperationNotSupportedException();
}
public DirContext c_getSchema(Name name, Continuation cont)
throws NamingException {
cont.setError(this, name);
throw cont.fillInException(
new OperationNotSupportedException());
}
public DirContext c_getSchemaClassDefinition(Name name, Continuation cont)
throws NamingException {
cont.setError(this, name);
throw cont.fillInException(
new OperationNotSupportedException());
}
//---------- Name-related operations
public String getNameInNamespace() {
return domain.toString();
}
public Name composeName(Name name, Name prefix) throws NamingException {
Name result;
// Any name that's not a CompositeName is assumed to be a DNS
// compound name. Convert each to a DnsName for syntax checking.
if (!(prefix instanceof DnsName || prefix instanceof CompositeName)) {
prefix = (new DnsName()).addAll(prefix);
}
if (!(name instanceof DnsName || name instanceof CompositeName)) {
name = (new DnsName()).addAll(name);
}
// Each of prefix and name is now either a DnsName or a CompositeName.
// If we have two DnsNames, simply join them together.
if ((prefix instanceof DnsName) && (name instanceof DnsName)) {
result = (DnsName) (prefix.clone());
result.addAll(name);
return new CompositeName().add(result.toString());
}
// Wrap compound names in composite names.
Name prefixC = (prefix instanceof CompositeName)
? prefix
: new CompositeName().add(prefix.toString());
Name nameC = (name instanceof CompositeName)
? name
: new CompositeName().add(name.toString());
int prefixLast = prefixC.size() - 1;
// Let toolkit do the work at namespace boundaries.
if (nameC.isEmpty() || nameC.get(0).equals("") ||
prefixC.isEmpty() || prefixC.get(prefixLast).equals("")) {
return super.composeName(nameC, prefixC);
}
result = (prefix == prefixC)
? (CompositeName) prefixC.clone()
: prefixC; // prefixC is already a clone
result.addAll(nameC);
if (parentIsDns) {
DnsName dnsComp = (prefix instanceof DnsName)
? (DnsName) prefix.clone()
: new DnsName(prefixC.get(prefixLast));
dnsComp.addAll((name instanceof DnsName)
? name
: new DnsName(nameC.get(0)));
result.remove(prefixLast + 1);
result.remove(prefixLast);
result.add(prefixLast, dnsComp.toString());
}
return result;
}
//---------- Helper methods
/*
* Resolver is not created until needed, to allow time for updates
* to the environment.
*/
private synchronized Resolver getResolver() throws NamingException {
if (resolver == null) {
resolver = new Resolver(servers, timeout, retries);
}
return resolver;
}
/*
* Returns the fully-qualified domain name of a name given
* relative to this context. Result includes a root label (an
* empty component at position 0).
*/
DnsName fullyQualify(Name name) throws NamingException {
if (name.isEmpty()) {
return domain;
}
DnsName dnsName = (name instanceof CompositeName)
? new DnsName(name.get(0)) // parse name
: (DnsName) (new DnsName()).addAll(name); // clone & check syntax
if (dnsName.hasRootLabel()) {
// Be overly generous and allow root label if we're in root domain.
if (domain.size() == 1) {
return dnsName;
} else {
throw new InvalidNameException(
"DNS name " + dnsName + " not relative to " + domain);
}
}
return (DnsName) dnsName.addAll(0, domain);
}
/*
* Converts resource records to an attribute set. Only resource
* records in the answer section are used, and only those that
* match the classes and types in cts (see classAndTypeMatch()
* for matching rules).
*/
private static Attributes rrsToAttrs(ResourceRecords rrs, CT[] cts) {
BasicAttributes attrs = new BasicAttributes(true);
for (int i = 0; i < rrs.answer.size(); i++) {
ResourceRecord rr = rrs.answer.elementAt(i);
int rrtype = rr.getType();
int rrclass = rr.getRrclass();
if (!classAndTypeMatch(rrclass, rrtype, cts)) {
continue;
}
String attrId = toAttrId(rrclass, rrtype);
Attribute attr = attrs.get(attrId);
if (attr == null) {
attr = new BasicAttribute(attrId);
attrs.put(attr);
}
attr.add(rr.getRdata());
}
return attrs;
}
/*
* Returns true if rrclass and rrtype match some element of cts.
* A match occurs if corresponding classes and types are equal,
* or if the array value is ANY. If cts is null, then any class
* and type match.
*/
private static boolean classAndTypeMatch(int rrclass, int rrtype,
CT[] cts) {
if (cts == null) {
return true;
}
for (int i = 0; i < cts.length; i++) {
CT ct = cts[i];
boolean classMatch = (ct.rrclass == ANY) ||
(ct.rrclass == rrclass);
boolean typeMatch = (ct.rrtype == ANY) ||
(ct.rrtype == rrtype);
if (classMatch && typeMatch) {
return true;
}
}
return false;
}
/*
* Returns the attribute ID for a resource record given its class
* and type. If the record is in the internet class, the
* corresponding attribute ID is the record's type name (or the
* integer type value if the name is not known). If the record is
* not in the internet class, the class name (or integer class
* value) is prepended to the attribute ID, separated by a space.
*
* A class or type value of ANY represents an indeterminate class
* or type, and is represented within the attribute ID by "*".
* For example, the attribute ID "IN *" represents
* any type in the internet class, and "* NS" represents an NS
* record of any class.
*/
private static String toAttrId(int rrclass, int rrtype) {
String attrId = ResourceRecord.getTypeName(rrtype);
if (rrclass != ResourceRecord.CLASS_INTERNET) {
attrId = ResourceRecord.getRrclassName(rrclass) + " " + attrId;
}
return attrId;
}
/*
* Returns the class and type values corresponding to an attribute
* ID. An indeterminate class or type is represented by ANY. See
* toAttrId() for the format of attribute IDs.
*
* @throws InvalidAttributeIdentifierException
* if class or type is unknown
*/
private static CT fromAttrId(String attrId)
throws InvalidAttributeIdentifierException {
if (attrId.equals("")) {
throw new InvalidAttributeIdentifierException(
"Attribute ID cannot be empty");
}
int rrclass;
int rrtype;
int space = attrId.indexOf(' ');
// class
if (space < 0) {
rrclass = ResourceRecord.CLASS_INTERNET;
} else {
String className = attrId.substring(0, space);
rrclass = ResourceRecord.getRrclass(className);
if (rrclass < 0) {
throw new InvalidAttributeIdentifierException(
"Unknown resource record class '" + className + '\'');
}
}
// type
String typeName = attrId.substring(space + 1);
rrtype = ResourceRecord.getType(typeName);
if (rrtype < 0) {
throw new InvalidAttributeIdentifierException(
"Unknown resource record type '" + typeName + '\'');
}
return new CT(rrclass, rrtype);
}
/*
* Returns an array of the classes and types corresponding to a
* set of attribute IDs. See toAttrId() for the format of
* attribute IDs, and classAndTypeMatch() for the format of the
* array returned.
*/
private static CT[] attrIdsToClassesAndTypes(String[] attrIds)
throws InvalidAttributeIdentifierException {
if (attrIds == null) {
return null;
}
CT[] cts = new CT[attrIds.length];
for (int i = 0; i < attrIds.length; i++) {
cts[i] = fromAttrId(attrIds[i]);
}
return cts;
}
/*
* Returns the most restrictive resource record class and type
* that may be used to query for records matching cts.
* See classAndTypeMatch() for matching rules.
*/
private static CT getClassAndTypeToQuery(CT[] cts) {
int rrclass;
int rrtype;
if (cts == null) {
// Query all records.
rrclass = ANY;
rrtype = ANY;
} else if (cts.length == 0) {
// No records are requested, but we need to ask for something.
rrclass = ResourceRecord.CLASS_INTERNET;
rrtype = ANY;
} else {
rrclass = cts[0].rrclass;
rrtype = cts[0].rrtype;
for (int i = 1; i < cts.length; i++) {
if (rrclass != cts[i].rrclass) {
rrclass = ANY;
}
if (rrtype != cts[i].rrtype) {
rrtype = ANY;
}
}
}
return new CT(rrclass, rrtype);
}
//---------- Support for list operations
/*
* Synchronization notes:
*
* Any access to zoneTree that walks the tree, whether it modifies
* the tree or not, is synchronized on zoneTree.
* [%%% Note: a read/write lock would allow increased concurrency.]
* The depth of a ZoneNode can thereafter be accessed without
* further synchronization. Access to other fields and methods
* should be synchronized on the node itself.
*
* A zone's contents is a NameNode tree that, once created, is never
* modified. The only synchronization needed is to ensure that it
* gets flushed into shared memory after being created, which is
* accomplished by ZoneNode.populate(). The contents are accessed
* via a soft reference, so a ZoneNode may be seen to be populated
* one moment and unpopulated the next.
*/
/*
* Returns the node in the zone tree corresponding to a
* fully-qualified domain name. If the desired portion of the
* tree has not yet been populated or has been outdated, a zone
* transfer is done to populate the tree.
*/
private NameNode getNameNode(DnsName fqdn) throws NamingException {
dprint("getNameNode(" + fqdn + ")");
// Find deepest related zone in zone tree.
ZoneNode znode;
DnsName zone;
synchronized (zoneTree) {
znode = zoneTree.getDeepestPopulated(fqdn);
}
dprint("Deepest related zone in zone tree: " +
((znode != null) ? znode.getLabel() : "[none]"));
NameNode topOfZone;
NameNode nnode;
if (znode != null) {
synchronized (znode) {
topOfZone = znode.getContents();
}
// If fqdn is in znode's zone, is not at a zone cut, and
// is current, we're done.
if (topOfZone != null) {
nnode = topOfZone.get(fqdn, znode.depth() + 1); // +1 for root
if ((nnode != null) && !nnode.isZoneCut()) {
dprint("Found node " + fqdn + " in zone tree");
zone = (DnsName)
fqdn.getPrefix(znode.depth() + 1); // +1 for root
boolean current = isZoneCurrent(znode, zone);
boolean restart = false;
synchronized (znode) {
if (topOfZone != znode.getContents()) {
// Zone was modified while we were examining it.
// All bets are off.
restart = true;
} else if (!current) {
znode.depopulate();
} else {
return nnode; // cache hit!
}
}
dprint("Zone not current; discarding node");
if (restart) {
return getNameNode(fqdn);
}
}
}
}
// Cache miss... do it the expensive way.
dprint("Adding node " + fqdn + " to zone tree");
// Find fqdn's zone and add it to the tree.
zone = getResolver().findZoneName(fqdn, ResourceRecord.CLASS_INTERNET,
recursion);
dprint("Node's zone is " + zone);
synchronized (zoneTree) {
znode = (ZoneNode) zoneTree.add(zone, 1); // "1" to skip root
}
// If znode is now populated we know -- because the first half of
// getNodeName() didn't find it -- that it was populated by another
// thread during this method call. Assume then that it's current.
synchronized (znode) {
topOfZone = znode.isPopulated()
? znode.getContents()
: populateZone(znode, zone);
}
// Desired node should now be in znode's populated zone. Find it.
nnode = topOfZone.get(fqdn, zone.size());
if (nnode == null) {
throw new ConfigurationException(
"DNS error: node not found in its own zone");
}
dprint("Found node in newly-populated zone");
return nnode;
}
/*
* Does a zone transfer to [re]populate a zone in the zone tree.
* Returns the zone's new contents.
*/
private NameNode populateZone(ZoneNode znode, DnsName zone)
throws NamingException {
dprint("Populating zone " + zone);
// assert Thread.holdsLock(znode);
ResourceRecords rrs =
getResolver().queryZone(zone,
ResourceRecord.CLASS_INTERNET, recursion);
dprint("zone xfer complete: " + rrs.answer.size() + " records");
return znode.populate(zone, rrs);
}
/*
* Determine if a ZoneNode's data is current.
* We base this on a comparison between the cached serial
* number and the latest SOA record.
*
* If there is no SOA record, znode is not (or is no longer) a zone:
* depopulate znode and return false.
*
* Since this method may perform a network operation, it is best
* to call it with znode unlocked. Caller must then note that the
* result may be outdated by the time this method returns.
*/
private boolean isZoneCurrent(ZoneNode znode, DnsName zone)
throws NamingException {
// former version: return !znode.isExpired();
if (!znode.isPopulated()) {
return false;
}
ResourceRecord soa =
getResolver().findSoa(zone, ResourceRecord.CLASS_INTERNET,
recursion);
synchronized (znode) {
if (soa == null) {
znode.depopulate();
}
return (znode.isPopulated() &&
znode.compareSerialNumberTo(soa) >= 0);
}
}
//---------- Debugging
private static final boolean debug = false;
private static final void dprint(String msg) {
if (debug) {
System.err.println("** " + msg);
}
}
}
//----------
/*
* A pairing of a resource record class and a resource record type.
* A value of ANY in either field represents an indeterminate value.
*/
class CT {
int rrclass;
int rrtype;
CT(int rrclass, int rrtype) {
this.rrclass = rrclass;
this.rrtype = rrtype;
}
}
//----------
/*
* Common base class for NameClassPairEnumeration and BindingEnumeration.
*/
abstract class BaseNameClassPairEnumeration<T> implements NamingEnumeration<T> {
protected Enumeration<NameNode> nodes; // nodes to be enumerated, or null if none
protected DnsContext ctx; // context being enumerated
BaseNameClassPairEnumeration(DnsContext ctx, Hashtable<String,NameNode> nodes) {
this.ctx = ctx;
this.nodes = (nodes != null)
? nodes.elements()
: null;
}
/*
* ctx will be set to null when no longer needed by the enumeration.
*/
public final void close() {
nodes = null;
ctx = null;
}
public final boolean hasMore() {
boolean more = ((nodes != null) && nodes.hasMoreElements());
if (!more) {
close();
}
return more;
}
public final boolean hasMoreElements() {
return hasMore();
}
abstract public T next() throws NamingException;
public final T nextElement() {
try {
return next();
} catch (NamingException e) {
java.util.NoSuchElementException nsee =
new java.util.NoSuchElementException();
nsee.initCause(e);
throw nsee;
}
}
}
/*
* An enumeration of name/classname pairs.
*
* Nodes that have children or that are zone cuts are returned with
* classname DirContext. Other nodes are returned with classname
* Object even though they are DirContexts as well, since this might
* make the namespace easier to browse.
*/
final class NameClassPairEnumeration
extends BaseNameClassPairEnumeration<NameClassPair>
implements NamingEnumeration<NameClassPair> {
NameClassPairEnumeration(DnsContext ctx, Hashtable<String,NameNode> nodes) {
super(ctx, nodes);
}
@Override
public NameClassPair next() throws NamingException {
if (!hasMore()) {
throw new java.util.NoSuchElementException();
}
NameNode nnode = nodes.nextElement();
String className = (nnode.isZoneCut() ||
(nnode.getChildren() != null))
? "javax.naming.directory.DirContext"
: "java.lang.Object";
String label = nnode.getLabel();
Name compName = (new DnsName()).add(label);
Name cname = (new CompositeName()).add(compName.toString());
NameClassPair ncp = new NameClassPair(cname.toString(), className);
ncp.setNameInNamespace(ctx.fullyQualify(cname).toString());
return ncp;
}
}
/*
* An enumeration of Bindings.
*/
final class BindingEnumeration extends BaseNameClassPairEnumeration<Binding>
implements NamingEnumeration<Binding> {
BindingEnumeration(DnsContext ctx, Hashtable<String,NameNode> nodes) {
super(ctx, nodes);
}
// Finalizer not needed since it's safe to leave ctx unclosed.
// protected void finalize() {
// close();
// }
@Override
public Binding next() throws NamingException {
if (!hasMore()) {
throw (new java.util.NoSuchElementException());
}
NameNode nnode = nodes.nextElement();
String label = nnode.getLabel();
Name compName = (new DnsName()).add(label);
String compNameStr = compName.toString();
Name cname = (new CompositeName()).add(compNameStr);
String cnameStr = cname.toString();
DnsName fqdn = ctx.fullyQualify(compName);
// Clone ctx to create the child context.
DnsContext child = new DnsContext(ctx, fqdn);
try {
Object obj = DirectoryManager.getObjectInstance(
child, cname, ctx, child.environment, null);
Binding binding = new Binding(cnameStr, obj);
binding.setNameInNamespace(ctx.fullyQualify(cname).toString());
return binding;
} catch (Exception e) {
NamingException ne = new NamingException(
"Problem generating object using object factory");
ne.setRootCause(e);
throw ne;
}
}
}
|
apache/tajo
| 37,813
|
tajo-jdbc/src/main/java/org/apache/tajo/jdbc/TajoDatabaseMetaData.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tajo.jdbc;
import com.google.common.collect.Lists;
import org.apache.tajo.annotation.Nullable;
import org.apache.tajo.catalog.*;
import org.apache.tajo.client.CatalogAdminClient;
import org.apache.tajo.client.ResultSetUtil;
import org.apache.tajo.common.TajoDataTypes.Type;
import org.apache.tajo.common.type.TajoTypeUtil;
import org.apache.tajo.datum.Datum;
import org.apache.tajo.datum.NullDatum;
import org.apache.tajo.datum.TextDatum;
import org.apache.tajo.schema.IdentifierUtil;
import org.apache.tajo.util.VersionInfo;
import java.sql.*;
import java.util.*;
import static org.apache.tajo.TajoConstants.DEFAULT_SCHEMA_NAME;
/**
* TajoDatabaseMetaData.
*/
public class TajoDatabaseMetaData implements DatabaseMetaData {
private static final char SEARCH_STRING_ESCAPE = '\\';
private static final String KEYWORDS = "add,binary,boolean,explain,index,rename";
private static final String NUMERIC_FUNCTIONS =
"abs,acos,asin,atan,atan2,ceiling,cos,degrees,exp,,floor,mod,pi,pow," +
"radians,round,sign,sin,sqrt,tan";
private static final String STRING_FUNCTIONS = "ascii,chr,concat,left,length,ltrim,repeat,rtrim,substring";
private static final String PROCEDURE_TERM = "UDF";
private final JdbcConnection conn;
public TajoDatabaseMetaData(JdbcConnection conn) {
this.conn = conn;
}
@Override
public boolean allProceduresAreCallable() throws SQLException {
return true;
}
@Override
public boolean allTablesAreSelectable() throws SQLException {
return true;
}
@Override
public String getURL() throws SQLException {
return conn.getUri();
}
@Override
public String getUserName() throws SQLException {
return "tajo";
}
@Override
public boolean isReadOnly() throws SQLException {
return true;
}
@Override
public String getDatabaseProductName() throws SQLException {
return "Tajo";
}
@Override
public String getDatabaseProductVersion() throws SQLException {
return VersionInfo.getVersion();
}
@Override
public String getDriverName() throws SQLException {
return "tajo";
}
@Override
public String getDriverVersion() throws SQLException {
return TajoDriver.MAJOR_VERSION + "." + TajoDriver.MINOR_VERSION;
}
@Override
public int getDriverMajorVersion() {
return TajoDriver.MAJOR_VERSION;
}
@Override
public int getDriverMinorVersion() {
return TajoDriver.MINOR_VERSION;
}
@Override
public String getIdentifierQuoteString() throws SQLException {
return IdentifierUtil.IDENTIFIER_QUOTE_STRING;
}
@Override
public String getSQLKeywords() throws SQLException {
return KEYWORDS;
}
@Override
public String getNumericFunctions() throws SQLException {
return NUMERIC_FUNCTIONS;
}
@Override
public String getStringFunctions() throws SQLException {
return STRING_FUNCTIONS;
}
@Override
public String getSystemFunctions() throws SQLException {
return "";
}
@Override
public String getTimeDateFunctions()
throws SQLException {
return "";
}
@Override
public String getSearchStringEscape()
throws SQLException {
return "\\";
}
@Override
public String getExtraNameCharacters() throws SQLException {
return "";
}
@Override
public String getSchemaTerm() throws SQLException {
return "";
}
@Override
public String getProcedureTerm() throws SQLException {
return PROCEDURE_TERM;
}
@Override
public String getCatalogTerm() throws SQLException {
return "database";
}
@Override
public String getCatalogSeparator() throws SQLException {
return IdentifierUtil.IDENTIFIER_DELIMITER;
}
@Override
public int getMaxBinaryLiteralLength() throws SQLException {
return 0; // no limit
}
@Override
public int getMaxCharLiteralLength() throws SQLException {
return 0; // no limit
}
@Override
public int getMaxColumnNameLength() throws SQLException {
return IdentifierUtil.MAX_IDENTIFIER_LENGTH;
}
@Override
public int getMaxColumnsInGroupBy() throws SQLException {
return 0; // no limit
}
@Override
public int getMaxColumnsInIndex() throws SQLException {
return 0; // no limit
}
@Override
public int getMaxColumnsInOrderBy() throws SQLException {
return 0; // no limit
}
@Override
public int getMaxColumnsInSelect() throws SQLException {
return 0; // no limit
}
@Override
public int getMaxColumnsInTable() throws SQLException {
return 0; // no limit
}
@Override
public int getMaxConnections() throws SQLException {
return CatalogConstants.MAX_CONNECTION_LENGTH;
}
@Override
public int getMaxCursorNameLength() throws SQLException {
return IdentifierUtil.MAX_IDENTIFIER_LENGTH;
}
@Override
public int getMaxIndexLength() throws SQLException {
return 0;
}
@Override
public int getMaxSchemaNameLength() throws SQLException {
return IdentifierUtil.MAX_IDENTIFIER_LENGTH;
}
@Override
public int getMaxProcedureNameLength() throws SQLException {
return IdentifierUtil.MAX_IDENTIFIER_LENGTH;
}
@Override
public int getMaxCatalogNameLength() throws SQLException {
return IdentifierUtil.MAX_IDENTIFIER_LENGTH;
}
@Override
public int getMaxRowSize() throws SQLException {
return 0; // no limit
}
@Override
public boolean doesMaxRowSizeIncludeBlobs() throws SQLException {
return false;
}
@Override
public int getMaxStatementLength() throws SQLException {
return CatalogConstants.MAX_STATEMENT_LENGTH;
}
@Override
public int getMaxStatements() throws SQLException {
return 0;
}
@Override
public int getMaxTableNameLength() throws SQLException {
return IdentifierUtil.MAX_IDENTIFIER_LENGTH;
}
@Override
public int getMaxTablesInSelect() throws SQLException {
return 0; // no limit
}
@Override
public int getMaxUserNameLength() throws SQLException {
return CatalogConstants.MAX_USERNAME_LENGTH;
}
@Override
public int getDefaultTransactionIsolation() throws SQLException {
return Connection.TRANSACTION_NONE;
}
@Override
public boolean dataDefinitionCausesTransactionCommit()
throws SQLException {
return false;
}
@Override
public boolean dataDefinitionIgnoredInTransactions()
throws SQLException {
return false;
}
@Override
public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern)
throws SQLException {
return new TajoMetaDataResultSet(Arrays.asList("PROCEDURE_CAT", "PROCEDURE_SCHEM",
"PROCEDURE_NAME", "NUM_INPUT_PARAMS", "NUM_OUTPUT_PARAMS", "NUM_RESULT_SETS", "REMARKS",
"PROCEDURE_TYPE"),
Arrays.asList(Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.INT4, Type.INT4, Type.INT4,
Type.VARCHAR, Type.INT2),
new ArrayList<MetaDataTuple>());
}
@Override
public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern,
String columnNamePattern)
throws SQLException {
return new TajoMetaDataResultSet(Arrays.asList(
"PROCEDURE_CAT", "PROCEDURE_SCHEM", "PROCEDURE_NAME", "COLUMN_NAME", "COLUMN_TYPE",
"DATA_TYPE", "TYPE_NAME", "PRECISION", "LENGTH", "SCALE",
"RADIX", "NULLABLE", "REMARKS", "COLUMN_DEF", "SQL_DATA_TYPE",
"SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION", "IS_NULLABLE", "SPECIFIC_NAME"),
Arrays.asList(
Type.VARCHAR, Type.VARCHAR, Type.VARCHAR,Type.VARCHAR, Type.INT2,
Type.INT2, Type.VARCHAR, Type.INT4, Type.INT4, Type.INT2,
Type.INT2, Type.INT2, Type.VARCHAR, Type.VARCHAR, Type.INT2,
Type.INT2, Type.INT2, Type.INT1, Type.VARCHAR, Type.VARCHAR),
new ArrayList<MetaDataTuple>());
}
/**
* Convert a pattern containing JDBC catalog search wildcards into
* Java regex patterns.
*
* @param pattern input which may contain '%' or '_' wildcard characters, or
* these characters escaped using {@link #getSearchStringEscape()}.
* @return replace %/_ with regex search characters, also handle escaped
* characters.
*/
private String convertPattern(final String pattern) {
if (pattern == null) {
return ".*";
} else {
StringBuilder result = new StringBuilder(pattern.length());
boolean escaped = false;
for (int i = 0, len = pattern.length(); i < len; i++) {
char c = pattern.charAt(i);
if (escaped) {
if (c != SEARCH_STRING_ESCAPE) {
escaped = false;
}
result.append(c);
} else {
if (c == SEARCH_STRING_ESCAPE) {
escaped = true;
continue;
} else if (c == '%') {
result.append(".*");
} else if (c == '_') {
result.append('.');
} else {
result.append(c);
}
}
}
return result.toString();
}
}
@Override
public ResultSet getTables(@Nullable String catalog, @Nullable String schemaPattern,
@Nullable String tableNamePattern, @Nullable String [] types) throws SQLException {
final List<MetaDataTuple> resultTables = new ArrayList<>();
String regtableNamePattern = convertPattern(tableNamePattern == null ? null : tableNamePattern);
List<String> targetCatalogs = Lists.newArrayList();
if (catalog != null) {
targetCatalogs.add(catalog);
}
try {
CatalogAdminClient catalogAdmin = conn.getCatalogAdminClient();
// if catalog is null, all databases are targets.
if (targetCatalogs.isEmpty()) {
targetCatalogs.addAll(catalogAdmin.getAllDatabaseNames());
}
for (String databaseName : targetCatalogs) {
List<String> tableNames = catalogAdmin.getTableList(databaseName);
for (String eachTableName: tableNames) {
if (eachTableName.matches(regtableNamePattern)) {
MetaDataTuple tuple = new MetaDataTuple(5);
int index = 0;
tuple.put(index++, new TextDatum(databaseName)); // TABLE_CAT
tuple.put(index++, new TextDatum(DEFAULT_SCHEMA_NAME)); // TABLE_SCHEM
tuple.put(index++, new TextDatum(eachTableName)); // TABLE_NAME
tuple.put(index++, new TextDatum("TABLE")); // TABLE_TYPE
tuple.put(index++, NullDatum.get()); // REMARKS
resultTables.add(tuple);
}
}
}
Collections.sort(resultTables, new Comparator<MetaDataTuple> () {
@Override
public int compare(MetaDataTuple table1, MetaDataTuple table2) {
int compVal = table1.getText(1).compareTo(table2.getText(1));
if (compVal == 0) {
compVal = table1.getText(2).compareTo(table2.getText(2));
}
return compVal;
}
});
} catch (Throwable e) {
throw new SQLException(e);
}
TajoMetaDataResultSet result = new TajoMetaDataResultSet(
Arrays.asList("TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "TABLE_TYPE", "REMARKS"),
Arrays.asList(Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR),
resultTables);
return result;
}
@Override
public ResultSet getSchemas() throws SQLException {
String databaseName;
databaseName = conn.getQueryClient().getCurrentDatabase();
MetaDataTuple tuple = new MetaDataTuple(2);
tuple.put(0, new TextDatum(DEFAULT_SCHEMA_NAME));
tuple.put(1, new TextDatum(databaseName));
return new TajoMetaDataResultSet(
Arrays.asList("TABLE_SCHEM", "TABLE_CATALOG"),
Arrays.asList(Type.VARCHAR, Type.VARCHAR),
Collections.singletonList(tuple));
}
@Override
public ResultSet getCatalogs() throws SQLException {
Collection<String> databaseNames;
databaseNames = conn.getCatalogAdminClient().getAllDatabaseNames();
List<MetaDataTuple> tuples = new ArrayList<>();
for (String databaseName : databaseNames) {
MetaDataTuple tuple = new MetaDataTuple(1);
tuple.put(0, new TextDatum(databaseName));
tuples.add(tuple);
}
return new TajoMetaDataResultSet(
Collections.singletonList("TABLE_CAT"),
Collections.singletonList(Type.VARCHAR),
tuples);
}
@Override
public ResultSet getTableTypes() throws SQLException {
List<MetaDataTuple> columns = new ArrayList<>();
MetaDataTuple tuple = new MetaDataTuple(2);
tuple.put(0, new TextDatum("TABLE"));
columns.add(tuple);
ResultSet result = new TajoMetaDataResultSet(
Collections.singletonList("TABLE_TYPE")
, Collections.singletonList(Type.VARCHAR)
, columns);
return result;
}
@Override
public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types)
throws SQLException {
List<MetaDataTuple> columns = new ArrayList<>();
return new TajoMetaDataResultSet(
Arrays.asList("TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "CLASS_NAME", "DATA_TYPE"
, "REMARKS", "BASE_TYPE")
, Arrays.asList(Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.INT4, Type.VARCHAR, Type.INT4)
, columns);
}
@Override
public ResultSet getColumns(@Nullable String catalog, @Nullable String schemaPattern,
@Nullable String tableNamePattern, @Nullable String columnNamePattern)
throws SQLException {
List<String> targetCatalogs = Lists.newArrayList();
if (catalog != null) {
targetCatalogs.add(catalog);
}
List<MetaDataTuple> columns = new ArrayList<>();
try {
if (targetCatalogs.isEmpty()) {
targetCatalogs.addAll(conn.getCatalogAdminClient().getAllDatabaseNames());
}
for (String databaseName : targetCatalogs) {
String regtableNamePattern = convertPattern(tableNamePattern == null ? null : tableNamePattern);
String regcolumnNamePattern = convertPattern(columnNamePattern == null ? null : columnNamePattern);
List<String> tables = conn.getCatalogAdminClient().getTableList(databaseName);
for (String table: tables) {
if (table.matches(regtableNamePattern)) {
TableDesc tableDesc = conn.getCatalogAdminClient().getTableDesc(
IdentifierUtil.buildFQName(databaseName, table));
int pos = 0;
for (Column column: tableDesc.getLogicalSchema().getRootColumns()) {
if (column.getSimpleName().matches(regcolumnNamePattern)) {
MetaDataTuple tuple = new MetaDataTuple(22);
int index = 0;
tuple.put(index++, new TextDatum(databaseName)); // TABLE_CAT
tuple.put(index++, new TextDatum(DEFAULT_SCHEMA_NAME)); // TABLE_SCHEM
tuple.put(index++, new TextDatum(table)); // TABLE_NAME
tuple.put(index++, new TextDatum(column.getSimpleName())); // COLUMN_NAME
// TODO - DATA_TYPE
tuple.put(index++, new TextDatum("" + ResultSetUtil.tajoTypeToSqlType(column.getDataType())));
tuple.put(index++, new TextDatum(ResultSetUtil.toSqlType(column.getDataType()))); //TYPE_NAME
tuple.put(index++, new TextDatum("0")); // COLUMN_SIZE
tuple.put(index++, new TextDatum("0")); // BUFFER_LENGTH
tuple.put(index++, new TextDatum("0")); // DECIMAL_DIGITS
tuple.put(index++, new TextDatum("0")); // NUM_PREC_RADIX
tuple.put(index++, new TextDatum("" + DatabaseMetaData.columnNullable)); // NULLABLE
tuple.put(index++, NullDatum.get()); // REMARKS
tuple.put(index++, NullDatum.get()); // COLUMN_DEF
tuple.put(index++, NullDatum.get()); // SQL_DATA_TYPE
tuple.put(index++, NullDatum.get()); // SQL_DATETIME_SUB
tuple.put(index++, new TextDatum("0")); // CHAR_OCTET_LENGTH
tuple.put(index++, new TextDatum("" + pos)); // ORDINAL_POSITION
tuple.put(index++, new TextDatum("YES")); // IS_NULLABLE
tuple.put(index++, NullDatum.get()); // SCOPE_CATLOG
tuple.put(index++, NullDatum.get()); // SCOPE_SCHEMA
tuple.put(index++, NullDatum.get()); // SCOPE_TABLE
tuple.put(index++, new TextDatum("0")); // SOURCE_DATA_TYPE
columns.add(tuple);
}
pos++;
}
}
}
}
return new TajoMetaDataResultSet(
Arrays.asList("TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME", "DATA_TYPE"
, "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", "NUM_PREC_RADIX"
, "NULLABLE", "REMARKS", "COLUMN_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB"
, "CHAR_OCTET_LENGTH", "ORDINAL_POSITION", "IS_NULLABLE", "SCOPE_CATLOG", "SCOPE_SCHEMA"
, "SCOPE_TABLE", "SOURCE_DATA_TYPE")
, Arrays.asList(Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.INT4
, Type.VARCHAR, Type.INT4, Type.INT4, Type.INT4, Type.INT4
, Type.INT4, Type.VARCHAR, Type.VARCHAR, Type.INT4, Type.INT4
, Type.INT4, Type.INT4, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR
, Type.VARCHAR, Type.INT4)
, columns);
} catch (Throwable e) {
throw new SQLException(e);
}
}
@Override
public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern)
throws SQLException {
return new TajoMetaDataResultSet(Arrays.asList("TABLE_CAT", "TABLE_SCHEM",
"TABLE_NAME", "COLUMN_NAME", "GRANTOR", "GRANTEE", "PRIVILEGE",
"IS_GRANTABLE"),
Arrays.asList(Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR,
Type.VARCHAR, Type.VARCHAR),
new ArrayList<MetaDataTuple>());
}
@Override
public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern)
throws SQLException {
return new TajoMetaDataResultSet(Arrays.asList("TABLE_CAT", "TABLE_SCHEM",
"TABLE_NAME", "GRANTOR", "GRANTEE", "PRIVILEGE", "IS_GRANTABLE"),
Arrays.asList(Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR),
new ArrayList<MetaDataTuple>());
}
@Override
public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable)
throws SQLException {
return new TajoMetaDataResultSet(Arrays.asList("SCOPE", "COLUMN_NAME",
"DATA_TYPE", "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", "PSEUDO_COLUMN"),
Arrays.asList(Type.INT2, Type.VARCHAR, Type.INT2, Type.VARCHAR, Type.INT4, Type.INT4, Type.INT2, Type.INT2),
new ArrayList<MetaDataTuple>());
}
@Override
public ResultSet getVersionColumns(String catalog, String schema, String table)
throws SQLException {
return new TajoMetaDataResultSet(Arrays.asList("SCOPE", "COLUMN_NAME",
"DATA_TYPE", "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", "PSEUDO_COLUMN"),
Arrays.asList(Type.INT2, Type.VARCHAR, Type.INT2, Type.VARCHAR, Type.INT4, Type.INT4, Type.INT2, Type.INT2),
new ArrayList<MetaDataTuple>());
}
@Override
public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException {
return new TajoMetaDataResultSet(
Arrays.asList("TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME", "KEY_SEQ", "PK_NAME")
, Arrays.asList(Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.INT4, Type.VARCHAR)
, new ArrayList<MetaDataTuple>());
}
private final static Schema importedExportedSchema = SchemaBuilder.builder()
.add("PKTABLE_CAT", Type.VARCHAR) // 0
.add("PKTABLE_SCHEM", Type.VARCHAR) // 1
.add("PKTABLE_NAME", Type.VARCHAR) // 2
.add("PKCOLUMN_NAME", Type.VARCHAR) // 3
.add("FKTABLE_CAT", Type.VARCHAR) // 4
.add("FKTABLE_SCHEM", Type.VARCHAR) // 5
.add("FKTABLE_NAME", Type.VARCHAR) // 6
.add("FKCOLUMN_NAME", Type.VARCHAR) // 7
.add("KEY_SEQ", Type.INT2) // 8
.add("UPDATE_RULE", Type.INT2) // 9
.add("DELETE_RULE", Type.INT2) // 10
.add("FK_NAME", Type.VARCHAR) // 11
.add("PK_NAME", Type.VARCHAR) // 12
.add("DEFERRABILITY", Type.INT2) // 13
.build();
@Override
public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException {
return new TajoMetaDataResultSet(importedExportedSchema, new ArrayList<MetaDataTuple>());
}
@Override
public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException {
return new TajoMetaDataResultSet(importedExportedSchema, new ArrayList<MetaDataTuple>());
}
@Override
public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable,
String foreignCatalog, String foreignSchema, String foreignTable)
throws SQLException {
return new TajoMetaDataResultSet(importedExportedSchema, new ArrayList<MetaDataTuple>());
}
@Override
public ResultSet getTypeInfo() throws SQLException {
List<MetaDataTuple> tuples = new ArrayList<>();
for (Datum[] eachDatums: TajoTypeUtil.getTypeInfos()) {
MetaDataTuple tuple = new MetaDataTuple(eachDatums.length);
for (int i = 0; i < eachDatums.length; i++) {
tuple.put(i, eachDatums[i]);
}
tuples.add(tuple);
}
return new TajoMetaDataResultSet(
Arrays.asList(
"TYPE_NAME", "DATA_TYPE", "PRECISION", "LITERAL_PREFIX", "LITERAL_SUFFIX",
"CREATE_PARAMS", "NULLABLE", "CASE_SENSITIVE", "SEARCHABLE", "UNSIGNED_ATTRIBUTE",
"FIXED_PREC_SCALE", "AUTO_INCREMENT", "LOCAL_TYPE_NAME", "MINIMUM_SCALE", "MAXIMUM_SCALE",
"SQL_DATA_TYPE", "SQL_DATETIME_SUB", "NUM_PREC_RADIX"),
Arrays.asList(
Type.VARCHAR, Type.INT2, Type.INT4, Type.VARCHAR, Type.VARCHAR,
Type.VARCHAR, Type.INT2, Type.BOOLEAN, Type.INT2, Type.BOOLEAN,
Type.BOOLEAN, Type.BOOLEAN, Type.VARCHAR, Type.INT2, Type.INT2,
Type.INT4, Type.INT4, Type.INT4)
, tuples);
}
@Override
public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate)
throws SQLException {
return new TajoMetaDataResultSet(
Arrays.asList(
"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "NON_UNIQUE", "INDEX_QUALIFIER",
"INDEX_NAME", "TYPE", "ORDINAL_POSITION", "COLUMN_NAME", "ASC_OR_DESC",
"CARDINALITY", "PAGES", "FILTER_CONDITION"),
Arrays.asList(
Type.VARCHAR, Type.VARCHAR, Type.VARCHAR, Type.BOOLEAN, Type.VARCHAR,
Type.VARCHAR, Type.INT2, Type.INT2, Type.VARCHAR, Type.VARCHAR,
Type.INT4, Type.INT4, Type.VARCHAR)
, new ArrayList<MetaDataTuple>());
}
@Override
public boolean deletesAreDetected(int type)
throws SQLException {
return false;
}
@Override
public boolean insertsAreDetected(int type) throws SQLException {
return false;
}
@Override
public Connection getConnection() throws SQLException {
return conn;
}
@Override
public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern)
throws SQLException {
throw new SQLFeatureNotSupportedException("type hierarchies not supported");
}
@Override
public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern)
throws SQLException {
throw new SQLFeatureNotSupportedException("type hierarchies not supported");
}
@Override
public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern)
throws SQLException {
throw new SQLFeatureNotSupportedException("user-defined types not supported");
}
@Override
public int getResultSetHoldability()
throws SQLException {
return ResultSet.HOLD_CURSORS_OVER_COMMIT;
}
@Override
public int getDatabaseMajorVersion()
throws SQLException {
return TajoDriver.MAJOR_VERSION;
}
@Override
public int getDatabaseMinorVersion()
throws SQLException {
return TajoDriver.MINOR_VERSION;
}
@Override
public int getJDBCMajorVersion()
throws SQLException {
return TajoDriver.JDBC_VERSION_MAJOR;
}
@Override
public int getJDBCMinorVersion()
throws SQLException {
return TajoDriver.JDBC_VERSION_MINOR;
}
@Override
public int getSQLStateType()
throws SQLException {
return DatabaseMetaData.sqlStateSQL;
}
@Override
public RowIdLifetime getRowIdLifetime()
throws SQLException {
return RowIdLifetime.ROWID_UNSUPPORTED;
}
@Override
public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException {
String databaseName;
databaseName = conn.getQueryClient().getCurrentDatabase();
MetaDataTuple tuple = new MetaDataTuple(2);
tuple.put(0, new TextDatum(DEFAULT_SCHEMA_NAME));
tuple.put(1, new TextDatum(databaseName));
return new TajoMetaDataResultSet(
Arrays.asList("TABLE_SCHEM", "TABLE_CATALOG"),
Arrays.asList(Type.VARCHAR, Type.VARCHAR),
Collections.singletonList(tuple));
}
@Override
public boolean autoCommitFailureClosesAllResultSets()
throws SQLException {
return false;
}
@Override
public ResultSet getClientInfoProperties()
throws SQLException {
return new TajoMetaDataResultSet(Arrays.asList("NAME", "MAX_LEN", "DEFAULT_VALUE", "DESCRIPTION"),
Arrays.asList(Type.VARCHAR, Type.INT4, Type.VARCHAR, Type.VARCHAR),
new ArrayList<MetaDataTuple>());
}
@Override
public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException {
throw new SQLFeatureNotSupportedException("getFunctions not supported");
}
@Override
public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern,
String columnNamePattern) throws SQLException {
throw new SQLFeatureNotSupportedException("getFunctionColumns not supported");
}
@Override
public boolean isCatalogAtStart() throws SQLException {
return true;
}
@Override
public boolean locatorsUpdateCopy() throws SQLException {
return false;
}
@Override
public boolean nullPlusNonNullIsNull() throws SQLException {
return true;
}
@Override
public boolean nullsAreSortedAtEnd() throws SQLException {
return true;
}
@Override
public boolean nullsAreSortedAtStart() throws SQLException {
return false;
}
@Override
public boolean nullsAreSortedHigh() throws SQLException {
return false;
}
@Override
public boolean nullsAreSortedLow() throws SQLException {
return true;
}
@Override
public boolean othersDeletesAreVisible(int type) throws SQLException {
return false;
}
@Override
public boolean othersInsertsAreVisible(int type) throws SQLException {
return false;
}
@Override
public boolean othersUpdatesAreVisible(int type) throws SQLException {
return false;
}
@Override
public boolean ownDeletesAreVisible(int type) throws SQLException {
return false;
}
@Override
public boolean ownInsertsAreVisible(int type) throws SQLException {
return false;
}
@Override
public boolean ownUpdatesAreVisible(int type) throws SQLException {
return false;
}
@Override
public boolean storesLowerCaseIdentifiers() throws SQLException {
return true;
}
@Override
public boolean storesLowerCaseQuotedIdentifiers() throws SQLException {
return false;
}
@Override
public boolean storesMixedCaseIdentifiers() throws SQLException {
return false;
}
@Override
public boolean storesMixedCaseQuotedIdentifiers() throws SQLException {
return true;
}
@Override
public boolean storesUpperCaseIdentifiers() throws SQLException {
return false;
}
@Override
public boolean storesUpperCaseQuotedIdentifiers() throws SQLException {
return false;
}
@Override
public boolean supportsANSI92EntryLevelSQL() throws SQLException {
return false;
}
@Override
public boolean supportsANSI92FullSQL() throws SQLException {
return false;
}
@Override
public boolean supportsANSI92IntermediateSQL() throws SQLException {
return false;
}
@Override
public boolean supportsAlterTableWithAddColumn() throws SQLException {
return true;
}
@Override
public boolean supportsAlterTableWithDropColumn() throws SQLException {
return false;
}
@Override
public boolean supportsBatchUpdates() throws SQLException {
return false;
}
@Override
public boolean supportsCatalogsInDataManipulation() throws SQLException {
return false;
}
@Override
public boolean supportsCatalogsInIndexDefinitions() throws SQLException {
return false;
}
@Override
public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException {
return false;
}
@Override
public boolean supportsCatalogsInProcedureCalls() throws SQLException {
return false;
}
@Override
public boolean supportsCatalogsInTableDefinitions() throws SQLException {
return false;
}
@Override
public boolean supportsColumnAliasing() throws SQLException {
return true;
}
@Override
public boolean supportsConvert() throws SQLException {
return false;
}
@Override
public boolean supportsConvert(int fromType, int toType) throws SQLException {
return false;
}
@Override
public boolean supportsCoreSQLGrammar() throws SQLException {
return false;
}
@Override
public boolean supportsCorrelatedSubqueries() throws SQLException {
return false;
}
@Override
public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException {
return false;
}
@Override
public boolean supportsDataManipulationTransactionsOnly() throws SQLException {
return false;
}
@Override
public boolean supportsDifferentTableCorrelationNames() throws SQLException {
return false;
}
@Override
public boolean supportsExpressionsInOrderBy() throws SQLException {
return true;
}
@Override
public boolean supportsExtendedSQLGrammar() throws SQLException {
return false;
}
@Override
public boolean supportsFullOuterJoins() throws SQLException {
return true;
}
@Override
public boolean supportsGetGeneratedKeys() throws SQLException {
return false;
}
@Override
public boolean supportsGroupBy() throws SQLException {
return true;
}
@Override
public boolean supportsGroupByBeyondSelect() throws SQLException {
return false;
}
@Override
public boolean supportsGroupByUnrelated() throws SQLException {
return true;
}
@Override
public boolean supportsIntegrityEnhancementFacility() throws SQLException {
return false;
}
@Override
public boolean supportsLikeEscapeClause() throws SQLException {
return false;
}
@Override
public boolean supportsLimitedOuterJoins() throws SQLException {
return false;
}
@Override
public boolean supportsMinimumSQLGrammar() throws SQLException {
return false;
}
@Override
public boolean supportsMixedCaseIdentifiers() throws SQLException {
return false;
}
@Override
public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException {
return true;
}
@Override
public boolean supportsMultipleOpenResults() throws SQLException {
return false;
}
@Override
public boolean supportsMultipleResultSets() throws SQLException {
return false;
}
@Override
public boolean supportsMultipleTransactions() throws SQLException {
return false;
}
@Override
public boolean supportsNamedParameters() throws SQLException {
return false;
}
@Override
public boolean supportsNonNullableColumns() throws SQLException {
return false;
}
@Override
public boolean supportsOpenCursorsAcrossCommit() throws SQLException {
return false;
}
@Override
public boolean supportsOpenCursorsAcrossRollback() throws SQLException {
return false;
}
@Override
public boolean supportsOpenStatementsAcrossCommit() throws SQLException {
return false;
}
@Override
public boolean supportsOpenStatementsAcrossRollback() throws SQLException {
return false;
}
@Override
public boolean supportsOrderByUnrelated() throws SQLException {
return true;
}
@Override
public boolean supportsOuterJoins() throws SQLException {
return true;
}
@Override
public boolean supportsPositionedDelete() throws SQLException {
return false;
}
@Override
public boolean supportsPositionedUpdate() throws SQLException {
return false;
}
@Override
public boolean supportsResultSetConcurrency(int type, int concurrency)
throws SQLException {
return false;
}
@Override
public boolean supportsResultSetHoldability(int holdability) throws SQLException {
return false;
}
@Override
public boolean supportsResultSetType(int type) throws SQLException {
return false;
}
@Override
public boolean supportsSavepoints() throws SQLException {
return false;
}
@Override
public boolean supportsSchemasInDataManipulation() throws SQLException {
return false;
}
@Override
public boolean supportsSchemasInIndexDefinitions() throws SQLException {
return false;
}
@Override
public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException {
return false;
}
@Override
public boolean supportsSchemasInProcedureCalls() throws SQLException {
return false;
}
@Override
public boolean supportsSchemasInTableDefinitions() throws SQLException {
return false;
}
@Override
public boolean supportsSelectForUpdate() throws SQLException {
return false;
}
@Override
public boolean supportsStatementPooling() throws SQLException {
return false;
}
@Override
public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException {
return false;
}
@Override
public boolean supportsStoredProcedures() throws SQLException {
return false;
}
@Override
public boolean supportsSubqueriesInComparisons() throws SQLException {
return false;
}
@Override
public boolean supportsSubqueriesInExists() throws SQLException {
return false;
}
@Override
public boolean supportsSubqueriesInIns() throws SQLException {
return false;
}
@Override
public boolean supportsSubqueriesInQuantifieds() throws SQLException {
return false;
}
@Override
public boolean supportsTableCorrelationNames() throws SQLException {
return false;
}
@Override
public boolean supportsTransactionIsolationLevel(int level) throws SQLException {
return false;
}
@Override
public boolean supportsTransactions() throws SQLException {
return false;
}
@Override
public boolean supportsUnion() throws SQLException {
return false;
}
@Override
public boolean supportsUnionAll() throws SQLException {
return true;
}
@Override
public boolean updatesAreDetected(int type) throws SQLException {
return false;
}
@Override
public boolean usesLocalFilePerTable() throws SQLException {
return false;
}
@Override
public boolean usesLocalFiles() throws SQLException {
return false;
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
if (isWrapperFor(iface)) {
return (T) this;
}
throw new SQLFeatureNotSupportedException("No wrapper for " + iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface.isInstance(this);
}
@Override
public boolean generatedKeyAlwaysReturned() throws SQLException {
return false;
}
@Override
public ResultSet getPseudoColumns(String catalog, String schemaPattern,
String tableNamePattern, String columnNamePattern) throws SQLException {
throw new SQLFeatureNotSupportedException("getPseudoColumns not supported");
}
}
|
googleapis/google-cloud-java
| 38,223
|
java-meet/proto-google-cloud-meet-v2beta/src/main/java/com/google/apps/meet/v2beta/ListConferenceRecordsResponse.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/apps/meet/v2beta/service.proto
// Protobuf Java Version: 3.25.8
package com.google.apps.meet.v2beta;
/**
*
*
* <pre>
* Response of ListConferenceRecords method.
* </pre>
*
* Protobuf type {@code google.apps.meet.v2beta.ListConferenceRecordsResponse}
*/
public final class ListConferenceRecordsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.apps.meet.v2beta.ListConferenceRecordsResponse)
ListConferenceRecordsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListConferenceRecordsResponse.newBuilder() to construct.
private ListConferenceRecordsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListConferenceRecordsResponse() {
conferenceRecords_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListConferenceRecordsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.apps.meet.v2beta.ServiceProto
.internal_static_google_apps_meet_v2beta_ListConferenceRecordsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.apps.meet.v2beta.ServiceProto
.internal_static_google_apps_meet_v2beta_ListConferenceRecordsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.apps.meet.v2beta.ListConferenceRecordsResponse.class,
com.google.apps.meet.v2beta.ListConferenceRecordsResponse.Builder.class);
}
public static final int CONFERENCE_RECORDS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.apps.meet.v2beta.ConferenceRecord> conferenceRecords_;
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.apps.meet.v2beta.ConferenceRecord> getConferenceRecordsList() {
return conferenceRecords_;
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.apps.meet.v2beta.ConferenceRecordOrBuilder>
getConferenceRecordsOrBuilderList() {
return conferenceRecords_;
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
@java.lang.Override
public int getConferenceRecordsCount() {
return conferenceRecords_.size();
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
@java.lang.Override
public com.google.apps.meet.v2beta.ConferenceRecord getConferenceRecords(int index) {
return conferenceRecords_.get(index);
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
@java.lang.Override
public com.google.apps.meet.v2beta.ConferenceRecordOrBuilder getConferenceRecordsOrBuilder(
int index) {
return conferenceRecords_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to be circulated back for further List call if current List does NOT
* include all the Conferences. Unset if all conferences have been returned.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Token to be circulated back for further List call if current List does NOT
* include all the Conferences. Unset if all conferences have been returned.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < conferenceRecords_.size(); i++) {
output.writeMessage(1, conferenceRecords_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < conferenceRecords_.size(); i++) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(1, conferenceRecords_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.apps.meet.v2beta.ListConferenceRecordsResponse)) {
return super.equals(obj);
}
com.google.apps.meet.v2beta.ListConferenceRecordsResponse other =
(com.google.apps.meet.v2beta.ListConferenceRecordsResponse) obj;
if (!getConferenceRecordsList().equals(other.getConferenceRecordsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getConferenceRecordsCount() > 0) {
hash = (37 * hash) + CONFERENCE_RECORDS_FIELD_NUMBER;
hash = (53 * hash) + getConferenceRecordsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.apps.meet.v2beta.ListConferenceRecordsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response of ListConferenceRecords method.
* </pre>
*
* Protobuf type {@code google.apps.meet.v2beta.ListConferenceRecordsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.apps.meet.v2beta.ListConferenceRecordsResponse)
com.google.apps.meet.v2beta.ListConferenceRecordsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.apps.meet.v2beta.ServiceProto
.internal_static_google_apps_meet_v2beta_ListConferenceRecordsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.apps.meet.v2beta.ServiceProto
.internal_static_google_apps_meet_v2beta_ListConferenceRecordsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.apps.meet.v2beta.ListConferenceRecordsResponse.class,
com.google.apps.meet.v2beta.ListConferenceRecordsResponse.Builder.class);
}
// Construct using com.google.apps.meet.v2beta.ListConferenceRecordsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (conferenceRecordsBuilder_ == null) {
conferenceRecords_ = java.util.Collections.emptyList();
} else {
conferenceRecords_ = null;
conferenceRecordsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.apps.meet.v2beta.ServiceProto
.internal_static_google_apps_meet_v2beta_ListConferenceRecordsResponse_descriptor;
}
@java.lang.Override
public com.google.apps.meet.v2beta.ListConferenceRecordsResponse getDefaultInstanceForType() {
return com.google.apps.meet.v2beta.ListConferenceRecordsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.apps.meet.v2beta.ListConferenceRecordsResponse build() {
com.google.apps.meet.v2beta.ListConferenceRecordsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.apps.meet.v2beta.ListConferenceRecordsResponse buildPartial() {
com.google.apps.meet.v2beta.ListConferenceRecordsResponse result =
new com.google.apps.meet.v2beta.ListConferenceRecordsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.apps.meet.v2beta.ListConferenceRecordsResponse result) {
if (conferenceRecordsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
conferenceRecords_ = java.util.Collections.unmodifiableList(conferenceRecords_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.conferenceRecords_ = conferenceRecords_;
} else {
result.conferenceRecords_ = conferenceRecordsBuilder_.build();
}
}
private void buildPartial0(com.google.apps.meet.v2beta.ListConferenceRecordsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.apps.meet.v2beta.ListConferenceRecordsResponse) {
return mergeFrom((com.google.apps.meet.v2beta.ListConferenceRecordsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.apps.meet.v2beta.ListConferenceRecordsResponse other) {
if (other == com.google.apps.meet.v2beta.ListConferenceRecordsResponse.getDefaultInstance())
return this;
if (conferenceRecordsBuilder_ == null) {
if (!other.conferenceRecords_.isEmpty()) {
if (conferenceRecords_.isEmpty()) {
conferenceRecords_ = other.conferenceRecords_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureConferenceRecordsIsMutable();
conferenceRecords_.addAll(other.conferenceRecords_);
}
onChanged();
}
} else {
if (!other.conferenceRecords_.isEmpty()) {
if (conferenceRecordsBuilder_.isEmpty()) {
conferenceRecordsBuilder_.dispose();
conferenceRecordsBuilder_ = null;
conferenceRecords_ = other.conferenceRecords_;
bitField0_ = (bitField0_ & ~0x00000001);
conferenceRecordsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getConferenceRecordsFieldBuilder()
: null;
} else {
conferenceRecordsBuilder_.addAllMessages(other.conferenceRecords_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.apps.meet.v2beta.ConferenceRecord m =
input.readMessage(
com.google.apps.meet.v2beta.ConferenceRecord.parser(), extensionRegistry);
if (conferenceRecordsBuilder_ == null) {
ensureConferenceRecordsIsMutable();
conferenceRecords_.add(m);
} else {
conferenceRecordsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.apps.meet.v2beta.ConferenceRecord> conferenceRecords_ =
java.util.Collections.emptyList();
private void ensureConferenceRecordsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
conferenceRecords_ =
new java.util.ArrayList<com.google.apps.meet.v2beta.ConferenceRecord>(
conferenceRecords_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.apps.meet.v2beta.ConferenceRecord,
com.google.apps.meet.v2beta.ConferenceRecord.Builder,
com.google.apps.meet.v2beta.ConferenceRecordOrBuilder>
conferenceRecordsBuilder_;
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public java.util.List<com.google.apps.meet.v2beta.ConferenceRecord> getConferenceRecordsList() {
if (conferenceRecordsBuilder_ == null) {
return java.util.Collections.unmodifiableList(conferenceRecords_);
} else {
return conferenceRecordsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public int getConferenceRecordsCount() {
if (conferenceRecordsBuilder_ == null) {
return conferenceRecords_.size();
} else {
return conferenceRecordsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public com.google.apps.meet.v2beta.ConferenceRecord getConferenceRecords(int index) {
if (conferenceRecordsBuilder_ == null) {
return conferenceRecords_.get(index);
} else {
return conferenceRecordsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public Builder setConferenceRecords(
int index, com.google.apps.meet.v2beta.ConferenceRecord value) {
if (conferenceRecordsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureConferenceRecordsIsMutable();
conferenceRecords_.set(index, value);
onChanged();
} else {
conferenceRecordsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public Builder setConferenceRecords(
int index, com.google.apps.meet.v2beta.ConferenceRecord.Builder builderForValue) {
if (conferenceRecordsBuilder_ == null) {
ensureConferenceRecordsIsMutable();
conferenceRecords_.set(index, builderForValue.build());
onChanged();
} else {
conferenceRecordsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public Builder addConferenceRecords(com.google.apps.meet.v2beta.ConferenceRecord value) {
if (conferenceRecordsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureConferenceRecordsIsMutable();
conferenceRecords_.add(value);
onChanged();
} else {
conferenceRecordsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public Builder addConferenceRecords(
int index, com.google.apps.meet.v2beta.ConferenceRecord value) {
if (conferenceRecordsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureConferenceRecordsIsMutable();
conferenceRecords_.add(index, value);
onChanged();
} else {
conferenceRecordsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public Builder addConferenceRecords(
com.google.apps.meet.v2beta.ConferenceRecord.Builder builderForValue) {
if (conferenceRecordsBuilder_ == null) {
ensureConferenceRecordsIsMutable();
conferenceRecords_.add(builderForValue.build());
onChanged();
} else {
conferenceRecordsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public Builder addConferenceRecords(
int index, com.google.apps.meet.v2beta.ConferenceRecord.Builder builderForValue) {
if (conferenceRecordsBuilder_ == null) {
ensureConferenceRecordsIsMutable();
conferenceRecords_.add(index, builderForValue.build());
onChanged();
} else {
conferenceRecordsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public Builder addAllConferenceRecords(
java.lang.Iterable<? extends com.google.apps.meet.v2beta.ConferenceRecord> values) {
if (conferenceRecordsBuilder_ == null) {
ensureConferenceRecordsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, conferenceRecords_);
onChanged();
} else {
conferenceRecordsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public Builder clearConferenceRecords() {
if (conferenceRecordsBuilder_ == null) {
conferenceRecords_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
conferenceRecordsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public Builder removeConferenceRecords(int index) {
if (conferenceRecordsBuilder_ == null) {
ensureConferenceRecordsIsMutable();
conferenceRecords_.remove(index);
onChanged();
} else {
conferenceRecordsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public com.google.apps.meet.v2beta.ConferenceRecord.Builder getConferenceRecordsBuilder(
int index) {
return getConferenceRecordsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public com.google.apps.meet.v2beta.ConferenceRecordOrBuilder getConferenceRecordsOrBuilder(
int index) {
if (conferenceRecordsBuilder_ == null) {
return conferenceRecords_.get(index);
} else {
return conferenceRecordsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public java.util.List<? extends com.google.apps.meet.v2beta.ConferenceRecordOrBuilder>
getConferenceRecordsOrBuilderList() {
if (conferenceRecordsBuilder_ != null) {
return conferenceRecordsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(conferenceRecords_);
}
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public com.google.apps.meet.v2beta.ConferenceRecord.Builder addConferenceRecordsBuilder() {
return getConferenceRecordsFieldBuilder()
.addBuilder(com.google.apps.meet.v2beta.ConferenceRecord.getDefaultInstance());
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public com.google.apps.meet.v2beta.ConferenceRecord.Builder addConferenceRecordsBuilder(
int index) {
return getConferenceRecordsFieldBuilder()
.addBuilder(index, com.google.apps.meet.v2beta.ConferenceRecord.getDefaultInstance());
}
/**
*
*
* <pre>
* List of conferences in one page.
* </pre>
*
* <code>repeated .google.apps.meet.v2beta.ConferenceRecord conference_records = 1;</code>
*/
public java.util.List<com.google.apps.meet.v2beta.ConferenceRecord.Builder>
getConferenceRecordsBuilderList() {
return getConferenceRecordsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.apps.meet.v2beta.ConferenceRecord,
com.google.apps.meet.v2beta.ConferenceRecord.Builder,
com.google.apps.meet.v2beta.ConferenceRecordOrBuilder>
getConferenceRecordsFieldBuilder() {
if (conferenceRecordsBuilder_ == null) {
conferenceRecordsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.apps.meet.v2beta.ConferenceRecord,
com.google.apps.meet.v2beta.ConferenceRecord.Builder,
com.google.apps.meet.v2beta.ConferenceRecordOrBuilder>(
conferenceRecords_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
conferenceRecords_ = null;
}
return conferenceRecordsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to be circulated back for further List call if current List does NOT
* include all the Conferences. Unset if all conferences have been returned.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token to be circulated back for further List call if current List does NOT
* include all the Conferences. Unset if all conferences have been returned.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token to be circulated back for further List call if current List does NOT
* include all the Conferences. Unset if all conferences have been returned.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to be circulated back for further List call if current List does NOT
* include all the Conferences. Unset if all conferences have been returned.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to be circulated back for further List call if current List does NOT
* include all the Conferences. Unset if all conferences have been returned.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.apps.meet.v2beta.ListConferenceRecordsResponse)
}
// @@protoc_insertion_point(class_scope:google.apps.meet.v2beta.ListConferenceRecordsResponse)
private static final com.google.apps.meet.v2beta.ListConferenceRecordsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.apps.meet.v2beta.ListConferenceRecordsResponse();
}
public static com.google.apps.meet.v2beta.ListConferenceRecordsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListConferenceRecordsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListConferenceRecordsResponse>() {
@java.lang.Override
public ListConferenceRecordsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListConferenceRecordsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListConferenceRecordsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.apps.meet.v2beta.ListConferenceRecordsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,435
|
java-enterpriseknowledgegraph/google-cloud-enterpriseknowledgegraph/src/main/java/com/google/cloud/enterpriseknowledgegraph/v1/stub/HttpJsonEnterpriseKnowledgeGraphServiceStub.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.enterpriseknowledgegraph.v1.stub;
import static com.google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphServiceClient.ListEntityReconciliationJobsPagedResponse;
import com.google.api.core.InternalApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.httpjson.ApiMethodDescriptor;
import com.google.api.gax.httpjson.HttpJsonCallSettings;
import com.google.api.gax.httpjson.HttpJsonStubCallableFactory;
import com.google.api.gax.httpjson.ProtoMessageRequestFormatter;
import com.google.api.gax.httpjson.ProtoMessageResponseParser;
import com.google.api.gax.httpjson.ProtoRestSerializer;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.RequestParamsBuilder;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.enterpriseknowledgegraph.v1.CancelEntityReconciliationJobRequest;
import com.google.cloud.enterpriseknowledgegraph.v1.CreateEntityReconciliationJobRequest;
import com.google.cloud.enterpriseknowledgegraph.v1.DeleteEntityReconciliationJobRequest;
import com.google.cloud.enterpriseknowledgegraph.v1.EntityReconciliationJob;
import com.google.cloud.enterpriseknowledgegraph.v1.GetEntityReconciliationJobRequest;
import com.google.cloud.enterpriseknowledgegraph.v1.ListEntityReconciliationJobsRequest;
import com.google.cloud.enterpriseknowledgegraph.v1.ListEntityReconciliationJobsResponse;
import com.google.cloud.enterpriseknowledgegraph.v1.LookupPublicKgRequest;
import com.google.cloud.enterpriseknowledgegraph.v1.LookupPublicKgResponse;
import com.google.cloud.enterpriseknowledgegraph.v1.LookupRequest;
import com.google.cloud.enterpriseknowledgegraph.v1.LookupResponse;
import com.google.cloud.enterpriseknowledgegraph.v1.SearchPublicKgRequest;
import com.google.cloud.enterpriseknowledgegraph.v1.SearchPublicKgResponse;
import com.google.cloud.enterpriseknowledgegraph.v1.SearchRequest;
import com.google.cloud.enterpriseknowledgegraph.v1.SearchResponse;
import com.google.protobuf.Empty;
import com.google.protobuf.TypeRegistry;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* REST stub implementation for the EnterpriseKnowledgeGraphService service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@Generated("by gapic-generator-java")
public class HttpJsonEnterpriseKnowledgeGraphServiceStub
extends EnterpriseKnowledgeGraphServiceStub {
private static final TypeRegistry typeRegistry = TypeRegistry.newBuilder().build();
private static final ApiMethodDescriptor<
CreateEntityReconciliationJobRequest, EntityReconciliationJob>
createEntityReconciliationJobMethodDescriptor =
ApiMethodDescriptor
.<CreateEntityReconciliationJobRequest, EntityReconciliationJob>newBuilder()
.setFullMethodName(
"google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphService/CreateEntityReconciliationJob")
.setHttpMethod("POST")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<CreateEntityReconciliationJobRequest>newBuilder()
.setPath(
"/v1/{parent=projects/*/locations/*}/entityReconciliationJobs",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<CreateEntityReconciliationJobRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "parent", request.getParent());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<CreateEntityReconciliationJobRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(
request ->
ProtoRestSerializer.create()
.toBody(
"entityReconciliationJob",
request.getEntityReconciliationJob(),
true))
.build())
.setResponseParser(
ProtoMessageResponseParser.<EntityReconciliationJob>newBuilder()
.setDefaultInstance(EntityReconciliationJob.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<
GetEntityReconciliationJobRequest, EntityReconciliationJob>
getEntityReconciliationJobMethodDescriptor =
ApiMethodDescriptor
.<GetEntityReconciliationJobRequest, EntityReconciliationJob>newBuilder()
.setFullMethodName(
"google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphService/GetEntityReconciliationJob")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<GetEntityReconciliationJobRequest>newBuilder()
.setPath(
"/v1/{name=projects/*/locations/*/entityReconciliationJobs/*}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<GetEntityReconciliationJobRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "name", request.getName());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<GetEntityReconciliationJobRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<EntityReconciliationJob>newBuilder()
.setDefaultInstance(EntityReconciliationJob.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<
ListEntityReconciliationJobsRequest, ListEntityReconciliationJobsResponse>
listEntityReconciliationJobsMethodDescriptor =
ApiMethodDescriptor
.<ListEntityReconciliationJobsRequest, ListEntityReconciliationJobsResponse>
newBuilder()
.setFullMethodName(
"google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphService/ListEntityReconciliationJobs")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<ListEntityReconciliationJobsRequest>newBuilder()
.setPath(
"/v1/{parent=projects/*/locations/*}/entityReconciliationJobs",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<ListEntityReconciliationJobsRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "parent", request.getParent());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<ListEntityReconciliationJobsRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "filter", request.getFilter());
serializer.putQueryParam(fields, "pageSize", request.getPageSize());
serializer.putQueryParam(fields, "pageToken", request.getPageToken());
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<ListEntityReconciliationJobsResponse>newBuilder()
.setDefaultInstance(ListEntityReconciliationJobsResponse.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<CancelEntityReconciliationJobRequest, Empty>
cancelEntityReconciliationJobMethodDescriptor =
ApiMethodDescriptor.<CancelEntityReconciliationJobRequest, Empty>newBuilder()
.setFullMethodName(
"google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphService/CancelEntityReconciliationJob")
.setHttpMethod("POST")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<CancelEntityReconciliationJobRequest>newBuilder()
.setPath(
"/v1/{name=projects/*/locations/*/entityReconciliationJobs/*}:cancel",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<CancelEntityReconciliationJobRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "name", request.getName());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<CancelEntityReconciliationJobRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(
request ->
ProtoRestSerializer.create()
.toBody("*", request.toBuilder().clearName().build(), true))
.build())
.setResponseParser(
ProtoMessageResponseParser.<Empty>newBuilder()
.setDefaultInstance(Empty.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<DeleteEntityReconciliationJobRequest, Empty>
deleteEntityReconciliationJobMethodDescriptor =
ApiMethodDescriptor.<DeleteEntityReconciliationJobRequest, Empty>newBuilder()
.setFullMethodName(
"google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphService/DeleteEntityReconciliationJob")
.setHttpMethod("DELETE")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<DeleteEntityReconciliationJobRequest>newBuilder()
.setPath(
"/v1/{name=projects/*/locations/*/entityReconciliationJobs/*}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<DeleteEntityReconciliationJobRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "name", request.getName());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<DeleteEntityReconciliationJobRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<Empty>newBuilder()
.setDefaultInstance(Empty.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<LookupRequest, LookupResponse> lookupMethodDescriptor =
ApiMethodDescriptor.<LookupRequest, LookupResponse>newBuilder()
.setFullMethodName(
"google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphService/Lookup")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<LookupRequest>newBuilder()
.setPath(
"/v1/{parent=projects/*/locations/*}/cloudKnowledgeGraphEntities:Lookup",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<LookupRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "parent", request.getParent());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<LookupRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "ids", request.getIdsList());
serializer.putQueryParam(fields, "languages", request.getLanguagesList());
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<LookupResponse>newBuilder()
.setDefaultInstance(LookupResponse.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<SearchRequest, SearchResponse> searchMethodDescriptor =
ApiMethodDescriptor.<SearchRequest, SearchResponse>newBuilder()
.setFullMethodName(
"google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphService/Search")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<SearchRequest>newBuilder()
.setPath(
"/v1/{parent=projects/*/locations/*}/cloudKnowledgeGraphEntities:Search",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<SearchRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "parent", request.getParent());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<SearchRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "languages", request.getLanguagesList());
serializer.putQueryParam(fields, "limit", request.getLimit());
serializer.putQueryParam(fields, "query", request.getQuery());
serializer.putQueryParam(fields, "types", request.getTypesList());
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<SearchResponse>newBuilder()
.setDefaultInstance(SearchResponse.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<LookupPublicKgRequest, LookupPublicKgResponse>
lookupPublicKgMethodDescriptor =
ApiMethodDescriptor.<LookupPublicKgRequest, LookupPublicKgResponse>newBuilder()
.setFullMethodName(
"google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphService/LookupPublicKg")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<LookupPublicKgRequest>newBuilder()
.setPath(
"/v1/{parent=projects/*/locations/*}/publicKnowledgeGraphEntities:Lookup",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<LookupPublicKgRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "parent", request.getParent());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<LookupPublicKgRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "ids", request.getIdsList());
serializer.putQueryParam(
fields, "languages", request.getLanguagesList());
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<LookupPublicKgResponse>newBuilder()
.setDefaultInstance(LookupPublicKgResponse.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<SearchPublicKgRequest, SearchPublicKgResponse>
searchPublicKgMethodDescriptor =
ApiMethodDescriptor.<SearchPublicKgRequest, SearchPublicKgResponse>newBuilder()
.setFullMethodName(
"google.cloud.enterpriseknowledgegraph.v1.EnterpriseKnowledgeGraphService/SearchPublicKg")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<SearchPublicKgRequest>newBuilder()
.setPath(
"/v1/{parent=projects/*/locations/*}/publicKnowledgeGraphEntities:Search",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<SearchPublicKgRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "parent", request.getParent());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<SearchPublicKgRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(
fields, "languages", request.getLanguagesList());
serializer.putQueryParam(fields, "limit", request.getLimit());
serializer.putQueryParam(fields, "query", request.getQuery());
serializer.putQueryParam(fields, "types", request.getTypesList());
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<SearchPublicKgResponse>newBuilder()
.setDefaultInstance(SearchPublicKgResponse.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private final UnaryCallable<CreateEntityReconciliationJobRequest, EntityReconciliationJob>
createEntityReconciliationJobCallable;
private final UnaryCallable<GetEntityReconciliationJobRequest, EntityReconciliationJob>
getEntityReconciliationJobCallable;
private final UnaryCallable<
ListEntityReconciliationJobsRequest, ListEntityReconciliationJobsResponse>
listEntityReconciliationJobsCallable;
private final UnaryCallable<
ListEntityReconciliationJobsRequest, ListEntityReconciliationJobsPagedResponse>
listEntityReconciliationJobsPagedCallable;
private final UnaryCallable<CancelEntityReconciliationJobRequest, Empty>
cancelEntityReconciliationJobCallable;
private final UnaryCallable<DeleteEntityReconciliationJobRequest, Empty>
deleteEntityReconciliationJobCallable;
private final UnaryCallable<LookupRequest, LookupResponse> lookupCallable;
private final UnaryCallable<SearchRequest, SearchResponse> searchCallable;
private final UnaryCallable<LookupPublicKgRequest, LookupPublicKgResponse> lookupPublicKgCallable;
private final UnaryCallable<SearchPublicKgRequest, SearchPublicKgResponse> searchPublicKgCallable;
private final BackgroundResource backgroundResources;
private final HttpJsonStubCallableFactory callableFactory;
public static final HttpJsonEnterpriseKnowledgeGraphServiceStub create(
EnterpriseKnowledgeGraphServiceStubSettings settings) throws IOException {
return new HttpJsonEnterpriseKnowledgeGraphServiceStub(
settings, ClientContext.create(settings));
}
public static final HttpJsonEnterpriseKnowledgeGraphServiceStub create(
ClientContext clientContext) throws IOException {
return new HttpJsonEnterpriseKnowledgeGraphServiceStub(
EnterpriseKnowledgeGraphServiceStubSettings.newHttpJsonBuilder().build(), clientContext);
}
public static final HttpJsonEnterpriseKnowledgeGraphServiceStub create(
ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException {
return new HttpJsonEnterpriseKnowledgeGraphServiceStub(
EnterpriseKnowledgeGraphServiceStubSettings.newHttpJsonBuilder().build(),
clientContext,
callableFactory);
}
/**
* Constructs an instance of HttpJsonEnterpriseKnowledgeGraphServiceStub, using the given
* settings. This is protected so that it is easy to make a subclass, but otherwise, the static
* factory methods should be preferred.
*/
protected HttpJsonEnterpriseKnowledgeGraphServiceStub(
EnterpriseKnowledgeGraphServiceStubSettings settings, ClientContext clientContext)
throws IOException {
this(settings, clientContext, new HttpJsonEnterpriseKnowledgeGraphServiceCallableFactory());
}
/**
* Constructs an instance of HttpJsonEnterpriseKnowledgeGraphServiceStub, using the given
* settings. This is protected so that it is easy to make a subclass, but otherwise, the static
* factory methods should be preferred.
*/
protected HttpJsonEnterpriseKnowledgeGraphServiceStub(
EnterpriseKnowledgeGraphServiceStubSettings settings,
ClientContext clientContext,
HttpJsonStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
HttpJsonCallSettings<CreateEntityReconciliationJobRequest, EntityReconciliationJob>
createEntityReconciliationJobTransportSettings =
HttpJsonCallSettings
.<CreateEntityReconciliationJobRequest, EntityReconciliationJob>newBuilder()
.setMethodDescriptor(createEntityReconciliationJobMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
HttpJsonCallSettings<GetEntityReconciliationJobRequest, EntityReconciliationJob>
getEntityReconciliationJobTransportSettings =
HttpJsonCallSettings
.<GetEntityReconciliationJobRequest, EntityReconciliationJob>newBuilder()
.setMethodDescriptor(getEntityReconciliationJobMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
HttpJsonCallSettings<ListEntityReconciliationJobsRequest, ListEntityReconciliationJobsResponse>
listEntityReconciliationJobsTransportSettings =
HttpJsonCallSettings
.<ListEntityReconciliationJobsRequest, ListEntityReconciliationJobsResponse>
newBuilder()
.setMethodDescriptor(listEntityReconciliationJobsMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
HttpJsonCallSettings<CancelEntityReconciliationJobRequest, Empty>
cancelEntityReconciliationJobTransportSettings =
HttpJsonCallSettings.<CancelEntityReconciliationJobRequest, Empty>newBuilder()
.setMethodDescriptor(cancelEntityReconciliationJobMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
HttpJsonCallSettings<DeleteEntityReconciliationJobRequest, Empty>
deleteEntityReconciliationJobTransportSettings =
HttpJsonCallSettings.<DeleteEntityReconciliationJobRequest, Empty>newBuilder()
.setMethodDescriptor(deleteEntityReconciliationJobMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
HttpJsonCallSettings<LookupRequest, LookupResponse> lookupTransportSettings =
HttpJsonCallSettings.<LookupRequest, LookupResponse>newBuilder()
.setMethodDescriptor(lookupMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
HttpJsonCallSettings<SearchRequest, SearchResponse> searchTransportSettings =
HttpJsonCallSettings.<SearchRequest, SearchResponse>newBuilder()
.setMethodDescriptor(searchMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
HttpJsonCallSettings<LookupPublicKgRequest, LookupPublicKgResponse>
lookupPublicKgTransportSettings =
HttpJsonCallSettings.<LookupPublicKgRequest, LookupPublicKgResponse>newBuilder()
.setMethodDescriptor(lookupPublicKgMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
HttpJsonCallSettings<SearchPublicKgRequest, SearchPublicKgResponse>
searchPublicKgTransportSettings =
HttpJsonCallSettings.<SearchPublicKgRequest, SearchPublicKgResponse>newBuilder()
.setMethodDescriptor(searchPublicKgMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
this.createEntityReconciliationJobCallable =
callableFactory.createUnaryCallable(
createEntityReconciliationJobTransportSettings,
settings.createEntityReconciliationJobSettings(),
clientContext);
this.getEntityReconciliationJobCallable =
callableFactory.createUnaryCallable(
getEntityReconciliationJobTransportSettings,
settings.getEntityReconciliationJobSettings(),
clientContext);
this.listEntityReconciliationJobsCallable =
callableFactory.createUnaryCallable(
listEntityReconciliationJobsTransportSettings,
settings.listEntityReconciliationJobsSettings(),
clientContext);
this.listEntityReconciliationJobsPagedCallable =
callableFactory.createPagedCallable(
listEntityReconciliationJobsTransportSettings,
settings.listEntityReconciliationJobsSettings(),
clientContext);
this.cancelEntityReconciliationJobCallable =
callableFactory.createUnaryCallable(
cancelEntityReconciliationJobTransportSettings,
settings.cancelEntityReconciliationJobSettings(),
clientContext);
this.deleteEntityReconciliationJobCallable =
callableFactory.createUnaryCallable(
deleteEntityReconciliationJobTransportSettings,
settings.deleteEntityReconciliationJobSettings(),
clientContext);
this.lookupCallable =
callableFactory.createUnaryCallable(
lookupTransportSettings, settings.lookupSettings(), clientContext);
this.searchCallable =
callableFactory.createUnaryCallable(
searchTransportSettings, settings.searchSettings(), clientContext);
this.lookupPublicKgCallable =
callableFactory.createUnaryCallable(
lookupPublicKgTransportSettings, settings.lookupPublicKgSettings(), clientContext);
this.searchPublicKgCallable =
callableFactory.createUnaryCallable(
searchPublicKgTransportSettings, settings.searchPublicKgSettings(), clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
@InternalApi
public static List<ApiMethodDescriptor> getMethodDescriptors() {
List<ApiMethodDescriptor> methodDescriptors = new ArrayList<>();
methodDescriptors.add(createEntityReconciliationJobMethodDescriptor);
methodDescriptors.add(getEntityReconciliationJobMethodDescriptor);
methodDescriptors.add(listEntityReconciliationJobsMethodDescriptor);
methodDescriptors.add(cancelEntityReconciliationJobMethodDescriptor);
methodDescriptors.add(deleteEntityReconciliationJobMethodDescriptor);
methodDescriptors.add(lookupMethodDescriptor);
methodDescriptors.add(searchMethodDescriptor);
methodDescriptors.add(lookupPublicKgMethodDescriptor);
methodDescriptors.add(searchPublicKgMethodDescriptor);
return methodDescriptors;
}
@Override
public UnaryCallable<CreateEntityReconciliationJobRequest, EntityReconciliationJob>
createEntityReconciliationJobCallable() {
return createEntityReconciliationJobCallable;
}
@Override
public UnaryCallable<GetEntityReconciliationJobRequest, EntityReconciliationJob>
getEntityReconciliationJobCallable() {
return getEntityReconciliationJobCallable;
}
@Override
public UnaryCallable<ListEntityReconciliationJobsRequest, ListEntityReconciliationJobsResponse>
listEntityReconciliationJobsCallable() {
return listEntityReconciliationJobsCallable;
}
@Override
public UnaryCallable<
ListEntityReconciliationJobsRequest, ListEntityReconciliationJobsPagedResponse>
listEntityReconciliationJobsPagedCallable() {
return listEntityReconciliationJobsPagedCallable;
}
@Override
public UnaryCallable<CancelEntityReconciliationJobRequest, Empty>
cancelEntityReconciliationJobCallable() {
return cancelEntityReconciliationJobCallable;
}
@Override
public UnaryCallable<DeleteEntityReconciliationJobRequest, Empty>
deleteEntityReconciliationJobCallable() {
return deleteEntityReconciliationJobCallable;
}
@Override
public UnaryCallable<LookupRequest, LookupResponse> lookupCallable() {
return lookupCallable;
}
@Override
public UnaryCallable<SearchRequest, SearchResponse> searchCallable() {
return searchCallable;
}
@Override
public UnaryCallable<LookupPublicKgRequest, LookupPublicKgResponse> lookupPublicKgCallable() {
return lookupPublicKgCallable;
}
@Override
public UnaryCallable<SearchPublicKgRequest, SearchPublicKgResponse> searchPublicKgCallable() {
return searchPublicKgCallable;
}
@Override
public final void close() {
try {
backgroundResources.close();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to close resource", e);
}
}
@Override
public void shutdown() {
backgroundResources.shutdown();
}
@Override
public boolean isShutdown() {
return backgroundResources.isShutdown();
}
@Override
public boolean isTerminated() {
return backgroundResources.isTerminated();
}
@Override
public void shutdownNow() {
backgroundResources.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return backgroundResources.awaitTermination(duration, unit);
}
}
|
apache/pulsar
| 37,980
|
pulsar-broker/src/main/java/org/apache/pulsar/broker/admin/impl/SinksBase.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.broker.admin.impl;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import io.swagger.annotations.Example;
import io.swagger.annotations.ExampleProperty;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.apache.pulsar.broker.admin.AdminResource;
import org.apache.pulsar.common.functions.UpdateOptionsImpl;
import org.apache.pulsar.common.io.ConfigFieldDefinition;
import org.apache.pulsar.common.io.ConnectorDefinition;
import org.apache.pulsar.common.io.SinkConfig;
import org.apache.pulsar.common.policies.data.SinkStatus;
import org.apache.pulsar.functions.worker.WorkerService;
import org.apache.pulsar.functions.worker.service.api.Sinks;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
public class SinksBase extends AdminResource {
Sinks<? extends WorkerService> sinks() {
return validateAndGetWorkerService().getSinks();
}
@POST
@ApiOperation(value = "Creates a new Pulsar Sink in cluster mode")
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Invalid request (The Pulsar Sink already exists, etc.)"),
@ApiResponse(code = 200, message = "Pulsar Sink successfully created"),
@ApiResponse(code = 500, message =
"Internal server error (failed to authorize,"
+ " failed to get tenant data, failed to process package, etc.)"),
@ApiResponse(code = 401, message = "Client is not authorized to perform operation"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Path("/{tenant}/{namespace}/{sinkName}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void registerSink(@ApiParam(value = "The tenant of a Pulsar Sink") final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink") final @PathParam("namespace")
String namespace,
@ApiParam(value = "The name of a Pulsar Sink") final @PathParam("sinkName")
String sinkName,
final @FormDataParam("data") InputStream uploadedInputStream,
final @FormDataParam("data") FormDataContentDisposition fileDetail,
final @FormDataParam("url") String sinkPkgUrl,
@ApiParam(value =
"You can submit a sink (in any languages that you are familiar with) "
+ "to a Pulsar cluster. Follow the steps below.\n"
+ "1. Create a JSON object using some of the following parameters.\n"
+ "A JSON value presenting config payload of a Pulsar Sink."
+ " All available configuration options are:\n"
+ "- **classname**\n"
+ " The class name of a Pulsar Sink if"
+ " archive is file-url-path (file://)\n"
+ "- **sourceSubscriptionName**\n"
+ " Pulsar source subscription name if"
+ " user wants a specific\n"
+ " subscription-name for input-topic consumer\n"
+ "- **inputs**\n"
+ " The input topic or topics of"
+ " a Pulsar Sink (specified as a JSON array)\n"
+ "- **topicsPattern**\n"
+ " TopicsPattern to consume from list of topics under a namespace that "
+ " match the pattern. [input] and [topicsPattern] are mutually "
+ " exclusive. Add SerDe class name for a pattern in customSerdeInputs "
+ " (supported for java fun only)"
+ "- **topicToSerdeClassName**\n"
+ " The map of input topics to SerDe class names"
+ " (specified as a JSON object)\n"
+ "- **topicToSchemaType**\n"
+ " The map of input topics to Schema types or class names"
+ " (specified as a JSON object)\n"
+ "- **inputSpecs**\n"
+ " The map of input topics to its consumer configuration,"
+ " each configuration has schema of "
+ " {\"schemaType\": \"type-x\", \"serdeClassName\": \"name-x\","
+ " \"isRegexPattern\": true, \"receiverQueueSize\": 5}\n"
+ "- **configs**\n"
+ " The map of configs (specified as a JSON object)\n"
+ "- **secrets**\n"
+ " a map of secretName(aka how the secret is going to be \n"
+ " accessed in the function via context) to an object that \n"
+ " encapsulates how the secret is fetched by the underlying \n"
+ " secrets provider. The type of an value here can be found by the \n"
+ " SecretProviderConfigurator.getSecretObjectType() method."
+ " (specified as a JSON object)\n"
+ "- **parallelism**\n"
+ " The parallelism factor of a Pulsar Sink"
+ " (i.e. the number of a Pulsar Sink instances to run \n"
+ "- **processingGuarantees**\n"
+ " The processing guarantees (aka delivery semantics) applied to"
+ " the Pulsar Sink. Possible Values: \"ATLEAST_ONCE\","
+ " \"ATMOST_ONCE\", \"EFFECTIVELY_ONCE\"\n"
+ "- **retainOrdering**\n"
+ " Boolean denotes whether the Pulsar Sink"
+ " consumes and processes messages in order\n"
+ "- **resources**\n"
+ " {\"cpu\": 1, \"ram\": 2, \"disk\": 3} The CPU (in cores),"
+ " RAM (in bytes) and disk (in bytes) that needs to be "
+ "allocated per Pulsar Sink instance "
+ "(applicable only to Docker runtime)\n"
+ "- **autoAck**\n"
+ " Boolean denotes whether or not the framework"
+ " will automatically acknowledge messages\n"
+ "- **timeoutMs**\n"
+ " Long denotes the message timeout in milliseconds\n"
+ "- **cleanupSubscription**\n"
+ " Boolean denotes whether the subscriptions the functions"
+ " created/used should be deleted when the functions is deleted\n"
+ "- **runtimeFlags**\n"
+ " Any flags that you want to pass to the runtime as a single string\n"
+ "2. Encapsulate the JSON object to a multipart object.",
examples = @Example(
value = {
@ExampleProperty(
mediaType = MediaType.TEXT_PLAIN,
value = """
Example
1. Create a JSON object.
{
"classname": "org.example.MySinkTest",
"inputs": ["persistent://public/default/sink-input"],
"processingGuarantees": "EFFECTIVELY_ONCE",
"parallelism": "10"
}
2. Encapsulate the JSON object to a multipart object \
(in Python).
from requests_toolbelt.multipart.encoder import \
MultipartEncoder
mp_encoder = MultipartEncoder(\
[('sinkConfig',\
(None, json.dumps(config), 'application/json'))])
"""
)
}
)
)
final @FormDataParam("sinkConfig") SinkConfig sinkConfig) {
sinks().registerSink(tenant, namespace, sinkName, uploadedInputStream, fileDetail,
sinkPkgUrl, sinkConfig, authParams());
}
@PUT
@ApiOperation(value = "Updates a Pulsar Sink currently running in cluster mode")
@ApiResponses(value = {
@ApiResponse(code = 400, message =
"Invalid request (The Pulsar Sink doesn't exist, update contains no change, etc.)"),
@ApiResponse(code = 200, message = "Pulsar Sink successfully updated"),
@ApiResponse(code = 401, message = "Client is not authorized to perform operation"),
@ApiResponse(code = 404, message = "The Pulsar Sink doesn't exist"),
@ApiResponse(code = 500, message =
"Internal server error (failed to authorize, failed to process package, etc.)"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Path("/{tenant}/{namespace}/{sinkName}")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void updateSink(@ApiParam(value = "The tenant of a Pulsar Sink") final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink") final @PathParam("namespace")
String namespace,
@ApiParam(value = "The name of a Pulsar Sink") final @PathParam("sinkName") String sinkName,
final @FormDataParam("data") InputStream uploadedInputStream,
final @FormDataParam("data") FormDataContentDisposition fileDetail,
final @FormDataParam("url") String sinkPkgUrl,
@ApiParam(value =
"A JSON value presenting config payload of a Pulsar Sink."
+ " All available configuration options are:\n"
+ "- **classname**\n"
+ " The class name of a Pulsar Sink if"
+ " archive is file-url-path (file://)\n"
+ "- **sourceSubscriptionName**\n"
+ " Pulsar source subscription name if user wants a specific\n"
+ " subscription-name for input-topic consumer\n"
+ "- **inputs**\n"
+ " The input topic or topics of"
+ " a Pulsar Sink (specified as a JSON array)\n"
+ "- **topicsPattern**\n"
+ " TopicsPattern to consume from list of topics under a namespace that "
+ " match the pattern. [input] and [topicsPattern] are mutually "
+ " exclusive. Add SerDe class name for a pattern in customSerdeInputs "
+ " (supported for java fun only)"
+ "- **topicToSerdeClassName**\n"
+ " The map of input topics to"
+ " SerDe class names (specified as a JSON object)\n"
+ "- **topicToSchemaType**\n"
+ " The map of input topics to Schema types or"
+ " class names (specified as a JSON object)\n"
+ "- **inputSpecs**\n"
+ " The map of input topics to its consumer configuration,"
+ " each configuration has schema of "
+ " {\"schemaType\": \"type-x\", \"serdeClassName\": \"name-x\","
+ " \"isRegexPattern\": true, \"receiverQueueSize\": 5}\n"
+ "- **configs**\n"
+ " The map of configs (specified as a JSON object)\n"
+ "- **secrets**\n"
+ " a map of secretName(aka how the secret is going to be \n"
+ " accessed in the function via context) to an object that \n"
+ " encapsulates how the secret is fetched by the underlying \n"
+ " secrets provider. The type of an value here can be found by the \n"
+ " SecretProviderConfigurator.getSecretObjectType() method."
+ " (specified as a JSON object)\n"
+ "- **parallelism**\n"
+ " The parallelism factor of a Pulsar Sink "
+ "(i.e. the number of a Pulsar Sink instances to run \n"
+ "- **processingGuarantees**\n"
+ " The processing guarantees (aka delivery semantics) applied to the"
+ " Pulsar Sink. Possible Values: \"ATLEAST_ONCE\", \"ATMOST_ONCE\","
+ " \"EFFECTIVELY_ONCE\"\n"
+ "- **retainOrdering**\n"
+ " Boolean denotes whether the Pulsar Sink"
+ " consumes and processes messages in order\n"
+ "- **resources**\n"
+ " {\"cpu\": 1, \"ram\": 2, \"disk\": 3} The CPU (in cores),"
+ " RAM (in bytes) and disk (in bytes) that needs to be allocated per"
+ " Pulsar Sink instance (applicable only to Docker runtime)\n"
+ "- **autoAck**\n"
+ " Boolean denotes whether or not the framework will"
+ " automatically acknowledge messages\n"
+ "- **timeoutMs**\n"
+ " Long denotes the message timeout in milliseconds\n"
+ "- **cleanupSubscription**\n"
+ " Boolean denotes whether the subscriptions the functions"
+ " created/used should be deleted when the functions is deleted\n"
+ "- **runtimeFlags**\n"
+ " Any flags that you want to pass to the runtime as a single string\n",
examples = @Example(
value = @ExampleProperty(
mediaType = MediaType.APPLICATION_JSON,
value = """
{
"classname": "org.example.SinkStressTest",
"inputs": ["persistent://public/default/sink-input"],
"processingGuarantees": "EFFECTIVELY_ONCE",
"parallelism": 5
}
"""
)
)
)
final @FormDataParam("sinkConfig") SinkConfig sinkConfig,
@ApiParam(value = "Update options for the Pulsar Sink")
final @FormDataParam("updateOptions") UpdateOptionsImpl updateOptions) {
sinks().updateSink(tenant, namespace, sinkName, uploadedInputStream, fileDetail,
sinkPkgUrl, sinkConfig, authParams(), updateOptions);
}
@DELETE
@ApiOperation(value = "Deletes a Pulsar Sink currently running in cluster mode")
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Invalid deregister request"),
@ApiResponse(code = 404, message = "The Pulsar Sink does not exist"),
@ApiResponse(code = 200, message = "The Pulsar Sink was successfully deleted"),
@ApiResponse(code = 401, message = "Client is not authorized to perform operation"),
@ApiResponse(code = 500, message =
"Internal server error (failed to authorize, failed to deregister, etc.)"),
@ApiResponse(code = 408, message = "Got InterruptedException while deregistering the Pulsar Sink"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Path("/{tenant}/{namespace}/{sinkName}")
public void deregisterSink(@ApiParam(value = "The tenant of a Pulsar Sink")
final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink")
final @PathParam("namespace") String namespace,
@ApiParam(value = "The name of a Pulsar Sink")
final @PathParam("sinkName") String sinkName) {
sinks().deregisterFunction(tenant, namespace, sinkName, authParams());
}
@GET
@ApiOperation(
value = "Fetches information about a Pulsar Sink currently running in cluster mode",
response = SinkConfig.class
)
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Invalid request"),
@ApiResponse(code = 404, message = "The Pulsar Sink does not exist"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Path("/{tenant}/{namespace}/{sinkName}")
public SinkConfig getSinkInfo(@ApiParam(value = "The tenant of a Pulsar Sink")
final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink")
final @PathParam("namespace") String namespace,
@ApiParam(value = "The name of a Pulsar Sink")
final @PathParam("sinkName") String sinkName) throws IOException {
return sinks().getSinkInfo(tenant, namespace, sinkName, authParams());
}
@GET
@ApiOperation(
value = "Displays the status of a Pulsar Sink instance",
response = SinkStatus.SinkInstanceStatus.SinkInstanceStatusData.class
)
@ApiResponses(value = {
@ApiResponse(code = 307, message = "Current broker doesn't serve the namespace of this sink"),
@ApiResponse(code = 400, message = "The Pulsar Sink instance does not exist"),
@ApiResponse(code = 404, message = "The Pulsar Sink does not exist"),
@ApiResponse(code = 500, message = "Internal Server Error (got exception while getting status, etc.)"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Produces(MediaType.APPLICATION_JSON)
@Path("/{tenant}/{namespace}/{sinkName}/{instanceId}/status")
public SinkStatus.SinkInstanceStatus.SinkInstanceStatusData getSinkInstanceStatus(
@ApiParam(value = "The tenant of a Pulsar Sink")
final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink")
final @PathParam("namespace") String namespace,
@ApiParam(value = "The name of a Pulsar Sink")
final @PathParam("sinkName") String sinkName,
@ApiParam(value = "The instanceId of a Pulsar Sink")
final @PathParam("instanceId") String instanceId) throws IOException {
return sinks().getSinkInstanceStatus(
tenant, namespace, sinkName, instanceId, uri.getRequestUri(), authParams());
}
@GET
@ApiOperation(
value = "Displays the status of a Pulsar Sink running in cluster mode",
response = SinkStatus.class
)
@ApiResponses(value = {
@ApiResponse(code = 307, message = "Current broker doesn't serve the namespace of this sink"),
@ApiResponse(code = 400, message = "Invalid get status request"),
@ApiResponse(code = 401, message = "The client is not authorized to perform this operation"),
@ApiResponse(code = 404, message = "The Pulsar Sink does not exist"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later."),
})
@Produces(MediaType.APPLICATION_JSON)
@Path("/{tenant}/{namespace}/{sinkName}/status")
public SinkStatus getSinkStatus(@ApiParam(value = "The tenant of a Pulsar Sink")
final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink")
final @PathParam("namespace") String namespace,
@ApiParam(value = "The name of a Pulsar Sink")
final @PathParam("sinkName") String sinkName) throws IOException {
return sinks().getSinkStatus(tenant, namespace, sinkName, uri.getRequestUri(), authParams());
}
@GET
@ApiOperation(
value = "Lists all Pulsar Sinks currently deployed in a given namespace",
response = String.class,
responseContainer = "Collection"
)
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Invalid list request"),
@ApiResponse(code = 401, message = "The client is not authorized to perform this operation"),
@ApiResponse(code = 500, message = "Internal server error (failed to authorize, etc.)"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Path("/{tenant}/{namespace}")
public List<String> listSinks(@ApiParam(value = "The tenant of a Pulsar Sink")
final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink")
final @PathParam("namespace") String namespace) {
return sinks().listFunctions(tenant, namespace, authParams());
}
@POST
@ApiOperation(value = "Restart an instance of a Pulsar Sink")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Operation successful"),
@ApiResponse(code = 307, message = "Current broker doesn't serve the namespace of this sink"),
@ApiResponse(code = 400, message = "Invalid restart request"),
@ApiResponse(code = 401, message = "The client is not authorized to perform this operation"),
@ApiResponse(code = 404, message = "The Pulsar Sink does not exist"),
@ApiResponse(code = 500, message =
"Internal server error (failed to restart the instance of"
+ " a Pulsar Sink, failed to authorize, etc.)"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Path("/{tenant}/{namespace}/{sinkName}/{instanceId}/restart")
@Consumes(MediaType.APPLICATION_JSON)
public void restartSink(@ApiParam(value = "The tenant of a Pulsar Sink")
final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink")
final @PathParam("namespace") String namespace,
@ApiParam(value = "The name of a Pulsar Sink")
final @PathParam("sinkName") String sinkName,
@ApiParam(value = "The instanceId of a Pulsar Sink")
final @PathParam("instanceId") String instanceId) {
sinks().restartFunctionInstance(tenant, namespace, sinkName, instanceId,
uri.getRequestUri(), authParams());
}
@POST
@ApiOperation(value = "Restart all instances of a Pulsar Sink")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Operation successful"),
@ApiResponse(code = 400, message = "Invalid restart request"),
@ApiResponse(code = 401, message = "The client is not authorized to perform this operation"),
@ApiResponse(code = 404, message = "The Pulsar Sink does not exist"),
@ApiResponse(code = 500, message =
"Internal server error (failed to restart the Pulsar Sink, failed to authorize, etc.)"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Path("/{tenant}/{namespace}/{sinkName}/restart")
@Consumes(MediaType.APPLICATION_JSON)
public void restartSink(@ApiParam(value = "The tenant of a Pulsar Sink")
final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink")
final @PathParam("namespace") String namespace,
@ApiParam(value = "The name of a Pulsar Sink")
final @PathParam("sinkName") String sinkName) {
sinks().restartFunctionInstances(tenant, namespace, sinkName, authParams());
}
@POST
@ApiOperation(value = "Stop an instance of a Pulsar Sink")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Operation successful"),
@ApiResponse(code = 400, message = "Invalid stop request"),
@ApiResponse(code = 404, message = "The Pulsar Sink instance does not exist"),
@ApiResponse(code = 500, message =
"Internal server error (failed to stop the Pulsar Sink, failed to authorize, etc.)"),
@ApiResponse(code = 401, message = "The client is not authorized to perform this operation"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Path("/{tenant}/{namespace}/{sinkName}/{instanceId}/stop")
@Consumes(MediaType.APPLICATION_JSON)
public void stopSink(@ApiParam(value = "The tenant of a Pulsar Sink")
final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink")
final @PathParam("namespace") String namespace,
@ApiParam(value = "The name of a Pulsar Sink")
final @PathParam("sinkName") String sinkName,
@ApiParam(value = "The instanceId of a Pulsar Sink")
final @PathParam("instanceId") String instanceId) {
sinks().stopFunctionInstance(tenant, namespace,
sinkName, instanceId, uri.getRequestUri(), authParams());
}
@POST
@ApiOperation(value = "Stop all instances of a Pulsar Sink")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Operation successful"),
@ApiResponse(code = 400, message = "Invalid stop request"),
@ApiResponse(code = 404, message = "The Pulsar Sink does not exist"),
@ApiResponse(code = 500, message =
"Internal server error (failed to stop the Pulsar Sink, failed to authorize, etc.)"),
@ApiResponse(code = 401, message = "The client is not authorized to perform this operation"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Path("/{tenant}/{namespace}/{sinkName}/stop")
@Consumes(MediaType.APPLICATION_JSON)
public void stopSink(@ApiParam(value = "The tenant of a Pulsar Sink")
final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink")
final @PathParam("namespace") String namespace,
@ApiParam(value = "The name of a Pulsar Sink")
final @PathParam("sinkName") String sinkName) {
sinks().stopFunctionInstances(tenant, namespace, sinkName, authParams());
}
@POST
@ApiOperation(value = "Start an instance of a Pulsar Sink")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Operation successful"),
@ApiResponse(code = 400, message = "Invalid start request"),
@ApiResponse(code = 404, message = "The Pulsar Sink does not exist"),
@ApiResponse(code = 500, message =
"Internal server error (failed to start the Pulsar Sink, failed to authorize, etc.)"),
@ApiResponse(code = 401, message = "The client is not authorized to perform this operation"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Path("/{tenant}/{namespace}/{sinkName}/{instanceId}/start")
@Consumes(MediaType.APPLICATION_JSON)
public void startSink(@ApiParam(value = "The tenant of a Pulsar Sink")
final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink")
final @PathParam("namespace") String namespace,
@ApiParam(value = "The name of a Pulsar Sink")
final @PathParam("sinkName") String sinkName,
@ApiParam(value = "The instanceId of a Pulsar Sink")
final @PathParam("instanceId") String instanceId) {
sinks().startFunctionInstance(tenant, namespace, sinkName, instanceId,
uri.getRequestUri(), authParams());
}
@POST
@ApiOperation(value = "Start all instances of a Pulsar Sink")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Operation successful"),
@ApiResponse(code = 400, message = "Invalid start request"),
@ApiResponse(code = 404, message = "The Pulsar Sink does not exist"),
@ApiResponse(code = 500, message =
"Internal server error (failed to start the Pulsar Sink, failed to authorize, etc.)"),
@ApiResponse(code = 401, message = "The client is not authorized to perform this operation"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Path("/{tenant}/{namespace}/{sinkName}/start")
@Consumes(MediaType.APPLICATION_JSON)
public void startSink(@ApiParam(value = "The tenant of a Pulsar Sink")
final @PathParam("tenant") String tenant,
@ApiParam(value = "The namespace of a Pulsar Sink")
final @PathParam("namespace") String namespace,
@ApiParam(value = "The name of a Pulsar Sink")
final @PathParam("sinkName") String sinkName) {
sinks().startFunctionInstances(tenant, namespace, sinkName, authParams());
}
@GET
@ApiOperation(
value = "Fetches the list of built-in Pulsar IO sinks",
response = ConnectorDefinition.class,
responseContainer = "List"
)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Get builtin sinks successfully.")
})
@Path("/builtinsinks")
public List<ConnectorDefinition> getSinkList() {
return sinks().getSinkList();
}
@GET
@ApiOperation(
value = "Fetches information about config fields associated with the specified builtin sink",
response = ConfigFieldDefinition.class,
responseContainer = "List"
)
@ApiResponses(value = {
@ApiResponse(code = 403, message = "The requester doesn't have admin permissions"),
@ApiResponse(code = 404, message = "builtin sink does not exist"),
@ApiResponse(code = 500, message = "Internal server error"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later.")
})
@Produces(MediaType.APPLICATION_JSON)
@Path("/builtinsinks/{name}/configdefinition")
public List<ConfigFieldDefinition> getSinkConfigDefinition(
@ApiParam(value = "The name of the builtin sink")
final @PathParam("name") String name) throws IOException {
return sinks().getSinkConfigDefinition(name);
}
@POST
@ApiOperation(
value = "Reload the built-in connectors, including Sources and Sinks",
response = Void.class
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "This operation requires super-user access"),
@ApiResponse(code = 503, message = "Function worker service is now initializing. Please try again later."),
@ApiResponse(code = 500, message = "Internal server error")
})
@Path("/reloadBuiltInSinks")
public void reloadSinks() {
sinks().reloadConnectors(authParams());
}
}
|
googleapis/google-cloud-java
| 38,041
|
java-notebooks/proto-google-cloud-notebooks-v1/src/main/java/com/google/cloud/notebooks/v1/ListSchedulesRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/notebooks/v1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.notebooks.v1;
/**
*
*
* <pre>
* Request for listing scheduled notebook job.
* </pre>
*
* Protobuf type {@code google.cloud.notebooks.v1.ListSchedulesRequest}
*/
public final class ListSchedulesRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.notebooks.v1.ListSchedulesRequest)
ListSchedulesRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListSchedulesRequest.newBuilder() to construct.
private ListSchedulesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListSchedulesRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListSchedulesRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_ListSchedulesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_ListSchedulesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.notebooks.v1.ListSchedulesRequest.class,
com.google.cloud.notebooks.v1.ListSchedulesRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Format:
* `parent=projects/{project_id}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Format:
* `parent=projects/{project_id}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Maximum return size of the list call.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A previous returned page token that can be used to continue listing
* from the last result.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A previous returned page token that can be used to continue listing
* from the last result.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filter applied to resulting schedules.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Filter applied to resulting schedules.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Field to order results by.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Field to order results by.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.notebooks.v1.ListSchedulesRequest)) {
return super.equals(obj);
}
com.google.cloud.notebooks.v1.ListSchedulesRequest other =
(com.google.cloud.notebooks.v1.ListSchedulesRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.notebooks.v1.ListSchedulesRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for listing scheduled notebook job.
* </pre>
*
* Protobuf type {@code google.cloud.notebooks.v1.ListSchedulesRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.notebooks.v1.ListSchedulesRequest)
com.google.cloud.notebooks.v1.ListSchedulesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_ListSchedulesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_ListSchedulesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.notebooks.v1.ListSchedulesRequest.class,
com.google.cloud.notebooks.v1.ListSchedulesRequest.Builder.class);
}
// Construct using com.google.cloud.notebooks.v1.ListSchedulesRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_ListSchedulesRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.notebooks.v1.ListSchedulesRequest getDefaultInstanceForType() {
return com.google.cloud.notebooks.v1.ListSchedulesRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.notebooks.v1.ListSchedulesRequest build() {
com.google.cloud.notebooks.v1.ListSchedulesRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.notebooks.v1.ListSchedulesRequest buildPartial() {
com.google.cloud.notebooks.v1.ListSchedulesRequest result =
new com.google.cloud.notebooks.v1.ListSchedulesRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.notebooks.v1.ListSchedulesRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.notebooks.v1.ListSchedulesRequest) {
return mergeFrom((com.google.cloud.notebooks.v1.ListSchedulesRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.notebooks.v1.ListSchedulesRequest other) {
if (other == com.google.cloud.notebooks.v1.ListSchedulesRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Format:
* `parent=projects/{project_id}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Format:
* `parent=projects/{project_id}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Format:
* `parent=projects/{project_id}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Format:
* `parent=projects/{project_id}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Format:
* `parent=projects/{project_id}/locations/{location}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Maximum return size of the list call.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Maximum return size of the list call.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Maximum return size of the list call.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A previous returned page token that can be used to continue listing
* from the last result.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A previous returned page token that can be used to continue listing
* from the last result.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A previous returned page token that can be used to continue listing
* from the last result.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A previous returned page token that can be used to continue listing
* from the last result.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A previous returned page token that can be used to continue listing
* from the last result.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filter applied to resulting schedules.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Filter applied to resulting schedules.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Filter applied to resulting schedules.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Filter applied to resulting schedules.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Filter applied to resulting schedules.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Field to order results by.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Field to order results by.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Field to order results by.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Field to order results by.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Field to order results by.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.notebooks.v1.ListSchedulesRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.notebooks.v1.ListSchedulesRequest)
private static final com.google.cloud.notebooks.v1.ListSchedulesRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.notebooks.v1.ListSchedulesRequest();
}
public static com.google.cloud.notebooks.v1.ListSchedulesRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListSchedulesRequest> PARSER =
new com.google.protobuf.AbstractParser<ListSchedulesRequest>() {
@java.lang.Override
public ListSchedulesRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListSchedulesRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListSchedulesRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.notebooks.v1.ListSchedulesRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,051
|
java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/ListApplicationsRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/visionai/v1/platform.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.visionai.v1;
/**
*
*
* <pre>
* Message for requesting list of Applications.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.ListApplicationsRequest}
*/
public final class ListApplicationsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.ListApplicationsRequest)
ListApplicationsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListApplicationsRequest.newBuilder() to construct.
private ListApplicationsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListApplicationsRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListApplicationsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.PlatformProto
.internal_static_google_cloud_visionai_v1_ListApplicationsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.PlatformProto
.internal_static_google_cloud_visionai_v1_ListApplicationsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.ListApplicationsRequest.class,
com.google.cloud.visionai.v1.ListApplicationsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListApplicationsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListApplicationsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.visionai.v1.ListApplicationsRequest)) {
return super.equals(obj);
}
com.google.cloud.visionai.v1.ListApplicationsRequest other =
(com.google.cloud.visionai.v1.ListApplicationsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.visionai.v1.ListApplicationsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Message for requesting list of Applications.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.ListApplicationsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.ListApplicationsRequest)
com.google.cloud.visionai.v1.ListApplicationsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.PlatformProto
.internal_static_google_cloud_visionai_v1_ListApplicationsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.PlatformProto
.internal_static_google_cloud_visionai_v1_ListApplicationsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.ListApplicationsRequest.class,
com.google.cloud.visionai.v1.ListApplicationsRequest.Builder.class);
}
// Construct using com.google.cloud.visionai.v1.ListApplicationsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.visionai.v1.PlatformProto
.internal_static_google_cloud_visionai_v1_ListApplicationsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListApplicationsRequest getDefaultInstanceForType() {
return com.google.cloud.visionai.v1.ListApplicationsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListApplicationsRequest build() {
com.google.cloud.visionai.v1.ListApplicationsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListApplicationsRequest buildPartial() {
com.google.cloud.visionai.v1.ListApplicationsRequest result =
new com.google.cloud.visionai.v1.ListApplicationsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.visionai.v1.ListApplicationsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.visionai.v1.ListApplicationsRequest) {
return mergeFrom((com.google.cloud.visionai.v1.ListApplicationsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.visionai.v1.ListApplicationsRequest other) {
if (other == com.google.cloud.visionai.v1.ListApplicationsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. Parent value for ListApplicationsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListApplicationsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Parent value for ListApplicationsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListApplicationsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Parent value for ListApplicationsRequest.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Requested page size. Server may return fewer items than requested.
* If unspecified, server will pick an appropriate default.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token identifying a page of results the server should return.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Filtering results.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Hint for how to order the results.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.visionai.v1.ListApplicationsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.ListApplicationsRequest)
private static final com.google.cloud.visionai.v1.ListApplicationsRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.ListApplicationsRequest();
}
public static com.google.cloud.visionai.v1.ListApplicationsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListApplicationsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListApplicationsRequest>() {
@java.lang.Override
public ListApplicationsRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListApplicationsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListApplicationsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.visionai.v1.ListApplicationsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,186
|
java-discoveryengine/proto-google-cloud-discoveryengine-v1alpha/src/main/java/com/google/cloud/discoveryengine/v1alpha/ListSchemasResponse.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/discoveryengine/v1alpha/schema_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.discoveryengine.v1alpha;
/**
*
*
* <pre>
* Response message for
* [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1alpha.ListSchemasResponse}
*/
public final class ListSchemasResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.discoveryengine.v1alpha.ListSchemasResponse)
ListSchemasResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListSchemasResponse.newBuilder() to construct.
private ListSchemasResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListSchemasResponse() {
schemas_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListSchemasResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1alpha.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_ListSchemasResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1alpha.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_ListSchemasResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse.class,
com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse.Builder.class);
}
public static final int SCHEMAS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.discoveryengine.v1alpha.Schema> schemas_;
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.discoveryengine.v1alpha.Schema> getSchemasList() {
return schemas_;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.discoveryengine.v1alpha.SchemaOrBuilder>
getSchemasOrBuilderList() {
return schemas_;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
@java.lang.Override
public int getSchemasCount() {
return schemas_.size();
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.Schema getSchemas(int index) {
return schemas_.get(index);
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.SchemaOrBuilder getSchemasOrBuilder(int index) {
return schemas_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1alpha.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1alpha.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < schemas_.size(); i++) {
output.writeMessage(1, schemas_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < schemas_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, schemas_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse)) {
return super.equals(obj);
}
com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse other =
(com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse) obj;
if (!getSchemasList().equals(other.getSchemasList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getSchemasCount() > 0) {
hash = (37 * hash) + SCHEMAS_FIELD_NUMBER;
hash = (53 * hash) + getSchemasList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response message for
* [SchemaService.ListSchemas][google.cloud.discoveryengine.v1alpha.SchemaService.ListSchemas]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.discoveryengine.v1alpha.ListSchemasResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.discoveryengine.v1alpha.ListSchemasResponse)
com.google.cloud.discoveryengine.v1alpha.ListSchemasResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.discoveryengine.v1alpha.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_ListSchemasResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.discoveryengine.v1alpha.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_ListSchemasResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse.class,
com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse.Builder.class);
}
// Construct using com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (schemasBuilder_ == null) {
schemas_ = java.util.Collections.emptyList();
} else {
schemas_ = null;
schemasBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.discoveryengine.v1alpha.SchemaServiceProto
.internal_static_google_cloud_discoveryengine_v1alpha_ListSchemasResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse
getDefaultInstanceForType() {
return com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse build() {
com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse buildPartial() {
com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse result =
new com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse result) {
if (schemasBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
schemas_ = java.util.Collections.unmodifiableList(schemas_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.schemas_ = schemas_;
} else {
result.schemas_ = schemasBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse) {
return mergeFrom((com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse other) {
if (other
== com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse.getDefaultInstance())
return this;
if (schemasBuilder_ == null) {
if (!other.schemas_.isEmpty()) {
if (schemas_.isEmpty()) {
schemas_ = other.schemas_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureSchemasIsMutable();
schemas_.addAll(other.schemas_);
}
onChanged();
}
} else {
if (!other.schemas_.isEmpty()) {
if (schemasBuilder_.isEmpty()) {
schemasBuilder_.dispose();
schemasBuilder_ = null;
schemas_ = other.schemas_;
bitField0_ = (bitField0_ & ~0x00000001);
schemasBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getSchemasFieldBuilder()
: null;
} else {
schemasBuilder_.addAllMessages(other.schemas_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.discoveryengine.v1alpha.Schema m =
input.readMessage(
com.google.cloud.discoveryengine.v1alpha.Schema.parser(),
extensionRegistry);
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.add(m);
} else {
schemasBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.discoveryengine.v1alpha.Schema> schemas_ =
java.util.Collections.emptyList();
private void ensureSchemasIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
schemas_ =
new java.util.ArrayList<com.google.cloud.discoveryengine.v1alpha.Schema>(schemas_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.discoveryengine.v1alpha.Schema,
com.google.cloud.discoveryengine.v1alpha.Schema.Builder,
com.google.cloud.discoveryengine.v1alpha.SchemaOrBuilder>
schemasBuilder_;
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public java.util.List<com.google.cloud.discoveryengine.v1alpha.Schema> getSchemasList() {
if (schemasBuilder_ == null) {
return java.util.Collections.unmodifiableList(schemas_);
} else {
return schemasBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public int getSchemasCount() {
if (schemasBuilder_ == null) {
return schemas_.size();
} else {
return schemasBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1alpha.Schema getSchemas(int index) {
if (schemasBuilder_ == null) {
return schemas_.get(index);
} else {
return schemasBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public Builder setSchemas(int index, com.google.cloud.discoveryengine.v1alpha.Schema value) {
if (schemasBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSchemasIsMutable();
schemas_.set(index, value);
onChanged();
} else {
schemasBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public Builder setSchemas(
int index, com.google.cloud.discoveryengine.v1alpha.Schema.Builder builderForValue) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.set(index, builderForValue.build());
onChanged();
} else {
schemasBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public Builder addSchemas(com.google.cloud.discoveryengine.v1alpha.Schema value) {
if (schemasBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSchemasIsMutable();
schemas_.add(value);
onChanged();
} else {
schemasBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public Builder addSchemas(int index, com.google.cloud.discoveryengine.v1alpha.Schema value) {
if (schemasBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSchemasIsMutable();
schemas_.add(index, value);
onChanged();
} else {
schemasBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public Builder addSchemas(
com.google.cloud.discoveryengine.v1alpha.Schema.Builder builderForValue) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.add(builderForValue.build());
onChanged();
} else {
schemasBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public Builder addSchemas(
int index, com.google.cloud.discoveryengine.v1alpha.Schema.Builder builderForValue) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.add(index, builderForValue.build());
onChanged();
} else {
schemasBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public Builder addAllSchemas(
java.lang.Iterable<? extends com.google.cloud.discoveryengine.v1alpha.Schema> values) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, schemas_);
onChanged();
} else {
schemasBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public Builder clearSchemas() {
if (schemasBuilder_ == null) {
schemas_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
schemasBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public Builder removeSchemas(int index) {
if (schemasBuilder_ == null) {
ensureSchemasIsMutable();
schemas_.remove(index);
onChanged();
} else {
schemasBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1alpha.Schema.Builder getSchemasBuilder(int index) {
return getSchemasFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1alpha.SchemaOrBuilder getSchemasOrBuilder(int index) {
if (schemasBuilder_ == null) {
return schemas_.get(index);
} else {
return schemasBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public java.util.List<? extends com.google.cloud.discoveryengine.v1alpha.SchemaOrBuilder>
getSchemasOrBuilderList() {
if (schemasBuilder_ != null) {
return schemasBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(schemas_);
}
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1alpha.Schema.Builder addSchemasBuilder() {
return getSchemasFieldBuilder()
.addBuilder(com.google.cloud.discoveryengine.v1alpha.Schema.getDefaultInstance());
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public com.google.cloud.discoveryengine.v1alpha.Schema.Builder addSchemasBuilder(int index) {
return getSchemasFieldBuilder()
.addBuilder(index, com.google.cloud.discoveryengine.v1alpha.Schema.getDefaultInstance());
}
/**
*
*
* <pre>
* The [Schema][google.cloud.discoveryengine.v1alpha.Schema]s.
* </pre>
*
* <code>repeated .google.cloud.discoveryengine.v1alpha.Schema schemas = 1;</code>
*/
public java.util.List<com.google.cloud.discoveryengine.v1alpha.Schema.Builder>
getSchemasBuilderList() {
return getSchemasFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.discoveryengine.v1alpha.Schema,
com.google.cloud.discoveryengine.v1alpha.Schema.Builder,
com.google.cloud.discoveryengine.v1alpha.SchemaOrBuilder>
getSchemasFieldBuilder() {
if (schemasBuilder_ == null) {
schemasBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.discoveryengine.v1alpha.Schema,
com.google.cloud.discoveryengine.v1alpha.Schema.Builder,
com.google.cloud.discoveryengine.v1alpha.SchemaOrBuilder>(
schemas_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
schemas_ = null;
}
return schemasBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1alpha.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1alpha.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1alpha.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1alpha.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that can be sent as
* [ListSchemasRequest.page_token][google.cloud.discoveryengine.v1alpha.ListSchemasRequest.page_token]
* to retrieve the next page. If this field is omitted, there are no
* subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.discoveryengine.v1alpha.ListSchemasResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.discoveryengine.v1alpha.ListSchemasResponse)
private static final com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse();
}
public static com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListSchemasResponse> PARSER =
new com.google.protobuf.AbstractParser<ListSchemasResponse>() {
@java.lang.Override
public ListSchemasResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListSchemasResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListSchemasResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.discoveryengine.v1alpha.ListSchemasResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,131
|
java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/IndexAssetMetadata.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/visionai/v1/warehouse.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.visionai.v1;
/**
*
*
* <pre>
* Metadata for IndexAsset.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.IndexAssetMetadata}
*/
public final class IndexAssetMetadata extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.IndexAssetMetadata)
IndexAssetMetadataOrBuilder {
private static final long serialVersionUID = 0L;
// Use IndexAssetMetadata.newBuilder() to construct.
private IndexAssetMetadata(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private IndexAssetMetadata() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new IndexAssetMetadata();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_IndexAssetMetadata_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_IndexAssetMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.IndexAssetMetadata.class,
com.google.cloud.visionai.v1.IndexAssetMetadata.Builder.class);
}
private int bitField0_;
public static final int STATUS_FIELD_NUMBER = 4;
private com.google.cloud.visionai.v1.IndexingStatus status_;
/**
*
*
* <pre>
* The status of indexing this asset.
* </pre>
*
* <code>.google.cloud.visionai.v1.IndexingStatus status = 4;</code>
*
* @return Whether the status field is set.
*/
@java.lang.Override
public boolean hasStatus() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The status of indexing this asset.
* </pre>
*
* <code>.google.cloud.visionai.v1.IndexingStatus status = 4;</code>
*
* @return The status.
*/
@java.lang.Override
public com.google.cloud.visionai.v1.IndexingStatus getStatus() {
return status_ == null
? com.google.cloud.visionai.v1.IndexingStatus.getDefaultInstance()
: status_;
}
/**
*
*
* <pre>
* The status of indexing this asset.
* </pre>
*
* <code>.google.cloud.visionai.v1.IndexingStatus status = 4;</code>
*/
@java.lang.Override
public com.google.cloud.visionai.v1.IndexingStatusOrBuilder getStatusOrBuilder() {
return status_ == null
? com.google.cloud.visionai.v1.IndexingStatus.getDefaultInstance()
: status_;
}
public static final int START_TIME_FIELD_NUMBER = 2;
private com.google.protobuf.Timestamp startTime_;
/**
*
*
* <pre>
* The start time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*
* @return Whether the startTime field is set.
*/
@java.lang.Override
public boolean hasStartTime() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The start time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*
* @return The startTime.
*/
@java.lang.Override
public com.google.protobuf.Timestamp getStartTime() {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
}
/**
*
*
* <pre>
* The start time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
}
public static final int UPDATE_TIME_FIELD_NUMBER = 3;
private com.google.protobuf.Timestamp updateTime_;
/**
*
*
* <pre>
* The update time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 3;</code>
*
* @return Whether the updateTime field is set.
*/
@java.lang.Override
public boolean hasUpdateTime() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* The update time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 3;</code>
*
* @return The updateTime.
*/
@java.lang.Override
public com.google.protobuf.Timestamp getUpdateTime() {
return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_;
}
/**
*
*
* <pre>
* The update time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 3;</code>
*/
@java.lang.Override
public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() {
return updateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : updateTime_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getStartTime());
}
if (((bitField0_ & 0x00000004) != 0)) {
output.writeMessage(3, getUpdateTime());
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(4, getStatus());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getStartTime());
}
if (((bitField0_ & 0x00000004) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getUpdateTime());
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, getStatus());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.visionai.v1.IndexAssetMetadata)) {
return super.equals(obj);
}
com.google.cloud.visionai.v1.IndexAssetMetadata other =
(com.google.cloud.visionai.v1.IndexAssetMetadata) obj;
if (hasStatus() != other.hasStatus()) return false;
if (hasStatus()) {
if (!getStatus().equals(other.getStatus())) return false;
}
if (hasStartTime() != other.hasStartTime()) return false;
if (hasStartTime()) {
if (!getStartTime().equals(other.getStartTime())) return false;
}
if (hasUpdateTime() != other.hasUpdateTime()) return false;
if (hasUpdateTime()) {
if (!getUpdateTime().equals(other.getUpdateTime())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasStatus()) {
hash = (37 * hash) + STATUS_FIELD_NUMBER;
hash = (53 * hash) + getStatus().hashCode();
}
if (hasStartTime()) {
hash = (37 * hash) + START_TIME_FIELD_NUMBER;
hash = (53 * hash) + getStartTime().hashCode();
}
if (hasUpdateTime()) {
hash = (37 * hash) + UPDATE_TIME_FIELD_NUMBER;
hash = (53 * hash) + getUpdateTime().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.visionai.v1.IndexAssetMetadata prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Metadata for IndexAsset.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.IndexAssetMetadata}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.IndexAssetMetadata)
com.google.cloud.visionai.v1.IndexAssetMetadataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_IndexAssetMetadata_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_IndexAssetMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.IndexAssetMetadata.class,
com.google.cloud.visionai.v1.IndexAssetMetadata.Builder.class);
}
// Construct using com.google.cloud.visionai.v1.IndexAssetMetadata.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getStatusFieldBuilder();
getStartTimeFieldBuilder();
getUpdateTimeFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
status_ = null;
if (statusBuilder_ != null) {
statusBuilder_.dispose();
statusBuilder_ = null;
}
startTime_ = null;
if (startTimeBuilder_ != null) {
startTimeBuilder_.dispose();
startTimeBuilder_ = null;
}
updateTime_ = null;
if (updateTimeBuilder_ != null) {
updateTimeBuilder_.dispose();
updateTimeBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.visionai.v1.WarehouseProto
.internal_static_google_cloud_visionai_v1_IndexAssetMetadata_descriptor;
}
@java.lang.Override
public com.google.cloud.visionai.v1.IndexAssetMetadata getDefaultInstanceForType() {
return com.google.cloud.visionai.v1.IndexAssetMetadata.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.visionai.v1.IndexAssetMetadata build() {
com.google.cloud.visionai.v1.IndexAssetMetadata result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.visionai.v1.IndexAssetMetadata buildPartial() {
com.google.cloud.visionai.v1.IndexAssetMetadata result =
new com.google.cloud.visionai.v1.IndexAssetMetadata(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.visionai.v1.IndexAssetMetadata result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.status_ = statusBuilder_ == null ? status_ : statusBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.startTime_ = startTimeBuilder_ == null ? startTime_ : startTimeBuilder_.build();
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.updateTime_ = updateTimeBuilder_ == null ? updateTime_ : updateTimeBuilder_.build();
to_bitField0_ |= 0x00000004;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.visionai.v1.IndexAssetMetadata) {
return mergeFrom((com.google.cloud.visionai.v1.IndexAssetMetadata) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.visionai.v1.IndexAssetMetadata other) {
if (other == com.google.cloud.visionai.v1.IndexAssetMetadata.getDefaultInstance())
return this;
if (other.hasStatus()) {
mergeStatus(other.getStatus());
}
if (other.hasStartTime()) {
mergeStartTime(other.getStartTime());
}
if (other.hasUpdateTime()) {
mergeUpdateTime(other.getUpdateTime());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 18:
{
input.readMessage(getStartTimeFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getUpdateTimeFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
input.readMessage(getStatusFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 34
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.visionai.v1.IndexingStatus status_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.visionai.v1.IndexingStatus,
com.google.cloud.visionai.v1.IndexingStatus.Builder,
com.google.cloud.visionai.v1.IndexingStatusOrBuilder>
statusBuilder_;
/**
*
*
* <pre>
* The status of indexing this asset.
* </pre>
*
* <code>.google.cloud.visionai.v1.IndexingStatus status = 4;</code>
*
* @return Whether the status field is set.
*/
public boolean hasStatus() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The status of indexing this asset.
* </pre>
*
* <code>.google.cloud.visionai.v1.IndexingStatus status = 4;</code>
*
* @return The status.
*/
public com.google.cloud.visionai.v1.IndexingStatus getStatus() {
if (statusBuilder_ == null) {
return status_ == null
? com.google.cloud.visionai.v1.IndexingStatus.getDefaultInstance()
: status_;
} else {
return statusBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The status of indexing this asset.
* </pre>
*
* <code>.google.cloud.visionai.v1.IndexingStatus status = 4;</code>
*/
public Builder setStatus(com.google.cloud.visionai.v1.IndexingStatus value) {
if (statusBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
status_ = value;
} else {
statusBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The status of indexing this asset.
* </pre>
*
* <code>.google.cloud.visionai.v1.IndexingStatus status = 4;</code>
*/
public Builder setStatus(com.google.cloud.visionai.v1.IndexingStatus.Builder builderForValue) {
if (statusBuilder_ == null) {
status_ = builderForValue.build();
} else {
statusBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The status of indexing this asset.
* </pre>
*
* <code>.google.cloud.visionai.v1.IndexingStatus status = 4;</code>
*/
public Builder mergeStatus(com.google.cloud.visionai.v1.IndexingStatus value) {
if (statusBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& status_ != null
&& status_ != com.google.cloud.visionai.v1.IndexingStatus.getDefaultInstance()) {
getStatusBuilder().mergeFrom(value);
} else {
status_ = value;
}
} else {
statusBuilder_.mergeFrom(value);
}
if (status_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The status of indexing this asset.
* </pre>
*
* <code>.google.cloud.visionai.v1.IndexingStatus status = 4;</code>
*/
public Builder clearStatus() {
bitField0_ = (bitField0_ & ~0x00000001);
status_ = null;
if (statusBuilder_ != null) {
statusBuilder_.dispose();
statusBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The status of indexing this asset.
* </pre>
*
* <code>.google.cloud.visionai.v1.IndexingStatus status = 4;</code>
*/
public com.google.cloud.visionai.v1.IndexingStatus.Builder getStatusBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getStatusFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The status of indexing this asset.
* </pre>
*
* <code>.google.cloud.visionai.v1.IndexingStatus status = 4;</code>
*/
public com.google.cloud.visionai.v1.IndexingStatusOrBuilder getStatusOrBuilder() {
if (statusBuilder_ != null) {
return statusBuilder_.getMessageOrBuilder();
} else {
return status_ == null
? com.google.cloud.visionai.v1.IndexingStatus.getDefaultInstance()
: status_;
}
}
/**
*
*
* <pre>
* The status of indexing this asset.
* </pre>
*
* <code>.google.cloud.visionai.v1.IndexingStatus status = 4;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.visionai.v1.IndexingStatus,
com.google.cloud.visionai.v1.IndexingStatus.Builder,
com.google.cloud.visionai.v1.IndexingStatusOrBuilder>
getStatusFieldBuilder() {
if (statusBuilder_ == null) {
statusBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.visionai.v1.IndexingStatus,
com.google.cloud.visionai.v1.IndexingStatus.Builder,
com.google.cloud.visionai.v1.IndexingStatusOrBuilder>(
getStatus(), getParentForChildren(), isClean());
status_ = null;
}
return statusBuilder_;
}
private com.google.protobuf.Timestamp startTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
startTimeBuilder_;
/**
*
*
* <pre>
* The start time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*
* @return Whether the startTime field is set.
*/
public boolean hasStartTime() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The start time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*
* @return The startTime.
*/
public com.google.protobuf.Timestamp getStartTime() {
if (startTimeBuilder_ == null) {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
} else {
return startTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The start time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
public Builder setStartTime(com.google.protobuf.Timestamp value) {
if (startTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
startTime_ = value;
} else {
startTimeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The start time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
public Builder setStartTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (startTimeBuilder_ == null) {
startTime_ = builderForValue.build();
} else {
startTimeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The start time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
public Builder mergeStartTime(com.google.protobuf.Timestamp value) {
if (startTimeBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& startTime_ != null
&& startTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) {
getStartTimeBuilder().mergeFrom(value);
} else {
startTime_ = value;
}
} else {
startTimeBuilder_.mergeFrom(value);
}
if (startTime_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The start time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
public Builder clearStartTime() {
bitField0_ = (bitField0_ & ~0x00000002);
startTime_ = null;
if (startTimeBuilder_ != null) {
startTimeBuilder_.dispose();
startTimeBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The start time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
public com.google.protobuf.Timestamp.Builder getStartTimeBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getStartTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The start time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() {
if (startTimeBuilder_ != null) {
return startTimeBuilder_.getMessageOrBuilder();
} else {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
}
}
/**
*
*
* <pre>
* The start time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp start_time = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getStartTimeFieldBuilder() {
if (startTimeBuilder_ == null) {
startTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getStartTime(), getParentForChildren(), isClean());
startTime_ = null;
}
return startTimeBuilder_;
}
private com.google.protobuf.Timestamp updateTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
updateTimeBuilder_;
/**
*
*
* <pre>
* The update time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 3;</code>
*
* @return Whether the updateTime field is set.
*/
public boolean hasUpdateTime() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* The update time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 3;</code>
*
* @return The updateTime.
*/
public com.google.protobuf.Timestamp getUpdateTime() {
if (updateTimeBuilder_ == null) {
return updateTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: updateTime_;
} else {
return updateTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The update time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 3;</code>
*/
public Builder setUpdateTime(com.google.protobuf.Timestamp value) {
if (updateTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateTime_ = value;
} else {
updateTimeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The update time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 3;</code>
*/
public Builder setUpdateTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (updateTimeBuilder_ == null) {
updateTime_ = builderForValue.build();
} else {
updateTimeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The update time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 3;</code>
*/
public Builder mergeUpdateTime(com.google.protobuf.Timestamp value) {
if (updateTimeBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& updateTime_ != null
&& updateTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) {
getUpdateTimeBuilder().mergeFrom(value);
} else {
updateTime_ = value;
}
} else {
updateTimeBuilder_.mergeFrom(value);
}
if (updateTime_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The update time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 3;</code>
*/
public Builder clearUpdateTime() {
bitField0_ = (bitField0_ & ~0x00000004);
updateTime_ = null;
if (updateTimeBuilder_ != null) {
updateTimeBuilder_.dispose();
updateTimeBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The update time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 3;</code>
*/
public com.google.protobuf.Timestamp.Builder getUpdateTimeBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getUpdateTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The update time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 3;</code>
*/
public com.google.protobuf.TimestampOrBuilder getUpdateTimeOrBuilder() {
if (updateTimeBuilder_ != null) {
return updateTimeBuilder_.getMessageOrBuilder();
} else {
return updateTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: updateTime_;
}
}
/**
*
*
* <pre>
* The update time of the operation.
* </pre>
*
* <code>.google.protobuf.Timestamp update_time = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getUpdateTimeFieldBuilder() {
if (updateTimeBuilder_ == null) {
updateTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getUpdateTime(), getParentForChildren(), isClean());
updateTime_ = null;
}
return updateTimeBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.visionai.v1.IndexAssetMetadata)
}
// @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.IndexAssetMetadata)
private static final com.google.cloud.visionai.v1.IndexAssetMetadata DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.IndexAssetMetadata();
}
public static com.google.cloud.visionai.v1.IndexAssetMetadata getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<IndexAssetMetadata> PARSER =
new com.google.protobuf.AbstractParser<IndexAssetMetadata>() {
@java.lang.Override
public IndexAssetMetadata parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<IndexAssetMetadata> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<IndexAssetMetadata> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.visionai.v1.IndexAssetMetadata getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/ofbiz-framework
| 38,278
|
applications/content/src/main/java/org/apache/ofbiz/content/data/DataServices.java
|
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.apache.ofbiz.content.data;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.imaging.ImageReadException;
import org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.GeneralException;
import org.apache.ofbiz.base.util.UtilDateTime;
import org.apache.ofbiz.base.util.UtilGenerics;
import org.apache.ofbiz.base.util.UtilMisc;
import org.apache.ofbiz.base.util.UtilProperties;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.security.SecuredUpload;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.ModelService;
import org.apache.ofbiz.service.ServiceUtil;
/**
* DataServices Class
*/
public class DataServices {
private static final String MODULE = DataServices.class.getName();
private static final String RESOURCE = "ContentUiLabels";
public static Map<String, Object> clearAssociatedRenderCache(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
String dataResourceId = (String) context.get("dataResourceId");
Locale locale = (Locale) context.get("locale");
try {
DataResourceWorker.clearAssociatedRenderCache(delegator, dataResourceId);
} catch (GeneralException e) {
Debug.logError(e, "Unable to clear associated render cache with dataResourceId=" + dataResourceId, MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentClearAssociatedRenderCacheError",
UtilMisc.toMap("dataResourceId", dataResourceId), locale));
}
return ServiceUtil.returnSuccess();
}
/**
* A top-level service for creating a DataResource and ElectronicText together.
*/
public static Map<String, Object> createDataResourceAndText(DispatchContext dctx, Map<String, ? extends Object> rcontext) {
Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
Map<String, Object> result = new HashMap<>();
Map<String, Object> thisResult = createDataResourceMethod(dctx, context);
if (thisResult.get(ModelService.RESPONSE_MESSAGE) != null) {
return ServiceUtil.returnError((String) thisResult.get(ModelService.ERROR_MESSAGE));
}
result.put("dataResourceId", thisResult.get("dataResourceId"));
context.put("dataResourceId", thisResult.get("dataResourceId"));
String dataResourceTypeId = (String) context.get("dataResourceTypeId");
if (dataResourceTypeId != null && "ELECTRONIC_TEXT".equals(dataResourceTypeId)) {
thisResult = createElectronicText(dctx, context);
if (thisResult.get(ModelService.RESPONSE_MESSAGE) != null) {
return ServiceUtil.returnError((String) thisResult.get(ModelService.ERROR_MESSAGE));
}
}
return result;
}
/**
* A service wrapper for the createDataResourceMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> createDataResource(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = createDataResourceMethod(dctx, context);
return result;
}
public static Map<String, Object> createDataResourceMethod(DispatchContext dctx, Map<String, ? extends Object> rcontext) {
Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
Map<String, Object> result = new HashMap<>();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String userLoginId = (String) userLogin.get("userLoginId");
String createdByUserLogin = userLoginId;
String lastModifiedByUserLogin = userLoginId;
Timestamp createdDate = UtilDateTime.nowTimestamp();
Timestamp lastModifiedDate = UtilDateTime.nowTimestamp();
String dataTemplateTypeId = (String) context.get("dataTemplateTypeId");
if (UtilValidate.isEmpty(dataTemplateTypeId)) {
dataTemplateTypeId = "NONE";
context.put("dataTemplateTypeId", dataTemplateTypeId);
}
// If textData exists, then create DataResource and return dataResourceId
String dataResourceId = (String) context.get("dataResourceId");
if (UtilValidate.isEmpty(dataResourceId)) {
dataResourceId = delegator.getNextSeqId("DataResource");
}
if (Debug.infoOn()) {
Debug.logInfo("in createDataResourceMethod, dataResourceId:" + dataResourceId, MODULE);
}
GenericValue dataResource = delegator.makeValue("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
dataResource.setNonPKFields(context);
dataResource.put("createdByUserLogin", createdByUserLogin);
dataResource.put("lastModifiedByUserLogin", lastModifiedByUserLogin);
dataResource.put("createdDate", createdDate);
dataResource.put("lastModifiedDate", lastModifiedDate);
// get first statusId for content out of the statusItem table if not provided
if (UtilValidate.isEmpty(dataResource.get("statusId"))) {
try {
GenericValue statusItem = EntityQuery.use(delegator).from("StatusItem").where("statusTypeId", "CONTENT_STATUS")
.orderBy("sequenceId").queryFirst();
if (statusItem != null) {
dataResource.put("statusId", statusItem.get("statusId"));
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
}
try {
dataResource.create();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
result.put("dataResourceId", dataResourceId);
result.put("dataResource", dataResource);
return result;
}
/**
* A service wrapper for the createElectronicTextMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> createElectronicText(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = createElectronicTextMethod(dctx, context);
return result;
}
public static Map<String, Object> createElectronicTextMethod(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = new HashMap<>();
Delegator delegator = dctx.getDelegator();
String dataResourceId = (String) context.get("dataResourceId");
String textData = (String) context.get("textData");
if (UtilValidate.isNotEmpty(textData)) {
GenericValue electronicText = delegator.makeValue("ElectronicText",
UtilMisc.toMap("dataResourceId", dataResourceId, "textData", textData));
try {
electronicText.create();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
}
return result;
}
/**
* A service wrapper for the createFileMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> createFile(DispatchContext dctx, Map<String, ? extends Object> context) {
return createFileMethod(dctx, context);
}
public static Map<String, Object> createFileNoPerm(DispatchContext dctx, Map<String, ? extends Object> rcontext) throws IOException,
ImageReadException {
String originalFileName = (String) rcontext.get("dataResourceName");
String fileNameAndPath = (String) rcontext.get("objectInfo");
Delegator delegator = dctx.getDelegator();
Locale locale = (Locale) rcontext.get("locale");
File file = new File(fileNameAndPath);
if (!originalFileName.isEmpty()) {
// Check the file name
if (!SecuredUpload.isValidFileName(originalFileName, delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
return ServiceUtil.returnError(errorMessage);
}
// TODO we could verify the file type (here "All") with dataResourceTypeId. Anyway it's done with isValidFile()
// We would just have a better error message
if (file.exists()) {
// Check if a webshell is not uploaded
if (!SecuredUpload.isValidFile(fileNameAndPath, "All", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
return ServiceUtil.returnError(errorMessage);
}
}
}
Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
context.put("skipPermissionCheck", "true");
return createFileMethod(dctx, context);
}
public static Map<String, Object> createFileMethod(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
String dataResourceTypeId = (String) context.get("dataResourceTypeId");
String objectInfo = (String) context.get("objectInfo");
ByteBuffer binData = (ByteBuffer) context.get("binData");
String textData = (String) context.get("textData");
Locale locale = (Locale) context.get("locale");
// a few place holders
String prefix = "";
String sep = "";
// extended validation for binary/character data
if (UtilValidate.isNotEmpty(textData) && binData != null) {
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentCannotProcessBothCharacterAndBinaryFile", locale));
}
// obtain a reference to the file
File file = null;
if (UtilValidate.isEmpty(objectInfo)) {
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentUnableObtainReferenceToFile",
UtilMisc.toMap("objectInfo", ""), locale));
}
if (UtilValidate.isEmpty(dataResourceTypeId) || "LOCAL_FILE".equals(dataResourceTypeId) || "LOCAL_FILE_BIN".equals(dataResourceTypeId)) {
file = new File(objectInfo);
if (!file.isAbsolute()) {
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentLocalFileDoesNotPointToAbsoluteLocation", locale));
}
} else if ("OFBIZ_FILE".equals(dataResourceTypeId) || "OFBIZ_FILE_BIN".equals(dataResourceTypeId)) {
prefix = System.getProperty("ofbiz.home");
if (objectInfo.indexOf('/') != 0 && prefix.lastIndexOf('/') != (prefix.length() - 1)) {
sep = "/";
}
file = new File(prefix + sep + objectInfo);
} else if ("CONTEXT_FILE".equals(dataResourceTypeId) || "CONTEXT_FILE_BIN".equals(dataResourceTypeId)) {
prefix = (String) context.get("rootDir");
if (UtilValidate.isEmpty(prefix)) {
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentCannotFindContextFileWithEmptyContextRoot", locale));
}
if (objectInfo.indexOf('/') != 0 && prefix.lastIndexOf('/') != (prefix.length() - 1)) {
sep = "/";
}
file = new File(prefix + sep + objectInfo);
}
if (file == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentUnableObtainReferenceToFile",
UtilMisc.toMap("objectInfo", objectInfo), locale));
}
// write the data to the file
if (UtilValidate.isNotEmpty(textData)) {
try (OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);) {
out.write(textData);
// Check if a webshell is not uploaded
// TODO I believe the call below to SecuredUpload::isValidFile is now useless because of the same in createFileNoPerm
if (!SecuredUpload.isValidFile(file.getAbsolutePath(), "Text", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedTextFileFormats", locale);
return ServiceUtil.returnError(errorMessage);
}
} catch (IOException | ImageReadException e) {
Debug.logWarning(e, MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentUnableWriteCharacterDataToFile",
UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
} else if (binData != null) {
try {
Path tempFile = Files.createTempFile(null, null);
Files.write(tempFile, binData.array(), StandardOpenOption.APPEND);
// Check if a webshell is not uploaded
// TODO I believe the call below to SecuredUpload::isValidFile is now useless because of the same in createFileNoPerm
if (!SecuredUpload.isValidFile(tempFile.toString(), "All", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
return ServiceUtil.returnError(errorMessage);
}
File tempFileToDelete = new File(tempFile.toString());
tempFileToDelete.deleteOnExit();
RandomAccessFile out = new RandomAccessFile(file, "rw");
out.write(binData.array());
out.close();
} catch (FileNotFoundException | ImageReadException e) {
Debug.logError(e, MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentUnableToOpenFileForWriting",
UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
} catch (IOException e) {
Debug.logError(e, MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentUnableWriteBinaryDataToFile",
UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentNoContentFilePassed",
UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
Map<String, Object> result = ServiceUtil.returnSuccess();
return result;
}
/**
* A top-level service for updating a DataResource and ElectronicText together.
*/
public static Map<String, Object> updateDataResourceAndText(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> thisResult = updateDataResourceMethod(dctx, context);
if (thisResult.get(ModelService.RESPONSE_MESSAGE) != null) {
return ServiceUtil.returnError((String) thisResult.get(ModelService.ERROR_MESSAGE));
}
String dataResourceTypeId = (String) context.get("dataResourceTypeId");
if (dataResourceTypeId != null && "ELECTRONIC_TEXT".equals(dataResourceTypeId)) {
thisResult = updateElectronicText(dctx, context);
if (thisResult.get(ModelService.RESPONSE_MESSAGE) != null) {
return ServiceUtil.returnError((String) thisResult.get(ModelService.ERROR_MESSAGE));
}
}
return ServiceUtil.returnSuccess();
}
/**
* A service wrapper for the updateDataResourceMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> updateDataResource(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = updateDataResourceMethod(dctx, context);
return result;
}
public static Map<String, Object> updateDataResourceMethod(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = new HashMap<>();
Delegator delegator = dctx.getDelegator();
GenericValue dataResource = null;
Locale locale = (Locale) context.get("locale");
GenericValue userLogin = (GenericValue) context.get("userLogin");
String userLoginId = (String) userLogin.get("userLoginId");
String lastModifiedByUserLogin = userLoginId;
Timestamp lastModifiedDate = UtilDateTime.nowTimestamp();
// If textData exists, then create DataResource and return dataResourceId
String dataResourceId = (String) context.get("dataResourceId");
try {
dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
} catch (GenericEntityException e) {
Debug.logWarning(e, MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentDataResourceNotFound",
UtilMisc.toMap("parameters.dataResourceId", dataResourceId), locale));
}
dataResource.setNonPKFields(context);
dataResource.put("lastModifiedByUserLogin", lastModifiedByUserLogin);
dataResource.put("lastModifiedDate", lastModifiedDate);
try {
dataResource.store();
} catch (GenericEntityException e) {
Debug.logError(e, MODULE);
return ServiceUtil.returnError(e.getMessage());
}
result.put("dataResource", dataResource);
return result;
}
/**
* A service wrapper for the updateElectronicTextMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> updateElectronicText(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = updateElectronicTextMethod(dctx, context);
return result;
}
/**
* Because sometimes a DataResource will exist, but no ElectronicText has been created, this method will create an
* ElectronicText if it does not exist.
* @param dctx the dispatch context
* @param context the context
* @return update the ElectronicText
*/
public static Map<String, Object> updateElectronicTextMethod(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = new HashMap<>();
Delegator delegator = dctx.getDelegator();
GenericValue electronicText = null;
Locale locale = (Locale) context.get("locale");
String dataResourceId = (String) context.get("dataResourceId");
result.put("dataResourceId", dataResourceId);
String contentId = (String) context.get("contentId");
result.put("contentId", contentId);
if (UtilValidate.isEmpty(dataResourceId)) {
Debug.logError("dataResourceId is null.", MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentDataResourceIsNull", locale));
}
String textData = (String) context.get("textData");
if (Debug.verboseOn()) {
Debug.logVerbose("in updateElectronicText, textData:" + textData, MODULE);
}
try {
electronicText = EntityQuery.use(delegator).from("ElectronicText").where("dataResourceId", dataResourceId).queryOne();
if (electronicText != null) {
electronicText.put("textData", textData);
electronicText.store();
} else {
electronicText = delegator.makeValue("ElectronicText");
electronicText.put("dataResourceId", dataResourceId);
electronicText.put("textData", textData);
electronicText.create();
}
} catch (GenericEntityException e) {
Debug.logWarning(e, MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentElectronicTextNotFound", locale) + " " + e.getMessage());
}
return result;
}
/**
* A service wrapper for the updateFileMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> updateFile(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = null;
try {
result = updateFileMethod(dctx, context);
} catch (GenericServiceException e) {
return ServiceUtil.returnError(e.getMessage());
}
return result;
}
public static Map<String, Object> updateFileMethod(DispatchContext dctx, Map<String, ? extends Object> context) throws GenericServiceException {
Delegator delegator = dctx.getDelegator();
Map<String, Object> result = new HashMap<>();
Locale locale = (Locale) context.get("locale");
String dataResourceTypeId = (String) context.get("dataResourceTypeId");
String objectInfo = (String) context.get("objectInfo");
String textData = (String) context.get("textData");
ByteBuffer binData = (ByteBuffer) context.get("binData");
String prefix = "";
File file = null;
String fileName = "";
String sep = "";
try {
if (UtilValidate.isEmpty(dataResourceTypeId) || dataResourceTypeId.startsWith("LOCAL_FILE")) {
fileName = prefix + sep + objectInfo;
file = new File(fileName);
if (!file.isAbsolute()) {
throw new GenericServiceException("File: " + fileName + " is not absolute.");
}
} else if (dataResourceTypeId.startsWith("OFBIZ_FILE")) {
prefix = System.getProperty("ofbiz.home");
if (objectInfo.indexOf('/') != 0 && prefix.lastIndexOf('/') != (prefix.length() - 1)) {
sep = "/";
}
file = new File(prefix + sep + objectInfo);
} else if (dataResourceTypeId.startsWith("CONTEXT_FILE")) {
prefix = (String) context.get("rootDir");
if (objectInfo.indexOf('/') != 0 && prefix.lastIndexOf('/') != (prefix.length() - 1)) {
sep = "/";
}
file = new File(prefix + sep + objectInfo);
}
if (file == null) {
throw new IOException("File is null");
}
// write the data to the file
if (UtilValidate.isNotEmpty(textData)) {
try (OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);) {
out.write(textData);
// Check if a webshell is not uploaded
// TODO I believe the call below to SecuredUpload::isValidFile is now useless because of the same in createFileNoPerm
if (!SecuredUpload.isValidFile(file.getAbsolutePath(), "Text", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedTextFileFormats", locale);
return ServiceUtil.returnError(errorMessage);
}
} catch (IOException | ImageReadException e) {
Debug.logWarning(e, MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentUnableWriteCharacterDataToFile",
UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
} else if (binData != null) {
try {
// Check if a webshell is not uploaded
// TODO I believe the call below to SecuredUpload::isValidFile is now useless because of the same in createFileNoPerm
Path tempFile = Files.createTempFile(null, null);
Files.write(tempFile, binData.array(), StandardOpenOption.APPEND);
if (!SecuredUpload.isValidFile(tempFile.toString(), "Image", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
return ServiceUtil.returnError(errorMessage);
}
File tempFileToDelete = new File(tempFile.toString());
tempFileToDelete.deleteOnExit();
RandomAccessFile out = new RandomAccessFile(file, "rw");
out.setLength(binData.array().length);
out.write(binData.array());
out.close();
} catch (FileNotFoundException | ImageReadException e) {
Debug.logError(e, MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentUnableToOpenFileForWriting",
UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
} catch (IOException e) {
Debug.logError(e, MODULE);
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentUnableWriteBinaryDataToFile",
UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentNoContentFilePassed",
UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
} catch (IOException e) {
Debug.logWarning(e, MODULE);
throw new GenericServiceException(e.getMessage());
}
return result;
}
public static Map<String, Object> renderDataResourceAsText(DispatchContext dctx, Map<String, ? extends Object> context)
throws GeneralException, IOException {
Map<String, Object> results = new HashMap<>();
//LocalDispatcher dispatcher = dctx.getDispatcher();
Writer out = (Writer) context.get("outWriter");
Map<String, Object> templateContext = UtilGenerics.cast(context.get("templateContext"));
//GenericValue userLogin = (GenericValue) context.get("userLogin");
String dataResourceId = (String) context.get("dataResourceId");
if (templateContext != null && UtilValidate.isEmpty(dataResourceId)) {
dataResourceId = (String) templateContext.get("dataResourceId");
}
String mimeTypeId = (String) context.get("mimeTypeId");
if (templateContext != null && UtilValidate.isEmpty(mimeTypeId)) {
mimeTypeId = (String) templateContext.get("mimeTypeId");
}
Locale locale = (Locale) context.get("locale");
if (templateContext == null) {
templateContext = new HashMap<>();
}
Writer outWriter = new StringWriter();
DataResourceWorker.renderDataResourceAsText(dctx.getDispatcher(), dataResourceId, outWriter, templateContext, locale, mimeTypeId, true);
try {
out.write(outWriter.toString());
results.put("textData", outWriter.toString());
} catch (IOException e) {
Debug.logError(e, "Error rendering sub-content text", MODULE);
return ServiceUtil.returnError(e.toString());
}
return results;
}
/**
* A service wrapper for the updateImageMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> updateImage(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = updateImageMethod(dctx, context);
return result;
}
public static Map<String, Object> updateImageMethod(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = new HashMap<>();
Delegator delegator = dctx.getDelegator();
//Locale locale = (Locale) context.get("locale");
String dataResourceId = (String) context.get("dataResourceId");
ByteBuffer byteBuffer = (ByteBuffer) context.get("imageData");
if (byteBuffer != null) {
byte[] imageBytes = byteBuffer.array();
try {
GenericValue imageDataResource = EntityQuery.use(delegator).from("ImageDataResource")
.where("dataResourceId", dataResourceId).queryOne();
if (Debug.infoOn()) {
Debug.logInfo("imageDataResource(U):" + imageDataResource, MODULE);
Debug.logInfo("imageBytes(U):" + Arrays.toString(imageBytes), MODULE);
}
if (imageDataResource == null) {
return createImageMethod(dctx, context);
}
imageDataResource.setBytes("imageData", imageBytes);
imageDataResource.store();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
}
return result;
}
/**
* A service wrapper for the createImageMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> createImage(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = createImageMethod(dctx, context);
return result;
}
public static Map<String, Object> createImageMethod(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = new HashMap<>();
Delegator delegator = dctx.getDelegator();
String dataResourceId = (String) context.get("dataResourceId");
ByteBuffer byteBuffer = (ByteBuffer) context.get("imageData");
if (byteBuffer != null) {
byte[] imageBytes = byteBuffer.array();
try {
GenericValue imageDataResource = delegator.makeValue("ImageDataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
imageDataResource.setBytes("imageData", imageBytes);
if (Debug.infoOn()) {
Debug.logInfo("imageDataResource(C):" + imageDataResource, MODULE);
}
imageDataResource.create();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
}
return result;
}
/**
* A service wrapper for the createBinaryFileMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> createBinaryFile(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = null;
try {
result = createBinaryFileMethod(dctx, context);
} catch (GenericServiceException e) {
return ServiceUtil.returnError(e.getMessage());
}
return result;
}
public static Map<String, Object> createBinaryFileMethod(DispatchContext dctx, Map<String, ? extends Object> context)
throws GenericServiceException {
Delegator delegator = dctx.getDelegator();
Map<String, Object> result = new HashMap<>();
GenericValue dataResource = (GenericValue) context.get("dataResource");
String dataResourceTypeId = (String) dataResource.get("dataResourceTypeId");
String objectInfo = (String) dataResource.get("objectInfo");
byte[] imageData = (byte[]) context.get("imageData");
String rootDir = (String) context.get("rootDir");
Locale locale = (Locale) context.get("locale");
File file = null;
if (Debug.infoOn()) {
Debug.logInfo("in createBinaryFileMethod, dataResourceTypeId:" + dataResourceTypeId, MODULE);
Debug.logInfo("in createBinaryFileMethod, objectInfo:" + objectInfo, MODULE);
Debug.logInfo("in createBinaryFileMethod, rootDir:" + rootDir, MODULE);
}
try {
file = DataResourceWorker.getContentFile(dataResourceTypeId, objectInfo, rootDir);
} catch (FileNotFoundException | GeneralException e) {
Debug.logWarning(e, MODULE);
throw new GenericServiceException(e.getMessage());
}
if (Debug.infoOn()) {
Debug.logInfo("in createBinaryFileMethod, file:" + file, MODULE);
Debug.logInfo("in createBinaryFileMethod, imageData:" + imageData.length, MODULE);
}
if (imageData != null && imageData.length > 0) {
try (FileOutputStream out = new FileOutputStream(file);) {
out.write(imageData);
// Check if a webshell is not uploaded
// TODO I believe the call below to SecuredUpload::isValidFile is now useless because of the same in createFileNoPerm
if (!SecuredUpload.isValidFile(file.getAbsolutePath(), "All", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
return ServiceUtil.returnError(errorMessage);
}
if (Debug.infoOn()) {
Debug.logInfo("in createBinaryFileMethod, length:" + file.length(), MODULE);
}
} catch (IOException | ImageReadException e) {
Debug.logWarning(e, MODULE);
throw new GenericServiceException(e.getMessage());
}
}
return result;
}
/**
* A service wrapper for the createBinaryFileMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> updateBinaryFile(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = null;
try {
result = updateBinaryFileMethod(dctx, context);
} catch (GenericServiceException e) {
return ServiceUtil.returnError(e.getMessage());
}
return result;
}
public static Map<String, Object> updateBinaryFileMethod(DispatchContext dctx, Map<String, ? extends Object> context)
throws GenericServiceException {
Delegator delegator = dctx.getDelegator();
Map<String, Object> result = new HashMap<>();
GenericValue dataResource = (GenericValue) context.get("dataResource");
String dataResourceTypeId = (String) dataResource.get("dataResourceTypeId");
String objectInfo = (String) dataResource.get("objectInfo");
byte[] imageData = (byte[]) context.get("imageData");
String rootDir = (String) context.get("rootDir");
Locale locale = (Locale) context.get("locale");
File file = null;
if (Debug.infoOn()) {
Debug.logInfo("in updateBinaryFileMethod, dataResourceTypeId:" + dataResourceTypeId, MODULE);
Debug.logInfo("in updateBinaryFileMethod, objectInfo:" + objectInfo, MODULE);
Debug.logInfo("in updateBinaryFileMethod, rootDir:" + rootDir, MODULE);
}
try {
file = DataResourceWorker.getContentFile(dataResourceTypeId, objectInfo, rootDir);
} catch (FileNotFoundException | GeneralException e) {
Debug.logWarning(e, MODULE);
throw new GenericServiceException(e.getMessage());
}
if (Debug.infoOn()) {
Debug.logInfo("in updateBinaryFileMethod, file:" + file, MODULE);
Debug.logInfo("in updateBinaryFileMethod, imageData:" + Arrays.toString(imageData), MODULE);
}
if (imageData != null && imageData.length > 0) {
try (FileOutputStream out = new FileOutputStream(file);) {
out.write(imageData);
// Check if a webshell is not uploaded
// TODO I believe the call below to SecuredUpload::isValidFile is now useless because of the same in createFileNoPerm
if (!SecuredUpload.isValidFile(file.getAbsolutePath(), "All", delegator)) {
String errorMessage = UtilProperties.getMessage("SecurityUiLabels", "SupportedFileFormatsIncludingSvg", locale);
return ServiceUtil.returnError(errorMessage);
}
if (Debug.infoOn()) {
Debug.logInfo("in updateBinaryFileMethod, length:" + file.length(), MODULE);
}
} catch (IOException | ImageReadException e) {
Debug.logWarning(e, MODULE);
throw new GenericServiceException(e.getMessage());
}
}
return result;
}
}
|
googleapis/google-cloud-java
| 38,178
|
java-contact-center-insights/proto-google-cloud-contact-center-insights-v1/src/main/java/com/google/cloud/contactcenterinsights/v1/ListQaQuestionsResponse.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/contactcenterinsights/v1/contact_center_insights.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.contactcenterinsights.v1;
/**
*
*
* <pre>
* The response from a ListQaQuestions request.
* </pre>
*
* Protobuf type {@code google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse}
*/
public final class ListQaQuestionsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse)
ListQaQuestionsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListQaQuestionsResponse.newBuilder() to construct.
private ListQaQuestionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListQaQuestionsResponse() {
qaQuestions_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListQaQuestionsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_ListQaQuestionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_ListQaQuestionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse.class,
com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse.Builder.class);
}
public static final int QA_QUESTIONS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.contactcenterinsights.v1.QaQuestion> qaQuestions_;
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.contactcenterinsights.v1.QaQuestion> getQaQuestionsList() {
return qaQuestions_;
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.contactcenterinsights.v1.QaQuestionOrBuilder>
getQaQuestionsOrBuilderList() {
return qaQuestions_;
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
@java.lang.Override
public int getQaQuestionsCount() {
return qaQuestions_.size();
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.QaQuestion getQaQuestions(int index) {
return qaQuestions_.get(index);
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.QaQuestionOrBuilder getQaQuestionsOrBuilder(
int index) {
return qaQuestions_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < qaQuestions_.size(); i++) {
output.writeMessage(1, qaQuestions_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < qaQuestions_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, qaQuestions_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse)) {
return super.equals(obj);
}
com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse other =
(com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse) obj;
if (!getQaQuestionsList().equals(other.getQaQuestionsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getQaQuestionsCount() > 0) {
hash = (37 * hash) + QA_QUESTIONS_FIELD_NUMBER;
hash = (53 * hash) + getQaQuestionsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The response from a ListQaQuestions request.
* </pre>
*
* Protobuf type {@code google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse)
com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_ListQaQuestionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_ListQaQuestionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse.class,
com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse.Builder.class);
}
// Construct using
// com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (qaQuestionsBuilder_ == null) {
qaQuestions_ = java.util.Collections.emptyList();
} else {
qaQuestions_ = null;
qaQuestionsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.contactcenterinsights.v1.ContactCenterInsightsProto
.internal_static_google_cloud_contactcenterinsights_v1_ListQaQuestionsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse
getDefaultInstanceForType() {
return com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse build() {
com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse buildPartial() {
com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse result =
new com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse result) {
if (qaQuestionsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
qaQuestions_ = java.util.Collections.unmodifiableList(qaQuestions_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.qaQuestions_ = qaQuestions_;
} else {
result.qaQuestions_ = qaQuestionsBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse) {
return mergeFrom((com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse other) {
if (other
== com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse.getDefaultInstance())
return this;
if (qaQuestionsBuilder_ == null) {
if (!other.qaQuestions_.isEmpty()) {
if (qaQuestions_.isEmpty()) {
qaQuestions_ = other.qaQuestions_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureQaQuestionsIsMutable();
qaQuestions_.addAll(other.qaQuestions_);
}
onChanged();
}
} else {
if (!other.qaQuestions_.isEmpty()) {
if (qaQuestionsBuilder_.isEmpty()) {
qaQuestionsBuilder_.dispose();
qaQuestionsBuilder_ = null;
qaQuestions_ = other.qaQuestions_;
bitField0_ = (bitField0_ & ~0x00000001);
qaQuestionsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getQaQuestionsFieldBuilder()
: null;
} else {
qaQuestionsBuilder_.addAllMessages(other.qaQuestions_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.contactcenterinsights.v1.QaQuestion m =
input.readMessage(
com.google.cloud.contactcenterinsights.v1.QaQuestion.parser(),
extensionRegistry);
if (qaQuestionsBuilder_ == null) {
ensureQaQuestionsIsMutable();
qaQuestions_.add(m);
} else {
qaQuestionsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.contactcenterinsights.v1.QaQuestion> qaQuestions_ =
java.util.Collections.emptyList();
private void ensureQaQuestionsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
qaQuestions_ =
new java.util.ArrayList<com.google.cloud.contactcenterinsights.v1.QaQuestion>(
qaQuestions_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.contactcenterinsights.v1.QaQuestion,
com.google.cloud.contactcenterinsights.v1.QaQuestion.Builder,
com.google.cloud.contactcenterinsights.v1.QaQuestionOrBuilder>
qaQuestionsBuilder_;
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public java.util.List<com.google.cloud.contactcenterinsights.v1.QaQuestion>
getQaQuestionsList() {
if (qaQuestionsBuilder_ == null) {
return java.util.Collections.unmodifiableList(qaQuestions_);
} else {
return qaQuestionsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public int getQaQuestionsCount() {
if (qaQuestionsBuilder_ == null) {
return qaQuestions_.size();
} else {
return qaQuestionsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public com.google.cloud.contactcenterinsights.v1.QaQuestion getQaQuestions(int index) {
if (qaQuestionsBuilder_ == null) {
return qaQuestions_.get(index);
} else {
return qaQuestionsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public Builder setQaQuestions(
int index, com.google.cloud.contactcenterinsights.v1.QaQuestion value) {
if (qaQuestionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureQaQuestionsIsMutable();
qaQuestions_.set(index, value);
onChanged();
} else {
qaQuestionsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public Builder setQaQuestions(
int index, com.google.cloud.contactcenterinsights.v1.QaQuestion.Builder builderForValue) {
if (qaQuestionsBuilder_ == null) {
ensureQaQuestionsIsMutable();
qaQuestions_.set(index, builderForValue.build());
onChanged();
} else {
qaQuestionsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public Builder addQaQuestions(com.google.cloud.contactcenterinsights.v1.QaQuestion value) {
if (qaQuestionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureQaQuestionsIsMutable();
qaQuestions_.add(value);
onChanged();
} else {
qaQuestionsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public Builder addQaQuestions(
int index, com.google.cloud.contactcenterinsights.v1.QaQuestion value) {
if (qaQuestionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureQaQuestionsIsMutable();
qaQuestions_.add(index, value);
onChanged();
} else {
qaQuestionsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public Builder addQaQuestions(
com.google.cloud.contactcenterinsights.v1.QaQuestion.Builder builderForValue) {
if (qaQuestionsBuilder_ == null) {
ensureQaQuestionsIsMutable();
qaQuestions_.add(builderForValue.build());
onChanged();
} else {
qaQuestionsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public Builder addQaQuestions(
int index, com.google.cloud.contactcenterinsights.v1.QaQuestion.Builder builderForValue) {
if (qaQuestionsBuilder_ == null) {
ensureQaQuestionsIsMutable();
qaQuestions_.add(index, builderForValue.build());
onChanged();
} else {
qaQuestionsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public Builder addAllQaQuestions(
java.lang.Iterable<? extends com.google.cloud.contactcenterinsights.v1.QaQuestion> values) {
if (qaQuestionsBuilder_ == null) {
ensureQaQuestionsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, qaQuestions_);
onChanged();
} else {
qaQuestionsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public Builder clearQaQuestions() {
if (qaQuestionsBuilder_ == null) {
qaQuestions_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
qaQuestionsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public Builder removeQaQuestions(int index) {
if (qaQuestionsBuilder_ == null) {
ensureQaQuestionsIsMutable();
qaQuestions_.remove(index);
onChanged();
} else {
qaQuestionsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public com.google.cloud.contactcenterinsights.v1.QaQuestion.Builder getQaQuestionsBuilder(
int index) {
return getQaQuestionsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public com.google.cloud.contactcenterinsights.v1.QaQuestionOrBuilder getQaQuestionsOrBuilder(
int index) {
if (qaQuestionsBuilder_ == null) {
return qaQuestions_.get(index);
} else {
return qaQuestionsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public java.util.List<? extends com.google.cloud.contactcenterinsights.v1.QaQuestionOrBuilder>
getQaQuestionsOrBuilderList() {
if (qaQuestionsBuilder_ != null) {
return qaQuestionsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(qaQuestions_);
}
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public com.google.cloud.contactcenterinsights.v1.QaQuestion.Builder addQaQuestionsBuilder() {
return getQaQuestionsFieldBuilder()
.addBuilder(com.google.cloud.contactcenterinsights.v1.QaQuestion.getDefaultInstance());
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public com.google.cloud.contactcenterinsights.v1.QaQuestion.Builder addQaQuestionsBuilder(
int index) {
return getQaQuestionsFieldBuilder()
.addBuilder(
index, com.google.cloud.contactcenterinsights.v1.QaQuestion.getDefaultInstance());
}
/**
*
*
* <pre>
* The QaQuestions under the parent.
* </pre>
*
* <code>repeated .google.cloud.contactcenterinsights.v1.QaQuestion qa_questions = 1;</code>
*/
public java.util.List<com.google.cloud.contactcenterinsights.v1.QaQuestion.Builder>
getQaQuestionsBuilderList() {
return getQaQuestionsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.contactcenterinsights.v1.QaQuestion,
com.google.cloud.contactcenterinsights.v1.QaQuestion.Builder,
com.google.cloud.contactcenterinsights.v1.QaQuestionOrBuilder>
getQaQuestionsFieldBuilder() {
if (qaQuestionsBuilder_ == null) {
qaQuestionsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.contactcenterinsights.v1.QaQuestion,
com.google.cloud.contactcenterinsights.v1.QaQuestion.Builder,
com.google.cloud.contactcenterinsights.v1.QaQuestionOrBuilder>(
qaQuestions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
qaQuestions_ = null;
}
return qaQuestionsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse)
private static final com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse();
}
public static com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListQaQuestionsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListQaQuestionsResponse>() {
@java.lang.Override
public ListQaQuestionsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListQaQuestionsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListQaQuestionsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.contactcenterinsights.v1.ListQaQuestionsResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,301
|
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/DeleteInterconnectRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* A request message for Interconnects.Delete. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.DeleteInterconnectRequest}
*/
public final class DeleteInterconnectRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.DeleteInterconnectRequest)
DeleteInterconnectRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use DeleteInterconnectRequest.newBuilder() to construct.
private DeleteInterconnectRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeleteInterconnectRequest() {
interconnect_ = "";
project_ = "";
requestId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DeleteInterconnectRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteInterconnectRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteInterconnectRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.DeleteInterconnectRequest.class,
com.google.cloud.compute.v1.DeleteInterconnectRequest.Builder.class);
}
private int bitField0_;
public static final int INTERCONNECT_FIELD_NUMBER = 224601230;
@SuppressWarnings("serial")
private volatile java.lang.Object interconnect_ = "";
/**
*
*
* <pre>
* Name of the interconnect to delete.
* </pre>
*
* <code>string interconnect = 224601230 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The interconnect.
*/
@java.lang.Override
public java.lang.String getInterconnect() {
java.lang.Object ref = interconnect_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
interconnect_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name of the interconnect to delete.
* </pre>
*
* <code>string interconnect = 224601230 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for interconnect.
*/
@java.lang.Override
public com.google.protobuf.ByteString getInterconnectBytes() {
java.lang.Object ref = interconnect_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
interconnect_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PROJECT_FIELD_NUMBER = 227560217;
@SuppressWarnings("serial")
private volatile java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
@java.lang.Override
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int REQUEST_ID_FIELD_NUMBER = 37109963;
@SuppressWarnings("serial")
private volatile java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return Whether the requestId field is set.
*/
@java.lang.Override
public boolean hasRequestId() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The requestId.
*/
@java.lang.Override
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The bytes for requestId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 37109963, requestId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(interconnect_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 224601230, interconnect_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(37109963, requestId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(interconnect_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(224601230, interconnect_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.DeleteInterconnectRequest)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.DeleteInterconnectRequest other =
(com.google.cloud.compute.v1.DeleteInterconnectRequest) obj;
if (!getInterconnect().equals(other.getInterconnect())) return false;
if (!getProject().equals(other.getProject())) return false;
if (hasRequestId() != other.hasRequestId()) return false;
if (hasRequestId()) {
if (!getRequestId().equals(other.getRequestId())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + INTERCONNECT_FIELD_NUMBER;
hash = (53 * hash) + getInterconnect().hashCode();
hash = (37 * hash) + PROJECT_FIELD_NUMBER;
hash = (53 * hash) + getProject().hashCode();
if (hasRequestId()) {
hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER;
hash = (53 * hash) + getRequestId().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.compute.v1.DeleteInterconnectRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A request message for Interconnects.Delete. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.DeleteInterconnectRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.DeleteInterconnectRequest)
com.google.cloud.compute.v1.DeleteInterconnectRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteInterconnectRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteInterconnectRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.DeleteInterconnectRequest.class,
com.google.cloud.compute.v1.DeleteInterconnectRequest.Builder.class);
}
// Construct using com.google.cloud.compute.v1.DeleteInterconnectRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
interconnect_ = "";
project_ = "";
requestId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteInterconnectRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteInterconnectRequest getDefaultInstanceForType() {
return com.google.cloud.compute.v1.DeleteInterconnectRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteInterconnectRequest build() {
com.google.cloud.compute.v1.DeleteInterconnectRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteInterconnectRequest buildPartial() {
com.google.cloud.compute.v1.DeleteInterconnectRequest result =
new com.google.cloud.compute.v1.DeleteInterconnectRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.compute.v1.DeleteInterconnectRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.interconnect_ = interconnect_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.project_ = project_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.requestId_ = requestId_;
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.DeleteInterconnectRequest) {
return mergeFrom((com.google.cloud.compute.v1.DeleteInterconnectRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.DeleteInterconnectRequest other) {
if (other == com.google.cloud.compute.v1.DeleteInterconnectRequest.getDefaultInstance())
return this;
if (!other.getInterconnect().isEmpty()) {
interconnect_ = other.interconnect_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getProject().isEmpty()) {
project_ = other.project_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasRequestId()) {
requestId_ = other.requestId_;
bitField0_ |= 0x00000004;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 296879706:
{
requestId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 296879706
case 1796809842:
{
interconnect_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 1796809842
case 1820481738:
{
project_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 1820481738
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object interconnect_ = "";
/**
*
*
* <pre>
* Name of the interconnect to delete.
* </pre>
*
* <code>string interconnect = 224601230 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The interconnect.
*/
public java.lang.String getInterconnect() {
java.lang.Object ref = interconnect_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
interconnect_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name of the interconnect to delete.
* </pre>
*
* <code>string interconnect = 224601230 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for interconnect.
*/
public com.google.protobuf.ByteString getInterconnectBytes() {
java.lang.Object ref = interconnect_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
interconnect_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name of the interconnect to delete.
* </pre>
*
* <code>string interconnect = 224601230 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The interconnect to set.
* @return This builder for chaining.
*/
public Builder setInterconnect(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
interconnect_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the interconnect to delete.
* </pre>
*
* <code>string interconnect = 224601230 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearInterconnect() {
interconnect_ = getDefaultInstance().getInterconnect();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name of the interconnect to delete.
* </pre>
*
* <code>string interconnect = 224601230 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for interconnect to set.
* @return This builder for chaining.
*/
public Builder setInterconnectBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
interconnect_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @param value The project to set.
* @return This builder for chaining.
*/
public Builder setProject(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearProject() {
project_ = getDefaultInstance().getProject();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @param value The bytes for project to set.
* @return This builder for chaining.
*/
public Builder setProjectBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return Whether the requestId field is set.
*/
public boolean hasRequestId() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The requestId.
*/
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The bytes for requestId.
*/
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @param value The requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
requestId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return This builder for chaining.
*/
public Builder clearRequestId() {
requestId_ = getDefaultInstance().getRequestId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @param value The bytes for requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
requestId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.DeleteInterconnectRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.DeleteInterconnectRequest)
private static final com.google.cloud.compute.v1.DeleteInterconnectRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.DeleteInterconnectRequest();
}
public static com.google.cloud.compute.v1.DeleteInterconnectRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeleteInterconnectRequest> PARSER =
new com.google.protobuf.AbstractParser<DeleteInterconnectRequest>() {
@java.lang.Override
public DeleteInterconnectRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<DeleteInterconnectRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeleteInterconnectRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteInterconnectRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,184
|
java-service-usage/proto-google-cloud-service-usage-v1beta1/src/main/java/com/google/api/serviceusage/v1beta1/ListConsumerQuotaMetricsResponse.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/serviceusage/v1beta1/serviceusage.proto
// Protobuf Java Version: 3.25.8
package com.google.api.serviceusage.v1beta1;
/**
*
*
* <pre>
* Response message for ListConsumerQuotaMetrics
* </pre>
*
* Protobuf type {@code google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse}
*/
public final class ListConsumerQuotaMetricsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse)
ListConsumerQuotaMetricsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListConsumerQuotaMetricsResponse.newBuilder() to construct.
private ListConsumerQuotaMetricsResponse(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListConsumerQuotaMetricsResponse() {
metrics_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListConsumerQuotaMetricsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.api.serviceusage.v1beta1.ServiceUsageProto
.internal_static_google_api_serviceusage_v1beta1_ListConsumerQuotaMetricsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.serviceusage.v1beta1.ServiceUsageProto
.internal_static_google_api_serviceusage_v1beta1_ListConsumerQuotaMetricsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse.class,
com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse.Builder.class);
}
public static final int METRICS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric> metrics_;
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric> getMetricsList() {
return metrics_;
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.api.serviceusage.v1beta1.ConsumerQuotaMetricOrBuilder>
getMetricsOrBuilderList() {
return metrics_;
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
@java.lang.Override
public int getMetricsCount() {
return metrics_.size();
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
@java.lang.Override
public com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric getMetrics(int index) {
return metrics_.get(index);
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
@java.lang.Override
public com.google.api.serviceusage.v1beta1.ConsumerQuotaMetricOrBuilder getMetricsOrBuilder(
int index) {
return metrics_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < metrics_.size(); i++) {
output.writeMessage(1, metrics_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < metrics_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, metrics_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse)) {
return super.equals(obj);
}
com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse other =
(com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse) obj;
if (!getMetricsList().equals(other.getMetricsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getMetricsCount() > 0) {
hash = (37 * hash) + METRICS_FIELD_NUMBER;
hash = (53 * hash) + getMetricsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response message for ListConsumerQuotaMetrics
* </pre>
*
* Protobuf type {@code google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse)
com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.api.serviceusage.v1beta1.ServiceUsageProto
.internal_static_google_api_serviceusage_v1beta1_ListConsumerQuotaMetricsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.api.serviceusage.v1beta1.ServiceUsageProto
.internal_static_google_api_serviceusage_v1beta1_ListConsumerQuotaMetricsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse.class,
com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse.Builder.class);
}
// Construct using
// com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (metricsBuilder_ == null) {
metrics_ = java.util.Collections.emptyList();
} else {
metrics_ = null;
metricsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.api.serviceusage.v1beta1.ServiceUsageProto
.internal_static_google_api_serviceusage_v1beta1_ListConsumerQuotaMetricsResponse_descriptor;
}
@java.lang.Override
public com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse
getDefaultInstanceForType() {
return com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse
.getDefaultInstance();
}
@java.lang.Override
public com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse build() {
com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse buildPartial() {
com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse result =
new com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse result) {
if (metricsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
metrics_ = java.util.Collections.unmodifiableList(metrics_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.metrics_ = metrics_;
} else {
result.metrics_ = metricsBuilder_.build();
}
}
private void buildPartial0(
com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse) {
return mergeFrom(
(com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse other) {
if (other
== com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse
.getDefaultInstance()) return this;
if (metricsBuilder_ == null) {
if (!other.metrics_.isEmpty()) {
if (metrics_.isEmpty()) {
metrics_ = other.metrics_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureMetricsIsMutable();
metrics_.addAll(other.metrics_);
}
onChanged();
}
} else {
if (!other.metrics_.isEmpty()) {
if (metricsBuilder_.isEmpty()) {
metricsBuilder_.dispose();
metricsBuilder_ = null;
metrics_ = other.metrics_;
bitField0_ = (bitField0_ & ~0x00000001);
metricsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getMetricsFieldBuilder()
: null;
} else {
metricsBuilder_.addAllMessages(other.metrics_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric m =
input.readMessage(
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.parser(),
extensionRegistry);
if (metricsBuilder_ == null) {
ensureMetricsIsMutable();
metrics_.add(m);
} else {
metricsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric> metrics_ =
java.util.Collections.emptyList();
private void ensureMetricsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
metrics_ =
new java.util.ArrayList<com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric>(
metrics_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric,
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.Builder,
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetricOrBuilder>
metricsBuilder_;
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public java.util.List<com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric>
getMetricsList() {
if (metricsBuilder_ == null) {
return java.util.Collections.unmodifiableList(metrics_);
} else {
return metricsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public int getMetricsCount() {
if (metricsBuilder_ == null) {
return metrics_.size();
} else {
return metricsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric getMetrics(int index) {
if (metricsBuilder_ == null) {
return metrics_.get(index);
} else {
return metricsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public Builder setMetrics(
int index, com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric value) {
if (metricsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMetricsIsMutable();
metrics_.set(index, value);
onChanged();
} else {
metricsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public Builder setMetrics(
int index,
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.Builder builderForValue) {
if (metricsBuilder_ == null) {
ensureMetricsIsMutable();
metrics_.set(index, builderForValue.build());
onChanged();
} else {
metricsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public Builder addMetrics(com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric value) {
if (metricsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMetricsIsMutable();
metrics_.add(value);
onChanged();
} else {
metricsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public Builder addMetrics(
int index, com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric value) {
if (metricsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMetricsIsMutable();
metrics_.add(index, value);
onChanged();
} else {
metricsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public Builder addMetrics(
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.Builder builderForValue) {
if (metricsBuilder_ == null) {
ensureMetricsIsMutable();
metrics_.add(builderForValue.build());
onChanged();
} else {
metricsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public Builder addMetrics(
int index,
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.Builder builderForValue) {
if (metricsBuilder_ == null) {
ensureMetricsIsMutable();
metrics_.add(index, builderForValue.build());
onChanged();
} else {
metricsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public Builder addAllMetrics(
java.lang.Iterable<? extends com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric>
values) {
if (metricsBuilder_ == null) {
ensureMetricsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, metrics_);
onChanged();
} else {
metricsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public Builder clearMetrics() {
if (metricsBuilder_ == null) {
metrics_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
metricsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public Builder removeMetrics(int index) {
if (metricsBuilder_ == null) {
ensureMetricsIsMutable();
metrics_.remove(index);
onChanged();
} else {
metricsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.Builder getMetricsBuilder(
int index) {
return getMetricsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public com.google.api.serviceusage.v1beta1.ConsumerQuotaMetricOrBuilder getMetricsOrBuilder(
int index) {
if (metricsBuilder_ == null) {
return metrics_.get(index);
} else {
return metricsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public java.util.List<
? extends com.google.api.serviceusage.v1beta1.ConsumerQuotaMetricOrBuilder>
getMetricsOrBuilderList() {
if (metricsBuilder_ != null) {
return metricsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(metrics_);
}
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.Builder addMetricsBuilder() {
return getMetricsFieldBuilder()
.addBuilder(com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.getDefaultInstance());
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.Builder addMetricsBuilder(
int index) {
return getMetricsFieldBuilder()
.addBuilder(
index, com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.getDefaultInstance());
}
/**
*
*
* <pre>
* Quota settings for the consumer, organized by quota metric.
* </pre>
*
* <code>repeated .google.api.serviceusage.v1beta1.ConsumerQuotaMetric metrics = 1;</code>
*/
public java.util.List<com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.Builder>
getMetricsBuilderList() {
return getMetricsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric,
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.Builder,
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetricOrBuilder>
getMetricsFieldBuilder() {
if (metricsBuilder_ == null) {
metricsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric,
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetric.Builder,
com.google.api.serviceusage.v1beta1.ConsumerQuotaMetricOrBuilder>(
metrics_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
metrics_ = null;
}
return metricsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token identifying which result to start with; returned by a previous list
* call.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse)
}
// @@protoc_insertion_point(class_scope:google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse)
private static final com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse();
}
public static com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListConsumerQuotaMetricsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListConsumerQuotaMetricsResponse>() {
@java.lang.Override
public ListConsumerQuotaMetricsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListConsumerQuotaMetricsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListConsumerQuotaMetricsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.api.serviceusage.v1beta1.ListConsumerQuotaMetricsResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/paimon
| 37,457
|
paimon-flink/paimon-flink-cdc/src/test/java/org/apache/paimon/flink/kafka/StreamingReadWriteTableWithKafkaLogITCase.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.paimon.flink.kafka;
import org.apache.paimon.CoreOptions;
import org.apache.paimon.utils.BlockingIterator;
import org.apache.flink.types.Row;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.flink.table.planner.factories.TestValuesTableFactory.changelogRow;
import static org.apache.paimon.CoreOptions.SCAN_MODE;
import static org.apache.paimon.CoreOptions.SCAN_TIMESTAMP_MILLIS;
import static org.apache.paimon.flink.kafka.KafkaLogTestUtils.createTableWithKafkaLog;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.SCAN_LATEST;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.assertNoMoreRecords;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.buildQuery;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.buildQueryWithTableOptions;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.buildSimpleQuery;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.checkFileStorePath;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.createTemporaryTable;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.init;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.insertInto;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.insertIntoFromTable;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.insertIntoPartition;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.insertOverwritePartition;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.testBatchRead;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.testStreamingRead;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.testStreamingReadWithReadFirst;
import static org.apache.paimon.flink.util.ReadWriteTableTestUtil.validateStreamingReadResult;
/** Streaming reading and writing with Kafka log IT cases. */
public class StreamingReadWriteTableWithKafkaLogITCase extends KafkaTableTestBase {
@BeforeEach
public void setUp() {
init(createAndRegisterTempFile("").toString());
}
// ----------------------------------------------------------------------------------------------------------------
// Write First/Kafka log table auto created/scan.mode = latest-full (default setting)
// ----------------------------------------------------------------------------------------------------------------
@Test
public void testReadWriteWithPartitionedRecordsWithPk() throws Exception {
// test hybrid read
List<Row> initialRecords =
Arrays.asList(
// dt = 2022-01-01
changelogRow("+I", "US Dollar", 102L, "2022-01-01"),
changelogRow("+I", "Euro", 114L, "2022-01-01"),
changelogRow("+I", "Yen", 1L, "2022-01-01"),
changelogRow("+U", "Euro", 116L, "2022-01-01"),
changelogRow("-D", "Yen", 1L, "2022-01-01"),
changelogRow("-D", "Euro", 116L, "2022-01-01"),
// dt = 2022-01-02
changelogRow("+I", "Euro", 119L, "2022-01-02"),
changelogRow("+U", "Euro", 119L, "2022-01-02"));
String temporaryTable =
createTemporaryTable(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Arrays.asList("currency", "dt"),
Collections.singletonList("dt"),
initialRecords,
"dt:2022-01-01;dt:2022-01-02",
false,
"I,UA,D");
String table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Arrays.asList("currency", "dt"),
Collections.singletonList("dt"),
false);
insertIntoFromTable(temporaryTable, table);
checkFileStorePath(table, Arrays.asList("dt=2022-01-01", "dt=2022-01-02"));
BlockingIterator<Row, Row> streamItr =
testStreamingRead(
buildQuery(
table,
"*",
"WHERE dt >= '2022-01-01' AND dt <= '2022-01-03' OR currency = 'HK Dollar'"),
Arrays.asList(
changelogRow("+I", "US Dollar", 102L, "2022-01-01"),
changelogRow("+I", "Euro", 119L, "2022-01-02")));
// test log store in hybrid mode accepts all filters
insertIntoPartition(
table, "PARTITION (dt = '2022-01-03')", "('HK Dollar', 100)", "('Yen', 20)");
insertIntoPartition(table, "PARTITION (dt = '2022-01-04')", "('Yen', 20)");
validateStreamingReadResult(
streamItr,
Arrays.asList(
changelogRow("+I", "HK Dollar", 100L, "2022-01-03"),
changelogRow("+I", "Yen", 20L, "2022-01-03")));
// overwrite partition 2022-01-02
insertOverwritePartition(
table, "PARTITION (dt = '2022-01-02')", "('Euro', 100)", "('Yen', 1)");
// check no changelog generated for streaming read
assertNoMoreRecords(streamItr);
streamItr.close();
// batch read to check data refresh
testBatchRead(
buildSimpleQuery(table),
Arrays.asList(
changelogRow("+I", "US Dollar", 102L, "2022-01-01"),
changelogRow("+I", "Euro", 100L, "2022-01-02"),
changelogRow("+I", "Yen", 1L, "2022-01-02"),
changelogRow("+I", "HK Dollar", 100L, "2022-01-03"),
changelogRow("+I", "Yen", 20L, "2022-01-03"),
changelogRow("+I", "Yen", 20L, "2022-01-04")));
// filter on partition
testStreamingRead(
buildQuery(table, "*", "WHERE dt = '2022-01-01'"),
Collections.singletonList(
changelogRow("+I", "US Dollar", 102L, "2022-01-01")))
.close();
// test field filter
testStreamingRead(
buildQuery(table, "*", "WHERE currency = 'US Dollar'"),
Collections.singletonList(
changelogRow("+I", "US Dollar", 102L, "2022-01-01")))
.close();
// test partition and field filter
testStreamingRead(
buildQuery(table, "*", "WHERE dt = '2022-01-01' AND rate = 1"),
Collections.emptyList())
.close();
// test projection and filter
testStreamingRead(
buildQuery(
table,
"rate, dt, currency",
"WHERE dt = '2022-01-02' AND currency = 'Euro'"),
Collections.singletonList(changelogRow("+I", 100L, "2022-01-02", "Euro")))
.close();
}
@Test
public void testSReadWriteWithNonPartitionedRecordsWithPk() throws Exception {
// file store bounded read with merge
List<Row> initialRecords =
Arrays.asList(
changelogRow("+I", "US Dollar", 102L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Yen", 1L),
changelogRow("+U", "Euro", 116L),
changelogRow("-D", "Euro", 116L),
changelogRow("+I", "Euro", 119L),
changelogRow("+U", "Euro", 119L),
changelogRow("-D", "Yen", 1L));
String temporaryTable =
createTemporaryTable(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
initialRecords,
null,
false,
"I, UA, D");
String table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
false);
insertIntoFromTable(temporaryTable, table);
checkFileStorePath(table, Collections.emptyList());
testStreamingRead(
buildSimpleQuery(table),
Arrays.asList(
changelogRow("+I", "US Dollar", 102L),
changelogRow("+I", "Euro", 119L)))
.close();
// test field filter
testStreamingRead(buildQuery(table, "*", "WHERE currency = 'Yen'"), Collections.emptyList())
.close();
// test projection
testStreamingRead(
buildQuery(table, "currency", ""),
Arrays.asList(changelogRow("+I", "US Dollar"), changelogRow("+I", "Euro")))
.close();
// test projection and filter
testStreamingRead(
buildQuery(table, "currency", "WHERE rate = 102"),
Collections.singletonList(changelogRow("+I", "US Dollar")))
.close();
}
// ----------------------------------------------------------------------------------------------------------------
// Read First/Manually create Kafka log table/scan.mode = latest
// ----------------------------------------------------------------------------------------------------------------
@Test
public void testReadLatestChangelogOfPartitionedRecordsWithPk() throws Exception {
List<Row> initialRecords =
Arrays.asList(
// dt = 2022-01-01
changelogRow("+I", "US Dollar", 102L, "2022-01-01"),
changelogRow("+I", "Euro", 114L, "2022-01-01"),
changelogRow("+I", "Yen", 1L, "2022-01-01"),
changelogRow("+U", "Euro", 116L, "2022-01-01"),
changelogRow("-D", "Yen", 1L, "2022-01-01"),
changelogRow("-D", "Euro", 116L, "2022-01-01"),
// dt = 2022-01-02
changelogRow("+I", "Euro", 119L, "2022-01-02"),
changelogRow("+U", "Euro", 119L, "2022-01-02"));
String temporaryTable =
createTemporaryTable(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Arrays.asList("currency", "dt"),
Collections.singletonList("dt"),
initialRecords,
"dt:2022-01-01;dt:2022-01-02",
false,
"I,UA,D");
String table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Arrays.asList("currency", "dt"),
Collections.singletonList("dt"),
true);
BlockingIterator<Row, Row> streamItr =
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(table, "*", "", SCAN_LATEST),
Arrays.asList(
changelogRow("+I", "US Dollar", 102L, "2022-01-01"),
changelogRow("+I", "Euro", 114L, "2022-01-01"),
changelogRow("+I", "Yen", 1L, "2022-01-01"),
changelogRow("-U", "Euro", 114L, "2022-01-01"),
changelogRow("+U", "Euro", 116L, "2022-01-01"),
changelogRow("-D", "Yen", 1L, "2022-01-01"),
changelogRow("-D", "Euro", 116L, "2022-01-01"),
changelogRow("+I", "Euro", 119L, "2022-01-02")));
// test only read the latest log
insertInto(table, "('US Dollar', 104, '2022-01-01')", "('Euro', 100, '2022-01-02')");
validateStreamingReadResult(
streamItr,
Arrays.asList(
changelogRow("-U", "US Dollar", 102L, "2022-01-01"),
changelogRow("+U", "US Dollar", 104L, "2022-01-01"),
changelogRow("-U", "Euro", 119L, "2022-01-02"),
changelogRow("+U", "Euro", 100L, "2022-01-02")));
assertNoMoreRecords(streamItr);
streamItr.close();
// test partition filter
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Arrays.asList("currency", "dt"),
Collections.singletonList("dt"),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(
table, "*", "WHERE dt = '2022-01-01'", SCAN_LATEST),
Arrays.asList(
changelogRow("+I", "US Dollar", 102L, "2022-01-01"),
changelogRow("+I", "Euro", 114L, "2022-01-01"),
changelogRow("+I", "Yen", 1L, "2022-01-01"),
changelogRow("-U", "Euro", 114L, "2022-01-01"),
changelogRow("+U", "Euro", 116L, "2022-01-01"),
changelogRow("-D", "Yen", 1L, "2022-01-01"),
changelogRow("-D", "Euro", 116L, "2022-01-01")))
.close();
// test field filter
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Arrays.asList("currency", "dt"),
Collections.singletonList("dt"),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(
table, "*", "WHERE currency = 'Yen'", SCAN_LATEST),
Arrays.asList(
changelogRow("+I", "Yen", 1L, "2022-01-01"),
changelogRow("-D", "Yen", 1L, "2022-01-01")))
.close();
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Arrays.asList("currency", "dt"),
Collections.singletonList("dt"),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(table, "*", "WHERE rate = 114", SCAN_LATEST),
Arrays.asList(
// part = 2022-01-01
changelogRow("+I", "Euro", 114L, "2022-01-01"),
changelogRow("-U", "Euro", 114L, "2022-01-01")))
.close();
// test partition and field filter
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Arrays.asList("currency", "dt"),
Collections.singletonList("dt"),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(
table, "*", "WHERE rate = 114 AND dt = '2022-01-02'", SCAN_LATEST),
Collections.emptyList())
.close();
// test projection
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Arrays.asList("currency", "dt"),
Collections.singletonList("dt"),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(table, "rate", "", SCAN_LATEST),
Arrays.asList(
// part = 2022-01-01
changelogRow("+I", 102L), // US Dollar
changelogRow("+I", 114L), // Euro
changelogRow("+I", 1L), // Yen
changelogRow("-U", 114L), // Euro
changelogRow("+U", 116L), // Euro
changelogRow("-D", 1L), // Yen
changelogRow("-D", 116L), // Euro
// part = 2022-01-02
changelogRow("+I", 119L) // Euro
))
.close();
// test projection and filter
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Arrays.asList("currency", "dt"),
Collections.singletonList("dt"),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(
table, "rate", "WHERE dt = '2022-01-02'", SCAN_LATEST),
Collections.singletonList(changelogRow("+I", 119L)) // Euro
)
.close();
}
@Test
public void testReadLatestChangelogOfNonPartitionedRecordsWithPk() throws Exception {
List<Row> initialRecords =
Arrays.asList(
changelogRow("+I", "US Dollar", 102L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Yen", 1L),
changelogRow("+U", "Euro", 116L),
changelogRow("-D", "Euro", 116L),
changelogRow("+I", "Euro", 119L),
changelogRow("+U", "Euro", 119L),
changelogRow("-D", "Yen", 1L));
String temporaryTable =
createTemporaryTable(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
initialRecords,
null,
false,
"I,UA,D");
String table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(table, "*", "", SCAN_LATEST),
Arrays.asList(
changelogRow("+I", "US Dollar", 102L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Yen", 1L),
changelogRow("-U", "Euro", 114L),
changelogRow("+U", "Euro", 116L),
changelogRow("-D", "Euro", 116L),
changelogRow("+I", "Euro", 119L),
changelogRow("-D", "Yen", 1L)))
.close();
// test field filter
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(
table, "*", "WHERE currency = 'Euro'", SCAN_LATEST),
Arrays.asList(
changelogRow("+I", "Euro", 114L),
changelogRow("-U", "Euro", 114L),
changelogRow("+U", "Euro", 116L),
changelogRow("-D", "Euro", 116L),
changelogRow("+I", "Euro", 119L)))
.close();
// test projection
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(table, "currency", "", SCAN_LATEST),
Arrays.asList(
changelogRow("+I", "US Dollar"),
changelogRow("+I", "Euro"),
changelogRow("+I", "Yen"),
changelogRow("-D", "Euro"),
changelogRow("+I", "Euro"),
changelogRow("-D", "Yen")))
.close();
// test projection and filter
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(
table, "rate", "WHERE currency = 'Euro'", SCAN_LATEST),
Arrays.asList(
changelogRow("+I", 114L),
changelogRow("-U", 114L),
changelogRow("+U", 116L),
changelogRow("-D", 116L),
changelogRow("+I", 119L)))
.close();
}
@Test
public void testReadLatestChangelogOfInsertOnlyRecords() throws Exception {
List<Row> initialRecords =
Arrays.asList(
changelogRow("+I", "US Dollar", 102L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Yen", 1L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Euro", 119L));
// without pk
String temporaryTable =
createTemporaryTable(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.emptyList(),
Collections.emptyList(),
initialRecords,
null,
true,
"I");
String table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.emptyList(),
Collections.emptyList(),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(table, "*", "", SCAN_LATEST),
initialRecords)
.close();
// currency as pk in the next tests
temporaryTable =
createTemporaryTable(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
initialRecords,
null,
true,
"I");
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(table, "*", "", SCAN_LATEST),
Arrays.asList(
changelogRow("+I", "US Dollar", 102L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Yen", 1L),
changelogRow("-U", "Euro", 114L),
changelogRow("+U", "Euro", 119L)))
.close();
// test field filter
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(table, "*", "WHERE rate = 114", SCAN_LATEST),
Arrays.asList(
changelogRow("+I", "Euro", 114L), changelogRow("-U", "Euro", 114L)))
.close();
// test projection
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(table, "rate", "", SCAN_LATEST),
Arrays.asList(
changelogRow("+I", 102L),
changelogRow("+I", 114L),
changelogRow("+I", 1L),
changelogRow("-U", 114L),
changelogRow("+U", 119L)))
.close();
// test projection and filter
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
true);
testStreamingReadWithReadFirst(
temporaryTable,
table,
buildQueryWithTableOptions(
table, "currency", "WHERE rate = 114", SCAN_LATEST),
Arrays.asList(changelogRow("+I", "Euro"), changelogRow("-U", "Euro")))
.close();
}
// ----------------------------------------------------------------------------------------------------------------
// Write First/Kafka log table auto created/scan.mode = from-timestamp
// ----------------------------------------------------------------------------------------------------------------
@Test
public void testReadInsertOnlyChangelogFromTimestamp() throws Exception {
// test records 0
List<Row> initialRecords0 =
Arrays.asList(
// dt = 2022-01-01
changelogRow("+I", "US Dollar", 102L, "2022-01-01"),
changelogRow("+I", "Euro", 114L, "2022-01-01"),
changelogRow("+I", "Yen", 1L, "2022-01-01"),
changelogRow("+I", "Euro", 114L, "2022-01-01"),
changelogRow("+I", "US Dollar", 114L, "2022-01-01"),
// dt = 2022-01-02
changelogRow("+I", "Euro", 119L, "2022-01-02"));
// partitioned without pk, scan from timestamp 0
String temporaryTable =
createTemporaryTable(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Collections.emptyList(),
Collections.singletonList("dt"),
initialRecords0,
"dt:2022-01-01;dt:2022-01-02",
true,
"I");
String table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Collections.emptyList(),
Collections.singletonList("dt"),
false);
insertIntoFromTable(temporaryTable, table);
testStreamingRead(
buildQueryWithTableOptions(table, "*", "", scanFromTimeStampMillis(0L)),
initialRecords0)
.close();
// partitioned with pk, scan from timestamp 0
temporaryTable =
createTemporaryTable(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Arrays.asList("currency", "dt"),
Collections.singletonList("dt"),
initialRecords0,
"dt:2022-01-01;dt:2022-01-02",
true,
"I");
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT", "dt STRING"),
Arrays.asList("currency", "dt"),
Collections.singletonList("dt"),
false);
insertIntoFromTable(temporaryTable, table);
testStreamingRead(
buildQueryWithTableOptions(table, "*", "", scanFromTimeStampMillis(0L)),
Arrays.asList(
changelogRow("+I", "US Dollar", 102L, "2022-01-01"),
changelogRow("+I", "Yen", 1L, "2022-01-01"),
changelogRow("+I", "Euro", 114L, "2022-01-01"),
changelogRow("-U", "US Dollar", 102L, "2022-01-01"),
changelogRow("+U", "US Dollar", 114L, "2022-01-01"),
changelogRow("+I", "Euro", 119L, "2022-01-02")))
.close();
// test records 1
List<Row> initialRecords1 =
Arrays.asList(
changelogRow("+I", "US Dollar", 102L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Yen", 1L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Euro", 119L));
// non-partitioned with pk, scan from timestamp 0
temporaryTable =
createTemporaryTable(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
initialRecords1,
null,
true,
"I");
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.singletonList("currency"),
Collections.emptyList(),
false);
insertIntoFromTable(temporaryTable, table);
testStreamingRead(
buildQueryWithTableOptions(table, "*", "", scanFromTimeStampMillis(0L)),
Arrays.asList(
changelogRow("+I", "US Dollar", 102L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Yen", 1L),
changelogRow("-U", "Euro", 114L),
changelogRow("+U", "Euro", 119L)))
.close();
// non-partitioned without pk, scan from timestamp 0
temporaryTable =
createTemporaryTable(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.emptyList(),
Collections.emptyList(),
initialRecords1,
null,
true,
"I");
table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.emptyList(),
Collections.emptyList(),
false);
insertIntoFromTable(temporaryTable, table);
testStreamingRead(
buildQueryWithTableOptions(table, "*", "", scanFromTimeStampMillis(0L)),
initialRecords1)
.close();
}
@Test
public void testReadInsertOnlyChangelogFromEnormousTimestamp() throws Exception {
List<Row> initialRecords =
Arrays.asList(
changelogRow("+I", "US Dollar", 102L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Yen", 1L),
changelogRow("+I", "Euro", 114L),
changelogRow("+I", "Euro", 119L));
// non-partitioned without pk, scan from timestamp Long.MAX_VALUE - 1
String temporaryTable =
createTemporaryTable(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.emptyList(),
Collections.emptyList(),
initialRecords,
null,
true,
"I");
String table =
createTableWithKafkaLog(
Arrays.asList("currency STRING", "rate BIGINT"),
Collections.emptyList(),
Collections.emptyList(),
false);
insertIntoFromTable(temporaryTable, table);
testStreamingRead(
buildQueryWithTableOptions(
table, "*", "", scanFromTimeStampMillis(Long.MAX_VALUE - 1)),
Collections.emptyList())
.close();
}
// ----------------------------------------------------------------------------------------------------------------
// Tools
// ----------------------------------------------------------------------------------------------------------------
private Map<String, String> scanFromTimeStampMillis(Long timeStampMillis) {
return new HashMap<String, String>() {
{
put(SCAN_MODE.key(), CoreOptions.StartupMode.FROM_TIMESTAMP.toString());
put(SCAN_TIMESTAMP_MILLIS.key(), String.valueOf(timeStampMillis));
}
};
}
}
|
googleapis/google-cloud-java
| 38,197
|
java-telcoautomation/proto-google-cloud-telcoautomation-v1/src/main/java/com/google/cloud/telcoautomation/v1/SearchDeploymentRevisionsResponse.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/telcoautomation/v1/telcoautomation.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.telcoautomation.v1;
/**
*
*
* <pre>
* Response object for `SearchDeploymentRevisions`.
* </pre>
*
* Protobuf type {@code google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse}
*/
public final class SearchDeploymentRevisionsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse)
SearchDeploymentRevisionsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use SearchDeploymentRevisionsResponse.newBuilder() to construct.
private SearchDeploymentRevisionsResponse(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SearchDeploymentRevisionsResponse() {
deployments_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SearchDeploymentRevisionsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.telcoautomation.v1.TelcoautomationProto
.internal_static_google_cloud_telcoautomation_v1_SearchDeploymentRevisionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.telcoautomation.v1.TelcoautomationProto
.internal_static_google_cloud_telcoautomation_v1_SearchDeploymentRevisionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse.class,
com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse.Builder.class);
}
public static final int DEPLOYMENTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.telcoautomation.v1.Deployment> deployments_;
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.telcoautomation.v1.Deployment> getDeploymentsList() {
return deployments_;
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.telcoautomation.v1.DeploymentOrBuilder>
getDeploymentsOrBuilderList() {
return deployments_;
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
@java.lang.Override
public int getDeploymentsCount() {
return deployments_.size();
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
@java.lang.Override
public com.google.cloud.telcoautomation.v1.Deployment getDeployments(int index) {
return deployments_.get(index);
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
@java.lang.Override
public com.google.cloud.telcoautomation.v1.DeploymentOrBuilder getDeploymentsOrBuilder(
int index) {
return deployments_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token that can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < deployments_.size(); i++) {
output.writeMessage(1, deployments_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < deployments_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, deployments_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse)) {
return super.equals(obj);
}
com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse other =
(com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse) obj;
if (!getDeploymentsList().equals(other.getDeploymentsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getDeploymentsCount() > 0) {
hash = (37 * hash) + DEPLOYMENTS_FIELD_NUMBER;
hash = (53 * hash) + getDeploymentsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response object for `SearchDeploymentRevisions`.
* </pre>
*
* Protobuf type {@code google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse)
com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.telcoautomation.v1.TelcoautomationProto
.internal_static_google_cloud_telcoautomation_v1_SearchDeploymentRevisionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.telcoautomation.v1.TelcoautomationProto
.internal_static_google_cloud_telcoautomation_v1_SearchDeploymentRevisionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse.class,
com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse.Builder.class);
}
// Construct using
// com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (deploymentsBuilder_ == null) {
deployments_ = java.util.Collections.emptyList();
} else {
deployments_ = null;
deploymentsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.telcoautomation.v1.TelcoautomationProto
.internal_static_google_cloud_telcoautomation_v1_SearchDeploymentRevisionsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse
getDefaultInstanceForType() {
return com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse build() {
com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse buildPartial() {
com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse result =
new com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse result) {
if (deploymentsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
deployments_ = java.util.Collections.unmodifiableList(deployments_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.deployments_ = deployments_;
} else {
result.deployments_ = deploymentsBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse) {
return mergeFrom(
(com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse other) {
if (other
== com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse
.getDefaultInstance()) return this;
if (deploymentsBuilder_ == null) {
if (!other.deployments_.isEmpty()) {
if (deployments_.isEmpty()) {
deployments_ = other.deployments_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureDeploymentsIsMutable();
deployments_.addAll(other.deployments_);
}
onChanged();
}
} else {
if (!other.deployments_.isEmpty()) {
if (deploymentsBuilder_.isEmpty()) {
deploymentsBuilder_.dispose();
deploymentsBuilder_ = null;
deployments_ = other.deployments_;
bitField0_ = (bitField0_ & ~0x00000001);
deploymentsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getDeploymentsFieldBuilder()
: null;
} else {
deploymentsBuilder_.addAllMessages(other.deployments_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.telcoautomation.v1.Deployment m =
input.readMessage(
com.google.cloud.telcoautomation.v1.Deployment.parser(), extensionRegistry);
if (deploymentsBuilder_ == null) {
ensureDeploymentsIsMutable();
deployments_.add(m);
} else {
deploymentsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.telcoautomation.v1.Deployment> deployments_ =
java.util.Collections.emptyList();
private void ensureDeploymentsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
deployments_ =
new java.util.ArrayList<com.google.cloud.telcoautomation.v1.Deployment>(deployments_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.telcoautomation.v1.Deployment,
com.google.cloud.telcoautomation.v1.Deployment.Builder,
com.google.cloud.telcoautomation.v1.DeploymentOrBuilder>
deploymentsBuilder_;
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public java.util.List<com.google.cloud.telcoautomation.v1.Deployment> getDeploymentsList() {
if (deploymentsBuilder_ == null) {
return java.util.Collections.unmodifiableList(deployments_);
} else {
return deploymentsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public int getDeploymentsCount() {
if (deploymentsBuilder_ == null) {
return deployments_.size();
} else {
return deploymentsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public com.google.cloud.telcoautomation.v1.Deployment getDeployments(int index) {
if (deploymentsBuilder_ == null) {
return deployments_.get(index);
} else {
return deploymentsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public Builder setDeployments(int index, com.google.cloud.telcoautomation.v1.Deployment value) {
if (deploymentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDeploymentsIsMutable();
deployments_.set(index, value);
onChanged();
} else {
deploymentsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public Builder setDeployments(
int index, com.google.cloud.telcoautomation.v1.Deployment.Builder builderForValue) {
if (deploymentsBuilder_ == null) {
ensureDeploymentsIsMutable();
deployments_.set(index, builderForValue.build());
onChanged();
} else {
deploymentsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public Builder addDeployments(com.google.cloud.telcoautomation.v1.Deployment value) {
if (deploymentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDeploymentsIsMutable();
deployments_.add(value);
onChanged();
} else {
deploymentsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public Builder addDeployments(int index, com.google.cloud.telcoautomation.v1.Deployment value) {
if (deploymentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDeploymentsIsMutable();
deployments_.add(index, value);
onChanged();
} else {
deploymentsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public Builder addDeployments(
com.google.cloud.telcoautomation.v1.Deployment.Builder builderForValue) {
if (deploymentsBuilder_ == null) {
ensureDeploymentsIsMutable();
deployments_.add(builderForValue.build());
onChanged();
} else {
deploymentsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public Builder addDeployments(
int index, com.google.cloud.telcoautomation.v1.Deployment.Builder builderForValue) {
if (deploymentsBuilder_ == null) {
ensureDeploymentsIsMutable();
deployments_.add(index, builderForValue.build());
onChanged();
} else {
deploymentsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public Builder addAllDeployments(
java.lang.Iterable<? extends com.google.cloud.telcoautomation.v1.Deployment> values) {
if (deploymentsBuilder_ == null) {
ensureDeploymentsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, deployments_);
onChanged();
} else {
deploymentsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public Builder clearDeployments() {
if (deploymentsBuilder_ == null) {
deployments_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
deploymentsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public Builder removeDeployments(int index) {
if (deploymentsBuilder_ == null) {
ensureDeploymentsIsMutable();
deployments_.remove(index);
onChanged();
} else {
deploymentsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public com.google.cloud.telcoautomation.v1.Deployment.Builder getDeploymentsBuilder(int index) {
return getDeploymentsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public com.google.cloud.telcoautomation.v1.DeploymentOrBuilder getDeploymentsOrBuilder(
int index) {
if (deploymentsBuilder_ == null) {
return deployments_.get(index);
} else {
return deploymentsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public java.util.List<? extends com.google.cloud.telcoautomation.v1.DeploymentOrBuilder>
getDeploymentsOrBuilderList() {
if (deploymentsBuilder_ != null) {
return deploymentsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(deployments_);
}
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public com.google.cloud.telcoautomation.v1.Deployment.Builder addDeploymentsBuilder() {
return getDeploymentsFieldBuilder()
.addBuilder(com.google.cloud.telcoautomation.v1.Deployment.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public com.google.cloud.telcoautomation.v1.Deployment.Builder addDeploymentsBuilder(int index) {
return getDeploymentsFieldBuilder()
.addBuilder(index, com.google.cloud.telcoautomation.v1.Deployment.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of requested deployment revisions.
* </pre>
*
* <code>repeated .google.cloud.telcoautomation.v1.Deployment deployments = 1;</code>
*/
public java.util.List<com.google.cloud.telcoautomation.v1.Deployment.Builder>
getDeploymentsBuilderList() {
return getDeploymentsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.telcoautomation.v1.Deployment,
com.google.cloud.telcoautomation.v1.Deployment.Builder,
com.google.cloud.telcoautomation.v1.DeploymentOrBuilder>
getDeploymentsFieldBuilder() {
if (deploymentsBuilder_ == null) {
deploymentsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.telcoautomation.v1.Deployment,
com.google.cloud.telcoautomation.v1.Deployment.Builder,
com.google.cloud.telcoautomation.v1.DeploymentOrBuilder>(
deployments_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
deployments_ = null;
}
return deploymentsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token that can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token that can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token that can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token that can be sent as `page_token` to retrieve the next page.
* If this field is omitted, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse)
private static final com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse();
}
public static com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SearchDeploymentRevisionsResponse> PARSER =
new com.google.protobuf.AbstractParser<SearchDeploymentRevisionsResponse>() {
@java.lang.Override
public SearchDeploymentRevisionsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<SearchDeploymentRevisionsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SearchDeploymentRevisionsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.telcoautomation.v1.SearchDeploymentRevisionsResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,489
|
java-speech/google-cloud-speech/src/main/java/com/google/cloud/speech/v1p1beta1/stub/HttpJsonAdaptationStub.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.speech.v1p1beta1.stub;
import static com.google.cloud.speech.v1p1beta1.AdaptationClient.ListCustomClassesPagedResponse;
import static com.google.cloud.speech.v1p1beta1.AdaptationClient.ListPhraseSetPagedResponse;
import com.google.api.core.BetaApi;
import com.google.api.core.InternalApi;
import com.google.api.gax.core.BackgroundResource;
import com.google.api.gax.core.BackgroundResourceAggregation;
import com.google.api.gax.httpjson.ApiMethodDescriptor;
import com.google.api.gax.httpjson.HttpJsonCallSettings;
import com.google.api.gax.httpjson.HttpJsonStubCallableFactory;
import com.google.api.gax.httpjson.ProtoMessageRequestFormatter;
import com.google.api.gax.httpjson.ProtoMessageResponseParser;
import com.google.api.gax.httpjson.ProtoRestSerializer;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.RequestParamsBuilder;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.speech.v1p1beta1.CreateCustomClassRequest;
import com.google.cloud.speech.v1p1beta1.CreatePhraseSetRequest;
import com.google.cloud.speech.v1p1beta1.CustomClass;
import com.google.cloud.speech.v1p1beta1.DeleteCustomClassRequest;
import com.google.cloud.speech.v1p1beta1.DeletePhraseSetRequest;
import com.google.cloud.speech.v1p1beta1.GetCustomClassRequest;
import com.google.cloud.speech.v1p1beta1.GetPhraseSetRequest;
import com.google.cloud.speech.v1p1beta1.ListCustomClassesRequest;
import com.google.cloud.speech.v1p1beta1.ListCustomClassesResponse;
import com.google.cloud.speech.v1p1beta1.ListPhraseSetRequest;
import com.google.cloud.speech.v1p1beta1.ListPhraseSetResponse;
import com.google.cloud.speech.v1p1beta1.PhraseSet;
import com.google.cloud.speech.v1p1beta1.UpdateCustomClassRequest;
import com.google.cloud.speech.v1p1beta1.UpdatePhraseSetRequest;
import com.google.protobuf.Empty;
import com.google.protobuf.TypeRegistry;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* REST stub implementation for the Adaptation service API.
*
* <p>This class is for advanced usage and reflects the underlying API directly.
*/
@BetaApi
@Generated("by gapic-generator-java")
public class HttpJsonAdaptationStub extends AdaptationStub {
private static final TypeRegistry typeRegistry = TypeRegistry.newBuilder().build();
private static final ApiMethodDescriptor<CreatePhraseSetRequest, PhraseSet>
createPhraseSetMethodDescriptor =
ApiMethodDescriptor.<CreatePhraseSetRequest, PhraseSet>newBuilder()
.setFullMethodName("google.cloud.speech.v1p1beta1.Adaptation/CreatePhraseSet")
.setHttpMethod("POST")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<CreatePhraseSetRequest>newBuilder()
.setPath(
"/v1p1beta1/{parent=projects/*/locations/*}/phraseSets",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<CreatePhraseSetRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "parent", request.getParent());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<CreatePhraseSetRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(
request ->
ProtoRestSerializer.create()
.toBody("*", request.toBuilder().clearParent().build(), true))
.build())
.setResponseParser(
ProtoMessageResponseParser.<PhraseSet>newBuilder()
.setDefaultInstance(PhraseSet.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<GetPhraseSetRequest, PhraseSet>
getPhraseSetMethodDescriptor =
ApiMethodDescriptor.<GetPhraseSetRequest, PhraseSet>newBuilder()
.setFullMethodName("google.cloud.speech.v1p1beta1.Adaptation/GetPhraseSet")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<GetPhraseSetRequest>newBuilder()
.setPath(
"/v1p1beta1/{name=projects/*/locations/*/phraseSets/*}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<GetPhraseSetRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "name", request.getName());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<GetPhraseSetRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<PhraseSet>newBuilder()
.setDefaultInstance(PhraseSet.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<ListPhraseSetRequest, ListPhraseSetResponse>
listPhraseSetMethodDescriptor =
ApiMethodDescriptor.<ListPhraseSetRequest, ListPhraseSetResponse>newBuilder()
.setFullMethodName("google.cloud.speech.v1p1beta1.Adaptation/ListPhraseSet")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<ListPhraseSetRequest>newBuilder()
.setPath(
"/v1p1beta1/{parent=projects/*/locations/*}/phraseSets",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<ListPhraseSetRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "parent", request.getParent());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<ListPhraseSetRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "pageSize", request.getPageSize());
serializer.putQueryParam(fields, "pageToken", request.getPageToken());
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<ListPhraseSetResponse>newBuilder()
.setDefaultInstance(ListPhraseSetResponse.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<UpdatePhraseSetRequest, PhraseSet>
updatePhraseSetMethodDescriptor =
ApiMethodDescriptor.<UpdatePhraseSetRequest, PhraseSet>newBuilder()
.setFullMethodName("google.cloud.speech.v1p1beta1.Adaptation/UpdatePhraseSet")
.setHttpMethod("PATCH")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<UpdatePhraseSetRequest>newBuilder()
.setPath(
"/v1p1beta1/{phraseSet.name=projects/*/locations/*/phraseSets/*}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<UpdatePhraseSetRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(
fields, "phraseSet.name", request.getPhraseSet().getName());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<UpdatePhraseSetRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "updateMask", request.getUpdateMask());
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(
request ->
ProtoRestSerializer.create()
.toBody("phraseSet", request.getPhraseSet(), true))
.build())
.setResponseParser(
ProtoMessageResponseParser.<PhraseSet>newBuilder()
.setDefaultInstance(PhraseSet.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<DeletePhraseSetRequest, Empty>
deletePhraseSetMethodDescriptor =
ApiMethodDescriptor.<DeletePhraseSetRequest, Empty>newBuilder()
.setFullMethodName("google.cloud.speech.v1p1beta1.Adaptation/DeletePhraseSet")
.setHttpMethod("DELETE")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<DeletePhraseSetRequest>newBuilder()
.setPath(
"/v1p1beta1/{name=projects/*/locations/*/phraseSets/*}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<DeletePhraseSetRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "name", request.getName());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<DeletePhraseSetRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<Empty>newBuilder()
.setDefaultInstance(Empty.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<CreateCustomClassRequest, CustomClass>
createCustomClassMethodDescriptor =
ApiMethodDescriptor.<CreateCustomClassRequest, CustomClass>newBuilder()
.setFullMethodName("google.cloud.speech.v1p1beta1.Adaptation/CreateCustomClass")
.setHttpMethod("POST")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<CreateCustomClassRequest>newBuilder()
.setPath(
"/v1p1beta1/{parent=projects/*/locations/*}/customClasses",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<CreateCustomClassRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "parent", request.getParent());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<CreateCustomClassRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(
request ->
ProtoRestSerializer.create()
.toBody("*", request.toBuilder().clearParent().build(), true))
.build())
.setResponseParser(
ProtoMessageResponseParser.<CustomClass>newBuilder()
.setDefaultInstance(CustomClass.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<GetCustomClassRequest, CustomClass>
getCustomClassMethodDescriptor =
ApiMethodDescriptor.<GetCustomClassRequest, CustomClass>newBuilder()
.setFullMethodName("google.cloud.speech.v1p1beta1.Adaptation/GetCustomClass")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<GetCustomClassRequest>newBuilder()
.setPath(
"/v1p1beta1/{name=projects/*/locations/*/customClasses/*}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<GetCustomClassRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "name", request.getName());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<GetCustomClassRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<CustomClass>newBuilder()
.setDefaultInstance(CustomClass.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<ListCustomClassesRequest, ListCustomClassesResponse>
listCustomClassesMethodDescriptor =
ApiMethodDescriptor.<ListCustomClassesRequest, ListCustomClassesResponse>newBuilder()
.setFullMethodName("google.cloud.speech.v1p1beta1.Adaptation/ListCustomClasses")
.setHttpMethod("GET")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<ListCustomClassesRequest>newBuilder()
.setPath(
"/v1p1beta1/{parent=projects/*/locations/*}/customClasses",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<ListCustomClassesRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "parent", request.getParent());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<ListCustomClassesRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "pageSize", request.getPageSize());
serializer.putQueryParam(fields, "pageToken", request.getPageToken());
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<ListCustomClassesResponse>newBuilder()
.setDefaultInstance(ListCustomClassesResponse.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<UpdateCustomClassRequest, CustomClass>
updateCustomClassMethodDescriptor =
ApiMethodDescriptor.<UpdateCustomClassRequest, CustomClass>newBuilder()
.setFullMethodName("google.cloud.speech.v1p1beta1.Adaptation/UpdateCustomClass")
.setHttpMethod("PATCH")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<UpdateCustomClassRequest>newBuilder()
.setPath(
"/v1p1beta1/{customClass.name=projects/*/locations/*/customClasses/*}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<UpdateCustomClassRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(
fields, "customClass.name", request.getCustomClass().getName());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<UpdateCustomClassRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "updateMask", request.getUpdateMask());
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(
request ->
ProtoRestSerializer.create()
.toBody("customClass", request.getCustomClass(), true))
.build())
.setResponseParser(
ProtoMessageResponseParser.<CustomClass>newBuilder()
.setDefaultInstance(CustomClass.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private static final ApiMethodDescriptor<DeleteCustomClassRequest, Empty>
deleteCustomClassMethodDescriptor =
ApiMethodDescriptor.<DeleteCustomClassRequest, Empty>newBuilder()
.setFullMethodName("google.cloud.speech.v1p1beta1.Adaptation/DeleteCustomClass")
.setHttpMethod("DELETE")
.setType(ApiMethodDescriptor.MethodType.UNARY)
.setRequestFormatter(
ProtoMessageRequestFormatter.<DeleteCustomClassRequest>newBuilder()
.setPath(
"/v1p1beta1/{name=projects/*/locations/*/customClasses/*}",
request -> {
Map<String, String> fields = new HashMap<>();
ProtoRestSerializer<DeleteCustomClassRequest> serializer =
ProtoRestSerializer.create();
serializer.putPathParam(fields, "name", request.getName());
return fields;
})
.setQueryParamsExtractor(
request -> {
Map<String, List<String>> fields = new HashMap<>();
ProtoRestSerializer<DeleteCustomClassRequest> serializer =
ProtoRestSerializer.create();
serializer.putQueryParam(fields, "$alt", "json;enum-encoding=int");
return fields;
})
.setRequestBodyExtractor(request -> null)
.build())
.setResponseParser(
ProtoMessageResponseParser.<Empty>newBuilder()
.setDefaultInstance(Empty.getDefaultInstance())
.setDefaultTypeRegistry(typeRegistry)
.build())
.build();
private final UnaryCallable<CreatePhraseSetRequest, PhraseSet> createPhraseSetCallable;
private final UnaryCallable<GetPhraseSetRequest, PhraseSet> getPhraseSetCallable;
private final UnaryCallable<ListPhraseSetRequest, ListPhraseSetResponse> listPhraseSetCallable;
private final UnaryCallable<ListPhraseSetRequest, ListPhraseSetPagedResponse>
listPhraseSetPagedCallable;
private final UnaryCallable<UpdatePhraseSetRequest, PhraseSet> updatePhraseSetCallable;
private final UnaryCallable<DeletePhraseSetRequest, Empty> deletePhraseSetCallable;
private final UnaryCallable<CreateCustomClassRequest, CustomClass> createCustomClassCallable;
private final UnaryCallable<GetCustomClassRequest, CustomClass> getCustomClassCallable;
private final UnaryCallable<ListCustomClassesRequest, ListCustomClassesResponse>
listCustomClassesCallable;
private final UnaryCallable<ListCustomClassesRequest, ListCustomClassesPagedResponse>
listCustomClassesPagedCallable;
private final UnaryCallable<UpdateCustomClassRequest, CustomClass> updateCustomClassCallable;
private final UnaryCallable<DeleteCustomClassRequest, Empty> deleteCustomClassCallable;
private final BackgroundResource backgroundResources;
private final HttpJsonStubCallableFactory callableFactory;
public static final HttpJsonAdaptationStub create(AdaptationStubSettings settings)
throws IOException {
return new HttpJsonAdaptationStub(settings, ClientContext.create(settings));
}
public static final HttpJsonAdaptationStub create(ClientContext clientContext)
throws IOException {
return new HttpJsonAdaptationStub(
AdaptationStubSettings.newHttpJsonBuilder().build(), clientContext);
}
public static final HttpJsonAdaptationStub create(
ClientContext clientContext, HttpJsonStubCallableFactory callableFactory) throws IOException {
return new HttpJsonAdaptationStub(
AdaptationStubSettings.newHttpJsonBuilder().build(), clientContext, callableFactory);
}
/**
* Constructs an instance of HttpJsonAdaptationStub, using the given settings. This is protected
* so that it is easy to make a subclass, but otherwise, the static factory methods should be
* preferred.
*/
protected HttpJsonAdaptationStub(AdaptationStubSettings settings, ClientContext clientContext)
throws IOException {
this(settings, clientContext, new HttpJsonAdaptationCallableFactory());
}
/**
* Constructs an instance of HttpJsonAdaptationStub, using the given settings. This is protected
* so that it is easy to make a subclass, but otherwise, the static factory methods should be
* preferred.
*/
protected HttpJsonAdaptationStub(
AdaptationStubSettings settings,
ClientContext clientContext,
HttpJsonStubCallableFactory callableFactory)
throws IOException {
this.callableFactory = callableFactory;
HttpJsonCallSettings<CreatePhraseSetRequest, PhraseSet> createPhraseSetTransportSettings =
HttpJsonCallSettings.<CreatePhraseSetRequest, PhraseSet>newBuilder()
.setMethodDescriptor(createPhraseSetMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
HttpJsonCallSettings<GetPhraseSetRequest, PhraseSet> getPhraseSetTransportSettings =
HttpJsonCallSettings.<GetPhraseSetRequest, PhraseSet>newBuilder()
.setMethodDescriptor(getPhraseSetMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
HttpJsonCallSettings<ListPhraseSetRequest, ListPhraseSetResponse>
listPhraseSetTransportSettings =
HttpJsonCallSettings.<ListPhraseSetRequest, ListPhraseSetResponse>newBuilder()
.setMethodDescriptor(listPhraseSetMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
HttpJsonCallSettings<UpdatePhraseSetRequest, PhraseSet> updatePhraseSetTransportSettings =
HttpJsonCallSettings.<UpdatePhraseSetRequest, PhraseSet>newBuilder()
.setMethodDescriptor(updatePhraseSetMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("phrase_set.name", String.valueOf(request.getPhraseSet().getName()));
return builder.build();
})
.build();
HttpJsonCallSettings<DeletePhraseSetRequest, Empty> deletePhraseSetTransportSettings =
HttpJsonCallSettings.<DeletePhraseSetRequest, Empty>newBuilder()
.setMethodDescriptor(deletePhraseSetMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
HttpJsonCallSettings<CreateCustomClassRequest, CustomClass> createCustomClassTransportSettings =
HttpJsonCallSettings.<CreateCustomClassRequest, CustomClass>newBuilder()
.setMethodDescriptor(createCustomClassMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
HttpJsonCallSettings<GetCustomClassRequest, CustomClass> getCustomClassTransportSettings =
HttpJsonCallSettings.<GetCustomClassRequest, CustomClass>newBuilder()
.setMethodDescriptor(getCustomClassMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
HttpJsonCallSettings<ListCustomClassesRequest, ListCustomClassesResponse>
listCustomClassesTransportSettings =
HttpJsonCallSettings.<ListCustomClassesRequest, ListCustomClassesResponse>newBuilder()
.setMethodDescriptor(listCustomClassesMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("parent", String.valueOf(request.getParent()));
return builder.build();
})
.build();
HttpJsonCallSettings<UpdateCustomClassRequest, CustomClass> updateCustomClassTransportSettings =
HttpJsonCallSettings.<UpdateCustomClassRequest, CustomClass>newBuilder()
.setMethodDescriptor(updateCustomClassMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add(
"custom_class.name", String.valueOf(request.getCustomClass().getName()));
return builder.build();
})
.build();
HttpJsonCallSettings<DeleteCustomClassRequest, Empty> deleteCustomClassTransportSettings =
HttpJsonCallSettings.<DeleteCustomClassRequest, Empty>newBuilder()
.setMethodDescriptor(deleteCustomClassMethodDescriptor)
.setTypeRegistry(typeRegistry)
.setParamsExtractor(
request -> {
RequestParamsBuilder builder = RequestParamsBuilder.create();
builder.add("name", String.valueOf(request.getName()));
return builder.build();
})
.build();
this.createPhraseSetCallable =
callableFactory.createUnaryCallable(
createPhraseSetTransportSettings, settings.createPhraseSetSettings(), clientContext);
this.getPhraseSetCallable =
callableFactory.createUnaryCallable(
getPhraseSetTransportSettings, settings.getPhraseSetSettings(), clientContext);
this.listPhraseSetCallable =
callableFactory.createUnaryCallable(
listPhraseSetTransportSettings, settings.listPhraseSetSettings(), clientContext);
this.listPhraseSetPagedCallable =
callableFactory.createPagedCallable(
listPhraseSetTransportSettings, settings.listPhraseSetSettings(), clientContext);
this.updatePhraseSetCallable =
callableFactory.createUnaryCallable(
updatePhraseSetTransportSettings, settings.updatePhraseSetSettings(), clientContext);
this.deletePhraseSetCallable =
callableFactory.createUnaryCallable(
deletePhraseSetTransportSettings, settings.deletePhraseSetSettings(), clientContext);
this.createCustomClassCallable =
callableFactory.createUnaryCallable(
createCustomClassTransportSettings,
settings.createCustomClassSettings(),
clientContext);
this.getCustomClassCallable =
callableFactory.createUnaryCallable(
getCustomClassTransportSettings, settings.getCustomClassSettings(), clientContext);
this.listCustomClassesCallable =
callableFactory.createUnaryCallable(
listCustomClassesTransportSettings,
settings.listCustomClassesSettings(),
clientContext);
this.listCustomClassesPagedCallable =
callableFactory.createPagedCallable(
listCustomClassesTransportSettings,
settings.listCustomClassesSettings(),
clientContext);
this.updateCustomClassCallable =
callableFactory.createUnaryCallable(
updateCustomClassTransportSettings,
settings.updateCustomClassSettings(),
clientContext);
this.deleteCustomClassCallable =
callableFactory.createUnaryCallable(
deleteCustomClassTransportSettings,
settings.deleteCustomClassSettings(),
clientContext);
this.backgroundResources =
new BackgroundResourceAggregation(clientContext.getBackgroundResources());
}
@InternalApi
public static List<ApiMethodDescriptor> getMethodDescriptors() {
List<ApiMethodDescriptor> methodDescriptors = new ArrayList<>();
methodDescriptors.add(createPhraseSetMethodDescriptor);
methodDescriptors.add(getPhraseSetMethodDescriptor);
methodDescriptors.add(listPhraseSetMethodDescriptor);
methodDescriptors.add(updatePhraseSetMethodDescriptor);
methodDescriptors.add(deletePhraseSetMethodDescriptor);
methodDescriptors.add(createCustomClassMethodDescriptor);
methodDescriptors.add(getCustomClassMethodDescriptor);
methodDescriptors.add(listCustomClassesMethodDescriptor);
methodDescriptors.add(updateCustomClassMethodDescriptor);
methodDescriptors.add(deleteCustomClassMethodDescriptor);
return methodDescriptors;
}
@Override
public UnaryCallable<CreatePhraseSetRequest, PhraseSet> createPhraseSetCallable() {
return createPhraseSetCallable;
}
@Override
public UnaryCallable<GetPhraseSetRequest, PhraseSet> getPhraseSetCallable() {
return getPhraseSetCallable;
}
@Override
public UnaryCallable<ListPhraseSetRequest, ListPhraseSetResponse> listPhraseSetCallable() {
return listPhraseSetCallable;
}
@Override
public UnaryCallable<ListPhraseSetRequest, ListPhraseSetPagedResponse>
listPhraseSetPagedCallable() {
return listPhraseSetPagedCallable;
}
@Override
public UnaryCallable<UpdatePhraseSetRequest, PhraseSet> updatePhraseSetCallable() {
return updatePhraseSetCallable;
}
@Override
public UnaryCallable<DeletePhraseSetRequest, Empty> deletePhraseSetCallable() {
return deletePhraseSetCallable;
}
@Override
public UnaryCallable<CreateCustomClassRequest, CustomClass> createCustomClassCallable() {
return createCustomClassCallable;
}
@Override
public UnaryCallable<GetCustomClassRequest, CustomClass> getCustomClassCallable() {
return getCustomClassCallable;
}
@Override
public UnaryCallable<ListCustomClassesRequest, ListCustomClassesResponse>
listCustomClassesCallable() {
return listCustomClassesCallable;
}
@Override
public UnaryCallable<ListCustomClassesRequest, ListCustomClassesPagedResponse>
listCustomClassesPagedCallable() {
return listCustomClassesPagedCallable;
}
@Override
public UnaryCallable<UpdateCustomClassRequest, CustomClass> updateCustomClassCallable() {
return updateCustomClassCallable;
}
@Override
public UnaryCallable<DeleteCustomClassRequest, Empty> deleteCustomClassCallable() {
return deleteCustomClassCallable;
}
@Override
public final void close() {
try {
backgroundResources.close();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new IllegalStateException("Failed to close resource", e);
}
}
@Override
public void shutdown() {
backgroundResources.shutdown();
}
@Override
public boolean isShutdown() {
return backgroundResources.isShutdown();
}
@Override
public boolean isTerminated() {
return backgroundResources.isTerminated();
}
@Override
public void shutdownNow() {
backgroundResources.shutdownNow();
}
@Override
public boolean awaitTermination(long duration, TimeUnit unit) throws InterruptedException {
return backgroundResources.awaitTermination(duration, unit);
}
}
|
googleapis/google-cloud-java
| 38,266
|
java-securitycenter/proto-google-cloud-securitycenter-v1/src/main/java/com/google/cloud/securitycenter/v1/UpdateEventThreatDetectionCustomModuleRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/securitycenter/v1/securitycenter_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.securitycenter.v1;
/**
*
*
* <pre>
* Request to update an Event Threat Detection custom module.
* </pre>
*
* Protobuf type {@code
* google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest}
*/
public final class UpdateEventThreatDetectionCustomModuleRequest
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest)
UpdateEventThreatDetectionCustomModuleRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateEventThreatDetectionCustomModuleRequest.newBuilder() to construct.
private UpdateEventThreatDetectionCustomModuleRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateEventThreatDetectionCustomModuleRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateEventThreatDetectionCustomModuleRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_UpdateEventThreatDetectionCustomModuleRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_UpdateEventThreatDetectionCustomModuleRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest.class,
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest.Builder
.class);
}
private int bitField0_;
public static final int EVENT_THREAT_DETECTION_CUSTOM_MODULE_FIELD_NUMBER = 1;
private com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule
eventThreatDetectionCustomModule_;
/**
*
*
* <pre>
* Required. The module being updated.
* </pre>
*
* <code>
* .google.cloud.securitycenter.v1.EventThreatDetectionCustomModule event_threat_detection_custom_module = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the eventThreatDetectionCustomModule field is set.
*/
@java.lang.Override
public boolean hasEventThreatDetectionCustomModule() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The module being updated.
* </pre>
*
* <code>
* .google.cloud.securitycenter.v1.EventThreatDetectionCustomModule event_threat_detection_custom_module = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The eventThreatDetectionCustomModule.
*/
@java.lang.Override
public com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule
getEventThreatDetectionCustomModule() {
return eventThreatDetectionCustomModule_ == null
? com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule.getDefaultInstance()
: eventThreatDetectionCustomModule_;
}
/**
*
*
* <pre>
* Required. The module being updated.
* </pre>
*
* <code>
* .google.cloud.securitycenter.v1.EventThreatDetectionCustomModule event_threat_detection_custom_module = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModuleOrBuilder
getEventThreatDetectionCustomModuleOrBuilder() {
return eventThreatDetectionCustomModule_ == null
? com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule.getDefaultInstance()
: eventThreatDetectionCustomModule_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* The list of fields to be updated.
* If empty all mutable fields will be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The list of fields to be updated.
* If empty all mutable fields will be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* If empty all mutable fields will be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getEventThreatDetectionCustomModule());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getUpdateMask());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, getEventThreatDetectionCustomModule());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj
instanceof
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest)) {
return super.equals(obj);
}
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest other =
(com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest) obj;
if (hasEventThreatDetectionCustomModule() != other.hasEventThreatDetectionCustomModule())
return false;
if (hasEventThreatDetectionCustomModule()) {
if (!getEventThreatDetectionCustomModule()
.equals(other.getEventThreatDetectionCustomModule())) return false;
}
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasEventThreatDetectionCustomModule()) {
hash = (37 * hash) + EVENT_THREAT_DETECTION_CUSTOM_MODULE_FIELD_NUMBER;
hash = (53 * hash) + getEventThreatDetectionCustomModule().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request to update an Event Threat Detection custom module.
* </pre>
*
* Protobuf type {@code
* google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest)
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_UpdateEventThreatDetectionCustomModuleRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_UpdateEventThreatDetectionCustomModuleRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
.class,
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
.Builder.class);
}
// Construct using
// com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getEventThreatDetectionCustomModuleFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
eventThreatDetectionCustomModule_ = null;
if (eventThreatDetectionCustomModuleBuilder_ != null) {
eventThreatDetectionCustomModuleBuilder_.dispose();
eventThreatDetectionCustomModuleBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.securitycenter.v1.SecuritycenterService
.internal_static_google_cloud_securitycenter_v1_UpdateEventThreatDetectionCustomModuleRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
getDefaultInstanceForType() {
return com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
build() {
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
buildPartial() {
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest result =
new com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest(
this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.eventThreatDetectionCustomModule_ =
eventThreatDetectionCustomModuleBuilder_ == null
? eventThreatDetectionCustomModule_
: eventThreatDetectionCustomModuleBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other
instanceof
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest) {
return mergeFrom(
(com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest)
other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest other) {
if (other
== com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
.getDefaultInstance()) return this;
if (other.hasEventThreatDetectionCustomModule()) {
mergeEventThreatDetectionCustomModule(other.getEventThreatDetectionCustomModule());
}
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(
getEventThreatDetectionCustomModuleFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule
eventThreatDetectionCustomModule_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule,
com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule.Builder,
com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModuleOrBuilder>
eventThreatDetectionCustomModuleBuilder_;
/**
*
*
* <pre>
* Required. The module being updated.
* </pre>
*
* <code>
* .google.cloud.securitycenter.v1.EventThreatDetectionCustomModule event_threat_detection_custom_module = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the eventThreatDetectionCustomModule field is set.
*/
public boolean hasEventThreatDetectionCustomModule() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The module being updated.
* </pre>
*
* <code>
* .google.cloud.securitycenter.v1.EventThreatDetectionCustomModule event_threat_detection_custom_module = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The eventThreatDetectionCustomModule.
*/
public com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule
getEventThreatDetectionCustomModule() {
if (eventThreatDetectionCustomModuleBuilder_ == null) {
return eventThreatDetectionCustomModule_ == null
? com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule
.getDefaultInstance()
: eventThreatDetectionCustomModule_;
} else {
return eventThreatDetectionCustomModuleBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The module being updated.
* </pre>
*
* <code>
* .google.cloud.securitycenter.v1.EventThreatDetectionCustomModule event_threat_detection_custom_module = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setEventThreatDetectionCustomModule(
com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule value) {
if (eventThreatDetectionCustomModuleBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
eventThreatDetectionCustomModule_ = value;
} else {
eventThreatDetectionCustomModuleBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The module being updated.
* </pre>
*
* <code>
* .google.cloud.securitycenter.v1.EventThreatDetectionCustomModule event_threat_detection_custom_module = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setEventThreatDetectionCustomModule(
com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule.Builder
builderForValue) {
if (eventThreatDetectionCustomModuleBuilder_ == null) {
eventThreatDetectionCustomModule_ = builderForValue.build();
} else {
eventThreatDetectionCustomModuleBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The module being updated.
* </pre>
*
* <code>
* .google.cloud.securitycenter.v1.EventThreatDetectionCustomModule event_threat_detection_custom_module = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeEventThreatDetectionCustomModule(
com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule value) {
if (eventThreatDetectionCustomModuleBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& eventThreatDetectionCustomModule_ != null
&& eventThreatDetectionCustomModule_
!= com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule
.getDefaultInstance()) {
getEventThreatDetectionCustomModuleBuilder().mergeFrom(value);
} else {
eventThreatDetectionCustomModule_ = value;
}
} else {
eventThreatDetectionCustomModuleBuilder_.mergeFrom(value);
}
if (eventThreatDetectionCustomModule_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The module being updated.
* </pre>
*
* <code>
* .google.cloud.securitycenter.v1.EventThreatDetectionCustomModule event_threat_detection_custom_module = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearEventThreatDetectionCustomModule() {
bitField0_ = (bitField0_ & ~0x00000001);
eventThreatDetectionCustomModule_ = null;
if (eventThreatDetectionCustomModuleBuilder_ != null) {
eventThreatDetectionCustomModuleBuilder_.dispose();
eventThreatDetectionCustomModuleBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The module being updated.
* </pre>
*
* <code>
* .google.cloud.securitycenter.v1.EventThreatDetectionCustomModule event_threat_detection_custom_module = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule.Builder
getEventThreatDetectionCustomModuleBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getEventThreatDetectionCustomModuleFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The module being updated.
* </pre>
*
* <code>
* .google.cloud.securitycenter.v1.EventThreatDetectionCustomModule event_threat_detection_custom_module = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModuleOrBuilder
getEventThreatDetectionCustomModuleOrBuilder() {
if (eventThreatDetectionCustomModuleBuilder_ != null) {
return eventThreatDetectionCustomModuleBuilder_.getMessageOrBuilder();
} else {
return eventThreatDetectionCustomModule_ == null
? com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule
.getDefaultInstance()
: eventThreatDetectionCustomModule_;
}
}
/**
*
*
* <pre>
* Required. The module being updated.
* </pre>
*
* <code>
* .google.cloud.securitycenter.v1.EventThreatDetectionCustomModule event_threat_detection_custom_module = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule,
com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule.Builder,
com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModuleOrBuilder>
getEventThreatDetectionCustomModuleFieldBuilder() {
if (eventThreatDetectionCustomModuleBuilder_ == null) {
eventThreatDetectionCustomModuleBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule,
com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModule.Builder,
com.google.cloud.securitycenter.v1.EventThreatDetectionCustomModuleOrBuilder>(
getEventThreatDetectionCustomModule(), getParentForChildren(), isClean());
eventThreatDetectionCustomModule_ = null;
}
return eventThreatDetectionCustomModuleBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* The list of fields to be updated.
* If empty all mutable fields will be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The list of fields to be updated.
* If empty all mutable fields will be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The list of fields to be updated.
* If empty all mutable fields will be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* If empty all mutable fields will be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* If empty all mutable fields will be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* If empty all mutable fields will be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The list of fields to be updated.
* If empty all mutable fields will be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The list of fields to be updated.
* If empty all mutable fields will be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* The list of fields to be updated.
* If empty all mutable fields will be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest)
private static final com.google.cloud.securitycenter.v1
.UpdateEventThreatDetectionCustomModuleRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest();
}
public static com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateEventThreatDetectionCustomModuleRequest>
PARSER =
new com.google.protobuf.AbstractParser<UpdateEventThreatDetectionCustomModuleRequest>() {
@java.lang.Override
public UpdateEventThreatDetectionCustomModuleRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException()
.setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<UpdateEventThreatDetectionCustomModuleRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateEventThreatDetectionCustomModuleRequest>
getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.securitycenter.v1.UpdateEventThreatDetectionCustomModuleRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,213
|
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/ListExecutionsResponse.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1beta1/metadata_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Response message for
* [MetadataService.ListExecutions][google.cloud.aiplatform.v1beta1.MetadataService.ListExecutions].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListExecutionsResponse}
*/
public final class ListExecutionsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.ListExecutionsResponse)
ListExecutionsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListExecutionsResponse.newBuilder() to construct.
private ListExecutionsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListExecutionsResponse() {
executions_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListExecutionsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListExecutionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListExecutionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse.class,
com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse.Builder.class);
}
public static final int EXECUTIONS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1beta1.Execution> executions_;
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1beta1.Execution> getExecutionsList() {
return executions_;
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.ExecutionOrBuilder>
getExecutionsOrBuilderList() {
return executions_;
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
@java.lang.Override
public int getExecutionsCount() {
return executions_.size();
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.Execution getExecutions(int index) {
return executions_.get(index);
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ExecutionOrBuilder getExecutionsOrBuilder(int index) {
return executions_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token, which can be sent as
* [ListExecutionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExecutionsRequest.page_token]
* to retrieve the next page.
* If this field is not populated, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token, which can be sent as
* [ListExecutionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExecutionsRequest.page_token]
* to retrieve the next page.
* If this field is not populated, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < executions_.size(); i++) {
output.writeMessage(1, executions_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < executions_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, executions_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse other =
(com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse) obj;
if (!getExecutionsList().equals(other.getExecutionsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getExecutionsCount() > 0) {
hash = (37 * hash) + EXECUTIONS_FIELD_NUMBER;
hash = (53 * hash) + getExecutionsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response message for
* [MetadataService.ListExecutions][google.cloud.aiplatform.v1beta1.MetadataService.ListExecutions].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.ListExecutionsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.ListExecutionsResponse)
com.google.cloud.aiplatform.v1beta1.ListExecutionsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListExecutionsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListExecutionsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse.class,
com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (executionsBuilder_ == null) {
executions_ = java.util.Collections.emptyList();
} else {
executions_ = null;
executionsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.MetadataServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_ListExecutionsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse build() {
com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse buildPartial() {
com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse result =
new com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse result) {
if (executionsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
executions_ = java.util.Collections.unmodifiableList(executions_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.executions_ = executions_;
} else {
result.executions_ = executionsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse other) {
if (other == com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse.getDefaultInstance())
return this;
if (executionsBuilder_ == null) {
if (!other.executions_.isEmpty()) {
if (executions_.isEmpty()) {
executions_ = other.executions_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureExecutionsIsMutable();
executions_.addAll(other.executions_);
}
onChanged();
}
} else {
if (!other.executions_.isEmpty()) {
if (executionsBuilder_.isEmpty()) {
executionsBuilder_.dispose();
executionsBuilder_ = null;
executions_ = other.executions_;
bitField0_ = (bitField0_ & ~0x00000001);
executionsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getExecutionsFieldBuilder()
: null;
} else {
executionsBuilder_.addAllMessages(other.executions_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.aiplatform.v1beta1.Execution m =
input.readMessage(
com.google.cloud.aiplatform.v1beta1.Execution.parser(), extensionRegistry);
if (executionsBuilder_ == null) {
ensureExecutionsIsMutable();
executions_.add(m);
} else {
executionsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.aiplatform.v1beta1.Execution> executions_ =
java.util.Collections.emptyList();
private void ensureExecutionsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
executions_ =
new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.Execution>(executions_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Execution,
com.google.cloud.aiplatform.v1beta1.Execution.Builder,
com.google.cloud.aiplatform.v1beta1.ExecutionOrBuilder>
executionsBuilder_;
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Execution> getExecutionsList() {
if (executionsBuilder_ == null) {
return java.util.Collections.unmodifiableList(executions_);
} else {
return executionsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public int getExecutionsCount() {
if (executionsBuilder_ == null) {
return executions_.size();
} else {
return executionsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Execution getExecutions(int index) {
if (executionsBuilder_ == null) {
return executions_.get(index);
} else {
return executionsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public Builder setExecutions(int index, com.google.cloud.aiplatform.v1beta1.Execution value) {
if (executionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureExecutionsIsMutable();
executions_.set(index, value);
onChanged();
} else {
executionsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public Builder setExecutions(
int index, com.google.cloud.aiplatform.v1beta1.Execution.Builder builderForValue) {
if (executionsBuilder_ == null) {
ensureExecutionsIsMutable();
executions_.set(index, builderForValue.build());
onChanged();
} else {
executionsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public Builder addExecutions(com.google.cloud.aiplatform.v1beta1.Execution value) {
if (executionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureExecutionsIsMutable();
executions_.add(value);
onChanged();
} else {
executionsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public Builder addExecutions(int index, com.google.cloud.aiplatform.v1beta1.Execution value) {
if (executionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureExecutionsIsMutable();
executions_.add(index, value);
onChanged();
} else {
executionsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public Builder addExecutions(
com.google.cloud.aiplatform.v1beta1.Execution.Builder builderForValue) {
if (executionsBuilder_ == null) {
ensureExecutionsIsMutable();
executions_.add(builderForValue.build());
onChanged();
} else {
executionsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public Builder addExecutions(
int index, com.google.cloud.aiplatform.v1beta1.Execution.Builder builderForValue) {
if (executionsBuilder_ == null) {
ensureExecutionsIsMutable();
executions_.add(index, builderForValue.build());
onChanged();
} else {
executionsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public Builder addAllExecutions(
java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.Execution> values) {
if (executionsBuilder_ == null) {
ensureExecutionsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, executions_);
onChanged();
} else {
executionsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public Builder clearExecutions() {
if (executionsBuilder_ == null) {
executions_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
executionsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public Builder removeExecutions(int index) {
if (executionsBuilder_ == null) {
ensureExecutionsIsMutable();
executions_.remove(index);
onChanged();
} else {
executionsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Execution.Builder getExecutionsBuilder(int index) {
return getExecutionsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.ExecutionOrBuilder getExecutionsOrBuilder(
int index) {
if (executionsBuilder_ == null) {
return executions_.get(index);
} else {
return executionsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.ExecutionOrBuilder>
getExecutionsOrBuilderList() {
if (executionsBuilder_ != null) {
return executionsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(executions_);
}
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Execution.Builder addExecutionsBuilder() {
return getExecutionsFieldBuilder()
.addBuilder(com.google.cloud.aiplatform.v1beta1.Execution.getDefaultInstance());
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.Execution.Builder addExecutionsBuilder(int index) {
return getExecutionsFieldBuilder()
.addBuilder(index, com.google.cloud.aiplatform.v1beta1.Execution.getDefaultInstance());
}
/**
*
*
* <pre>
* The Executions retrieved from the MetadataStore.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.Execution executions = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.Execution.Builder>
getExecutionsBuilderList() {
return getExecutionsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Execution,
com.google.cloud.aiplatform.v1beta1.Execution.Builder,
com.google.cloud.aiplatform.v1beta1.ExecutionOrBuilder>
getExecutionsFieldBuilder() {
if (executionsBuilder_ == null) {
executionsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.Execution,
com.google.cloud.aiplatform.v1beta1.Execution.Builder,
com.google.cloud.aiplatform.v1beta1.ExecutionOrBuilder>(
executions_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
executions_ = null;
}
return executionsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token, which can be sent as
* [ListExecutionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExecutionsRequest.page_token]
* to retrieve the next page.
* If this field is not populated, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as
* [ListExecutionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExecutionsRequest.page_token]
* to retrieve the next page.
* If this field is not populated, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token, which can be sent as
* [ListExecutionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExecutionsRequest.page_token]
* to retrieve the next page.
* If this field is not populated, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as
* [ListExecutionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExecutionsRequest.page_token]
* to retrieve the next page.
* If this field is not populated, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token, which can be sent as
* [ListExecutionsRequest.page_token][google.cloud.aiplatform.v1beta1.ListExecutionsRequest.page_token]
* to retrieve the next page.
* If this field is not populated, there are no subsequent pages.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.ListExecutionsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.ListExecutionsResponse)
private static final com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse();
}
public static com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListExecutionsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListExecutionsResponse>() {
@java.lang.Override
public ListExecutionsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListExecutionsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListExecutionsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ListExecutionsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,203
|
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/SearchDataItemsResponse.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1beta1/dataset_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Response message for
* [DatasetService.SearchDataItems][google.cloud.aiplatform.v1beta1.DatasetService.SearchDataItems].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.SearchDataItemsResponse}
*/
public final class SearchDataItemsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.SearchDataItemsResponse)
SearchDataItemsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use SearchDataItemsResponse.newBuilder() to construct.
private SearchDataItemsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SearchDataItemsResponse() {
dataItemViews_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SearchDataItemsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.DatasetServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_SearchDataItemsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.DatasetServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_SearchDataItemsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse.class,
com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse.Builder.class);
}
public static final int DATA_ITEM_VIEWS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1beta1.DataItemView> dataItemViews_;
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1beta1.DataItemView> getDataItemViewsList() {
return dataItemViews_;
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.DataItemViewOrBuilder>
getDataItemViewsOrBuilderList() {
return dataItemViews_;
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
@java.lang.Override
public int getDataItemViewsCount() {
return dataItemViews_.size();
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.DataItemView getDataItemViews(int index) {
return dataItemViews_.get(index);
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.DataItemViewOrBuilder getDataItemViewsOrBuilder(
int index) {
return dataItemViews_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [SearchDataItemsRequest.page_token][google.cloud.aiplatform.v1beta1.SearchDataItemsRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [SearchDataItemsRequest.page_token][google.cloud.aiplatform.v1beta1.SearchDataItemsRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < dataItemViews_.size(); i++) {
output.writeMessage(1, dataItemViews_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < dataItemViews_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dataItemViews_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse other =
(com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse) obj;
if (!getDataItemViewsList().equals(other.getDataItemViewsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getDataItemViewsCount() > 0) {
hash = (37 * hash) + DATA_ITEM_VIEWS_FIELD_NUMBER;
hash = (53 * hash) + getDataItemViewsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response message for
* [DatasetService.SearchDataItems][google.cloud.aiplatform.v1beta1.DatasetService.SearchDataItems].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.SearchDataItemsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.SearchDataItemsResponse)
com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.DatasetServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_SearchDataItemsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.DatasetServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_SearchDataItemsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse.class,
com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (dataItemViewsBuilder_ == null) {
dataItemViews_ = java.util.Collections.emptyList();
} else {
dataItemViews_ = null;
dataItemViewsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.DatasetServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_SearchDataItemsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse build() {
com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse buildPartial() {
com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse result =
new com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse result) {
if (dataItemViewsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
dataItemViews_ = java.util.Collections.unmodifiableList(dataItemViews_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.dataItemViews_ = dataItemViews_;
} else {
result.dataItemViews_ = dataItemViewsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse other) {
if (other == com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse.getDefaultInstance())
return this;
if (dataItemViewsBuilder_ == null) {
if (!other.dataItemViews_.isEmpty()) {
if (dataItemViews_.isEmpty()) {
dataItemViews_ = other.dataItemViews_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureDataItemViewsIsMutable();
dataItemViews_.addAll(other.dataItemViews_);
}
onChanged();
}
} else {
if (!other.dataItemViews_.isEmpty()) {
if (dataItemViewsBuilder_.isEmpty()) {
dataItemViewsBuilder_.dispose();
dataItemViewsBuilder_ = null;
dataItemViews_ = other.dataItemViews_;
bitField0_ = (bitField0_ & ~0x00000001);
dataItemViewsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getDataItemViewsFieldBuilder()
: null;
} else {
dataItemViewsBuilder_.addAllMessages(other.dataItemViews_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.aiplatform.v1beta1.DataItemView m =
input.readMessage(
com.google.cloud.aiplatform.v1beta1.DataItemView.parser(),
extensionRegistry);
if (dataItemViewsBuilder_ == null) {
ensureDataItemViewsIsMutable();
dataItemViews_.add(m);
} else {
dataItemViewsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.aiplatform.v1beta1.DataItemView> dataItemViews_ =
java.util.Collections.emptyList();
private void ensureDataItemViewsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
dataItemViews_ =
new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.DataItemView>(
dataItemViews_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.DataItemView,
com.google.cloud.aiplatform.v1beta1.DataItemView.Builder,
com.google.cloud.aiplatform.v1beta1.DataItemViewOrBuilder>
dataItemViewsBuilder_;
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.DataItemView> getDataItemViewsList() {
if (dataItemViewsBuilder_ == null) {
return java.util.Collections.unmodifiableList(dataItemViews_);
} else {
return dataItemViewsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public int getDataItemViewsCount() {
if (dataItemViewsBuilder_ == null) {
return dataItemViews_.size();
} else {
return dataItemViewsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.DataItemView getDataItemViews(int index) {
if (dataItemViewsBuilder_ == null) {
return dataItemViews_.get(index);
} else {
return dataItemViewsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public Builder setDataItemViews(
int index, com.google.cloud.aiplatform.v1beta1.DataItemView value) {
if (dataItemViewsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDataItemViewsIsMutable();
dataItemViews_.set(index, value);
onChanged();
} else {
dataItemViewsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public Builder setDataItemViews(
int index, com.google.cloud.aiplatform.v1beta1.DataItemView.Builder builderForValue) {
if (dataItemViewsBuilder_ == null) {
ensureDataItemViewsIsMutable();
dataItemViews_.set(index, builderForValue.build());
onChanged();
} else {
dataItemViewsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public Builder addDataItemViews(com.google.cloud.aiplatform.v1beta1.DataItemView value) {
if (dataItemViewsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDataItemViewsIsMutable();
dataItemViews_.add(value);
onChanged();
} else {
dataItemViewsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public Builder addDataItemViews(
int index, com.google.cloud.aiplatform.v1beta1.DataItemView value) {
if (dataItemViewsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureDataItemViewsIsMutable();
dataItemViews_.add(index, value);
onChanged();
} else {
dataItemViewsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public Builder addDataItemViews(
com.google.cloud.aiplatform.v1beta1.DataItemView.Builder builderForValue) {
if (dataItemViewsBuilder_ == null) {
ensureDataItemViewsIsMutable();
dataItemViews_.add(builderForValue.build());
onChanged();
} else {
dataItemViewsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public Builder addDataItemViews(
int index, com.google.cloud.aiplatform.v1beta1.DataItemView.Builder builderForValue) {
if (dataItemViewsBuilder_ == null) {
ensureDataItemViewsIsMutable();
dataItemViews_.add(index, builderForValue.build());
onChanged();
} else {
dataItemViewsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public Builder addAllDataItemViews(
java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.DataItemView> values) {
if (dataItemViewsBuilder_ == null) {
ensureDataItemViewsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dataItemViews_);
onChanged();
} else {
dataItemViewsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public Builder clearDataItemViews() {
if (dataItemViewsBuilder_ == null) {
dataItemViews_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
dataItemViewsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public Builder removeDataItemViews(int index) {
if (dataItemViewsBuilder_ == null) {
ensureDataItemViewsIsMutable();
dataItemViews_.remove(index);
onChanged();
} else {
dataItemViewsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.DataItemView.Builder getDataItemViewsBuilder(
int index) {
return getDataItemViewsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.DataItemViewOrBuilder getDataItemViewsOrBuilder(
int index) {
if (dataItemViewsBuilder_ == null) {
return dataItemViews_.get(index);
} else {
return dataItemViewsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public java.util.List<? extends com.google.cloud.aiplatform.v1beta1.DataItemViewOrBuilder>
getDataItemViewsOrBuilderList() {
if (dataItemViewsBuilder_ != null) {
return dataItemViewsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(dataItemViews_);
}
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.DataItemView.Builder addDataItemViewsBuilder() {
return getDataItemViewsFieldBuilder()
.addBuilder(com.google.cloud.aiplatform.v1beta1.DataItemView.getDefaultInstance());
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public com.google.cloud.aiplatform.v1beta1.DataItemView.Builder addDataItemViewsBuilder(
int index) {
return getDataItemViewsFieldBuilder()
.addBuilder(index, com.google.cloud.aiplatform.v1beta1.DataItemView.getDefaultInstance());
}
/**
*
*
* <pre>
* The DataItemViews read.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1beta1.DataItemView data_item_views = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.DataItemView.Builder>
getDataItemViewsBuilderList() {
return getDataItemViewsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.DataItemView,
com.google.cloud.aiplatform.v1beta1.DataItemView.Builder,
com.google.cloud.aiplatform.v1beta1.DataItemViewOrBuilder>
getDataItemViewsFieldBuilder() {
if (dataItemViewsBuilder_ == null) {
dataItemViewsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.DataItemView,
com.google.cloud.aiplatform.v1beta1.DataItemView.Builder,
com.google.cloud.aiplatform.v1beta1.DataItemViewOrBuilder>(
dataItemViews_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
dataItemViews_ = null;
}
return dataItemViewsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [SearchDataItemsRequest.page_token][google.cloud.aiplatform.v1beta1.SearchDataItemsRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [SearchDataItemsRequest.page_token][google.cloud.aiplatform.v1beta1.SearchDataItemsRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [SearchDataItemsRequest.page_token][google.cloud.aiplatform.v1beta1.SearchDataItemsRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [SearchDataItemsRequest.page_token][google.cloud.aiplatform.v1beta1.SearchDataItemsRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass to
* [SearchDataItemsRequest.page_token][google.cloud.aiplatform.v1beta1.SearchDataItemsRequest.page_token]
* to obtain that page.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.SearchDataItemsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.SearchDataItemsResponse)
private static final com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse();
}
public static com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SearchDataItemsResponse> PARSER =
new com.google.protobuf.AbstractParser<SearchDataItemsResponse>() {
@java.lang.Override
public SearchDataItemsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<SearchDataItemsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SearchDataItemsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.SearchDataItemsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 37,972
|
java-compute/google-cloud-compute/src/test/java/com/google/cloud/compute/v1/TargetPoolsClientTest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.compute.v1;
import static com.google.cloud.compute.v1.TargetPoolsClient.AggregatedListPagedResponse;
import static com.google.cloud.compute.v1.TargetPoolsClient.ListPagedResponse;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.testing.MockHttpService;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ApiExceptionFactory;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.testing.FakeStatusCode;
import com.google.cloud.compute.v1.Operation.Status;
import com.google.cloud.compute.v1.stub.HttpJsonTargetPoolsStub;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import javax.annotation.Generated;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@Generated("by gapic-generator-java")
public class TargetPoolsClientTest {
private static MockHttpService mockService;
private static TargetPoolsClient client;
@BeforeClass
public static void startStaticServer() throws IOException {
mockService =
new MockHttpService(
HttpJsonTargetPoolsStub.getMethodDescriptors(),
TargetPoolsSettings.getDefaultEndpoint());
TargetPoolsSettings settings =
TargetPoolsSettings.newBuilder()
.setTransportChannelProvider(
TargetPoolsSettings.defaultHttpJsonTransportProviderBuilder()
.setHttpTransport(mockService)
.build())
.setCredentialsProvider(NoCredentialsProvider.create())
.build();
client = TargetPoolsClient.create(settings);
}
@AfterClass
public static void stopServer() {
client.close();
}
@Before
public void setUp() {}
@After
public void tearDown() throws Exception {
mockService.reset();
}
@Test
public void addHealthCheckTest() throws Exception {
Operation expectedResponse =
Operation.newBuilder()
.setClientOperationId("clientOperationId-1230366697")
.setCreationTimestamp("creationTimestamp-370203401")
.setDescription("description-1724546052")
.setEndTime("endTime-1607243192")
.setError(Error.newBuilder().build())
.setHttpErrorMessage("httpErrorMessage1577303431")
.setHttpErrorStatusCode(0)
.setId(3355)
.setInsertTime("insertTime966165798")
.setInstancesBulkInsertOperationMetadata(
InstancesBulkInsertOperationMetadata.newBuilder().build())
.setKind("kind3292052")
.setName("name3373707")
.setOperationGroupId("operationGroupId1716161683")
.setOperationType("operationType91999553")
.setProgress(-1001078227)
.setRegion("region-934795532")
.setSelfLink("selfLink1191800166")
.setSetCommonInstanceMetadataOperationMetadata(
SetCommonInstanceMetadataOperationMetadata.newBuilder().build())
.setStartTime("startTime-2129294769")
.setStatus(Status.DONE)
.setStatusMessage("statusMessage-958704715")
.setTargetId(-815576439)
.setTargetLink("targetLink486368555")
.setUser("user3599307")
.addAllWarnings(new ArrayList<Warnings>())
.setZone("zone3744684")
.build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
TargetPoolsAddHealthCheckRequest targetPoolsAddHealthCheckRequestResource =
TargetPoolsAddHealthCheckRequest.newBuilder().build();
Operation actualResponse =
client
.addHealthCheckAsync(
project, region, targetPool, targetPoolsAddHealthCheckRequestResource)
.get();
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void addHealthCheckExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
TargetPoolsAddHealthCheckRequest targetPoolsAddHealthCheckRequestResource =
TargetPoolsAddHealthCheckRequest.newBuilder().build();
client
.addHealthCheckAsync(
project, region, targetPool, targetPoolsAddHealthCheckRequestResource)
.get();
Assert.fail("No exception raised");
} catch (ExecutionException e) {
}
}
@Test
public void addInstanceTest() throws Exception {
Operation expectedResponse =
Operation.newBuilder()
.setClientOperationId("clientOperationId-1230366697")
.setCreationTimestamp("creationTimestamp-370203401")
.setDescription("description-1724546052")
.setEndTime("endTime-1607243192")
.setError(Error.newBuilder().build())
.setHttpErrorMessage("httpErrorMessage1577303431")
.setHttpErrorStatusCode(0)
.setId(3355)
.setInsertTime("insertTime966165798")
.setInstancesBulkInsertOperationMetadata(
InstancesBulkInsertOperationMetadata.newBuilder().build())
.setKind("kind3292052")
.setName("name3373707")
.setOperationGroupId("operationGroupId1716161683")
.setOperationType("operationType91999553")
.setProgress(-1001078227)
.setRegion("region-934795532")
.setSelfLink("selfLink1191800166")
.setSetCommonInstanceMetadataOperationMetadata(
SetCommonInstanceMetadataOperationMetadata.newBuilder().build())
.setStartTime("startTime-2129294769")
.setStatus(Status.DONE)
.setStatusMessage("statusMessage-958704715")
.setTargetId(-815576439)
.setTargetLink("targetLink486368555")
.setUser("user3599307")
.addAllWarnings(new ArrayList<Warnings>())
.setZone("zone3744684")
.build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
TargetPoolsAddInstanceRequest targetPoolsAddInstanceRequestResource =
TargetPoolsAddInstanceRequest.newBuilder().build();
Operation actualResponse =
client
.addInstanceAsync(project, region, targetPool, targetPoolsAddInstanceRequestResource)
.get();
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void addInstanceExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
TargetPoolsAddInstanceRequest targetPoolsAddInstanceRequestResource =
TargetPoolsAddInstanceRequest.newBuilder().build();
client
.addInstanceAsync(project, region, targetPool, targetPoolsAddInstanceRequestResource)
.get();
Assert.fail("No exception raised");
} catch (ExecutionException e) {
}
}
@Test
public void aggregatedListTest() throws Exception {
TargetPoolsScopedList responsesElement = TargetPoolsScopedList.newBuilder().build();
TargetPoolAggregatedList expectedResponse =
TargetPoolAggregatedList.newBuilder()
.setNextPageToken("")
.putAllItems(Collections.singletonMap("items", responsesElement))
.build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
AggregatedListPagedResponse pagedListResponse = client.aggregatedList(project);
List<Map.Entry<String, TargetPoolsScopedList>> resources =
Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(
expectedResponse.getItemsMap().entrySet().iterator().next(), resources.get(0));
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void aggregatedListExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
client.aggregatedList(project);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void deleteTest() throws Exception {
Operation expectedResponse =
Operation.newBuilder()
.setClientOperationId("clientOperationId-1230366697")
.setCreationTimestamp("creationTimestamp-370203401")
.setDescription("description-1724546052")
.setEndTime("endTime-1607243192")
.setError(Error.newBuilder().build())
.setHttpErrorMessage("httpErrorMessage1577303431")
.setHttpErrorStatusCode(0)
.setId(3355)
.setInsertTime("insertTime966165798")
.setInstancesBulkInsertOperationMetadata(
InstancesBulkInsertOperationMetadata.newBuilder().build())
.setKind("kind3292052")
.setName("name3373707")
.setOperationGroupId("operationGroupId1716161683")
.setOperationType("operationType91999553")
.setProgress(-1001078227)
.setRegion("region-934795532")
.setSelfLink("selfLink1191800166")
.setSetCommonInstanceMetadataOperationMetadata(
SetCommonInstanceMetadataOperationMetadata.newBuilder().build())
.setStartTime("startTime-2129294769")
.setStatus(Status.DONE)
.setStatusMessage("statusMessage-958704715")
.setTargetId(-815576439)
.setTargetLink("targetLink486368555")
.setUser("user3599307")
.addAllWarnings(new ArrayList<Warnings>())
.setZone("zone3744684")
.build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
Operation actualResponse = client.deleteAsync(project, region, targetPool).get();
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void deleteExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
client.deleteAsync(project, region, targetPool).get();
Assert.fail("No exception raised");
} catch (ExecutionException e) {
}
}
@Test
public void getTest() throws Exception {
TargetPool expectedResponse =
TargetPool.newBuilder()
.setBackupPool("backupPool-934162178")
.setCreationTimestamp("creationTimestamp-370203401")
.setDescription("description-1724546052")
.setFailoverRatio(-861074818)
.addAllHealthChecks(new ArrayList<String>())
.setId(3355)
.addAllInstances(new ArrayList<String>())
.setKind("kind3292052")
.setName("name3373707")
.setRegion("region-934795532")
.setSecurityPolicy("securityPolicy-788621166")
.setSelfLink("selfLink1191800166")
.setSessionAffinity("sessionAffinity-289859106")
.build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
TargetPool actualResponse = client.get(project, region, targetPool);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void getExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
client.get(project, region, targetPool);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getHealthTest() throws Exception {
TargetPoolInstanceHealth expectedResponse =
TargetPoolInstanceHealth.newBuilder()
.addAllHealthStatus(new ArrayList<HealthStatus>())
.setKind("kind3292052")
.build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
InstanceReference instanceReferenceResource = InstanceReference.newBuilder().build();
TargetPoolInstanceHealth actualResponse =
client.getHealth(project, region, targetPool, instanceReferenceResource);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void getHealthExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
InstanceReference instanceReferenceResource = InstanceReference.newBuilder().build();
client.getHealth(project, region, targetPool, instanceReferenceResource);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void insertTest() throws Exception {
Operation expectedResponse =
Operation.newBuilder()
.setClientOperationId("clientOperationId-1230366697")
.setCreationTimestamp("creationTimestamp-370203401")
.setDescription("description-1724546052")
.setEndTime("endTime-1607243192")
.setError(Error.newBuilder().build())
.setHttpErrorMessage("httpErrorMessage1577303431")
.setHttpErrorStatusCode(0)
.setId(3355)
.setInsertTime("insertTime966165798")
.setInstancesBulkInsertOperationMetadata(
InstancesBulkInsertOperationMetadata.newBuilder().build())
.setKind("kind3292052")
.setName("name3373707")
.setOperationGroupId("operationGroupId1716161683")
.setOperationType("operationType91999553")
.setProgress(-1001078227)
.setRegion("region-934795532")
.setSelfLink("selfLink1191800166")
.setSetCommonInstanceMetadataOperationMetadata(
SetCommonInstanceMetadataOperationMetadata.newBuilder().build())
.setStartTime("startTime-2129294769")
.setStatus(Status.DONE)
.setStatusMessage("statusMessage-958704715")
.setTargetId(-815576439)
.setTargetLink("targetLink486368555")
.setUser("user3599307")
.addAllWarnings(new ArrayList<Warnings>())
.setZone("zone3744684")
.build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
String region = "region-9622";
TargetPool targetPoolResource = TargetPool.newBuilder().build();
Operation actualResponse = client.insertAsync(project, region, targetPoolResource).get();
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void insertExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
String region = "region-9622";
TargetPool targetPoolResource = TargetPool.newBuilder().build();
client.insertAsync(project, region, targetPoolResource).get();
Assert.fail("No exception raised");
} catch (ExecutionException e) {
}
}
@Test
public void listTest() throws Exception {
TargetPool responsesElement = TargetPool.newBuilder().build();
TargetPoolList expectedResponse =
TargetPoolList.newBuilder()
.setNextPageToken("")
.addAllItems(Arrays.asList(responsesElement))
.build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
String region = "region-9622";
ListPagedResponse pagedListResponse = client.list(project, region);
List<TargetPool> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getItemsList().get(0), resources.get(0));
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void listExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
String region = "region-9622";
client.list(project, region);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void removeHealthCheckTest() throws Exception {
Operation expectedResponse =
Operation.newBuilder()
.setClientOperationId("clientOperationId-1230366697")
.setCreationTimestamp("creationTimestamp-370203401")
.setDescription("description-1724546052")
.setEndTime("endTime-1607243192")
.setError(Error.newBuilder().build())
.setHttpErrorMessage("httpErrorMessage1577303431")
.setHttpErrorStatusCode(0)
.setId(3355)
.setInsertTime("insertTime966165798")
.setInstancesBulkInsertOperationMetadata(
InstancesBulkInsertOperationMetadata.newBuilder().build())
.setKind("kind3292052")
.setName("name3373707")
.setOperationGroupId("operationGroupId1716161683")
.setOperationType("operationType91999553")
.setProgress(-1001078227)
.setRegion("region-934795532")
.setSelfLink("selfLink1191800166")
.setSetCommonInstanceMetadataOperationMetadata(
SetCommonInstanceMetadataOperationMetadata.newBuilder().build())
.setStartTime("startTime-2129294769")
.setStatus(Status.DONE)
.setStatusMessage("statusMessage-958704715")
.setTargetId(-815576439)
.setTargetLink("targetLink486368555")
.setUser("user3599307")
.addAllWarnings(new ArrayList<Warnings>())
.setZone("zone3744684")
.build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
TargetPoolsRemoveHealthCheckRequest targetPoolsRemoveHealthCheckRequestResource =
TargetPoolsRemoveHealthCheckRequest.newBuilder().build();
Operation actualResponse =
client
.removeHealthCheckAsync(
project, region, targetPool, targetPoolsRemoveHealthCheckRequestResource)
.get();
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void removeHealthCheckExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
TargetPoolsRemoveHealthCheckRequest targetPoolsRemoveHealthCheckRequestResource =
TargetPoolsRemoveHealthCheckRequest.newBuilder().build();
client
.removeHealthCheckAsync(
project, region, targetPool, targetPoolsRemoveHealthCheckRequestResource)
.get();
Assert.fail("No exception raised");
} catch (ExecutionException e) {
}
}
@Test
public void removeInstanceTest() throws Exception {
Operation expectedResponse =
Operation.newBuilder()
.setClientOperationId("clientOperationId-1230366697")
.setCreationTimestamp("creationTimestamp-370203401")
.setDescription("description-1724546052")
.setEndTime("endTime-1607243192")
.setError(Error.newBuilder().build())
.setHttpErrorMessage("httpErrorMessage1577303431")
.setHttpErrorStatusCode(0)
.setId(3355)
.setInsertTime("insertTime966165798")
.setInstancesBulkInsertOperationMetadata(
InstancesBulkInsertOperationMetadata.newBuilder().build())
.setKind("kind3292052")
.setName("name3373707")
.setOperationGroupId("operationGroupId1716161683")
.setOperationType("operationType91999553")
.setProgress(-1001078227)
.setRegion("region-934795532")
.setSelfLink("selfLink1191800166")
.setSetCommonInstanceMetadataOperationMetadata(
SetCommonInstanceMetadataOperationMetadata.newBuilder().build())
.setStartTime("startTime-2129294769")
.setStatus(Status.DONE)
.setStatusMessage("statusMessage-958704715")
.setTargetId(-815576439)
.setTargetLink("targetLink486368555")
.setUser("user3599307")
.addAllWarnings(new ArrayList<Warnings>())
.setZone("zone3744684")
.build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
TargetPoolsRemoveInstanceRequest targetPoolsRemoveInstanceRequestResource =
TargetPoolsRemoveInstanceRequest.newBuilder().build();
Operation actualResponse =
client
.removeInstanceAsync(
project, region, targetPool, targetPoolsRemoveInstanceRequestResource)
.get();
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void removeInstanceExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
TargetPoolsRemoveInstanceRequest targetPoolsRemoveInstanceRequestResource =
TargetPoolsRemoveInstanceRequest.newBuilder().build();
client
.removeInstanceAsync(
project, region, targetPool, targetPoolsRemoveInstanceRequestResource)
.get();
Assert.fail("No exception raised");
} catch (ExecutionException e) {
}
}
@Test
public void setBackupTest() throws Exception {
Operation expectedResponse =
Operation.newBuilder()
.setClientOperationId("clientOperationId-1230366697")
.setCreationTimestamp("creationTimestamp-370203401")
.setDescription("description-1724546052")
.setEndTime("endTime-1607243192")
.setError(Error.newBuilder().build())
.setHttpErrorMessage("httpErrorMessage1577303431")
.setHttpErrorStatusCode(0)
.setId(3355)
.setInsertTime("insertTime966165798")
.setInstancesBulkInsertOperationMetadata(
InstancesBulkInsertOperationMetadata.newBuilder().build())
.setKind("kind3292052")
.setName("name3373707")
.setOperationGroupId("operationGroupId1716161683")
.setOperationType("operationType91999553")
.setProgress(-1001078227)
.setRegion("region-934795532")
.setSelfLink("selfLink1191800166")
.setSetCommonInstanceMetadataOperationMetadata(
SetCommonInstanceMetadataOperationMetadata.newBuilder().build())
.setStartTime("startTime-2129294769")
.setStatus(Status.DONE)
.setStatusMessage("statusMessage-958704715")
.setTargetId(-815576439)
.setTargetLink("targetLink486368555")
.setUser("user3599307")
.addAllWarnings(new ArrayList<Warnings>())
.setZone("zone3744684")
.build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
TargetReference targetReferenceResource = TargetReference.newBuilder().build();
Operation actualResponse =
client.setBackupAsync(project, region, targetPool, targetReferenceResource).get();
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void setBackupExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
TargetReference targetReferenceResource = TargetReference.newBuilder().build();
client.setBackupAsync(project, region, targetPool, targetReferenceResource).get();
Assert.fail("No exception raised");
} catch (ExecutionException e) {
}
}
@Test
public void setSecurityPolicyTest() throws Exception {
Operation expectedResponse =
Operation.newBuilder()
.setClientOperationId("clientOperationId-1230366697")
.setCreationTimestamp("creationTimestamp-370203401")
.setDescription("description-1724546052")
.setEndTime("endTime-1607243192")
.setError(Error.newBuilder().build())
.setHttpErrorMessage("httpErrorMessage1577303431")
.setHttpErrorStatusCode(0)
.setId(3355)
.setInsertTime("insertTime966165798")
.setInstancesBulkInsertOperationMetadata(
InstancesBulkInsertOperationMetadata.newBuilder().build())
.setKind("kind3292052")
.setName("name3373707")
.setOperationGroupId("operationGroupId1716161683")
.setOperationType("operationType91999553")
.setProgress(-1001078227)
.setRegion("region-934795532")
.setSelfLink("selfLink1191800166")
.setSetCommonInstanceMetadataOperationMetadata(
SetCommonInstanceMetadataOperationMetadata.newBuilder().build())
.setStartTime("startTime-2129294769")
.setStatus(Status.DONE)
.setStatusMessage("statusMessage-958704715")
.setTargetId(-815576439)
.setTargetLink("targetLink486368555")
.setUser("user3599307")
.addAllWarnings(new ArrayList<Warnings>())
.setZone("zone3744684")
.build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
SecurityPolicyReference securityPolicyReferenceResource =
SecurityPolicyReference.newBuilder().build();
Operation actualResponse =
client
.setSecurityPolicyAsync(project, region, targetPool, securityPolicyReferenceResource)
.get();
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void setSecurityPolicyExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
String region = "region-9622";
String targetPool = "targetPool-115";
SecurityPolicyReference securityPolicyReferenceResource =
SecurityPolicyReference.newBuilder().build();
client
.setSecurityPolicyAsync(project, region, targetPool, securityPolicyReferenceResource)
.get();
Assert.fail("No exception raised");
} catch (ExecutionException e) {
}
}
@Test
public void testIamPermissionsTest() throws Exception {
TestPermissionsResponse expectedResponse =
TestPermissionsResponse.newBuilder().addAllPermissions(new ArrayList<String>()).build();
mockService.addResponse(expectedResponse);
String project = "project-6911";
String region = "region-9622";
String resource = "resource-756";
TestPermissionsRequest testPermissionsRequestResource =
TestPermissionsRequest.newBuilder().build();
TestPermissionsResponse actualResponse =
client.testIamPermissions(project, region, resource, testPermissionsRequestResource);
Assert.assertEquals(expectedResponse, actualResponse);
List<String> actualRequests = mockService.getRequestPaths();
Assert.assertEquals(1, actualRequests.size());
String apiClientHeaderKey =
mockService
.getRequestHeaders()
.get(ApiClientHeaderProvider.getDefaultApiClientHeaderKey())
.iterator()
.next();
Assert.assertTrue(
GaxHttpJsonProperties.getDefaultApiClientHeaderPattern()
.matcher(apiClientHeaderKey)
.matches());
}
@Test
public void testIamPermissionsExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String project = "project-6911";
String region = "region-9622";
String resource = "resource-756";
TestPermissionsRequest testPermissionsRequestResource =
TestPermissionsRequest.newBuilder().build();
client.testIamPermissions(project, region, resource, testPermissionsRequestResource);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
}
|
apache/nifi-registry
| 38,083
|
nifi-registry-core/nifi-registry-framework/src/main/java/org/apache/nifi/registry/service/extension/docs/HtmlExtensionDocWriter.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.registry.service.extension.docs;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.registry.extension.bundle.BundleInfo;
import org.apache.nifi.registry.extension.component.ExtensionMetadata;
import org.apache.nifi.registry.extension.component.manifest.AllowableValue;
import org.apache.nifi.registry.extension.component.manifest.ControllerServiceDefinition;
import org.apache.nifi.registry.extension.component.manifest.DeprecationNotice;
import org.apache.nifi.registry.extension.component.manifest.DynamicProperty;
import org.apache.nifi.registry.extension.component.manifest.ExpressionLanguageScope;
import org.apache.nifi.registry.extension.component.manifest.Extension;
import org.apache.nifi.registry.extension.component.manifest.InputRequirement;
import org.apache.nifi.registry.extension.component.manifest.Property;
import org.apache.nifi.registry.extension.component.manifest.ProvidedServiceAPI;
import org.apache.nifi.registry.extension.component.manifest.Restricted;
import org.apache.nifi.registry.extension.component.manifest.Restriction;
import org.apache.nifi.registry.extension.component.manifest.Stateful;
import org.apache.nifi.registry.extension.component.manifest.SystemResourceConsideration;
import org.springframework.stereotype.Service;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.apache.nifi.registry.service.extension.docs.DocumentationConstants.CSS_PATH;
@Service
public class HtmlExtensionDocWriter implements ExtensionDocWriter {
@Override
public void write(final ExtensionMetadata extensionMetadata, final Extension extension, final OutputStream outputStream) throws IOException {
try {
final XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(outputStream, "UTF-8");
xmlStreamWriter.writeDTD("<!DOCTYPE html>");
xmlStreamWriter.writeStartElement("html");
xmlStreamWriter.writeAttribute("lang", "en");
writeHead(extensionMetadata, xmlStreamWriter);
writeBody(extensionMetadata, extension, xmlStreamWriter);
xmlStreamWriter.writeEndElement();
xmlStreamWriter.close();
outputStream.flush();
} catch (XMLStreamException | FactoryConfigurationError e) {
throw new IOException("Unable to create XMLOutputStream", e);
}
}
private void writeHead(final ExtensionMetadata extensionMetadata, final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
xmlStreamWriter.writeStartElement("head");
xmlStreamWriter.writeStartElement("meta");
xmlStreamWriter.writeAttribute("charset", "utf-8");
xmlStreamWriter.writeEndElement();
writeSimpleElement(xmlStreamWriter, "title", extensionMetadata.getDisplayName());
final String componentUsageCss = CSS_PATH + "component-usage.css";
xmlStreamWriter.writeStartElement("link");
xmlStreamWriter.writeAttribute("rel", "stylesheet");
xmlStreamWriter.writeAttribute("href", componentUsageCss);
xmlStreamWriter.writeAttribute("type", "text/css");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("script");
xmlStreamWriter.writeAttribute("type", "text/javascript");
xmlStreamWriter.writeCharacters("window.onload = function(){if(self==top) { " +
"document.getElementById('nameHeader').style.display = \"inherit\"; } }" );
xmlStreamWriter.writeEndElement();
}
private void writeBody(final ExtensionMetadata extensionMetadata, final Extension extension,
final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
xmlStreamWriter.writeStartElement("body");
writeHeader(extensionMetadata, extension, xmlStreamWriter);
writeBundleInfo(extensionMetadata, xmlStreamWriter);
writeDeprecationWarning(extension, xmlStreamWriter);
writeDescription(extensionMetadata, extension, xmlStreamWriter);
writeTags(extension, xmlStreamWriter);
writeProperties(extension, xmlStreamWriter);
writeDynamicProperties(extension, xmlStreamWriter);
writeAdditionalBodyInfo(extension, xmlStreamWriter);
writeStatefulInfo(extension, xmlStreamWriter);
writeRestrictedInfo(extension, xmlStreamWriter);
writeInputRequirementInfo(extension, xmlStreamWriter);
writeSystemResourceConsiderationInfo(extension, xmlStreamWriter);
writeProvidedServiceApis(extension, xmlStreamWriter);
writeSeeAlso(extension, xmlStreamWriter);
// end body
xmlStreamWriter.writeEndElement();
}
/**
* This method may be overridden by sub classes to write additional
* information to the body of the documentation.
*
* @param extension the component to describe
* @param xmlStreamWriter the stream writer
* @throws XMLStreamException thrown if there was a problem writing to the XML stream
*/
protected void writeAdditionalBodyInfo(final Extension extension, final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
}
private void writeHeader(final ExtensionMetadata extensionMetadata, final Extension extension,
final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
xmlStreamWriter.writeStartElement("h1");
xmlStreamWriter.writeAttribute("id", "nameHeader");
xmlStreamWriter.writeAttribute("style", "display: none;");
xmlStreamWriter.writeCharacters(extensionMetadata.getDisplayName());
xmlStreamWriter.writeEndElement();
}
private void writeBundleInfoString(final ExtensionMetadata extensionMetadata, final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
final BundleInfo bundleInfo = extensionMetadata.getBundleInfo();
final String bundleInfoText = bundleInfo.getGroupId() + "-" + bundleInfo.getArtifactId() + "-" + bundleInfo.getVersion();
xmlStreamWriter.writeStartElement("p");
xmlStreamWriter.writeStartElement("i");
xmlStreamWriter.writeCharacters(bundleInfoText);
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEndElement();
}
private void writeBundleInfo(final ExtensionMetadata extensionMetadata, final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
final BundleInfo bundleInfo = extensionMetadata.getBundleInfo();
final String extenstionType;
switch (extensionMetadata.getType()) {
case PROCESSOR:
extenstionType = "Processor";
break;
case CONTROLLER_SERVICE:
extenstionType = "Controller Service";
break;
case REPORTING_TASK:
extenstionType = "Reporting Task";
break;
default:
throw new IllegalArgumentException("Unknown extension type: " + extensionMetadata.getType());
}
xmlStreamWriter.writeStartElement("table");
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "th", "Extension Info");
writeSimpleElement(xmlStreamWriter, "th", "Value");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "td", "Full Name", true, "bundle-info");
writeSimpleElement(xmlStreamWriter, "td", extensionMetadata.getName());
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "td", "Type", true, "bundle-info");
writeSimpleElement(xmlStreamWriter, "td", extenstionType);
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "td", "Bundle Group", true, "bundle-info");
writeSimpleElement(xmlStreamWriter, "td", bundleInfo.getGroupId());
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "td", "Bundle Artifact", true, "bundle-info");
writeSimpleElement(xmlStreamWriter, "td", bundleInfo.getArtifactId());
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "td", "Bundle Version", true, "bundle-info");
writeSimpleElement(xmlStreamWriter, "td", bundleInfo.getVersion());
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "td", "Bundle Type", true, "bundle-info");
writeSimpleElement(xmlStreamWriter, "td", bundleInfo.getBundleType().toString());
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "td", "System API Version", true, "bundle-info");
writeSimpleElement(xmlStreamWriter, "td", bundleInfo.getSystemApiVersion());
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEndElement(); // end table
}
private void writeDeprecationWarning(final Extension extension, final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
final DeprecationNotice deprecationNotice = extension.getDeprecationNotice();
if (deprecationNotice != null) {
xmlStreamWriter.writeStartElement("h2");
xmlStreamWriter.writeCharacters("Deprecation notice: ");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("p");
xmlStreamWriter.writeCharacters("");
if (!StringUtils.isEmpty(deprecationNotice.getReason())) {
xmlStreamWriter.writeCharacters(deprecationNotice.getReason());
} else {
xmlStreamWriter.writeCharacters("Please be aware this processor is deprecated and may be removed in the near future.");
}
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("p");
xmlStreamWriter.writeCharacters("Please consider using one the following alternatives: ");
final List<String> alternatives = deprecationNotice.getAlternatives();
if (alternatives != null && alternatives.size() > 0) {
xmlStreamWriter.writeStartElement("ul");
for (final String alternative : alternatives) {
xmlStreamWriter.writeStartElement("li");
xmlStreamWriter.writeCharacters(alternative);
xmlStreamWriter.writeEndElement();
}
xmlStreamWriter.writeEndElement();
} else {
xmlStreamWriter.writeCharacters("No alternative components suggested.");
}
xmlStreamWriter.writeEndElement();
}
}
private void writeDescription(final ExtensionMetadata extensionMetadata, final Extension extension, final XMLStreamWriter xmlStreamWriter)
throws XMLStreamException {
final String description = StringUtils.isBlank(extension.getDescription())
? "No description provided." : extension.getDescription();
writeSimpleElement(xmlStreamWriter, "h2", "Description: ");
writeSimpleElement(xmlStreamWriter, "p", description);
if (extensionMetadata.getHasAdditionalDetails()) {
xmlStreamWriter.writeStartElement("p");
final BundleInfo bundleInfo = extensionMetadata.getBundleInfo();
final String bucketName = bundleInfo.getBucketName();
final String groupId = bundleInfo.getGroupId();
final String artifactId = bundleInfo.getArtifactId();
final String version = bundleInfo.getVersion();
final String extensionName = extensionMetadata.getName();
final String additionalDetailsPath = "/nifi-registry-api/extension-repository/"
+ bucketName + "/" + groupId + "/" + artifactId + "/" + version
+ "/extensions/" + extensionName + "/docs/additional-details";
writeLink(xmlStreamWriter, "Additional Details...", additionalDetailsPath);
xmlStreamWriter.writeEndElement();
}
}
private void writeTags(final Extension extension, final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
final List<String> tags = extension.getTags();
xmlStreamWriter.writeStartElement("h3");
xmlStreamWriter.writeCharacters("Tags: ");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("p");
if (tags != null) {
final String tagString = StringUtils.join(tags, ", ");
xmlStreamWriter.writeCharacters(tagString);
} else {
xmlStreamWriter.writeCharacters("No tags provided.");
}
xmlStreamWriter.writeEndElement();
}
protected void writeProperties(final Extension extension, final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
final List<Property> properties = extension.getProperties();
writeSimpleElement(xmlStreamWriter, "h3", "Properties: ");
if (properties != null && properties.size() > 0) {
final boolean containsExpressionLanguage = containsExpressionLanguage(extension);
final boolean containsSensitiveProperties = containsSensitiveProperties(extension);
xmlStreamWriter.writeStartElement("p");
xmlStreamWriter.writeCharacters("In the list below, the names of required properties appear in ");
writeSimpleElement(xmlStreamWriter, "strong", "bold");
xmlStreamWriter.writeCharacters(". Any other properties (not in bold) are considered optional. " +
"The table also indicates any default values");
if (containsExpressionLanguage) {
if (!containsSensitiveProperties) {
xmlStreamWriter.writeCharacters(", and ");
} else {
xmlStreamWriter.writeCharacters(", ");
}
xmlStreamWriter.writeCharacters("whether a property supports the NiFi Expression Language");
}
if (containsSensitiveProperties) {
xmlStreamWriter.writeCharacters(", and whether a property is considered " + "\"sensitive\", meaning that its value will be encrypted");
}
xmlStreamWriter.writeCharacters(".");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("table");
xmlStreamWriter.writeAttribute("id", "properties");
// write the header row
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "th", "Name");
writeSimpleElement(xmlStreamWriter, "th", "Default Value");
writeSimpleElement(xmlStreamWriter, "th", "Allowable Values");
writeSimpleElement(xmlStreamWriter, "th", "Description");
xmlStreamWriter.writeEndElement();
// write the individual properties
for (Property property : properties) {
xmlStreamWriter.writeStartElement("tr");
xmlStreamWriter.writeStartElement("td");
xmlStreamWriter.writeAttribute("id", "name");
if (property.isRequired()) {
writeSimpleElement(xmlStreamWriter, "strong", property.getDisplayName());
} else {
xmlStreamWriter.writeCharacters(property.getDisplayName());
}
xmlStreamWriter.writeEndElement();
writeSimpleElement(xmlStreamWriter, "td", property.getDefaultValue(), false, "default-value");
xmlStreamWriter.writeStartElement("td");
xmlStreamWriter.writeAttribute("id", "allowable-values");
writeValidValues(xmlStreamWriter, property);
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("td");
xmlStreamWriter.writeAttribute("id", "description");
if (property.getDescription() != null && property.getDescription().trim().length() > 0) {
xmlStreamWriter.writeCharacters(property.getDescription());
} else {
xmlStreamWriter.writeCharacters("No Description Provided.");
}
if (property.isSensitive()) {
xmlStreamWriter.writeEmptyElement("br");
writeSimpleElement(xmlStreamWriter, "strong", "Sensitive Property: true");
}
if (property.isExpressionLanguageSupported()) {
xmlStreamWriter.writeEmptyElement("br");
String text = "Supports Expression Language: true";
final String perFF = " (will be evaluated using flow file attributes and variable registry)";
final String registry = " (will be evaluated using variable registry only)";
final InputRequirement inputRequirement = extension.getInputRequirement();
switch(property.getExpressionLanguageScope()) {
case FLOWFILE_ATTRIBUTES:
if(inputRequirement != null && inputRequirement.equals(InputRequirement.INPUT_FORBIDDEN)) {
text += registry;
} else {
text += perFF;
}
break;
case VARIABLE_REGISTRY:
text += registry;
break;
case NONE:
default:
// in case legacy/deprecated method has been used to specify EL support
text += " (undefined scope)";
break;
}
writeSimpleElement(xmlStreamWriter, "strong", text);
}
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEndElement();
}
xmlStreamWriter.writeEndElement();
} else {
writeSimpleElement(xmlStreamWriter, "p", "This component has no required or optional properties.");
}
}
private boolean containsExpressionLanguage(final Extension extension) {
for (Property property : extension.getProperties()) {
if (property.isExpressionLanguageSupported()) {
return true;
}
}
return false;
}
private boolean containsSensitiveProperties(final Extension extension) {
for (Property property : extension.getProperties()) {
if (property.isSensitive()) {
return true;
}
}
return false;
}
protected void writeValidValues(final XMLStreamWriter xmlStreamWriter, final Property property) throws XMLStreamException {
if (property.getAllowableValues() != null && property.getAllowableValues().size() > 0) {
xmlStreamWriter.writeStartElement("ul");
for (AllowableValue value : property.getAllowableValues()) {
xmlStreamWriter.writeStartElement("li");
xmlStreamWriter.writeCharacters(value.getDisplayName());
if (!StringUtils.isBlank(value.getDescription())) {
writeValidValueDescription(xmlStreamWriter, value.getDescription());
}
xmlStreamWriter.writeEndElement();
}
xmlStreamWriter.writeEndElement();
} else if (property.getControllerServiceDefinition() != null) {
final ControllerServiceDefinition serviceDefinition = property.getControllerServiceDefinition();
final String controllerServiceClass = getSimpleName(serviceDefinition.getClassName());
final String group = serviceDefinition.getGroupId() == null ? "unknown" : serviceDefinition.getGroupId();
final String artifact = serviceDefinition.getArtifactId() == null ? "unknown" : serviceDefinition.getArtifactId();
final String version = serviceDefinition.getVersion() == null ? "unknown" : serviceDefinition.getVersion();
writeSimpleElement(xmlStreamWriter, "strong", "Controller Service API: ");
xmlStreamWriter.writeEmptyElement("br");
xmlStreamWriter.writeCharacters(controllerServiceClass);
writeValidValueDescription(xmlStreamWriter, group + "-" + artifact + "-" + version);
// xmlStreamWriter.writeEmptyElement("br");
// xmlStreamWriter.writeCharacters(group);
// xmlStreamWriter.writeEmptyElement("br");
// xmlStreamWriter.writeCharacters(artifact);
// xmlStreamWriter.writeEmptyElement("br");
// xmlStreamWriter.writeCharacters(version);
}
}
private String getSimpleName(final String extensionName) {
int index = extensionName.lastIndexOf('.');
if (index > 0 && (index < (extensionName.length() - 1))) {
return extensionName.substring(index + 1);
} else {
return extensionName;
}
}
private void writeValidValueDescription(final XMLStreamWriter xmlStreamWriter, final String description) throws XMLStreamException {
xmlStreamWriter.writeCharacters(" ");
xmlStreamWriter.writeStartElement("img");
xmlStreamWriter.writeAttribute("src", "/nifi-registry-docs/images/iconInfo.png");
xmlStreamWriter.writeAttribute("alt", description);
xmlStreamWriter.writeAttribute("title", description);
xmlStreamWriter.writeEndElement();
}
private void writeDynamicProperties(final Extension extension, final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
final List<DynamicProperty> dynamicProperties = extension.getDynamicProperties();
if (dynamicProperties != null && dynamicProperties.size() > 0) {
writeSimpleElement(xmlStreamWriter, "h3", "Dynamic Properties: ");
xmlStreamWriter.writeStartElement("p");
xmlStreamWriter.writeCharacters("Dynamic Properties allow the user to specify both the name and value of a property.");
xmlStreamWriter.writeStartElement("table");
xmlStreamWriter.writeAttribute("id", "dynamic-properties");
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "th", "Name");
writeSimpleElement(xmlStreamWriter, "th", "Value");
writeSimpleElement(xmlStreamWriter, "th", "Description");
xmlStreamWriter.writeEndElement();
for (final DynamicProperty dynamicProperty : dynamicProperties) {
final String name = StringUtils.isBlank(dynamicProperty.getName()) ? "Not Specified" : dynamicProperty.getName();
final String value = StringUtils.isBlank(dynamicProperty.getValue()) ? "Not Specified" : dynamicProperty.getValue();
final String description = StringUtils.isBlank(dynamicProperty.getDescription()) ? "Not Specified" : dynamicProperty.getDescription();
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "td", name, false, "name");
writeSimpleElement(xmlStreamWriter, "td", value, false, "value");
xmlStreamWriter.writeStartElement("td");
xmlStreamWriter.writeCharacters(description);
xmlStreamWriter.writeEmptyElement("br");
final ExpressionLanguageScope elScope = dynamicProperty.getExpressionLanguageScope() == null
? ExpressionLanguageScope.NONE : dynamicProperty.getExpressionLanguageScope();
String text;
if(elScope.equals(ExpressionLanguageScope.NONE)) {
if(dynamicProperty.isExpressionLanguageSupported()) {
text = "Supports Expression Language: true (undefined scope)";
} else {
text = "Supports Expression Language: false";
}
} else {
switch(elScope) {
case FLOWFILE_ATTRIBUTES:
text = "Supports Expression Language: true (will be evaluated using flow file attributes and variable registry)";
break;
case VARIABLE_REGISTRY:
text = "Supports Expression Language: true (will be evaluated using variable registry only)";
break;
case NONE:
default:
text = "Supports Expression Language: false";
break;
}
}
writeSimpleElement(xmlStreamWriter, "strong", text);
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEndElement();
}
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEndElement();
}
}
private void writeStatefulInfo(final Extension extension, final XMLStreamWriter xmlStreamWriter)
throws XMLStreamException {
final Stateful stateful = extension.getStateful();
writeSimpleElement(xmlStreamWriter, "h3", "State management: ");
if(stateful != null) {
final List<String> scopes = Optional.ofNullable(stateful.getScopes())
.map(List::stream)
.orElseGet(Stream::empty)
.map(s -> s.toString())
.collect(Collectors.toList());
final String description = StringUtils.isBlank(stateful.getDescription()) ? "Not Specified" : stateful.getDescription();
xmlStreamWriter.writeStartElement("table");
xmlStreamWriter.writeAttribute("id", "stateful");
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "th", "Scope");
writeSimpleElement(xmlStreamWriter, "th", "Description");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "td", StringUtils.join(scopes, ", "));
writeSimpleElement(xmlStreamWriter, "td", description);
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEndElement();
} else {
xmlStreamWriter.writeCharacters("This component does not store state.");
}
}
private void writeRestrictedInfo(final Extension extension, final XMLStreamWriter xmlStreamWriter)
throws XMLStreamException {
final Restricted restricted = extension.getRestricted();
writeSimpleElement(xmlStreamWriter, "h3", "Restricted: ");
if(restricted != null) {
final String generalRestrictionExplanation = restricted.getGeneralRestrictionExplanation();
if (!StringUtils.isBlank(generalRestrictionExplanation)) {
xmlStreamWriter.writeCharacters(generalRestrictionExplanation);
}
final List<Restriction> restrictions = restricted.getRestrictions();
if (restrictions != null && restrictions.size() > 0) {
xmlStreamWriter.writeStartElement("table");
xmlStreamWriter.writeAttribute("id", "restrictions");
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "th", "Required Permission");
writeSimpleElement(xmlStreamWriter, "th", "Explanation");
xmlStreamWriter.writeEndElement();
for (Restriction restriction : restrictions) {
final String permission = StringUtils.isBlank(restriction.getRequiredPermission())
? "Not Specified" : restriction.getRequiredPermission();
final String explanation = StringUtils.isBlank(restriction.getExplanation())
? "Not Specified" : restriction.getExplanation();
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "td", permission);
writeSimpleElement(xmlStreamWriter, "td", explanation);
xmlStreamWriter.writeEndElement();
}
xmlStreamWriter.writeEndElement();
} else {
xmlStreamWriter.writeCharacters("This component requires access to restricted components regardless of restriction.");
}
} else {
xmlStreamWriter.writeCharacters("This component is not restricted.");
}
}
private void writeInputRequirementInfo(final Extension extension, final XMLStreamWriter xmlStreamWriter)
throws XMLStreamException {
final InputRequirement inputRequirement = extension.getInputRequirement();
if(inputRequirement != null) {
writeSimpleElement(xmlStreamWriter, "h3", "Input requirement: ");
switch (inputRequirement) {
case INPUT_FORBIDDEN:
xmlStreamWriter.writeCharacters("This component does not allow an incoming relationship.");
break;
case INPUT_ALLOWED:
xmlStreamWriter.writeCharacters("This component allows an incoming relationship.");
break;
case INPUT_REQUIRED:
xmlStreamWriter.writeCharacters("This component requires an incoming relationship.");
break;
default:
xmlStreamWriter.writeCharacters("This component does not have input requirement.");
break;
}
}
}
private void writeSystemResourceConsiderationInfo(final Extension extension, final XMLStreamWriter xmlStreamWriter)
throws XMLStreamException {
List<SystemResourceConsideration> systemResourceConsiderations = extension.getSystemResourceConsiderations();
writeSimpleElement(xmlStreamWriter, "h3", "System Resource Considerations:");
if (systemResourceConsiderations != null && systemResourceConsiderations.size() > 0) {
xmlStreamWriter.writeStartElement("table");
xmlStreamWriter.writeAttribute("id", "system-resource-considerations");
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "th", "Resource");
writeSimpleElement(xmlStreamWriter, "th", "Description");
xmlStreamWriter.writeEndElement();
for (SystemResourceConsideration systemResourceConsideration : systemResourceConsiderations) {
final String resource = StringUtils.isBlank(systemResourceConsideration.getResource())
? "Not Specified" : systemResourceConsideration.getResource();
final String description = StringUtils.isBlank(systemResourceConsideration.getDescription())
? "Not Specified" : systemResourceConsideration.getDescription();
xmlStreamWriter.writeStartElement("tr");
writeSimpleElement(xmlStreamWriter, "td", resource);
writeSimpleElement(xmlStreamWriter, "td", description);
xmlStreamWriter.writeEndElement();
}
xmlStreamWriter.writeEndElement();
} else {
xmlStreamWriter.writeCharacters("None specified.");
}
}
private void writeProvidedServiceApis(final Extension extension, final XMLStreamWriter xmlStreamWriter) throws XMLStreamException {
final List<ProvidedServiceAPI> serviceAPIS = extension.getProvidedServiceAPIs();
if (serviceAPIS != null && serviceAPIS.size() > 0) {
writeSimpleElement(xmlStreamWriter, "h3", "Provided Service APIs:");
xmlStreamWriter.writeStartElement("ul");
for (final ProvidedServiceAPI serviceAPI : serviceAPIS) {
final String name = getSimpleName(serviceAPI.getClassName());
final String bundleInfo = " (" + serviceAPI.getGroupId() + "-" + serviceAPI.getArtifactId() + "-" + serviceAPI.getVersion() + ")";
xmlStreamWriter.writeStartElement("li");
xmlStreamWriter.writeCharacters(name);
xmlStreamWriter.writeStartElement("i");
xmlStreamWriter.writeCharacters(bundleInfo);
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEndElement();
}
xmlStreamWriter.writeEndElement();
}
}
private void writeSeeAlso(final Extension extension, final XMLStreamWriter xmlStreamWriter)
throws XMLStreamException {
final List<String> seeAlsos = extension.getSeeAlso();
if (seeAlsos != null && seeAlsos.size() > 0) {
writeSimpleElement(xmlStreamWriter, "h3", "See Also:");
xmlStreamWriter.writeStartElement("ul");
for (final String seeAlso : seeAlsos) {
writeSimpleElement(xmlStreamWriter, "li", seeAlso);
}
xmlStreamWriter.writeEndElement();
}
}
/**
* Writes a begin element, then text, then end element for the element of a
* users choosing. Example: <p>text</p>
*
* @param writer the stream writer to use
* @param elementName the name of the element
* @param characters the characters to insert into the element
* @throws XMLStreamException thrown if there was a problem writing to the
* stream
*/
protected final static void writeSimpleElement(final XMLStreamWriter writer, final String elementName,
final String characters) throws XMLStreamException {
writeSimpleElement(writer, elementName, characters, false);
}
/**
* Writes a begin element, then text, then end element for the element of a
* users choosing. Example: <p>text</p>
*
* @param writer the stream writer to use
* @param elementName the name of the element
* @param characters the characters to insert into the element
* @param strong whether the characters should be strong or not.
* @throws XMLStreamException thrown if there was a problem writing to the
* stream.
*/
protected final static void writeSimpleElement(final XMLStreamWriter writer, final String elementName,
final String characters, boolean strong) throws XMLStreamException {
writeSimpleElement(writer, elementName, characters, strong, null);
}
/**
* Writes a begin element, an id attribute(if specified), then text, then
* end element for element of the users choosing. Example: <p
* id="p-id">text</p>
*
* @param writer the stream writer to use
* @param elementName the name of the element
* @param characters the text of the element
* @param strong whether to bold the text of the element or not
* @param id the id of the element. specifying null will cause no element to
* be written.
* @throws XMLStreamException xse
*/
protected final static void writeSimpleElement(final XMLStreamWriter writer, final String elementName,
final String characters, boolean strong, String id) throws XMLStreamException {
writer.writeStartElement(elementName);
if (id != null) {
writer.writeAttribute("id", id);
}
if (strong) {
writer.writeStartElement("strong");
}
writer.writeCharacters(characters);
if (strong) {
writer.writeEndElement();
}
writer.writeEndElement();
}
/**
* A helper method to write a link
*
* @param xmlStreamWriter the stream to write to
* @param text the text of the link
* @param location the location of the link
* @throws XMLStreamException thrown if there was a problem writing to the
* stream
*/
protected void writeLink(final XMLStreamWriter xmlStreamWriter, final String text, final String location)
throws XMLStreamException {
xmlStreamWriter.writeStartElement("a");
xmlStreamWriter.writeAttribute("href", location);
xmlStreamWriter.writeCharacters(text);
xmlStreamWriter.writeEndElement();
}
}
|
google/filament
| 38,338
|
third_party/dawn/third_party/protobuf/java/core/src/test/java/com/google/protobuf/CodedOutputStreamTest.java
|
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package com.google.protobuf;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.common.truth.TruthJUnit.assume;
import static org.junit.Assert.assertThrows;
import com.google.protobuf.CodedOutputStream.OutOfSpaceException;
import proto2_unittest.UnittestProto.SparseEnumMessage;
import proto2_unittest.UnittestProto.TestAllTypes;
import proto2_unittest.UnittestProto.TestSparseEnum;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/** Unit test for {@link CodedOutputStream}. */
@RunWith(Parameterized.class)
public class CodedOutputStreamTest {
@Parameters(name = "OutputType={0}")
public static List<OutputType> data() {
return Arrays.asList(OutputType.values());
}
private final OutputType outputType;
public CodedOutputStreamTest(OutputType outputType) {
this.outputType = outputType;
}
private interface Coder {
CodedOutputStream stream();
byte[] toByteArray();
}
// Like ByteArrayOutputStream, but doesn't dynamically grow the backing byte[]. Instead, it
// throws OutOfSpaceException if we overflow the backing byte[].
private static final class FixedSizeByteArrayOutputStream extends OutputStream {
private final byte[] buf;
private int size = 0;
FixedSizeByteArrayOutputStream(int size) {
this.buf = new byte[size];
}
@Override
public void write(int b) throws IOException {
try {
buf[size] = (byte) b;
} catch (IndexOutOfBoundsException e) {
// Real OutputStreams probably won't be so kind as to throw the exact OutOfSpaceException
// that we want in our tests. Throwing this makes our tests simpler, and OutputStream
// doesn't really have a good protocol for signalling running out of buffer space.
throw new OutOfSpaceException(size, buf.length, 1, e);
}
size++;
}
public byte[] toByteArray() {
return Arrays.copyOf(buf, size);
}
}
private static final class OutputStreamCoder implements Coder {
private final CodedOutputStream stream;
private final FixedSizeByteArrayOutputStream output;
OutputStreamCoder(int size, int blockSize) {
output = new FixedSizeByteArrayOutputStream(size);
stream = CodedOutputStream.newInstance(output, blockSize);
}
@Override
public CodedOutputStream stream() {
return stream;
}
@Override
public byte[] toByteArray() {
return output.toByteArray();
}
}
private static final class ArrayCoder implements Coder {
private final CodedOutputStream stream;
private final byte[] bytes;
ArrayCoder(int size) {
bytes = new byte[size];
stream = CodedOutputStream.newInstance(bytes);
}
@Override
public CodedOutputStream stream() {
return stream;
}
@Override
public byte[] toByteArray() {
return Arrays.copyOf(bytes, stream.getTotalBytesWritten());
}
}
private static final class NioHeapCoder implements Coder {
private final CodedOutputStream stream;
private final ByteBuffer buffer;
private final int initialPosition;
NioHeapCoder(int size) {
this(size, 0);
}
NioHeapCoder(int size, int initialPosition) {
this.initialPosition = initialPosition;
buffer = ByteBuffer.allocate(size);
buffer.position(initialPosition);
stream = CodedOutputStream.newInstance(buffer);
}
@Override
public CodedOutputStream stream() {
return stream;
}
@Override
public byte[] toByteArray() {
ByteBuffer dup = buffer.duplicate();
dup.position(initialPosition);
dup.limit(buffer.position());
byte[] bytes = new byte[dup.remaining()];
dup.get(bytes);
return bytes;
}
}
private static final class NioDirectCoder implements Coder {
private final int initialPosition;
private final CodedOutputStream stream;
private final ByteBuffer buffer;
NioDirectCoder(int size, boolean unsafe) {
this(size, 0, unsafe);
}
NioDirectCoder(int size, int initialPosition, boolean unsafe) {
this.initialPosition = initialPosition;
buffer = ByteBuffer.allocateDirect(size);
buffer.position(initialPosition);
stream =
unsafe
? CodedOutputStream.newUnsafeInstance(buffer)
: CodedOutputStream.newSafeInstance(buffer);
}
@Override
public CodedOutputStream stream() {
return stream;
}
@Override
public byte[] toByteArray() {
ByteBuffer dup = buffer.duplicate();
dup.position(initialPosition);
dup.limit(buffer.position());
byte[] bytes = new byte[dup.remaining()];
dup.get(bytes);
return bytes;
}
}
private static final class ByteOutputWrappingArrayCoder implements Coder {
private final CodedOutputStream stream;
private final byte[] bytes;
ByteOutputWrappingArrayCoder(int size) {
bytes = new byte[size];
// Any ByteOutput subclass would do. All CodedInputStreams implement ByteOutput, so it
// seemed most convenient to this this with a CodedInputStream.newInstance(byte[]).
ByteOutput byteOutput = CodedOutputStream.newInstance(bytes);
stream = CodedOutputStream.newInstance(byteOutput, size);
}
@Override
public CodedOutputStream stream() {
return stream;
}
@Override
public byte[] toByteArray() {
return Arrays.copyOf(bytes, stream.getTotalBytesWritten());
}
}
private enum OutputType {
ARRAY() {
@Override
Coder newCoder(int size) {
return new ArrayCoder(size);
}
},
NIO_HEAP() {
@Override
Coder newCoder(int size) {
return new NioHeapCoder(size);
}
},
NIO_HEAP_WITH_INITIAL_OFFSET() {
@Override
Coder newCoder(int size) {
int offset = 2;
return new NioHeapCoder(size + offset, /* initialPosition= */ offset);
}
},
NIO_DIRECT_SAFE() {
@Override
Coder newCoder(int size) {
return new NioDirectCoder(size, /* unsafe= */ false);
}
},
NIO_DIRECT_SAFE_WITH_INITIAL_OFFSET() {
@Override
Coder newCoder(int size) {
int offset = 2;
return new NioDirectCoder(size + offset, offset, /* unsafe= */ false);
}
},
NIO_DIRECT_UNSAFE() {
@Override
Coder newCoder(int size) {
return new NioDirectCoder(size, /* unsafe= */ true);
}
},
NIO_DIRECT_UNSAFE_WITH_INITIAL_OFFSET() {
@Override
Coder newCoder(int size) {
int offset = 2;
return new NioDirectCoder(size + offset, offset, /* unsafe= */ true);
}
},
STREAM() {
@Override
Coder newCoder(int size) {
return new OutputStreamCoder(size, /* blockSize= */ size);
}
},
STREAM_MINIMUM_BUFFER_SIZE() {
@Override
Coder newCoder(int size) {
// Block Size 0 gets rounded up to minimum block size, see AbstractBufferedEncoder.
return new OutputStreamCoder(size, /* blockSize= */ 0);
}
},
BYTE_OUTPUT_WRAPPING_ARRAY() {
@Override
Coder newCoder(int size) {
return new ByteOutputWrappingArrayCoder(size);
}
};
abstract Coder newCoder(int size);
/** Whether we can call CodedOutputStream.spaceLeft(). */
boolean supportsSpaceLeft() {
// Buffered encoders don't know how much space is left.
switch (this) {
case STREAM:
case STREAM_MINIMUM_BUFFER_SIZE:
case BYTE_OUTPUT_WRAPPING_ARRAY:
return false;
default:
return true;
}
}
}
/** Checks that invariants are maintained for varint round trip input and output. */
@Test
public void testVarintRoundTrips() throws Exception {
assertVarintRoundTrip(0L);
for (int bits = 0; bits < 64; bits++) {
long value = 1L << bits;
assertVarintRoundTrip(value);
assertVarintRoundTrip(value + 1);
assertVarintRoundTrip(value - 1);
assertVarintRoundTrip(-value);
}
}
/** Tests writeRawVarint32() and writeRawVarint64(). */
@Test
public void testWriteVarint() throws Exception {
assertWriteVarint(bytes(0x00), 0);
assertWriteVarint(bytes(0x01), 1);
assertWriteVarint(bytes(0x7f), 127);
// 14882
assertWriteVarint(bytes(0xa2, 0x74), (0x22 << 0) | (0x74 << 7));
// 2961488830
assertWriteVarint(
bytes(0xbe, 0xf7, 0x92, 0x84, 0x0b),
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x0bL << 28));
// 64-bit
// 7256456126
assertWriteVarint(
bytes(0xbe, 0xf7, 0x92, 0x84, 0x1b),
(0x3e << 0) | (0x77 << 7) | (0x12 << 14) | (0x04 << 21) | (0x1bL << 28));
// 41256202580718336
assertWriteVarint(
bytes(0x80, 0xe6, 0xeb, 0x9c, 0xc3, 0xc9, 0xa4, 0x49),
(0x00 << 0)
| (0x66 << 7)
| (0x6b << 14)
| (0x1c << 21)
| (0x43L << 28)
| (0x49L << 35)
| (0x24L << 42)
| (0x49L << 49));
// 11964378330978735131
assertWriteVarint(
bytes(0x9b, 0xa8, 0xf9, 0xc2, 0xbb, 0xd6, 0x80, 0x85, 0xa6, 0x01),
(0x1b << 0)
| (0x28 << 7)
| (0x79 << 14)
| (0x42 << 21)
| (0x3bL << 28)
| (0x56L << 35)
| (0x00L << 42)
| (0x05L << 49)
| (0x26L << 56)
| (0x01L << 63));
}
@Test
public void testWriteFixed32NoTag() throws Exception {
assertWriteFixed32(bytes(0x78, 0x56, 0x34, 0x12), 0x12345678);
assertWriteFixed32(bytes(0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef0);
}
@Test
public void testWriteFixed64NoTag() throws Exception {
assertWriteFixed64(bytes(0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12), 0x123456789abcdef0L);
assertWriteFixed64(bytes(0x78, 0x56, 0x34, 0x12, 0xf0, 0xde, 0xbc, 0x9a), 0x9abcdef012345678L);
}
@Test
public void testWriteFixed32NoTag_outOfBounds_throws() throws Exception {
for (int i = 0; i < 4; i++) {
Coder coder = outputType.newCoder(i);
// Some coders throw immediately on write, some throw on flush.
@SuppressWarnings("AssertThrowsMultipleStatements")
OutOfSpaceException e =
assertThrows(
OutOfSpaceException.class,
() -> {
coder.stream().writeFixed32NoTag(1);
coder.stream().flush();
});
// STREAM writes one byte at a time.
if (outputType != OutputType.STREAM && outputType != OutputType.STREAM_MINIMUM_BUFFER_SIZE) {
assertThat(e).hasMessageThat().contains("len: 4");
}
if (outputType.supportsSpaceLeft()) {
assertThat(coder.stream().spaceLeft()).isEqualTo(i);
}
}
}
@Test
public void testWriteFixed64NoTag_outOfBounds_throws() throws Exception {
for (int i = 0; i < 8; i++) {
Coder coder = outputType.newCoder(i);
// Some coders throw immediately on write, some throw on flush.
@SuppressWarnings("AssertThrowsMultipleStatements")
OutOfSpaceException e =
assertThrows(
OutOfSpaceException.class,
() -> {
coder.stream().writeFixed64NoTag(1);
coder.stream().flush();
});
if (outputType != OutputType.STREAM && outputType != OutputType.STREAM_MINIMUM_BUFFER_SIZE) {
assertThat(e).hasMessageThat().contains("len: 8");
}
if (outputType.supportsSpaceLeft()) {
assertThat(coder.stream().spaceLeft()).isEqualTo(i);
}
}
}
@Test
// Some coders throw immediately on write, some throw on flush.
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testWriteUInt32NoTag_outOfBounds_throws() throws Exception {
for (int i = 0; i < 5; i++) {
Coder coder = outputType.newCoder(i);
assertThrows(
OutOfSpaceException.class,
() -> {
coder.stream().writeUInt32NoTag(Integer.MAX_VALUE);
coder.stream().flush();
});
// Space left should not go negative.
if (outputType.supportsSpaceLeft()) {
assertWithMessage("i=%s", i).that(coder.stream().spaceLeft()).isAtLeast(0);
}
}
}
@Test
// Some coders throw immediately on write, some throw on flush.
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testWriteUInt64NoTag_outOfBounds_throws() throws Exception {
for (int i = 0; i < 9; i++) {
Coder coder = outputType.newCoder(i);
assertThrows(
OutOfSpaceException.class,
() -> {
coder.stream().writeUInt64NoTag(Long.MAX_VALUE);
coder.stream().flush();
});
// Space left should not go negative.
if (outputType.supportsSpaceLeft()) {
assertWithMessage("i=%s", i).that(coder.stream().spaceLeft()).isAtLeast(0);
}
}
}
/** Test encodeZigZag32() and encodeZigZag64(). */
@Test
public void testEncodeZigZag() throws Exception {
// We only need to run this test once, they don't depend on outputType.
// Arbitrarily run them just for ARRAY.
assume().that(outputType).isEqualTo(OutputType.ARRAY);
assertThat(CodedOutputStream.encodeZigZag32(0)).isEqualTo(0);
assertThat(CodedOutputStream.encodeZigZag32(-1)).isEqualTo(1);
assertThat(CodedOutputStream.encodeZigZag32(1)).isEqualTo(2);
assertThat(CodedOutputStream.encodeZigZag32(-2)).isEqualTo(3);
assertThat(CodedOutputStream.encodeZigZag32(0x3FFFFFFF)).isEqualTo(0x7FFFFFFE);
assertThat(CodedOutputStream.encodeZigZag32(0xC0000000)).isEqualTo(0x7FFFFFFF);
assertThat(CodedOutputStream.encodeZigZag32(0x7FFFFFFF)).isEqualTo(0xFFFFFFFE);
assertThat(CodedOutputStream.encodeZigZag32(0x80000000)).isEqualTo(0xFFFFFFFF);
assertThat(CodedOutputStream.encodeZigZag64(0)).isEqualTo(0);
assertThat(CodedOutputStream.encodeZigZag64(-1)).isEqualTo(1);
assertThat(CodedOutputStream.encodeZigZag64(1)).isEqualTo(2);
assertThat(CodedOutputStream.encodeZigZag64(-2)).isEqualTo(3);
assertThat(CodedOutputStream.encodeZigZag64(0x000000003FFFFFFFL))
.isEqualTo(0x000000007FFFFFFEL);
assertThat(CodedOutputStream.encodeZigZag64(0xFFFFFFFFC0000000L))
.isEqualTo(0x000000007FFFFFFFL);
assertThat(CodedOutputStream.encodeZigZag64(0x000000007FFFFFFFL))
.isEqualTo(0x00000000FFFFFFFEL);
assertThat(CodedOutputStream.encodeZigZag64(0xFFFFFFFF80000000L))
.isEqualTo(0x00000000FFFFFFFFL);
assertThat(CodedOutputStream.encodeZigZag64(0x7FFFFFFFFFFFFFFFL))
.isEqualTo(0xFFFFFFFFFFFFFFFEL);
assertThat(CodedOutputStream.encodeZigZag64(0x8000000000000000L))
.isEqualTo(0xFFFFFFFFFFFFFFFFL);
// Some easier-to-verify round-trip tests. The inputs (other than 0, 1, -1)
// were chosen semi-randomly via keyboard bashing.
assertThat(CodedOutputStream.encodeZigZag32(CodedInputStream.decodeZigZag32(0))).isEqualTo(0);
assertThat(CodedOutputStream.encodeZigZag32(CodedInputStream.decodeZigZag32(1))).isEqualTo(1);
assertThat(CodedOutputStream.encodeZigZag32(CodedInputStream.decodeZigZag32(-1))).isEqualTo(-1);
assertThat(CodedOutputStream.encodeZigZag32(CodedInputStream.decodeZigZag32(14927)))
.isEqualTo(14927);
assertThat(CodedOutputStream.encodeZigZag32(CodedInputStream.decodeZigZag32(-3612)))
.isEqualTo(-3612);
assertThat(CodedOutputStream.encodeZigZag64(CodedInputStream.decodeZigZag64(0))).isEqualTo(0);
assertThat(CodedOutputStream.encodeZigZag64(CodedInputStream.decodeZigZag64(1))).isEqualTo(1);
assertThat(CodedOutputStream.encodeZigZag64(CodedInputStream.decodeZigZag64(-1))).isEqualTo(-1);
assertThat(CodedOutputStream.encodeZigZag64(CodedInputStream.decodeZigZag64(14927)))
.isEqualTo(14927);
assertThat(CodedOutputStream.encodeZigZag64(CodedInputStream.decodeZigZag64(-3612)))
.isEqualTo(-3612);
assertThat(CodedOutputStream.encodeZigZag64(CodedInputStream.decodeZigZag64(856912304801416L)))
.isEqualTo(856912304801416L);
assertThat(
CodedOutputStream.encodeZigZag64(CodedInputStream.decodeZigZag64(-75123905439571256L)))
.isEqualTo(-75123905439571256L);
}
@Test
public void computeIntSize() {
// We only need to run this test once, they don't depend on outputType.
// Arbitrarily run them just for ARRAY.
assume().that(outputType).isEqualTo(OutputType.ARRAY);
assertThat(CodedOutputStream.computeUInt32SizeNoTag(0)).isEqualTo(1);
assertThat(CodedOutputStream.computeUInt64SizeNoTag(0)).isEqualTo(1);
int i;
for (i = 0; i < 7; i++) {
assertThat(CodedOutputStream.computeInt32SizeNoTag(1 << i)).isEqualTo(1);
assertThat(CodedOutputStream.computeUInt32SizeNoTag(1 << i)).isEqualTo(1);
assertThat(CodedOutputStream.computeUInt64SizeNoTag(1L << i)).isEqualTo(1);
}
for (; i < 14; i++) {
assertThat(CodedOutputStream.computeInt32SizeNoTag(1 << i)).isEqualTo(2);
assertThat(CodedOutputStream.computeUInt32SizeNoTag(1 << i)).isEqualTo(2);
assertThat(CodedOutputStream.computeUInt64SizeNoTag(1L << i)).isEqualTo(2);
}
for (; i < 21; i++) {
assertThat(CodedOutputStream.computeInt32SizeNoTag(1 << i)).isEqualTo(3);
assertThat(CodedOutputStream.computeUInt32SizeNoTag(1 << i)).isEqualTo(3);
assertThat(CodedOutputStream.computeUInt64SizeNoTag(1L << i)).isEqualTo(3);
}
for (; i < 28; i++) {
assertThat(CodedOutputStream.computeInt32SizeNoTag(1 << i)).isEqualTo(4);
assertThat(CodedOutputStream.computeUInt32SizeNoTag(1 << i)).isEqualTo(4);
assertThat(CodedOutputStream.computeUInt64SizeNoTag(1L << i)).isEqualTo(4);
}
for (; i < 31; i++) {
assertThat(CodedOutputStream.computeInt32SizeNoTag(1 << i)).isEqualTo(5);
assertThat(CodedOutputStream.computeUInt32SizeNoTag(1 << i)).isEqualTo(5);
assertThat(CodedOutputStream.computeUInt64SizeNoTag(1L << i)).isEqualTo(5);
}
for (; i < 32; i++) {
assertThat(CodedOutputStream.computeInt32SizeNoTag(1 << i)).isEqualTo(10);
assertThat(CodedOutputStream.computeUInt32SizeNoTag(1 << i)).isEqualTo(5);
assertThat(CodedOutputStream.computeUInt64SizeNoTag(1L << i)).isEqualTo(5);
}
for (; i < 35; i++) {
assertThat(CodedOutputStream.computeUInt64SizeNoTag(1L << i)).isEqualTo(5);
}
for (; i < 42; i++) {
assertThat(CodedOutputStream.computeUInt64SizeNoTag(1L << i)).isEqualTo(6);
}
for (; i < 49; i++) {
assertThat(CodedOutputStream.computeUInt64SizeNoTag(1L << i)).isEqualTo(7);
}
for (; i < 56; i++) {
assertThat(CodedOutputStream.computeUInt64SizeNoTag(1L << i)).isEqualTo(8);
}
for (; i < 63; i++) {
assertThat(CodedOutputStream.computeUInt64SizeNoTag(1L << i)).isEqualTo(9);
}
}
@Test
public void computeTagSize() {
// We only need to run this test once, they don't depend on outputType.
// Arbitrarily run them just for ARRAY.
assume().that(outputType).isEqualTo(OutputType.ARRAY);
assertThat(CodedOutputStream.computeTagSize(0)).isEqualTo(1);
int i;
for (i = 0; i < 4; i++) {
assertThat(CodedOutputStream.computeTagSize(1 << i)).isEqualTo(1);
}
for (; i < 11; i++) {
assertThat(CodedOutputStream.computeTagSize(1 << i)).isEqualTo(2);
}
for (; i < 18; i++) {
assertThat(CodedOutputStream.computeTagSize(1 << i)).isEqualTo(3);
}
for (; i < 25; i++) {
assertThat(CodedOutputStream.computeTagSize(1 << i)).isEqualTo(4);
}
for (; i < 29; i++) {
assertThat(CodedOutputStream.computeTagSize(1 << i)).isEqualTo(5);
}
// Invalid tags
assertThat(CodedOutputStream.computeTagSize((1 << 30) + 1)).isEqualTo(1);
}
/**
* Test writing a message containing a negative enum value. This used to fail because the size was
* not properly computed as a sign-extended varint.
*/
@Test
public void testWriteMessageWithNegativeEnumValue() throws Exception {
SparseEnumMessage message =
SparseEnumMessage.newBuilder().setSparseEnum(TestSparseEnum.SPARSE_E).build();
assertThat(message.getSparseEnum().getNumber()).isLessThan(0);
Coder coder = outputType.newCoder(message.getSerializedSize());
message.writeTo(coder.stream());
coder.stream().flush();
byte[] rawBytes = coder.toByteArray();
SparseEnumMessage message2 = SparseEnumMessage.parseFrom(rawBytes);
assertThat(message2.getSparseEnum()).isEqualTo(TestSparseEnum.SPARSE_E);
}
/** Test getTotalBytesWritten() */
@Test
public void testGetTotalBytesWritten() throws Exception {
assume().that(outputType).isEqualTo(OutputType.STREAM);
Coder coder = outputType.newCoder(/* size= */ 16 * 1024);
// Write some some bytes (more than the buffer can hold) and verify that totalWritten
// is correct.
byte[] value = "abcde".getBytes(Internal.UTF_8);
for (int i = 0; i < 1024; ++i) {
coder.stream().writeRawBytes(value, 0, value.length);
}
assertThat(coder.stream().getTotalBytesWritten()).isEqualTo(value.length * 1024);
// Now write an encoded string.
String string =
"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz";
// Ensure we take the slower fast path.
assertThat(CodedOutputStream.computeUInt32SizeNoTag(string.length()))
.isNotEqualTo(
CodedOutputStream.computeUInt32SizeNoTag(string.length() * Utf8.MAX_BYTES_PER_CHAR));
coder.stream().writeStringNoTag(string);
coder.stream().flush();
int stringSize = CodedOutputStream.computeStringSizeNoTag(string);
// Verify that the total bytes written is correct
assertThat(coder.stream().getTotalBytesWritten()).isEqualTo((value.length * 1024) + stringSize);
}
// TODO: Write a comprehensive test suite for CodedOutputStream that covers more than just
// this case.
@Test
public void testWriteStringNoTag_fastpath() throws Exception {
int bufferSize = 153;
String threeBytesPer = "\u0981";
String string = threeBytesPer;
for (int i = 0; i < 50; i++) {
string += threeBytesPer;
}
// These checks ensure we will tickle the slower fast path.
assertThat(CodedOutputStream.computeUInt32SizeNoTag(string.length())).isEqualTo(1);
assertThat(CodedOutputStream.computeUInt32SizeNoTag(string.length() * Utf8.MAX_BYTES_PER_CHAR))
.isEqualTo(2);
assertThat(bufferSize).isEqualTo(string.length() * Utf8.MAX_BYTES_PER_CHAR);
Coder coder = outputType.newCoder(bufferSize + 2);
coder.stream().writeStringNoTag(string);
coder.stream().flush();
}
@Test
public void testWriteToByteBuffer() throws Exception {
assume().that(outputType).isEqualTo(OutputType.NIO_HEAP);
final int bufferSize = 16 * 1024;
ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
CodedOutputStream codedStream = CodedOutputStream.newInstance(buffer);
// Write raw bytes into the ByteBuffer.
final int length1 = 5000;
for (int i = 0; i < length1; i++) {
codedStream.writeRawByte((byte) 1);
}
final int length2 = 8 * 1024;
byte[] data = new byte[length2];
Arrays.fill(data, 0, length2, (byte) 2);
codedStream.writeRawBytes(data);
final int length3 = bufferSize - length1 - length2;
for (int i = 0; i < length3; i++) {
codedStream.writeRawByte((byte) 3);
}
codedStream.flush();
// Check that data is correctly written to the ByteBuffer.
assertThat(buffer.remaining()).isEqualTo(0);
buffer.flip();
for (int i = 0; i < length1; i++) {
assertThat(buffer.get()).isEqualTo((byte) 1);
}
for (int i = 0; i < length2; i++) {
assertThat(buffer.get()).isEqualTo((byte) 2);
}
for (int i = 0; i < length3; i++) {
assertThat(buffer.get()).isEqualTo((byte) 3);
}
}
@Test
public void testWriteByte() throws Exception {
Coder coder = outputType.newCoder(5);
// Write 5 bytes
coder.stream().write((byte) 1);
coder.stream().write((byte) 1);
coder.stream().write((byte) 1);
coder.stream().write((byte) 1);
coder.stream().write((byte) 1);
coder.stream().flush();
byte[] rawBytes = coder.toByteArray();
assertThat(rawBytes).isEqualTo(new byte[] {1, 1, 1, 1, 1});
if (outputType.supportsSpaceLeft()) {
assertThat(coder.stream().spaceLeft()).isEqualTo(0);
}
// Some coders throw immediately on write, some throw on flush.
@SuppressWarnings("AssertThrowsMultipleStatements")
OutOfSpaceException e =
assertThrows(
OutOfSpaceException.class,
() -> {
coder.stream().write((byte) 1);
coder.stream().flush();
});
assertThat(e).hasMessageThat().contains("len: 1");
if (outputType.supportsSpaceLeft()) {
assertThat(coder.stream().spaceLeft()).isEqualTo(0);
}
}
@Test
public void testWriteRawBytes_byteBuffer() throws Exception {
byte[] value = "abcde".getBytes(Internal.UTF_8);
Coder coder = outputType.newCoder(100);
CodedOutputStream codedStream = coder.stream();
ByteBuffer byteBuffer = ByteBuffer.wrap(value, /* offset= */ 0, /* length= */ 1);
assertThat(byteBuffer.capacity()).isEqualTo(5);
// This will actually write 5 bytes into the CodedOutputStream as the
// ByteBuffer's capacity() is 5.
codedStream.writeRawBytes(byteBuffer);
assertThat(codedStream.getTotalBytesWritten()).isEqualTo(5);
// writeRawBytes shouldn't affect the ByteBuffer's state.
assertThat(byteBuffer.position()).isEqualTo(0);
assertThat(byteBuffer.limit()).isEqualTo(1);
// The correct way to write part of an array using ByteBuffer.
codedStream.writeRawBytes(ByteBuffer.wrap(value, /* offset= */ 2, /* length= */ 1).slice());
codedStream.flush();
byte[] result = coder.toByteArray();
assertThat(result).hasLength(6);
for (int i = 0; i < 5; i++) {
assertThat(value[i]).isEqualTo(result[i]);
}
assertThat(value[2]).isEqualTo(result[5]);
}
@Test
public void testWrite_byteBuffer() throws Exception {
byte[] bytes = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Coder coder = outputType.newCoder(100);
CodedOutputStream codedStream = coder.stream();
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
assertThat(byteBuffer.capacity()).isEqualTo(10);
assertThat(byteBuffer.position()).isEqualTo(0);
assertThat(byteBuffer.limit()).isEqualTo(10);
codedStream.write(byteBuffer);
codedStream.flush();
assertThat(codedStream.getTotalBytesWritten()).isEqualTo(10);
// write should update the ByteBuffer's state.
assertThat(byteBuffer.position()).isEqualTo(10);
assertThat(byteBuffer.limit()).isEqualTo(10);
assertThat(coder.toByteArray()).isEqualTo(bytes);
}
@Test
// Some coders throw immediately on write, some throw on flush.
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testWrite_byteBuffer_outOfSpace() throws Exception {
byte[] bytes = new byte[10];
for (int i = 0; i < 10; i++) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
Coder coder = outputType.newCoder(i);
CodedOutputStream codedStream = coder.stream();
assertThrows("i=" + i, OutOfSpaceException.class, () -> {
codedStream.write(byteBuffer);
codedStream.flush();
});
}
}
@Test
public void testWrite_byteArray() throws Exception {
byte[] bytes = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Coder coder = outputType.newCoder(100);
CodedOutputStream codedStream = coder.stream();
codedStream.write(bytes, 0, bytes.length);
codedStream.flush();
assertThat(codedStream.getTotalBytesWritten()).isEqualTo(10);
assertThat(coder.toByteArray()).isEqualTo(bytes);
}
@Test
// Some coders throw immediately on write, some throw on flush.
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testWrite_byteArray_outOfSpace() throws Exception {
byte[] bytes = new byte[10];
for (int i = 0; i < 10; i++) {
Coder coder = outputType.newCoder(i);
CodedOutputStream codedStream = coder.stream();
assertThrows("i=" + i, OutOfSpaceException.class, () -> {
codedStream.write(bytes, 0, bytes.length);
codedStream.flush();
});
}
}
@Test
public void testWriteByteArrayNoTag_withOffsets() throws Exception {
assume().that(outputType).isEqualTo(OutputType.ARRAY);
byte[] fullArray = bytes(0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88);
Coder coder = outputType.newCoder(4);
coder.stream().writeByteArrayNoTag(fullArray, 2, 2);
assertThat(coder.toByteArray()).isEqualTo(bytes(0x02, 0x33, 0x44));
assertThat(coder.stream().getTotalBytesWritten()).isEqualTo(3);
}
@Test
public void testSerializeUtf8_multipleSmallWrites() throws Exception {
final String source = "abcdefghijklmnopqrstuvwxyz";
// Generate the expected output if the source string is written 2 bytes at a time.
ByteArrayOutputStream expectedBytesStream = new ByteArrayOutputStream();
for (int pos = 0; pos < source.length(); pos += 2) {
String substr = source.substring(pos, pos + 2);
expectedBytesStream.write(2);
expectedBytesStream.write(substr.getBytes(Internal.UTF_8));
}
final byte[] expectedBytes = expectedBytesStream.toByteArray();
// Write the source string 2 bytes at a time and verify the output.
Coder coder = outputType.newCoder(expectedBytes.length);
for (int pos = 0; pos < source.length(); pos += 2) {
String substr = source.substring(pos, pos + 2);
coder.stream().writeStringNoTag(substr);
}
coder.stream().flush();
assertThat(coder.toByteArray()).isEqualTo(expectedBytes);
}
@Test
public void testSerializeInvalidUtf8() throws Exception {
String[] invalidStrings =
new String[] {
newString(Character.MIN_HIGH_SURROGATE),
"foobar" + newString(Character.MIN_HIGH_SURROGATE),
newString(Character.MIN_LOW_SURROGATE),
"foobar" + newString(Character.MIN_LOW_SURROGATE),
newString(Character.MIN_HIGH_SURROGATE, Character.MIN_HIGH_SURROGATE)
};
Coder coder = outputType.newCoder(10000);
for (String s : invalidStrings) {
// TODO: These should all fail; instead they are corrupting data.
CodedOutputStream.computeStringSizeNoTag(s);
coder.stream().writeStringNoTag(s);
}
}
// TODO: This test can be deleted once we properly throw IOException while
// encoding invalid UTF-8 strings.
@Test
public void testSerializeInvalidUtf8FollowedByOutOfSpace() throws Exception {
final int notEnoughBytes = 4;
// This test fails for BYTE_OUTPUT_WRAPPING_ARRAY
assume().that(outputType).isNotEqualTo(OutputType.BYTE_OUTPUT_WRAPPING_ARRAY);
Coder coder = outputType.newCoder(notEnoughBytes);
String invalidString = newString(Character.MIN_HIGH_SURROGATE, 'f', 'o', 'o', 'b', 'a', 'r');
// Some coders throw immediately on write, some throw on flush.
@SuppressWarnings("AssertThrowsMultipleStatements")
OutOfSpaceException e =
assertThrows(
OutOfSpaceException.class,
() -> {
coder.stream().writeStringNoTag(invalidString);
coder.stream().flush();
});
assertThat(e).hasCauseThat().isInstanceOf(IndexOutOfBoundsException.class);
}
/** Regression test for https://github.com/protocolbuffers/protobuf/issues/292 */
@Test
// Some coders throw immediately on write, some throw on flush.
@SuppressWarnings("AssertThrowsMultipleStatements")
public void testCorrectExceptionThrowWhenEncodingStringsWithoutEnoughSpace() throws Exception {
String testCase = "Foooooooo";
assertThat(CodedOutputStream.computeUInt32SizeNoTag(testCase.length()))
.isEqualTo(CodedOutputStream.computeUInt32SizeNoTag(testCase.length() * 3));
assertThat(CodedOutputStream.computeStringSize(1, testCase)).isEqualTo(11);
// Tag is one byte, varint describing string length is 1 byte, string length is 9 bytes.
// An array of size 1 will cause a failure when trying to write the varint.
// Stream's buffering means we don't throw.
assume().that(outputType).isNotEqualTo(OutputType.STREAM);
for (int i = 0; i < 11; i++) {
Coder coder = outputType.newCoder(i);
assertThrows(OutOfSpaceException.class, () -> {
coder.stream().writeString(1, testCase);
coder.stream().flush();
});
}
}
@Test
public void testDifferentStringLengths() throws Exception {
// Test string serialization roundtrip using strings of the following lengths,
// with ASCII and Unicode characters requiring different UTF-8 byte counts per
// char, hence causing the length delimiter varint to sometimes require more
// bytes for the Unicode strings than the ASCII string of the same length.
int[] lengths =
new int[] {
0,
1,
(1 << 4) - 1, // 1 byte for ASCII and Unicode
(1 << 7) - 1, // 1 byte for ASCII, 2 bytes for Unicode
(1 << 11) - 1, // 2 bytes for ASCII and Unicode
(1 << 14) - 1, // 2 bytes for ASCII, 3 bytes for Unicode
(1 << 17) - 1,
// 3 bytes for ASCII and Unicode
};
for (int i : lengths) {
testEncodingOfString('q', i); // 1 byte per char
testEncodingOfString('\u07FF', i); // 2 bytes per char
testEncodingOfString('\u0981', i); // 3 bytes per char
}
}
@Test
public void testWriteSmallString() throws Exception {
Coder coder = outputType.newCoder(10);
coder.stream().writeStringNoTag("abc");
coder.stream().flush();
assertThat(coder.toByteArray()).isEqualTo(new byte[] {3, 'a', 'b', 'c'});
}
/**
* Parses the given bytes using writeFixed32NoTag() and checks that the result matches the given
* value.
*/
private void assertWriteFixed32(byte[] data, int value) throws Exception {
Coder coder = outputType.newCoder(data.length);
coder.stream().writeFixed32NoTag(value);
coder.stream().flush();
assertThat(coder.toByteArray()).isEqualTo(data);
}
/**
* Parses the given bytes using writeFixed64NoTag() and checks that the result matches the given
* value.
*/
private void assertWriteFixed64(byte[] data, long value) throws Exception {
Coder coder = outputType.newCoder(data.length);
coder.stream().writeFixed64NoTag(value);
coder.stream().flush();
assertThat(coder.toByteArray()).isEqualTo(data);
}
private static String newString(char... chars) {
return new String(chars);
}
private void testEncodingOfString(char c, int length) throws Exception {
String fullString = fullString(c, length);
TestAllTypes testAllTypes = TestAllTypes.newBuilder().setOptionalString(fullString).build();
Coder coder = outputType.newCoder(testAllTypes.getSerializedSize());
testAllTypes.writeTo(coder.stream());
coder.stream().flush();
assertThat(fullString)
.isEqualTo(TestAllTypes.parseFrom(coder.toByteArray()).getOptionalString());
}
private static String fullString(char c, int length) {
char[] result = new char[length];
Arrays.fill(result, c);
return new String(result);
}
/**
* Helper to construct a byte array from a bunch of bytes. The inputs are actually ints so that I
* can use hex notation and not get stupid errors about precision.
*/
private static byte[] bytes(int... bytesAsInts) {
byte[] bytes = new byte[bytesAsInts.length];
for (int i = 0; i < bytesAsInts.length; i++) {
bytes[i] = (byte) bytesAsInts[i];
}
return bytes;
}
/**
* Writes the given value using writeRawVarint32() and writeRawVarint64() and checks that the
* result matches the given bytes.
*/
@SuppressWarnings("UnnecessaryLongToIntConversion") // Intentionally tests 32-bit int values.
private void assertWriteVarint(byte[] data, long value) throws Exception {
// Only test 32-bit write if the value fits into an int.
if (value == (int) value) {
Coder coder = outputType.newCoder(10);
coder.stream().writeUInt32NoTag((int) value);
coder.stream().flush();
assertThat(coder.toByteArray()).isEqualTo(data);
// Also try computing size.
assertThat(data).hasLength(CodedOutputStream.computeUInt32SizeNoTag((int) value));
}
{
Coder coder = outputType.newCoder(10);
coder.stream().writeUInt64NoTag(value);
coder.stream().flush();
assertThat(coder.toByteArray()).isEqualTo(data);
// Also try computing size.
assertThat(data).hasLength(CodedOutputStream.computeUInt64SizeNoTag(value));
}
}
private void assertVarintRoundTrip(long value) throws Exception {
{
Coder coder = outputType.newCoder(10);
coder.stream().writeUInt64NoTag(value);
coder.stream().flush();
byte[] bytes = coder.toByteArray();
assertThat(bytes).hasLength(CodedOutputStream.computeUInt64SizeNoTag(value));
CodedInputStream input = CodedInputStream.newInstance(new ByteArrayInputStream(bytes));
assertThat(input.readRawVarint64()).isEqualTo(value);
}
if (value == (int) value) {
Coder coder = outputType.newCoder(10);
coder.stream().writeUInt32NoTag((int) value);
coder.stream().flush();
byte[] bytes = coder.toByteArray();
assertThat(bytes).hasLength(CodedOutputStream.computeUInt32SizeNoTag((int) value));
CodedInputStream input = CodedInputStream.newInstance(new ByteArrayInputStream(bytes));
assertThat(input.readRawVarint32()).isEqualTo(value);
}
}
}
|
apache/iceberg
| 38,382
|
core/src/test/java/org/apache/iceberg/TestUpdateRequirements.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iceberg;
import static org.apache.iceberg.types.Types.NestedField.required;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.apache.iceberg.catalog.Namespace;
import org.apache.iceberg.exceptions.CommitFailedException;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
import org.apache.iceberg.relocated.com.google.common.collect.Sets;
import org.apache.iceberg.types.Types;
import org.apache.iceberg.view.ImmutableViewVersion;
import org.apache.iceberg.view.ViewMetadata;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class TestUpdateRequirements {
private final TableMetadata metadata = mock(TableMetadata.class);
private final TableMetadata updated = mock(TableMetadata.class);
private final ViewMetadata viewMetadata = mock(ViewMetadata.class);
private final ViewMetadata updatedViewMetadata = mock(ViewMetadata.class);
@BeforeEach
public void before() {
String uuid = UUID.randomUUID().toString();
when(metadata.uuid()).thenReturn(uuid);
when(updated.uuid()).thenReturn(uuid);
when(viewMetadata.uuid()).thenReturn(uuid);
when(updatedViewMetadata.uuid()).thenReturn(uuid);
}
@Test
public void nullCheck() {
assertThatThrownBy(() -> UpdateRequirements.forCreateTable(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid metadata updates: null");
assertThatThrownBy(() -> UpdateRequirements.forUpdateTable(null, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid table metadata: null");
assertThatThrownBy(() -> UpdateRequirements.forUpdateTable(metadata, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid metadata updates: null");
assertThatThrownBy(() -> UpdateRequirements.forReplaceTable(null, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid table metadata: null");
assertThatThrownBy(() -> UpdateRequirements.forReplaceTable(metadata, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid metadata updates: null");
assertThatThrownBy(() -> UpdateRequirements.forReplaceView(null, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid view metadata: null");
assertThatThrownBy(() -> UpdateRequirements.forReplaceView(viewMetadata, null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Invalid metadata updates: null");
}
@Test
public void emptyUpdatesForCreateTable() {
assertThat(UpdateRequirements.forCreateTable(ImmutableList.of()))
.hasSize(1)
.hasOnlyElementsOfType(UpdateRequirement.AssertTableDoesNotExist.class);
}
@Test
public void emptyUpdatesForUpdateAndReplaceTable() {
assertThat(UpdateRequirements.forReplaceTable(metadata, ImmutableList.of()))
.hasSize(1)
.hasOnlyElementsOfType(UpdateRequirement.AssertTableUUID.class);
assertThat(UpdateRequirements.forUpdateTable(metadata, ImmutableList.of()))
.hasSize(1)
.hasOnlyElementsOfType(UpdateRequirement.AssertTableUUID.class);
}
@Test
public void emptyUpdatesForReplaceView() {
assertThat(UpdateRequirements.forReplaceView(viewMetadata, ImmutableList.of()))
.hasSize(1)
.hasOnlyElementsOfType(UpdateRequirement.AssertViewUUID.class);
}
@Test
public void tableAlreadyExists() {
List<UpdateRequirement> requirements = UpdateRequirements.forCreateTable(ImmutableList.of());
assertThatThrownBy(() -> requirements.forEach(req -> req.validate(metadata)))
.isInstanceOf(CommitFailedException.class)
.hasMessage("Requirement failed: table already exists");
}
@Test
public void assignUUID() {
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.AssignUUID(metadata.uuid()),
new MetadataUpdate.AssignUUID(UUID.randomUUID().toString()),
new MetadataUpdate.AssignUUID(UUID.randomUUID().toString())));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfType(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
}
@Test
public void assignUUIDFailure() {
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.AssignUUID(metadata.uuid())));
when(updated.uuid()).thenReturn(UUID.randomUUID().toString());
assertThatThrownBy(() -> requirements.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage(
String.format(
"Requirement failed: UUID does not match: expected %s != %s",
updated.uuid(), metadata.uuid()));
}
@Test
public void assignUUIDToView() {
List<UpdateRequirement> requirements =
UpdateRequirements.forReplaceView(
viewMetadata,
ImmutableList.of(
new MetadataUpdate.AssignUUID(viewMetadata.uuid()),
new MetadataUpdate.AssignUUID(UUID.randomUUID().toString()),
new MetadataUpdate.AssignUUID(UUID.randomUUID().toString())));
requirements.forEach(req -> req.validate(viewMetadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfType(UpdateRequirement.AssertViewUUID.class);
assertViewUUID(requirements);
}
@Test
public void assignUUIDToViewFailure() {
List<UpdateRequirement> requirements =
UpdateRequirements.forReplaceView(
viewMetadata, ImmutableList.of(new MetadataUpdate.AssignUUID(viewMetadata.uuid())));
when(updatedViewMetadata.uuid()).thenReturn(UUID.randomUUID().toString());
assertThatThrownBy(() -> requirements.forEach(req -> req.validate(updatedViewMetadata)))
.isInstanceOf(CommitFailedException.class)
.hasMessage(
String.format(
"Requirement failed: view UUID does not match: expected %s != %s",
updatedViewMetadata.uuid(), viewMetadata.uuid()));
}
@ParameterizedTest
@ValueSource(ints = {2, 3})
public void upgradeFormatVersion(int formatVersion) {
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.UpgradeFormatVersion(formatVersion)));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfType(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
}
@Test
public void upgradeFormatVersionForView() {
List<UpdateRequirement> requirements =
UpdateRequirements.forReplaceView(
viewMetadata, ImmutableList.of(new MetadataUpdate.UpgradeFormatVersion(2)));
requirements.forEach(req -> req.validate(viewMetadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfType(UpdateRequirement.AssertViewUUID.class);
assertViewUUID(requirements);
}
@Test
public void addSchema() {
int lastColumnId = 1;
when(metadata.lastColumnId()).thenReturn(lastColumnId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.AddSchema(new Schema()),
new MetadataUpdate.AddSchema(new Schema()),
new MetadataUpdate.AddSchema(new Schema())));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(2)
.hasOnlyElementsOfTypes(
UpdateRequirement.AssertTableUUID.class,
UpdateRequirement.AssertLastAssignedFieldId.class);
assertTableUUID(requirements);
assertThat(requirements)
.element(1)
.asInstanceOf(
InstanceOfAssertFactories.type(UpdateRequirement.AssertLastAssignedFieldId.class))
.extracting(UpdateRequirement.AssertLastAssignedFieldId::lastAssignedFieldId)
.isEqualTo(lastColumnId);
}
@Test
public void addSchemaFailure() {
when(metadata.lastColumnId()).thenReturn(2);
when(updated.lastColumnId()).thenReturn(3);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.AddSchema(new Schema()),
new MetadataUpdate.AddSchema(new Schema()),
new MetadataUpdate.AddSchema(new Schema())));
assertThatThrownBy(() -> requirements.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage("Requirement failed: last assigned field id changed: expected id 2 != 3");
}
@Test
public void addSchemaForView() {
List<UpdateRequirement> requirements =
UpdateRequirements.forReplaceView(
viewMetadata,
ImmutableList.of(
new MetadataUpdate.AddSchema(new Schema()),
new MetadataUpdate.AddSchema(new Schema()),
new MetadataUpdate.AddSchema(new Schema())));
requirements.forEach(req -> req.validate(viewMetadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertViewUUID.class);
assertViewUUID(requirements);
}
@Test
public void setCurrentSchema() {
int schemaId = 3;
when(metadata.currentSchemaId()).thenReturn(schemaId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.SetCurrentSchema(schemaId),
new MetadataUpdate.SetCurrentSchema(schemaId + 1),
new MetadataUpdate.SetCurrentSchema(schemaId + 2)));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(2)
.hasOnlyElementsOfTypes(
UpdateRequirement.AssertTableUUID.class, UpdateRequirement.AssertCurrentSchemaID.class);
assertTableUUID(requirements);
assertCurrentSchemaId(requirements, 1, schemaId);
}
@Test
public void setCurrentSchemaFailure() {
int schemaId = 3;
when(metadata.currentSchemaId()).thenReturn(schemaId);
when(updated.currentSchemaId()).thenReturn(schemaId + 1);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.SetCurrentSchema(schemaId),
new MetadataUpdate.SetCurrentSchema(schemaId + 1),
new MetadataUpdate.SetCurrentSchema(schemaId + 2)));
assertThatThrownBy(() -> requirements.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage("Requirement failed: current schema changed: expected id 3 != 4");
}
@Test
public void addPartitionSpec() {
int lastAssignedPartitionId = 3;
when(metadata.lastAssignedPartitionId()).thenReturn(lastAssignedPartitionId);
Schema schema = new Schema(required(3, "id", Types.IntegerType.get()));
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.AddPartitionSpec(
PartitionSpec.builderFor(schema).withSpecId(lastAssignedPartitionId).build()),
new MetadataUpdate.AddPartitionSpec(
PartitionSpec.builderFor(schema)
.withSpecId(lastAssignedPartitionId + 1)
.build()),
new MetadataUpdate.AddPartitionSpec(
PartitionSpec.builderFor(schema)
.withSpecId(lastAssignedPartitionId + 2)
.build())));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(2)
.hasOnlyElementsOfTypes(
UpdateRequirement.AssertTableUUID.class,
UpdateRequirement.AssertLastAssignedPartitionId.class);
assertTableUUID(requirements);
assertThat(requirements)
.element(1)
.asInstanceOf(
InstanceOfAssertFactories.type(UpdateRequirement.AssertLastAssignedPartitionId.class))
.extracting(UpdateRequirement.AssertLastAssignedPartitionId::lastAssignedPartitionId)
.isEqualTo(lastAssignedPartitionId);
}
@Test
public void addPartitionSpecFailure() {
when(metadata.lastAssignedPartitionId()).thenReturn(3);
when(updated.lastAssignedPartitionId()).thenReturn(4);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(new MetadataUpdate.AddPartitionSpec(PartitionSpec.unpartitioned())));
assertThatThrownBy(() -> requirements.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage("Requirement failed: last assigned partition id changed: expected id 3 != 4");
}
@Test
public void setDefaultPartitionSpec() {
int specId = 3;
when(metadata.defaultSpecId()).thenReturn(specId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.SetDefaultPartitionSpec(specId),
new MetadataUpdate.SetDefaultPartitionSpec(specId + 1),
new MetadataUpdate.SetDefaultPartitionSpec(specId + 2)));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(2)
.hasOnlyElementsOfTypes(
UpdateRequirement.AssertTableUUID.class, UpdateRequirement.AssertDefaultSpecID.class);
assertTableUUID(requirements);
assertDefaultSpecId(requirements, 1, specId);
}
@Test
public void setDefaultPartitionSpecFailure() {
int specId = PartitionSpec.unpartitioned().specId();
when(updated.defaultSpecId()).thenReturn(specId + 1);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.SetDefaultPartitionSpec(specId),
new MetadataUpdate.SetDefaultPartitionSpec(specId + 1),
new MetadataUpdate.SetDefaultPartitionSpec(specId + 2)));
assertThatThrownBy(() -> requirements.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage("Requirement failed: default partition spec changed: expected id 0 != 1");
}
@Test
public void removePartitionSpec() {
int defaultSpecId = 3;
when(metadata.defaultSpecId()).thenReturn(defaultSpecId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(new MetadataUpdate.RemovePartitionSpecs(Sets.newHashSet(1, 2))));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(2)
.hasOnlyElementsOfTypes(
UpdateRequirement.AssertTableUUID.class, UpdateRequirement.AssertDefaultSpecID.class);
assertTableUUID(requirements);
assertDefaultSpecId(requirements, 1, defaultSpecId);
}
@Test
public void testRemovePartitionSpecsWithBranch() {
int defaultSpecId = 3;
long snapshotId = 42L;
when(metadata.defaultSpecId()).thenReturn(defaultSpecId);
mockBranch("branch", snapshotId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(new MetadataUpdate.RemovePartitionSpecs(Sets.newHashSet(1, 2))));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(3)
.hasOnlyElementsOfTypes(
UpdateRequirement.AssertTableUUID.class,
UpdateRequirement.AssertDefaultSpecID.class,
UpdateRequirement.AssertRefSnapshotID.class);
assertTableUUID(requirements);
assertDefaultSpecId(requirements, 1, defaultSpecId);
assertRefSnapshotId(requirements, 2, snapshotId);
}
@Test
public void testRemovePartitionSpecsWithSpecChangedFailure() {
int defaultSpecId = 3;
when(metadata.defaultSpecId()).thenReturn(defaultSpecId);
when(updated.defaultSpecId()).thenReturn(defaultSpecId + 1);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(new MetadataUpdate.RemovePartitionSpecs(Sets.newHashSet(1, 2))));
assertThatThrownBy(() -> requirements.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage(
"Requirement failed: default partition spec changed: expected id %s != %s",
defaultSpecId, defaultSpecId + 1);
}
@Test
public void testRemovePartitionSpecsWithBranchChangedFailure() {
int defaultSpecId = 3;
when(metadata.defaultSpecId()).thenReturn(defaultSpecId);
when(updated.defaultSpecId()).thenReturn(defaultSpecId);
long snapshotId = 42L;
String branch = "test";
mockBranchChanged(branch, snapshotId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(new MetadataUpdate.RemovePartitionSpecs(Sets.newHashSet(1, 2))));
assertThatThrownBy(() -> requirements.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage(
"Requirement failed: branch %s has changed: expected id %s != %s",
branch, snapshotId, snapshotId + 1);
}
private void mockBranchChanged(String branch, long snapshotId) {
mockBranch(branch, snapshotId);
SnapshotRef updatedRef = mock(SnapshotRef.class);
when(updatedRef.snapshotId()).thenReturn(snapshotId + 1);
when(updatedRef.isBranch()).thenReturn(true);
when(updated.ref(branch)).thenReturn(updatedRef);
}
private void mockBranch(String branch, long snapshotId) {
SnapshotRef snapshotRef = mock(SnapshotRef.class);
when(snapshotRef.snapshotId()).thenReturn(snapshotId);
when(snapshotRef.isBranch()).thenReturn(true);
when(metadata.refs()).thenReturn(ImmutableMap.of(branch, snapshotRef));
when(metadata.ref(branch)).thenReturn(snapshotRef);
}
@Test
public void removeSchemas() {
int currentSchemaId = 3;
when(metadata.currentSchemaId()).thenReturn(currentSchemaId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.RemoveSchemas(Sets.newHashSet(1, 2))));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(2)
.hasOnlyElementsOfTypes(
UpdateRequirement.AssertTableUUID.class, UpdateRequirement.AssertCurrentSchemaID.class);
assertTableUUID(requirements);
assertCurrentSchemaId(requirements, 1, currentSchemaId);
}
@Test
public void testRemoveSchemasWithBranch() {
int currentSchemaId = 3;
long snapshotId = 42L;
when(metadata.currentSchemaId()).thenReturn(currentSchemaId);
mockBranch("branch", snapshotId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.RemoveSchemas(Sets.newHashSet(1, 2))));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(3)
.hasOnlyElementsOfTypes(
UpdateRequirement.AssertTableUUID.class,
UpdateRequirement.AssertCurrentSchemaID.class,
UpdateRequirement.AssertRefSnapshotID.class);
assertTableUUID(requirements);
assertCurrentSchemaId(requirements, 1, currentSchemaId);
assertRefSnapshotId(requirements, 2, snapshotId);
}
@Test
public void testRemoveSchemasWithSchemaChangedFailure() {
int currentSchemaId = 3;
when(metadata.currentSchemaId()).thenReturn(currentSchemaId);
when(updated.currentSchemaId()).thenReturn(currentSchemaId + 1);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.RemoveSchemas(Sets.newHashSet(1, 2))));
assertThatThrownBy(() -> requirements.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage(
"Requirement failed: current schema changed: expected id %s != %s",
currentSchemaId, currentSchemaId + 1);
}
@Test
public void testRemoveSchemasWithBranchChangedFailure() {
int currentSchemaId = 3;
when(metadata.currentSchemaId()).thenReturn(currentSchemaId);
when(updated.currentSchemaId()).thenReturn(currentSchemaId);
long snapshotId = 42L;
String branch = "test";
mockBranchChanged(branch, snapshotId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.RemoveSchemas(Sets.newHashSet(1, 2))));
assertThatThrownBy(() -> requirements.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage(
"Requirement failed: branch %s has changed: expected id %s != %s",
branch, snapshotId, snapshotId + 1);
}
@Test
public void addSortOrder() {
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.AddSortOrder(SortOrder.unsorted())));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
}
@Test
public void setDefaultSortOrder() {
int sortOrderId = 3;
when(metadata.defaultSortOrderId()).thenReturn(sortOrderId);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.SetDefaultSortOrder(sortOrderId),
new MetadataUpdate.SetDefaultSortOrder(sortOrderId + 1),
new MetadataUpdate.SetDefaultSortOrder(sortOrderId + 2)));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(2)
.hasOnlyElementsOfTypes(
UpdateRequirement.AssertTableUUID.class,
UpdateRequirement.AssertDefaultSortOrderID.class);
assertTableUUID(requirements);
assertThat(requirements)
.element(1)
.asInstanceOf(
InstanceOfAssertFactories.type(UpdateRequirement.AssertDefaultSortOrderID.class))
.extracting(UpdateRequirement.AssertDefaultSortOrderID::sortOrderId)
.isEqualTo(sortOrderId);
}
@Test
public void setDefaultSortOrderFailure() {
int sortOrderId = SortOrder.unsorted().orderId();
when(updated.defaultSortOrderId()).thenReturn(sortOrderId + 1);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.SetDefaultSortOrder(sortOrderId)));
assertThatThrownBy(() -> requirements.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage("Requirement failed: default sort order changed: expected id 0 != 1");
}
@Test
public void setAndRemoveStatistics() {
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(new MetadataUpdate.SetStatistics(mock(StatisticsFile.class))));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.RemoveStatistics(0L)));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
}
@Test
public void addAndRemoveSnapshot() {
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.AddSnapshot(mock(Snapshot.class))));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.RemoveSnapshots(0L)));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
}
@Test
public void addAndRemoveSnapshots() {
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.AddSnapshot(mock(Snapshot.class))));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.RemoveSnapshots(Set.of(0L))));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
}
@Test
public void setAndRemoveSnapshotRef() {
long snapshotId = 14L;
String refName = "branch";
SnapshotRef snapshotRef = mock(SnapshotRef.class);
when(snapshotRef.snapshotId()).thenReturn(snapshotId);
when(metadata.ref(refName)).thenReturn(snapshotRef);
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(
new MetadataUpdate.SetSnapshotRef(
refName, snapshotId, SnapshotRefType.BRANCH, 0, 0L, 0L),
new MetadataUpdate.SetSnapshotRef(
refName, snapshotId + 1, SnapshotRefType.BRANCH, 0, 0L, 0L),
new MetadataUpdate.SetSnapshotRef(
refName, snapshotId + 2, SnapshotRefType.BRANCH, 0, 0L, 0L)));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(2)
.hasOnlyElementsOfTypes(
UpdateRequirement.AssertTableUUID.class, UpdateRequirement.AssertRefSnapshotID.class);
assertTableUUID(requirements);
UpdateRequirement.AssertRefSnapshotID assertRefSnapshotID =
(UpdateRequirement.AssertRefSnapshotID) requirements.get(1);
assertThat(assertRefSnapshotID.snapshotId()).isEqualTo(snapshotId);
assertThat(assertRefSnapshotID.refName()).isEqualTo(refName);
requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.RemoveSnapshots(Set.of(0L))));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
}
@Test
public void setSnapshotRefFailure() {
long snapshotId = 14L;
String refName = "random_branch";
SnapshotRef snapshotRef = mock(SnapshotRef.class);
when(snapshotRef.isBranch()).thenReturn(true);
when(snapshotRef.snapshotId()).thenReturn(snapshotId);
ImmutableList<MetadataUpdate> metadataUpdates =
ImmutableList.of(
new MetadataUpdate.SetSnapshotRef(
refName, snapshotId, SnapshotRefType.BRANCH, 0, 0L, 0L));
when(metadata.ref(refName)).thenReturn(null);
when(updated.ref(refName)).thenReturn(snapshotRef);
assertThatThrownBy(
() ->
UpdateRequirements.forUpdateTable(metadata, metadataUpdates)
.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage("Requirement failed: branch random_branch was created concurrently");
when(metadata.ref(refName)).thenReturn(snapshotRef);
when(updated.ref(refName)).thenReturn(null);
assertThatThrownBy(
() ->
UpdateRequirements.forUpdateTable(metadata, metadataUpdates)
.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage("Requirement failed: branch or tag random_branch is missing, expected 14");
SnapshotRef snapshotRefUpdated = mock(SnapshotRef.class);
when(snapshotRefUpdated.isBranch()).thenReturn(true);
when(snapshotRefUpdated.snapshotId()).thenReturn(snapshotId + 1);
when(updated.ref(refName)).thenReturn(snapshotRefUpdated);
assertThatThrownBy(
() ->
UpdateRequirements.forUpdateTable(metadata, metadataUpdates)
.forEach(req -> req.validate(updated)))
.isInstanceOf(CommitFailedException.class)
.hasMessage("Requirement failed: branch random_branch has changed: expected id 14 != 15");
}
@Test
public void setAndRemoveProperties() {
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(new MetadataUpdate.SetProperties(ImmutableMap.of("test", "test"))));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
requirements =
UpdateRequirements.forUpdateTable(
metadata,
ImmutableList.of(new MetadataUpdate.RemoveProperties(Sets.newHashSet("test"))));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
}
@Test
public void setAndRemovePropertiesForView() {
List<UpdateRequirement> requirements =
UpdateRequirements.forReplaceView(
viewMetadata,
ImmutableList.of(new MetadataUpdate.SetProperties(ImmutableMap.of("test", "test"))));
requirements.forEach(req -> req.validate(viewMetadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertViewUUID.class);
assertViewUUID(requirements);
requirements =
UpdateRequirements.forReplaceView(
viewMetadata,
ImmutableList.of(new MetadataUpdate.RemoveProperties(Sets.newHashSet("test"))));
requirements.forEach(req -> req.validate(viewMetadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertViewUUID.class);
assertViewUUID(requirements);
}
@Test
public void setLocation() {
List<UpdateRequirement> requirements =
UpdateRequirements.forUpdateTable(
metadata, ImmutableList.of(new MetadataUpdate.SetLocation("location")));
requirements.forEach(req -> req.validate(metadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertTableUUID.class);
assertTableUUID(requirements);
}
@Test
public void setLocationForView() {
List<UpdateRequirement> requirements =
UpdateRequirements.forReplaceView(
viewMetadata, ImmutableList.of(new MetadataUpdate.SetLocation("location")));
requirements.forEach(req -> req.validate(viewMetadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertViewUUID.class);
assertViewUUID(requirements);
}
@Test
public void addViewVersion() {
List<UpdateRequirement> requirements =
UpdateRequirements.forReplaceView(
viewMetadata,
ImmutableList.of(
new MetadataUpdate.AddViewVersion(
ImmutableViewVersion.builder()
.versionId(1)
.schemaId(1)
.timestampMillis(System.currentTimeMillis())
.defaultNamespace(Namespace.of("ns"))
.build()),
new MetadataUpdate.AddViewVersion(
ImmutableViewVersion.builder()
.versionId(2)
.schemaId(1)
.timestampMillis(System.currentTimeMillis())
.defaultNamespace(Namespace.of("ns"))
.build()),
new MetadataUpdate.AddViewVersion(
ImmutableViewVersion.builder()
.versionId(3)
.schemaId(1)
.timestampMillis(System.currentTimeMillis())
.defaultNamespace(Namespace.of("ns"))
.build())));
requirements.forEach(req -> req.validate(viewMetadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertViewUUID.class);
assertViewUUID(requirements);
}
@Test
public void setCurrentViewVersion() {
List<UpdateRequirement> requirements =
UpdateRequirements.forReplaceView(
viewMetadata,
ImmutableList.of(
new MetadataUpdate.AddViewVersion(
ImmutableViewVersion.builder()
.versionId(3)
.schemaId(1)
.timestampMillis(System.currentTimeMillis())
.defaultNamespace(Namespace.of("ns"))
.build()),
new MetadataUpdate.AddViewVersion(
ImmutableViewVersion.builder()
.versionId(2)
.schemaId(1)
.timestampMillis(System.currentTimeMillis())
.defaultNamespace(Namespace.of("ns"))
.build()),
new MetadataUpdate.AddViewVersion(
ImmutableViewVersion.builder()
.versionId(1)
.schemaId(1)
.timestampMillis(System.currentTimeMillis())
.defaultNamespace(Namespace.of("ns"))
.build()),
new MetadataUpdate.SetCurrentViewVersion(2)));
requirements.forEach(req -> req.validate(viewMetadata));
assertThat(requirements)
.hasSize(1)
.hasOnlyElementsOfTypes(UpdateRequirement.AssertViewUUID.class);
assertViewUUID(requirements);
}
private void assertTableUUID(List<UpdateRequirement> requirements) {
assertThat(requirements)
.element(0)
.asInstanceOf(InstanceOfAssertFactories.type(UpdateRequirement.AssertTableUUID.class))
.extracting(UpdateRequirement.AssertTableUUID::uuid)
.isEqualTo(metadata.uuid());
}
private void assertViewUUID(List<UpdateRequirement> requirements) {
assertThat(requirements)
.element(0)
.asInstanceOf(InstanceOfAssertFactories.type(UpdateRequirement.AssertViewUUID.class))
.extracting(UpdateRequirement.AssertViewUUID::uuid)
.isEqualTo(viewMetadata.uuid());
}
private void assertDefaultSpecId(
List<UpdateRequirement> requirements, int idx, int defaultSpecId) {
assertThat(requirements)
.element(idx)
.asInstanceOf(InstanceOfAssertFactories.type(UpdateRequirement.AssertDefaultSpecID.class))
.extracting(UpdateRequirement.AssertDefaultSpecID::specId)
.isEqualTo(defaultSpecId);
}
private void assertCurrentSchemaId(
List<UpdateRequirement> requirements, int idx, int currentSchemaId) {
assertThat(requirements)
.element(idx)
.asInstanceOf(InstanceOfAssertFactories.type(UpdateRequirement.AssertCurrentSchemaID.class))
.extracting(UpdateRequirement.AssertCurrentSchemaID::schemaId)
.isEqualTo(currentSchemaId);
}
private void assertRefSnapshotId(List<UpdateRequirement> requirements, int idx, long snapshotId) {
assertThat(requirements)
.element(idx)
.asInstanceOf(InstanceOfAssertFactories.type(UpdateRequirement.AssertRefSnapshotID.class))
.extracting(UpdateRequirement.AssertRefSnapshotID::snapshotId)
.isEqualTo(snapshotId);
}
}
|
apache/manifoldcf
| 38,330
|
connectors/nuxeo/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/nuxeo/NuxeoRepositoryConnector.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.manifoldcf.crawler.connectors.nuxeo;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import org.apache.commons.lang.StringUtils;
import org.apache.manifoldcf.agents.interfaces.RepositoryDocument;
import org.apache.manifoldcf.agents.interfaces.ServiceInterruption;
import org.apache.manifoldcf.core.interfaces.ConfigParams;
import org.apache.manifoldcf.core.interfaces.IHTTPOutput;
import org.apache.manifoldcf.core.interfaces.IPasswordMapperActivity;
import org.apache.manifoldcf.core.interfaces.IPostParameters;
import org.apache.manifoldcf.core.interfaces.IThreadContext;
import org.apache.manifoldcf.core.interfaces.ManifoldCFException;
import org.apache.manifoldcf.core.interfaces.Specification;
import org.apache.manifoldcf.core.interfaces.SpecificationNode;
import org.apache.manifoldcf.crawler.connectors.BaseRepositoryConnector;
import org.apache.manifoldcf.crawler.connectors.nuxeo.model.NuxeoAttachment;
import org.apache.manifoldcf.crawler.connectors.nuxeo.model.NuxeoDocumentHelper;
import org.apache.manifoldcf.crawler.interfaces.IExistingVersions;
import org.apache.manifoldcf.crawler.interfaces.IProcessActivity;
import org.apache.manifoldcf.crawler.interfaces.IRepositoryConnector;
import org.apache.manifoldcf.crawler.interfaces.ISeedingActivity;
import org.apache.manifoldcf.crawler.system.Logging;
import org.nuxeo.client.NuxeoClient;
import org.nuxeo.client.objects.Document;
import org.nuxeo.client.objects.Documents;
import org.nuxeo.client.spi.NuxeoClientException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
*
* Nuxeo Repository Connector class
*
* @author David Arroyo Escobar <arroyoescobardavid@gmail.com>
*
*/
public class NuxeoRepositoryConnector extends BaseRepositoryConnector {
private static final String URI_DOCUMENT = "SELECT * FROM Document";
private final static String ACTIVITY_READ = "read document";
// Configuration tabs
private static final String NUXEO_SERVER_TAB_PROPERTY = "NuxeoRepositoryConnector.Server";
// Specification tabs
private static final String CONF_DOMAINS_TAB_PROPERTY = "NuxeoRepositoryConnector.Domains";
private static final String CONF_DOCUMENTS_TYPE_TAB_PROPERTY = "NuxeoRepositoryConnector.DocumentsType";
private static final String CONF_DOCUMENT_PROPERTY = "NuxeoRepositoryConnector.Documents";
// Prefix for nuxeo configuration and specification parameters
private static final String PARAMETER_PREFIX = "nuxeo_";
// Templates for Nuxeo configuration
/**
* Javascript to check the configuration parameters
*/
private static final String EDIT_CONFIG_HEADER_FORWARD = "editConfiguration_conf.js";
/**
* Server edit tab template
*/
private static final String EDIT_CONFIG_FORWARD_SERVER = "editConfiguration_conf_server.html";
/**
* Server view tab template
*/
private static final String VIEW_CONFIG_FORWARD = "viewConfiguration_conf.html";
// Templates for Nuxeo specification
/**
* Forward to the javascript to check the specification parameters for the
* job
*/
private static final String EDIT_SPEC_HEADER_FORWARD = "editSpecification_conf.js";
/**
* Forward to the template to edit domains for the job
*/
private static final String EDIT_SPEC_FORWARD_CONF_DOMAINS = "editSpecification_confDomains.html";
/**
* Forward to the template to edit documents type for the job
*/
private static final String EDIT_SPEC_FORWARD_CONF_DOCUMENTS_TYPE = "editSpecification_confDocumentsType.html";
/**
* Forward to the template to edit document properties for the job
*/
private static final String EDIT_SPEC_FORWARD_CONF_DOCUMENTS = "editSpecification_confDocuments.html";
/**
* Forward to the template to view the specification parameters for the job
*/
private static final String VIEW_SPEC_FORWARD = "viewSpecification_conf.html";
protected long lastSessionFetch = -1L;
protected static final long timeToRelease = 300000L;
private Logger logger = LoggerFactory.getLogger(NuxeoRepositoryConnector.class);
/* Nuxeo instance parameters */
protected String protocol = null;
protected String host = null;
protected String port = null;
protected String path = null;
protected String username = null;
protected String password = null;
private NuxeoClient nuxeoClient = null;
// Constructor
public NuxeoRepositoryConnector() {
super();
}
void setNuxeoClient(NuxeoClient nuxeoClient) {
this.nuxeoClient = nuxeoClient;
}
@Override
public String[] getActivitiesList() {
return new String[] { ACTIVITY_READ };
}
@Override
public String[] getBinNames(String documentIdenfitier) {
return new String[] { host };
}
/** CONFIGURATION CONNECTOR **/
@Override
public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out, Locale locale,
ConfigParams parameters, List<String> tabsArray) throws ManifoldCFException, IOException {
// Server tab
tabsArray.add(Messages.getString(locale, NUXEO_SERVER_TAB_PROPERTY));
Map<String, String> paramMap = new HashMap<String, String>();
// Fill in the parameters form each tab
fillInServerConfigurationMap(paramMap, out, parameters);
Messages.outputResourceWithVelocity(out, locale, EDIT_CONFIG_HEADER_FORWARD, paramMap, true);
}
@Override
public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale,
ConfigParams parameters, String tabName) throws ManifoldCFException, IOException {
// Call the Velocity tempaltes for each tab
Map<String, String> paramMap = new HashMap<String, String>();
// Set the tab name
paramMap.put("TabName", tabName);
// Fill in the parameters
fillInServerConfigurationMap(paramMap, out, parameters);
// Server tab
Messages.outputResourceWithVelocity(out, locale, EDIT_CONFIG_FORWARD_SERVER, paramMap, true);
}
private static void fillInServerConfigurationMap(Map<String, String> serverMap, IPasswordMapperActivity mapper,
ConfigParams parameters) {
String nuxeoProtocol = parameters.getParameter(NuxeoConfiguration.Server.PROTOCOL);
String nuxeoHost = parameters.getParameter(NuxeoConfiguration.Server.HOST);
String nuxeoPort = parameters.getParameter(NuxeoConfiguration.Server.PORT);
String nuxeoPath = parameters.getParameter(NuxeoConfiguration.Server.PATH);
String nuxeoUsername = parameters.getParameter(NuxeoConfiguration.Server.USERNAME);
String nuxeoPassword = parameters.getObfuscatedParameter(NuxeoConfiguration.Server.PASSWORD);
if (nuxeoProtocol == null)
nuxeoProtocol = NuxeoConfiguration.Server.PROTOCOL_DEFAULT_VALUE;
if (nuxeoHost == null)
nuxeoHost = NuxeoConfiguration.Server.HOST_DEFAULT_VALUE;
if (nuxeoPort == null)
nuxeoPort = NuxeoConfiguration.Server.PORT_DEFAULT_VALUE;
if (nuxeoPath == null)
nuxeoPath = NuxeoConfiguration.Server.PATH_DEFAULT_VALUE;
if (nuxeoUsername == null)
nuxeoUsername = NuxeoConfiguration.Server.USERNAME_DEFAULT_VALUE;
if (nuxeoPassword == null)
nuxeoPassword = NuxeoConfiguration.Server.PASSWORD_DEFAULT_VALUE;
else
nuxeoPassword = mapper.mapPasswordToKey(nuxeoPassword);
serverMap.put(PARAMETER_PREFIX + NuxeoConfiguration.Server.PROTOCOL, nuxeoProtocol);
serverMap.put(PARAMETER_PREFIX + NuxeoConfiguration.Server.HOST, nuxeoHost);
serverMap.put(PARAMETER_PREFIX + NuxeoConfiguration.Server.PORT, nuxeoPort);
serverMap.put(PARAMETER_PREFIX + NuxeoConfiguration.Server.PATH, nuxeoPath);
serverMap.put(PARAMETER_PREFIX + NuxeoConfiguration.Server.USERNAME, nuxeoUsername);
serverMap.put(PARAMETER_PREFIX + NuxeoConfiguration.Server.PASSWORD, nuxeoPassword);
}
@Override
public String processConfigurationPost(IThreadContext thredContext, IPostParameters variableContext,
ConfigParams parameters) {
String nuxeoProtocol = variableContext.getParameter(PARAMETER_PREFIX + NuxeoConfiguration.Server.PROTOCOL);
if (nuxeoProtocol != null)
parameters.setParameter(NuxeoConfiguration.Server.PROTOCOL, nuxeoProtocol);
String nuxeoHost = variableContext.getParameter(PARAMETER_PREFIX + NuxeoConfiguration.Server.HOST);
if (nuxeoHost != null)
parameters.setParameter(NuxeoConfiguration.Server.HOST, nuxeoHost);
String nuxeoPort = variableContext.getParameter(PARAMETER_PREFIX + NuxeoConfiguration.Server.PORT);
if (nuxeoPort != null)
parameters.setParameter(NuxeoConfiguration.Server.PORT, nuxeoPort);
String nuxeoPath = variableContext.getParameter(PARAMETER_PREFIX + NuxeoConfiguration.Server.PATH);
if (nuxeoPath != null)
parameters.setParameter(NuxeoConfiguration.Server.PATH, nuxeoPath);
String nuxeoUsername = variableContext.getParameter(PARAMETER_PREFIX + NuxeoConfiguration.Server.USERNAME);
if (nuxeoUsername != null)
parameters.setParameter(NuxeoConfiguration.Server.USERNAME, nuxeoUsername);
String nuxeoPassword = variableContext.getParameter(PARAMETER_PREFIX + NuxeoConfiguration.Server.PASSWORD);
if (nuxeoPassword != null)
parameters.setObfuscatedParameter(NuxeoConfiguration.Server.PASSWORD,
variableContext.mapKeyToPassword(nuxeoPassword));
return null;
}
@Override
public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters)
throws ManifoldCFException, IOException {
Map<String, String> paramMap = new HashMap<String, String>();
fillInServerConfigurationMap(paramMap, out, parameters);
Messages.outputResourceWithVelocity(out, locale, VIEW_CONFIG_FORWARD, paramMap, true);
}
/** CONNECTION **/
@Override
public void connect(ConfigParams configParams) {
super.connect(configParams);
protocol = params.getParameter(NuxeoConfiguration.Server.PROTOCOL);
host = params.getParameter(NuxeoConfiguration.Server.HOST);
port = params.getParameter(NuxeoConfiguration.Server.PORT);
path = params.getParameter(NuxeoConfiguration.Server.PATH);
username = params.getParameter(NuxeoConfiguration.Server.USERNAME);
password = params.getObfuscatedParameter(NuxeoConfiguration.Server.PASSWORD);
}
@Override
public void disconnect() throws ManifoldCFException {
shutdownNuxeoClient();
protocol = null;
host = null;
port = null;
path = null;
username = null;
password = null;
super.disconnect();
}
// Check the connection
@Override
public String check() throws ManifoldCFException {
//shutdownNuxeoClient();
try {
initNuxeoClient();
} catch (NuxeoClientException ex) {
return "Connection failed: "+ex.getMessage();
}
return super.check();
}
/**
* Initialize Nuxeo client using the configured parameters.
*
* @throws ManifoldCFException
*/
private void initNuxeoClient() throws ManifoldCFException {
if (nuxeoClient == null) {
if (StringUtils.isEmpty(protocol)) {
throw new ManifoldCFException(
"Parameter " + NuxeoConfiguration.Server.PROTOCOL + " required but not set");
}
if (StringUtils.isEmpty(host)) {
throw new ManifoldCFException("Parameter " + NuxeoConfiguration.Server.HOST + " required but not set");
}
String url = getUrl();
nuxeoClient = new NuxeoClient.Builder().
url(url).
authentication(username, password).connect();
nuxeoClient.schemas("*"); // TODO Make This Configurable
nuxeoClient.header("properties", "*");
lastSessionFetch = System.currentTimeMillis();
}
}
/**
* Shut down Nuxeo client
*/
private void shutdownNuxeoClient() {
if (nuxeoClient != null) {
nuxeoClient.disconnect();
nuxeoClient = null;
lastSessionFetch = -1L;
}
}
/**
* Formatter URL
*
* @throws ManifoldCFException
*/
protected String getUrl() throws ManifoldCFException {
int portInt;
if (protocol == null || host == null || path == null){
throw new ManifoldCFException("Nuxeo Endpoint Bad Configured");
}
if (port != null && port.length() > 0) {
try {
portInt = Integer.parseInt(port);
} catch (NumberFormatException formatException) {
throw new ManifoldCFException("Bad number: " + formatException.getMessage(), formatException);
}
} else {
if (protocol.toLowerCase(Locale.ROOT).equals("http")) {
portInt = 80;
} else {
portInt = 443;
}
}
String url = protocol + "://" + host + ":" + portInt + "/" + path;
return url;
}
@Override
public boolean isConnected() {
return nuxeoClient != null;
}
@Override
public void poll() throws ManifoldCFException {
if (lastSessionFetch == -1L) {
return;
}
long currentTime = System.currentTimeMillis();
if (currentTime > lastSessionFetch + timeToRelease) {
shutdownNuxeoClient();
}
}
/** SEEDING **/
@Override
public String addSeedDocuments(ISeedingActivity activities, Specification spec, String lastSeedVersion,
long seedTime, int jobMode) throws ManifoldCFException, ServiceInterruption {
initNuxeoClient();
try {
int lastStart = 0;
int defaultSize = 50;
Boolean isLast = true;
NuxeoSpecification ns = NuxeoSpecification.from(spec);
List<String> domains = ns.getDomains();
List<String> documentsType = ns.getDocumentsType();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date currentDate = new Date();
do {
Documents docs = getDocsByDate(nuxeoClient, lastSeedVersion, domains, documentsType,
defaultSize, lastStart);
for (Document doc : docs.getDocuments()) {
activities.addSeedDocument(doc.getUid());
}
lastStart++;
isLast = docs.isNextPageAvailable();
} while (isLast);
return sdf.format(currentDate);
} catch (NuxeoClientException exception) {
Logging.connectors.warn("NUXEO: Error adding seed documents: " + exception.getMessage(), exception);
throw new ManifoldCFException("Failure during seeding: "+exception.getMessage(), exception);
}
}
Documents getDocsByDate(NuxeoClient nuxeoClient, String date, List<String> domains,
List<String> documentsType, int limit, int start) {
String query = "";
if (date == null || date.isEmpty()) {
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ROOT);
date = DATE_FORMAT.format(new Date(0));
}
query = "dc:modified > '" + date + "'";
if (!domains.isEmpty()) {
Iterator<String> itdom = domains.iterator();
query = String.format(Locale.ROOT, " %s AND ( ecm:path STARTSWITH '/%s'", query, itdom.next());
while (itdom.hasNext()) {
query = String.format(Locale.ROOT, "%s OR ecm:path STARTSWITH '/%s'", query, itdom.next());
}
query = String.format(Locale.ROOT, "%s )", query);
}
if (!documentsType.isEmpty()) {
Iterator<String> itDocTy = documentsType.iterator();
query = String.format(Locale.ROOT, " %s AND ( ecm:primaryType = '%s'", query, itDocTy.next());
while (itDocTy.hasNext()) {
query = String.format(Locale.ROOT, "%s OR ecm:primaryType = '%s'", query, itDocTy.next());
}
query = String.format(Locale.ROOT, "%s )", query);
}
query = String.format(Locale.ROOT, URI_DOCUMENT + " where ecm:mixinType != 'HiddenInNavigation' AND ecm:isProxy = 0 " +
"AND ecm:isCheckedInVersion = 0 AND %s ", query);
Documents docs = nuxeoClient.repository().query(query, String.valueOf(limit), String.valueOf(start), null, null,
null, null);
return docs;
}
/** PROCESS DOCUMENTS **/
@Override
public void processDocuments(String[] documentsIdentifieres, IExistingVersions statuses, Specification spec,
IProcessActivity activities, int jobMode, boolean usesDefaultAuthority)
throws ManifoldCFException, ServiceInterruption {
initNuxeoClient();
for (int i = 0; i < documentsIdentifieres.length; i++) {
String documentId = documentsIdentifieres[i];
String indexed_version = statuses.getIndexedVersionString(documentId);
long startTime = System.currentTimeMillis();
ProcessResult pResult = null;
try {
NuxeoDocumentHelper document = new NuxeoDocumentHelper(nuxeoClient.repository().fetchDocumentById(documentId));
String version = document.getVersion();
// Filtering
if (document.isFolder()){
activities.noDocument(documentId, version);
continue;
}
pResult = processDocument(document, documentId, spec, version, indexed_version,
activities, Maps.newHashMap());
} catch (NuxeoClientException exception) {
logger.info(String.format(Locale.ROOT, "Error Fetching Nuxeo Document %s. Marking for deletion", documentId));
activities.deleteDocument(documentId);
} catch (IOException exception) {
long interruptionRetryTime = 5L * 60L * 1000L;
String message = "Server appears down during seeding: " + exception.getMessage();
throw new ServiceInterruption(message, exception, System.currentTimeMillis() + interruptionRetryTime,
-1L, 3, true);
} finally {
if (pResult != null && pResult.errorCode != null && !pResult.errorCode.isEmpty()) {
activities.recordActivity(new Long(startTime), ACTIVITY_READ, pResult.fileSize, documentId,
pResult.errorCode, pResult.errorDecription, null);
}
}
}
}
private ProcessResult processDocument(NuxeoDocumentHelper doc, String manifoldDocumentIdentifier,
Specification spec, String version, String indexed_version,
IProcessActivity activities, HashMap<String, String> extraProperties)
throws ManifoldCFException, ServiceInterruption, IOException {
RepositoryDocument rd = new RepositoryDocument();
NuxeoSpecification ns = NuxeoSpecification.from(spec);
String lastModified = doc.getDocument().getLastModified();
Date lastModifiedDate = null;
if (lastModified != null) {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ROOT);
try {
lastModifiedDate = formatter.parse(lastModified);
} catch (Exception ex) {
lastModifiedDate = new Date(0);
}
}
int length = doc.getLength();
if (doc.getDocument().getState() != null
&& doc.getDocument().getState().equalsIgnoreCase(NuxeoDocumentHelper.DELETED)) {
activities.deleteDocument(manifoldDocumentIdentifier);
return new ProcessResult(length, "DELETED", "");
}
if (!activities.checkDocumentNeedsReindexing(manifoldDocumentIdentifier, lastModified)) {
return new ProcessResult(length, "RETAINED", "");
}
if (doc.getDocument().getUid() == null) {
activities.deleteDocument(manifoldDocumentIdentifier);
return new ProcessResult(length, "DELETED", "");
}
if (!activities.checkLengthIndexable(length))
{
activities.noDocument(manifoldDocumentIdentifier, version);
return new ProcessResult(length, activities.EXCLUDED_LENGTH,
"Document excluded because of length ("+length+")");
}
// Document URI
String url = getUrl();
if (url.endsWith("/"))
url = url.substring(0, url.length()-1);
String documentUri = url + "/nxpath/" +
doc.getDocument().getRepositoryName() + doc.getDocument().getPath() + "@view_documents";
if (!activities.checkURLIndexable(documentUri))
{
activities.noDocument(manifoldDocumentIdentifier, version);
return new ProcessResult(length, activities.EXCLUDED_URL,
"Document excluded because of URL ('"+documentUri+"')");
}
//Modified date
if (!activities.checkDateIndexable(lastModifiedDate))
{
activities.noDocument(manifoldDocumentIdentifier, version);
return new ProcessResult(length, activities.EXCLUDED_DATE,
"Document excluded because of date ("+lastModifiedDate+")");
}
// Mime type
if (!activities.checkMimeTypeIndexable(doc.getMimeType()))
{
activities.noDocument(manifoldDocumentIdentifier, version);
return new ProcessResult(length, activities.EXCLUDED_MIMETYPE,
"Document excluded because of mime type ('"+doc.getMimeType()+"')");
}
// Add respository document information
rd.setMimeType(doc.getMimeType());
rd.setModifiedDate(lastModifiedDate);
rd.setFileName(doc.getFilename());
rd.setIndexingDate(new Date());
rd.setBinary(doc.getContent(), length);
// Adding Document metadata
Map<String, Object> docMetadata = doc.getMetadata();
for (Entry<String, Object> entry : docMetadata.entrySet()) {
if (entry.getValue() instanceof List) {
List<?> list = (List<?>) entry.getValue();
try {
rd.addField(entry.getKey(), list.toArray(new String[list.size()]));
} catch (ArrayStoreException e){
continue;
}
} else {
rd.addField(entry.getKey(), entry.getValue().toString());
}
}
if (ns.isProcessTags())
rd.addField("Tags", doc.getTags(nuxeoClient));
// Set repository ACLs
String[] permissions = doc.getPermissions();
rd.setSecurityACL(RepositoryDocument.SECURITY_TYPE_DOCUMENT, permissions);
rd.setSecurityDenyACL(RepositoryDocument.SECURITY_TYPE_DOCUMENT, new String[] { GLOBAL_DENY_TOKEN });
// Action
activities.ingestDocumentWithException(manifoldDocumentIdentifier, version, documentUri, rd);
if (ns.isProcessAttachments()) {
for (NuxeoAttachment att : doc.getAttachments(nuxeoClient)) {
RepositoryDocument att_rd = new RepositoryDocument();
String attDocumentUri = att.getUrl();
att_rd.setMimeType(att.getMime_type());
att_rd.setBinary(att.getData(), att.getLength());
if (lastModified != null)
att_rd.setModifiedDate(lastModifiedDate);
att_rd.setIndexingDate(new Date());
att_rd.addField(NuxeoAttachment.ATT_KEY_NAME, att.getName());
att_rd.addField(NuxeoAttachment.ATT_KEY_LENGTH, String.valueOf(att.getLength()));
att_rd.addField(NuxeoAttachment.ATT_KEY_DIGEST, att.getDigest());
att_rd.addField(NuxeoAttachment.ATT_KEY_DIGEST_ALGORITHM, att.getDigestAlgorithm());
att_rd.addField(NuxeoAttachment.ATT_KEY_ENCODING, att.getEncoding());
// Set repository ACLs
att_rd.setSecurityACL(RepositoryDocument.SECURITY_TYPE_DOCUMENT, permissions);
att_rd.setSecurityDenyACL(RepositoryDocument.SECURITY_TYPE_DOCUMENT,
new String[] { GLOBAL_DENY_TOKEN });
activities.ingestDocumentWithException(manifoldDocumentIdentifier, attDocumentUri, lastModified,
attDocumentUri, att_rd);
}
}
return new ProcessResult(length, "OK", StringUtils.EMPTY);
}
private class ProcessResult {
private long fileSize;
private String errorCode;
private String errorDecription;
private ProcessResult(long fileSize, String errorCode, String errorDescription) {
this.fileSize = fileSize;
this.errorCode = errorCode;
this.errorDecription = errorDescription;
}
}
@Override
public int getConnectorModel() {
return IRepositoryConnector.MODEL_ADD_CHANGE_DELETE;
}
/** Specifications **/
@Override
public void viewSpecification(IHTTPOutput out, Locale locale, Specification spec, int connectionSequenceNumber)
throws ManifoldCFException, IOException {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("SeqNum", Integer.toString(connectionSequenceNumber));
NuxeoSpecification ns = NuxeoSpecification.from(spec);
paramMap.put(NuxeoConfiguration.Specification.DOMAINS.toUpperCase(Locale.ROOT), ns.getDomains());
paramMap.put(NuxeoConfiguration.Specification.DOCUMENTS_TYPE.toUpperCase(Locale.ROOT), ns.documentsType);
paramMap.put(NuxeoConfiguration.Specification.PROCESS_TAGS.toUpperCase(Locale.ROOT), ns.isProcessTags().toString());
paramMap.put(NuxeoConfiguration.Specification.PROCESS_ATTACHMENTS.toUpperCase(Locale.ROOT),
ns.isProcessAttachments().toString());
Messages.outputResourceWithVelocity(out, locale, VIEW_SPEC_FORWARD, paramMap);
}
@Override
public String processSpecificationPost(IPostParameters variableContext, Locale locale, Specification ds,
int connectionSequenceNumber) throws ManifoldCFException {
String seqPrefix = "s" + connectionSequenceNumber + "_";
// DOMAINS
String xc = variableContext.getParameter(seqPrefix + "domainscount");
if (xc != null) {
// Delete all preconfigured domains
int i = 0;
while (i < ds.getChildCount()) {
SpecificationNode sn = ds.getChild(i);
if (sn.getType().equals(NuxeoConfiguration.Specification.DOMAINS)) {
ds.removeChild(i);
} else {
i++;
}
}
SpecificationNode domains = new SpecificationNode(NuxeoConfiguration.Specification.DOMAINS);
ds.addChild(ds.getChildCount(), domains);
int domainsCount = Integer.parseInt(xc);
i = 0;
while (i < domainsCount) {
String domainDescription = "_" + Integer.toString(i);
String domainOpName = seqPrefix + "domainop" + domainDescription;
xc = variableContext.getParameter(domainOpName);
if (xc != null && xc.equals("Delete")) {
i++;
continue;
}
String domainKey = variableContext.getParameter(seqPrefix + "domain" + domainDescription);
SpecificationNode node = new SpecificationNode(NuxeoConfiguration.Specification.DOMAIN);
node.setAttribute(NuxeoConfiguration.Specification.DOMAIN_KEY, domainKey);
domains.addChild(domains.getChildCount(), node);
i++;
}
String op = variableContext.getParameter(seqPrefix + "domainop");
if (op != null && op.equals("Add")) {
String domainSpec = variableContext.getParameter(seqPrefix + "domain");
SpecificationNode node = new SpecificationNode(NuxeoConfiguration.Specification.DOMAIN);
node.setAttribute(NuxeoConfiguration.Specification.DOMAIN_KEY, domainSpec);
domains.addChild(domains.getChildCount(), node);
}
}
// TYPE OF DOCUMENTS
String xt = variableContext.getParameter(seqPrefix + "documentsTypecount");
if (xt != null) {
// Delete all preconfigured type of documents
int i = 0;
while (i < ds.getChildCount()) {
SpecificationNode sn = ds.getChild(i);
if (sn.getType().equals(NuxeoConfiguration.Specification.DOCUMENTS_TYPE)) {
ds.removeChild(i);
} else {
i++;
}
}
SpecificationNode documentsType = new SpecificationNode(NuxeoConfiguration.Specification.DOCUMENTS_TYPE);
ds.addChild(ds.getChildCount(), documentsType);
int documentsTypeCount = Integer.parseInt(xt);
i = 0;
while (i < documentsTypeCount) {
String documentTypeDescription = "_" + Integer.toString(i);
String documentTypeOpName = seqPrefix + "documentTypeop" + documentTypeDescription;
xt = variableContext.getParameter(documentTypeOpName);
if (xt != null && xt.equals("Delete")) {
i++;
continue;
}
String documentTypeKey = variableContext
.getParameter(seqPrefix + "documentType" + documentTypeDescription);
SpecificationNode node = new SpecificationNode(NuxeoConfiguration.Specification.DOCUMENT_TYPE);
node.setAttribute(NuxeoConfiguration.Specification.DOCUMENT_TYPE_KEY, documentTypeKey);
documentsType.addChild(documentsType.getChildCount(), node);
i++;
}
String op = variableContext.getParameter(seqPrefix + "documentTypeop");
if (op != null && op.equals("Add")) {
String documentTypeSpec = variableContext.getParameter(seqPrefix + "documentType");
SpecificationNode node = new SpecificationNode(NuxeoConfiguration.Specification.DOCUMENT_TYPE);
node.setAttribute(NuxeoConfiguration.Specification.DOCUMENT_TYPE_KEY, documentTypeSpec);
documentsType.addChild(documentsType.getChildCount(), node);
}
}
// TAGS
SpecificationNode documents = new SpecificationNode(NuxeoConfiguration.Specification.DOCUMENTS);
ds.addChild(ds.getChildCount(), documents);
String processTags = variableContext.getParameter(seqPrefix + NuxeoConfiguration.Specification.PROCESS_TAGS);
String processAttachments = variableContext
.getParameter(seqPrefix + NuxeoConfiguration.Specification.PROCESS_ATTACHMENTS);
if (processTags != null && !processTags.isEmpty()) {
documents.setAttribute(NuxeoConfiguration.Specification.PROCESS_TAGS, String.valueOf(processTags));
}
if (processAttachments != null && !processAttachments.isEmpty()) {
documents.setAttribute(NuxeoConfiguration.Specification.PROCESS_ATTACHMENTS,
String.valueOf(processAttachments));
}
return null;
}
@Override
public void outputSpecificationBody(IHTTPOutput out, Locale locale, Specification spec,
int connectionSequenceNumber, int actualSequenceNumber, String tabName)
throws ManifoldCFException, IOException {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("TabName", tabName);
paramMap.put("SeqNum", Integer.toString(connectionSequenceNumber));
paramMap.put("SelectedNum", Integer.toString(actualSequenceNumber));
NuxeoSpecification ns = NuxeoSpecification.from(spec);
paramMap.put(NuxeoConfiguration.Specification.DOMAINS.toUpperCase(Locale.ROOT), ns.getDomains());
paramMap.put(NuxeoConfiguration.Specification.DOCUMENTS_TYPE.toUpperCase(Locale.ROOT), ns.getDocumentsType());
paramMap.put(NuxeoConfiguration.Specification.PROCESS_TAGS.toUpperCase(Locale.ROOT), ns.isProcessTags());
paramMap.put(NuxeoConfiguration.Specification.PROCESS_ATTACHMENTS.toUpperCase(Locale.ROOT), ns.isProcessAttachments());
Messages.outputResourceWithVelocity(out, locale, EDIT_SPEC_FORWARD_CONF_DOMAINS, paramMap);
Messages.outputResourceWithVelocity(out, locale, EDIT_SPEC_FORWARD_CONF_DOCUMENTS_TYPE, paramMap);
Messages.outputResourceWithVelocity(out, locale, EDIT_SPEC_FORWARD_CONF_DOCUMENTS, paramMap);
}
@Override
public void outputSpecificationHeader(IHTTPOutput out, Locale locale, Specification spec,
int connectionSequenceNumber, List<String> tabsArray) throws ManifoldCFException, IOException {
tabsArray.add(Messages.getString(locale, CONF_DOMAINS_TAB_PROPERTY));
tabsArray.add(Messages.getString(locale, CONF_DOCUMENTS_TYPE_TAB_PROPERTY));
tabsArray.add(Messages.getString(locale, CONF_DOCUMENT_PROPERTY));
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("SeqNum", Integer.toString(connectionSequenceNumber));
Messages.outputResourceWithVelocity(out, locale, EDIT_SPEC_HEADER_FORWARD, paramMap);
}
static class NuxeoSpecification {
private List<String> domains;
private List<String> documentsType;
private Boolean processTags = false;
private Boolean processAttahcments = false;
public List<String> getDomains() {
return this.domains;
}
public List<String> getDocumentsType() {
return this.documentsType;
}
public Boolean isProcessTags() {
return this.processTags;
}
public Boolean isProcessAttachments() {
return this.processAttahcments;
}
/**
* @param spec
*/
public static NuxeoSpecification from(Specification spec) {
NuxeoSpecification ns = new NuxeoSpecification();
ns.domains = Lists.newArrayList();
ns.documentsType = Lists.newArrayList();
for (int i = 0, len = spec.getChildCount(); i < len; i++) {
SpecificationNode sn = spec.getChild(i);
if (sn.getType().equals(NuxeoConfiguration.Specification.DOMAINS)) {
for (int j = 0, sLen = sn.getChildCount(); j < sLen; j++) {
SpecificationNode spectNode = sn.getChild(j);
if (spectNode.getType().equals(NuxeoConfiguration.Specification.DOMAIN)) {
ns.domains.add(spectNode.getAttributeValue(NuxeoConfiguration.Specification.DOMAIN_KEY));
}
}
} else if (sn.getType().equals(NuxeoConfiguration.Specification.DOCUMENTS_TYPE)) {
for (int j = 0, sLen = sn.getChildCount(); j < sLen; j++) {
SpecificationNode spectNode = sn.getChild(j);
if (spectNode.getType().equals(NuxeoConfiguration.Specification.DOCUMENT_TYPE)) {
ns.documentsType.add(
spectNode.getAttributeValue(NuxeoConfiguration.Specification.DOCUMENT_TYPE_KEY));
}
}
} else if (sn.getType().equals(NuxeoConfiguration.Specification.DOCUMENTS)) {
String procTags = sn.getAttributeValue(NuxeoConfiguration.Specification.PROCESS_TAGS);
ns.processTags = Boolean.valueOf(procTags);
String procAtt = sn.getAttributeValue(NuxeoConfiguration.Specification.PROCESS_ATTACHMENTS);
ns.processAttahcments = Boolean.valueOf(procAtt);
}
}
return ns;
}
}
}
|
oracle/coherence
| 38,249
|
prj/coherence-core/src/main/java/com/tangosol/net/partition/ObservableSplittingBackingCache.java
|
/*
* Copyright (c) 2000, 2025, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* https://oss.oracle.com/licenses/upl.
*/
package com.tangosol.net.partition;
import com.tangosol.net.BackingMapManager;
import com.tangosol.net.cache.ConfigurableCacheMap;
import com.tangosol.util.AbstractKeyBasedMap;
import com.tangosol.util.AbstractKeySetBasedMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import static java.lang.Math.abs;
import static java.lang.Math.min;
/**
* The ObservableSplittingBackingCache is an implementation of the
* ConfigurableCacheMap interface that works as an observable backing map
* in a partitioned system. In other words, it acts like a
* {@link com.tangosol.net.cache.LocalCache LocalCache}, but it internally
* partitions its data across any number of caches that implement the
* ConfigurableCacheMap interface. Note that the underlying backing maps must
* implement the ConfigurableCacheMap interface or a runtime exception will
* occur.
*
* @author cp 2009.01.16
*/
public class ObservableSplittingBackingCache
extends ObservableSplittingBackingMap
implements ConfigurableCacheMap
{
// ----- constructors ---------------------------------------------------
/**
* Create a ObservableSplittingBackingCache that adds ConfigurableCacheMap
* functionality to an ObservableSplittingBackingMap.
*
* @param bmm a callback that knows how to create and release the
* backing maps that this ObservableSplittingBackingCache is
* responsible for
* @param sName the cache name for which this backing map exists
*/
public ObservableSplittingBackingCache(BackingMapManager bmm, String sName)
{
this(new CapacityAwareMap(bmm, sName));
}
/**
* Create an ObservableSplittingBackingCache that adds ConfigurableCacheMap
* functionality to an ObservableSplittingBackingMap.
*
* @param map the PartitionAwareBackingMap to delegate to
*/
protected ObservableSplittingBackingCache(PartitionAwareBackingMap map)
{
super(map);
((CapacityAwareMap) getPartitionSplittingBackingMap()).bind(this);
initializeConfiguredProperties();
}
// ----- PartitionAwareBackingMap methods -------------------------------
/**
* {@inheritDoc}
*/
public void createPartition(int nPid)
{
super.createPartition(nPid);
Map map = super.getPartitionMap(nPid);
if (map instanceof ConfigurableCacheMap)
{
// configure the new cache
ConfigurableCacheMap cache = (ConfigurableCacheMap) map;
int nUnitFactor = getPartitionUnitFactor();
if (nUnitFactor != -1)
{
cache.setUnitFactor(nUnitFactor);
}
int cExpiryDelayMillis = m_cExpiryDelayMillis;
if (cExpiryDelayMillis != -1)
{
cache.setExpiryDelay(cExpiryDelayMillis);
}
EvictionPolicy policy = m_policy;
if (policy != null)
{
cache.setEvictionPolicy(policy);
}
UnitCalculator calculator = m_calculator;
if (calculator != null)
{
cache.setUnitCalculator(calculator);
}
EvictionApprover approver = m_apprvrEvict;
if (approver != null)
{
cache.setEvictionApprover(approver);
}
m_cHighUnitFairShare = calcUnitFairShare(getCalibratedHighUnits());
m_cLowUnitFairShare = calcUnitFairShare(getCalibratedLowUnits());
claimUnused(cache);
// reset the cache of CCMs
m_acache = null;
}
else
{
super.destroyPartition(nPid);
throw new IllegalStateException("Partition backing map "
+ (map == null ? "is null" : map.getClass().getName()
+ " does not implement ConfigurableCacheMap"));
}
}
/**
* {@inheritDoc}
*/
public void destroyPartition(int nPid)
{
ConfigurableCacheMap mapInner = (ConfigurableCacheMap) getPartitionSplittingBackingMap().getPartitionMap(nPid);
int cHighUnits = mapInner == null ? 0 : mapInner.getHighUnits();
super.destroyPartition(nPid);
m_cHighUnitFairShare = calcUnitFairShare(getCalibratedHighUnits());
m_cLowUnitFairShare = calcUnitFairShare(getCalibratedLowUnits());
if (cHighUnits > 0)
{
adjustUnits(cHighUnits);
}
// reset the cache of CCMs
m_acache = null;
}
// ----- ConfigurableCacheMap interface ---------------------------------
/**
* {@inheritDoc}
*/
public int getUnits()
{
ConfigurableCacheMap[] acache = getPartitionCacheArray();
// get the actual units by summing up the backing maps
int cUnits = 0;
for (ConfigurableCacheMap cache : acache)
{
int cPartitionUnits = cache.getUnits();
if (cPartitionUnits >= 0)
{
cUnits = Math.max(0, cUnits) +
(int) ((long) cPartitionUnits * getPartitionUnitFactor() / m_nUnitFactor);
}
}
return cUnits;
}
/**
* {@inheritDoc}
*/
public int getHighUnits()
{
return m_cHighUnits;
}
/**
* {@inheritDoc}
*/
public void setHighUnits(int cMax)
{
if (cMax >= 0)
{
if (cMax == m_cHighUnits)
{
// the caller is requesting a prune
for (Map map : getPartitionSplittingBackingMap().getMapArray().getBackingMaps())
{
ConfigurableCacheMap mapPart = (ConfigurableCacheMap) map;
mapPart.setHighUnits(mapPart.getHighUnits());
}
}
else
{
int cPrevHighUnits = getCalibratedHighUnits();
if (m_cHighUnits >= 0)
{
m_cHighUnitsCalibrated = -1;
}
m_cHighUnits = cMax;
m_cHighUnitFairShare = calcUnitFairShare(getCalibratedHighUnits());
// either disseminate the addition or removal of units to all child
// maps; this method will also set the low units
adjustUnits(getCalibratedHighUnits() - cPrevHighUnits);
}
}
}
/**
* {@inheritDoc}
*/
public int getLowUnits()
{
return m_cLowUnits;
}
/**
* {@inheritDoc}
*/
public void setLowUnits(int cUnits)
{
if (cUnits != m_cLowUnits && cUnits >= 0)
{
if (m_cLowUnits >= 0)
{
m_cLowUnitsCalibrated = -1;
}
m_cLowUnits = cUnits;
m_cLowUnitFairShare = calcUnitFairShare(getCalibratedLowUnits());
// adjust the low units on all partitioned maps without modification
// to the high units
adjustUnits(0);
}
}
/**
* {@inheritDoc}
*/
public int getUnitFactor()
{
return m_nUnitFactor;
}
/**
* {@inheritDoc}
*/
public void setUnitFactor(int nFactor)
{
if (nFactor != m_nUnitFactor && nFactor > 0)
{
if (nFactor < MAX_PARTITION_MAP_UNIT_FACTOR)
{
// update all the backing maps
ConfigurableCacheMap[] amap = getPartitionCacheArray();
for (int i = 0, c = amap.length; i < c; ++i)
{
amap[i].setUnitFactor(nFactor);
}
}
m_cHighUnits = (m_cHighUnits * m_nUnitFactor) / nFactor;
m_cLowUnits = (m_cLowUnits * m_nUnitFactor) / nFactor;
m_nUnitFactor = nFactor;
}
}
/**
* {@inheritDoc}
*/
public EvictionPolicy getEvictionPolicy()
{
return m_policy;
}
/**
* {@inheritDoc}
*/
public void setEvictionPolicy(EvictionPolicy policy)
{
if (policy != m_policy)
{
ConfigurableCacheMap[] amap = getPartitionCacheArray();
for (int i = 0, c = amap.length; i < c; ++i)
{
amap[i].setEvictionPolicy(policy);
}
m_policy = policy;
}
}
/**
* {@inheritDoc}
*/
public void evict(Object oKey)
{
getPartitionCache(oKey).evict(oKey);
}
/**
* {@inheritDoc}
*/
public void evictAll(Collection colKeys)
{
// note: this is not an optimal implementation
for (Iterator iter = colKeys.iterator(); iter.hasNext(); )
{
evict(iter.next());
}
}
/**
* {@inheritDoc}
*/
public void evict()
{
// request each of the backing maps to evict
ConfigurableCacheMap[] amap = getPartitionCacheArray();
for (int i = 0, c = amap.length; i < c; ++i)
{
amap[i].evict();
}
}
/**
* {@inheritDoc}
*/
public EvictionApprover getEvictionApprover()
{
return m_apprvrEvict;
}
/**
* {@inheritDoc}
*/
public void setEvictionApprover(EvictionApprover approver)
{
if (approver != m_apprvrEvict)
{
ConfigurableCacheMap[] amap = getPartitionCacheArray();
for (int i = 0, c = amap.length; i < c; ++i)
{
amap[i].setEvictionApprover(approver);
}
m_apprvrEvict = approver;
}
}
/**
* {@inheritDoc}
*/
public int getExpiryDelay()
{
return m_cExpiryDelayMillis;
}
/**
* {@inheritDoc}
*/
public synchronized void setExpiryDelay(int cMillis)
{
if (cMillis != m_cExpiryDelayMillis)
{
// update all the backing maps
ConfigurableCacheMap[] amap = getPartitionCacheArray();
for (int i = 0, c = amap.length; i < c; ++i)
{
amap[i].setExpiryDelay(cMillis);
// with the first backing map, verify that it took the value
// (some maps might not support expiry delay, so their delay
// would be -1 and they may simply ignore the property set)
if (i == 0 && amap[i].getExpiryDelay() != cMillis)
{
return;
}
}
m_cExpiryDelayMillis = cMillis;
}
}
/**
* {@inheritDoc}
*/
public long getNextExpiryTime()
{
long ldtNext = Long.MAX_VALUE;
ConfigurableCacheMap[] amap = getPartitionCacheArray();
for (ConfigurableCacheMap map : amap)
{
long ldt = map.getNextExpiryTime();
if (ldt > 0)
{
ldtNext = Math.min(ldtNext, ldt);
}
}
return ldtNext == Long.MAX_VALUE ? 0 : ldtNext;
}
/**
* {@inheritDoc}
*/
public ConfigurableCacheMap.Entry getCacheEntry(Object oKey)
{
EntrySet.Entry entry = null;
// first get the backing map for the partition that contains the key
ConfigurableCacheMap cache = getPartitionCache(oKey);
// ask the backing map for the entry related to the key (it might
// not exist)
ConfigurableCacheMap.Entry entryReal = cache.getCacheEntry(oKey);
if (entryReal != null)
{
// since the real entry exists, create a veneer entry that
// will pipe the Map.Entry updates through the
// ObservableSplittingBackingCache but the other work
// (expiry, touches, etc.) directly to the real entry
entry = (EntrySet.Entry) ((EntrySet) entrySet())
.instantiateEntry(oKey, null);
entry.setCacheEntry(entryReal);
}
return entry;
}
/**
* {@inheritDoc}
*/
public UnitCalculator getUnitCalculator()
{
return m_calculator;
}
/**
* {@inheritDoc}
*/
public synchronized void setUnitCalculator(UnitCalculator calculator)
{
if (calculator != m_calculator)
{
ConfigurableCacheMap[] amap = getPartitionCacheArray();
for (int i = 0, c = amap.length; i < c; ++i)
{
amap[i].setUnitCalculator(calculator);
}
m_calculator = calculator;
}
}
/**
* Return the uniform type used by each partition map.
*
* @return the type of partition map
*/
public Class getPartitionMapType()
{
return m_clzPartitionMap;
}
// ----- ObservableSplittingBackingMap methods --------------------------
/**
* {@inheritDoc}
* <p>
* This implementation will check if mapPart is under-allocated for high
* units. If this is the case, demand the entitled unit amount from other
* maps.
*/
protected void prepareUpdate(Map mapPartition, Map mapUpdate)
{
ConfigurableCacheMap mapPart = (ConfigurableCacheMap) mapPartition;
int cHighUnits = mapPart.getHighUnits();
UnitCalculator unitCalc = mapPart.getUnitCalculator();
if (unitCalc != null && cHighUnits < getHighUnitFairShare())
{
// the high units value for this map are under-allocated, thus
// demand more if required
int cUnits = mapPart.getUnits();
int cUnitsNew = 0;
for (Map.Entry entry : (Set<Map.Entry>) mapUpdate.entrySet())
{
// determine whether this store will cause the map to exceed its
// high unit allocation; to avoid an extra entry lookup we are
// being aggressive on the unit calculation, always assuming an insert
cUnitsNew += unitCalc.calculateUnits(entry.getKey(), entry.getValue());
if (cUnitsNew + cUnits > cHighUnits)
{
claimAll(mapPart);
break;
}
}
}
}
// ----- unit partitioning methods --------------------------------------
// Internal Notes:
// Partitioning of units is implemented using a lazy credit based algorithm.
// Units are repartitioned in an effort to reduce cost to other maps with
// this map (OSBC) being able to determine whether maps are "overdrawn"
// based on their current high-unit allocation and the fair-share.
// The algorithm has two distinct phases with the pivot of each request being
// the ConfigurableCacheMap in question:
// - claimUnused claim as many unused units from all other partitioned
// maps, i.e. maintaining the constraint
// used-units < high-units && high-units >= fair-share.
// - claimAll a map may demand its fair share of units causing overdrawn
// maps to reduce their high-units to the fair share thus
// being likely to enact eviction. Typically this process
// commences when a put request would cause the map to surpass
// its under-allocated high-units.
// In addition to these two requests is the ability to adjust the high-units
// due to more units being made available, either by an adjustment to high
// or low units or the removal of a partitioned map; see adjustUnits.
/**
* Claim as many units as possible from existing maps without causing
* over-allocated maps to evict.
*
* @param mapRequestor the map requesting its fair share of units
*/
protected void claimUnused(ConfigurableCacheMap mapRequestor)
{
Map[] aMaps = getPartitionSplittingBackingMap().getMapArray().getBackingMaps();
int cFairHigh = getHighUnitFairShare();
int cFairLow = getLowUnitFairShare();
int cUnits = aMaps.length > 1 ? 0 : cFairHigh;
boolean fSetLowUnits = cFairLow >= 0;
for (int i = 0, c = aMaps.length; i < c; ++i)
{
ConfigurableCacheMap mapPart = (ConfigurableCacheMap) aMaps[i];
if (mapPart == mapRequestor)
{
continue;
}
int cUnitsCurr = mapPart.getUnits();
int cUnitsMax = mapPart.getHighUnits();
int cUnitsOver = min(cUnitsMax - cUnitsCurr, cUnitsMax - cFairHigh);
if (cUnitsOver > 0)
{
// protect against concurrent setting of high units for the same
// map; a worker thread may be adjusting the high units the same
// time as the service thread
synchronized (mapPart)
{
cUnitsCurr = mapPart.getUnits();
cUnitsMax = mapPart.getHighUnits();
cUnitsOver = min(cUnitsMax - cUnitsCurr, cUnitsMax - cFairHigh);
if (cUnitsOver > 0)
{
mapPart.setHighUnits(cUnitsMax - cUnitsOver);
cUnits += cUnitsOver;
}
}
}
// low units must be set after setting the high units
if (fSetLowUnits)
{
mapPart.setLowUnits(cFairLow);
}
}
mapRequestor.setHighUnits(cUnits);
if (fSetLowUnits)
{
mapRequestor.setLowUnits(cFairLow);
}
}
/**
* Claim the full entitlement of units for mapRequestor. This method
* should only be invoked if the map has insufficient units, based on a
* pending put request, however does not occupy its fair share.
*
* @param mapRequestor the map demanding its entitled fair share
*/
protected void claimAll(ConfigurableCacheMap mapRequestor)
{
int cFairHigh = getHighUnitFairShare();
int cUnitsMax = mapRequestor.getHighUnits();
int cUnitsEntitled = cFairHigh - cUnitsMax;
int cUnitsClaimed = 0;
Map[] aMaps = getPartitionSplittingBackingMap().getMapArray().getBackingMaps();
for (int i = 0, c = aMaps.length; cUnitsClaimed < cUnitsEntitled && i < c; ++i)
{
ConfigurableCacheMap mapPart = (ConfigurableCacheMap) aMaps[i];
if (mapPart == mapRequestor)
{
continue;
}
int cUnitsDebit = mapPart.getHighUnits() - cFairHigh;
if (cUnitsDebit > 0)
{
// we must double check due to demand being driven by put requests
// which can be executed on multiple threads
synchronized (mapPart)
{
cUnitsDebit = mapPart.getHighUnits() - cFairHigh;
if (cUnitsDebit > 0)
{
mapPart.setHighUnits(cFairHigh);
}
}
cUnitsClaimed += cUnitsDebit;
}
}
if (cUnitsClaimed > 0)
{
mapRequestor.setHighUnits(cUnitsMax + cUnitsClaimed);
}
}
/**
* Adjust the number of units for each map with the pool of units provided.
* The units provided is a total across all maps with the adjustment per
* map being made as prescribed below.
* <p>
* The provided units may be positive or negative, with the latter suggesting
* that this number of units should be retrieved, thus decremented, from
* child maps. If the provided units is positive, maps that are over-allocated
* may consumer the provided amount. If the provided units is negative
* maintain a
* positive delta between the fair share and their current high units may
* consume the minimum between what is available from the provided units
* and the determined delta. If the provided units is negative, those maps
* whose current high unit allocation is more than the fair share will have
* this delta decremented until the debt (cUnits) is reclaimed.
*
* @param cUnits the number of units to either disseminate (positive unit value)
* or retract across the maps
*/
protected void adjustUnits(int cUnits)
{
int cFairHigh = getHighUnitFairShare();
int cFairLow = getLowUnitFairShare();
int nSign = cUnits < 0 ? -1 : 1;
Map[] aMaps = getPartitionSplittingBackingMap().getMapArray().getBackingMaps();
for (int i = 0, c = aMaps.length; i < c; ++i)
{
ConfigurableCacheMap mapPart = (ConfigurableCacheMap) aMaps[i];
// determine the delta between the fair share and the consumers
// current allocation
int cMaxUnits = mapPart.getHighUnits();
int cUnitsDelta = cFairHigh - cMaxUnits;
// if adjusting with positive units, only adjust maps that are not
// "overdrawn" based on the current fair share; in the negative case,
// only adjust maps that are over the fair share
if (nSign == 1 && cUnits > 0 && cUnitsDelta >=0 ||
nSign == -1 && cUnits < 0 && cUnitsDelta < 0)
{
// protect against concurrent setting of high units for the same
// map; setHighUnits could be called by any thread (mgmt server)
// or service thread (destroyPartition)
synchronized (mapPart)
{
cMaxUnits = mapPart.getHighUnits();
cUnitsDelta = cFairHigh - cMaxUnits;
if (nSign == 1 && cUnits > 0 && cUnitsDelta >= 0 ||
nSign == -1 && cUnits < 0 && cUnitsDelta < 0)
{
int cUnitsAdjust = min(abs(cUnitsDelta), abs(cUnits)) * nSign;
mapPart.setHighUnits(cMaxUnits + cUnitsAdjust);
cUnits -= cUnitsAdjust;
}
}
}
// changing high units may force an adjustment of low units, so
// set those as well
if (cFairLow >= 0)
{
mapPart.setLowUnits(cFairLow);
}
}
}
// ----- internal -------------------------------------------------------
/**
* Initialize the configurable properties of this cache-map.
*/
protected void initializeConfiguredProperties()
{
// knowledge of certain CCM configuration parameters is known only to
// the partition-map BMM and not directly injected into the parent map;
// create a "dummy" map solely for the purpose of retrieving them
BackingMapManager bmm = getBackingMapManager();
String sName = getName() + "$synthetic";
Map map = bmm.instantiateBackingMap(sName);
if (map instanceof ConfigurableCacheMap)
{
ConfigurableCacheMap ccm = (ConfigurableCacheMap) map;
setEvictionPolicy(ccm.getEvictionPolicy());
setExpiryDelay (ccm.getExpiryDelay());
setUnitCalculator(ccm.getUnitCalculator());
setUnitFactor (ccm.getUnitFactor());
setHighUnits (ccm.getHighUnits());
setLowUnits (ccm.getLowUnits());
}
else
{
throw new IllegalStateException("Partition backing map "
+ (map == null ? "is null" : map.getClass().getName()
+ " does not implement ConfigurableCacheMap"));
}
m_clzPartitionMap = map.getClass();
bmm.releaseBackingMap(sName, map);
}
/**
* Obtain the backing cache for a particular key. If the key is not owned
* by a partition represented by this ObservableSplittingBackingCache,
* then a runtime exception is thrown.
*
* @param oKey the key of the desired entry
*
* @return the backing cache
*/
protected ConfigurableCacheMap getPartitionCache(Object oKey)
{
return (ConfigurableCacheMap) getPartitionSplittingBackingMap().getBackingMap(oKey);
}
/**
* Obtain the array of backing caches.
*
* @return an array of all the per-partition backing caches
*/
protected ConfigurableCacheMap[] getPartitionCacheArray()
{
ConfigurableCacheMap[] acache = m_acache;
if (acache == null)
{
Map[] amap = getPartitionSplittingBackingMap().getMapArray().getBackingMaps();
int cMaps = amap.length;
acache = new ConfigurableCacheMap[cMaps];
for (int i = 0; i <cMaps; ++i)
{
acache[i] = (ConfigurableCacheMap) amap[i];
}
m_acache = acache;
}
return acache;
}
/**
* Determine the high units adjusted based on the
* {@link #getPartitionUnitFactor partition unit factor}.
*
* @return the limit of the cache size in units adjusted by partition unitFactor
*/
protected int getCalibratedHighUnits()
{
int cUnits = m_cHighUnitsCalibrated;
if (cUnits > 0)
{
return cUnits;
}
cUnits = m_cHighUnits;
if (cUnits < 0)
{
return -1;
}
return m_cHighUnitsCalibrated = (int) ((long) cUnits * m_nUnitFactor / getPartitionUnitFactor());
}
/**
* Determine the low units adjusted based on the
* {@link #getPartitionUnitFactor partition unit factor}.
*
* @return the number of units adjusted by partition unitFactor that the cache prunes to
*/
protected int getCalibratedLowUnits()
{
int cUnits = m_cLowUnitsCalibrated;
if (cUnits > 0)
{
return cUnits;
}
cUnits = m_cLowUnits;
if (cUnits < 0)
{
return -1;
}
return m_cLowUnitsCalibrated = (int) ((long) cUnits * m_nUnitFactor / getPartitionUnitFactor());
}
/**
* Determine the unit factor for individual partition maps.
*
* @return the unit factor for partition maps
*/
protected int getPartitionUnitFactor()
{
return Math.min(MAX_PARTITION_MAP_UNIT_FACTOR, m_nUnitFactor);
}
/**
* Return the fair share of low-units per partition map.
*
* @return the fair share of low-units per partition map
*/
protected int getLowUnitFairShare()
{
return m_cLowUnitFairShare;
}
/**
* Return the fair share of high-units per partition map.
*
* @return the fair share of high-units per partition map
*/
protected int getHighUnitFairShare()
{
return m_cHighUnitFairShare;
}
/**
* Return the fair share of units for each child maps. The units provided
* would typically be either the high or low units allowed for all maps
* under this map.
*
* @param cUnits the units to distribute across all child maps
*
* @return the fair share of units for each child map
*/
protected int calcUnitFairShare(int cUnits)
{
int cConsumers = Math.max(getPartitionSplittingBackingMap().getMapArray().getBackingMaps().length, 1);
// Note: we do not round up, as was done previously, as the unit allocation
// algorithm extracts from the pool of units shared across partition
// maps. Consider having 10 units with 3 maps; previously we would
// allocate each map 4 units thus put us 2 units over quota {4,4,4},
// the current algorithm determines the fair share to be 3 units
// each and one map will hold the remainder {3,3,4}; see claimUnused
return cUnits < 0 ? -1 : cUnits / cConsumers;
}
// ----- inner class: EntrySet ------------------------------------------
/**
* {@inheritDoc}
*/
protected Set instantiateEntrySet()
{
return new EntrySet();
}
/**
* A set of ConfigurableCacheMap entries backed by this map.
*/
public class EntrySet
extends AbstractKeySetBasedMap.EntrySet
{
// ----- inner class: Entry -------------------------------------
/**
* {@inheritDoc}
*/
protected Map.Entry instantiateEntry(Object oKey, Object oValue)
{
return new Entry(oKey, oValue);
}
/**
* A Cache Entry implementation.
*/
public class Entry
extends AbstractKeyBasedMap.EntrySet.Entry
implements ConfigurableCacheMap.Entry
{
/**
* Construct an Entry.
*
* @param oKey the Entry key
* @param oValue the Entry value (optional)
*/
public Entry(Object oKey, Object oValue)
{
super(oKey, oValue);
}
/**
* {@inheritDoc}
*/
public Object getValue()
{
return getCacheEntry().getValue();
}
/**
* {@inheritDoc}
*/
public void touch()
{
getCacheEntry().touch();
}
/**
* {@inheritDoc}
*/
public int getTouchCount()
{
return getCacheEntry().getTouchCount();
}
/**
* {@inheritDoc}
*/
public long getLastTouchMillis()
{
return getCacheEntry().getLastTouchMillis();
}
/**
* {@inheritDoc}
*/
public long getExpiryMillis()
{
return getCacheEntry().getExpiryMillis();
}
/**
* {@inheritDoc}
*/
public void setExpiryMillis(long lMillis)
{
getCacheEntry().setExpiryMillis(lMillis);
}
/**
* {@inheritDoc}
*/
public int getUnits()
{
return getCacheEntry().getUnits();
}
/**
* {@inheritDoc}
*/
public void setUnits(int cUnits)
{
getCacheEntry().setUnits(cUnits);
}
/**
* Configure the backing map cache entry.
*
* @param entryBacking the entry to delegate most of this entry's
* operations to
*/
protected void setCacheEntry(ConfigurableCacheMap.Entry entryBacking)
{
m_entryBacking = entryBacking;
}
/**
* Obtain the actual cache entry from the partition-specific
* backing map.
*
* @return the actual underlying cache entry
*/
protected ConfigurableCacheMap.Entry getCacheEntry()
{
ConfigurableCacheMap.Entry entry = m_entryBacking;
if (entry == null)
{
Object oKey = getKey();
m_entryBacking = entry = getPartitionCache(oKey).getCacheEntry(oKey);
}
return entry;
}
/**
* The actual cache entry from the partition-specific backing map.
*/
ConfigurableCacheMap.Entry m_entryBacking;
}
}
// ----- inner class: CapacityAwareMap ----------------------------------
/**
* A subclass of PartitionSplittingBackingMap which allows an injected instance
* of {@link ObservableSplittingBackingMap} to be called immediately before
* inserting a value(s) in a partition map.
* <p>
* This class is intended for internal use only facilitating efficient use
* of PartitionSplittingBackingMap, by reducing the number of times the partitioned
* backing map is determined.
*
* @see ObservableSplittingBackingCache#prepareUpdate
*/
protected static class CapacityAwareMap
extends PartitionSplittingBackingMap
{
// ----- constructors -----------------------------------------------
/**
* Create a CapacityAwareMap.
*
* @param bmm a BackingMapManager that knows how to create and release
* the backing maps that this PartitionSplittingBackingMap is
* responsible for
* @param sName the cache name for which this backing map exists
*/
protected CapacityAwareMap(BackingMapManager bmm, String sName)
{
super(bmm, sName);
}
// ----- PartitionSplittingBackingMap methods -----------------------
/**
* {@inheritDoc}
*/
@Override
protected Object putInternal(Map mapPart, Object oKey, Object oValue)
{
m_mapOuter.prepareUpdate(mapPart, Collections.singletonMap(oKey, oValue));
return super.putInternal(mapPart, oKey, oValue);
}
/**
* {@inheritDoc}
*/
@Override
protected void putAllInternal(Map mapPart, Map map)
{
m_mapOuter.prepareUpdate(mapPart, map);
super.putAllInternal(mapPart, map);
}
// ----- helpers ----------------------------------------------------
/**
* Bind to the given {@link ObservableSplittingBackingMap} instance.
* This instance will have {@link ObservableSplittingBackingCache#prepareUpdate
* prepareUpdate} invoked immediately prior to an insert to a partition
* map.
*
* @param mapOuter the map used to call {@link ObservableSplittingBackingCache#prepareUpdate
* prepareUpdate}
*/
protected void bind(ObservableSplittingBackingCache mapOuter)
{
m_mapOuter = mapOuter;
}
// ----- data members -----------------------------------------------
/**
* The ObservableSplittingBackingMap used to call prepareUpdate.
*/
protected ObservableSplittingBackingCache m_mapOuter;
}
// ----- constants ------------------------------------------------------
/**
* The maximum unit factor for partition maps.
*/
protected static final int MAX_PARTITION_MAP_UNIT_FACTOR = 1024;
// ----- data members ---------------------------------------------------
/**
* High units is the number of units that triggers eviction. The value -1
* indicates that this cache has not been instructed to override the high
* units of the underlying caches.
*/
protected int m_cHighUnits = -1;
/**
* Low units is the number of units to evict down to. The value -1
* indicates that this cache has not been instructed to override the low
* units of the underlying caches.
*/
protected int m_cLowUnits = -1;
/**
* The high units adjusted based on the {@link #getPartitionUnitFactor partition unit factor}.
*/
protected int m_cHighUnitsCalibrated = -1;
/**
* The low units adjusted based on the {@link #getPartitionUnitFactor partition unit factor}.
*/
protected int m_cLowUnitsCalibrated = -1;
/**
* The unit factor. The value -1 indicates that this cache has not been
*instructed to override the unit factor of the underlying caches.
*/
protected int m_nUnitFactor = -1;
/**
* The expiry delay. The value -1 indicates that this cache has not been
* instructed to override the expiry delay of the underlying caches.
*/
protected int m_cExpiryDelayMillis = -1;
/**
* The fair share of high units for each partition map.
*/
protected int m_cHighUnitFairShare;
/**
* The fair share of low units for each partition map.
*/
protected int m_cLowUnitFairShare;
/**
* The eviction policy. The value of null indicates that this cache has
* not been instructed to override the eviction policy of the underlying
* caches.
*/
protected EvictionPolicy m_policy;
/**
* The unit calculator. The value of null indicates that this cache has
* not been instructed to override the unit calculator of the underlying
* caches.
*/
protected UnitCalculator m_calculator;
/**
* A cached array of the backing ConfigurableCacheMap instances.
*/
protected ConfigurableCacheMap[] m_acache;
/**
* An optional EvictionApprover registered with this cache.
*/
protected EvictionApprover m_apprvrEvict;
/*
* The uniform type used by each partition map.
*/
protected Class m_clzPartitionMap;
}
|
google/auto
| 38,012
|
common/src/test/java/com/google/auto/common/BasicAnnotationProcessorTest.java
|
/*
* Copyright 2014 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.auto.common;
import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION;
import static com.google.common.collect.Multimaps.transformValues;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.TruthJUnit.assume;
import static com.google.testing.compile.CompilationSubject.assertThat;
import static com.google.testing.compile.Compiler.javac;
import static javax.tools.Diagnostic.Kind.ERROR;
import com.google.auto.common.BasicAnnotationProcessor.ProcessingStep;
import com.google.auto.common.BasicAnnotationProcessor.Step;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.google.common.truth.Correspondence;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.testing.compile.Compilation;
import com.google.testing.compile.CompilationRule;
import com.google.testing.compile.JavaFileObjects;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.annotation.processing.Filer;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import javax.tools.JavaFileObject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class BasicAnnotationProcessorTest {
private abstract static class BaseAnnotationProcessor extends BasicAnnotationProcessor {
static final String ENCLOSING_CLASS_NAME =
BasicAnnotationProcessorTest.class.getCanonicalName();
@Override
public final SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
}
@Retention(RetentionPolicy.SOURCE)
public @interface RequiresGeneratedCode {}
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE_PARAMETER)
public @interface TypeParameterRequiresGeneratedCode {}
/**
* Rejects elements unless the class generated by {@link GeneratesCode}'s processor is present.
*/
private static class RequiresGeneratedCodeProcessor extends BaseAnnotationProcessor {
int rejectedRounds;
final ImmutableList.Builder<ImmutableSetMultimap<String, Element>> processArguments =
ImmutableList.builder();
@Override
protected Iterable<? extends Step> steps() {
return ImmutableList.of(
new Step() {
@Override
public ImmutableSet<? extends Element> process(
ImmutableSetMultimap<String, Element> elementsByAnnotation) {
processArguments.add(ImmutableSetMultimap.copyOf(elementsByAnnotation));
TypeElement requiredClass =
processingEnv.getElementUtils().getTypeElement("test.SomeGeneratedClass");
if (requiredClass == null) {
rejectedRounds++;
return ImmutableSet.copyOf(elementsByAnnotation.values());
}
generateClass(processingEnv.getFiler(), "GeneratedByRequiresGeneratedCodeProcessor");
return ImmutableSet.of();
}
@Override
public ImmutableSet<String> annotations() {
return ImmutableSet.of(
ENCLOSING_CLASS_NAME + ".RequiresGeneratedCode",
ENCLOSING_CLASS_NAME + ".TypeParameterRequiresGeneratedCode");
}
});
}
ImmutableList<ImmutableSetMultimap<String, Element>> processArguments() {
return processArguments.build();
}
}
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.METHOD)
public @interface OneMethodAtATime {}
private static class OneMethodAtATimeProcessor extends BaseAnnotationProcessor {
int rejectedRounds;
final ImmutableList.Builder<ImmutableSetMultimap<String, Element>> processArguments =
ImmutableList.builder();
@Override
protected Iterable<? extends Step> steps() {
return ImmutableSet.of(
new Step() {
@Override
public ImmutableSet<? extends Element> process(
ImmutableSetMultimap<String, Element> elementsByAnnotation) {
processArguments.add(ImmutableSetMultimap.copyOf(elementsByAnnotation));
int numberOfAnnotatedElements = elementsByAnnotation.size();
if (numberOfAnnotatedElements == 0) {
return ImmutableSet.of();
}
generateClass(
processingEnv.getFiler(),
"GeneratedByOneMethodAtATimeProcessor_"
+ elementsByAnnotation.values().iterator().next().getSimpleName());
if (numberOfAnnotatedElements > 1) {
rejectedRounds++;
}
return ImmutableSet.copyOf(
elementsByAnnotation.values().asList().subList(1, numberOfAnnotatedElements));
}
@Override
public ImmutableSet<String> annotations() {
return ImmutableSet.of(ENCLOSING_CLASS_NAME + ".OneMethodAtATime");
}
});
}
ImmutableList<ImmutableSetMultimap<String, Element>> processArguments() {
return processArguments.build();
}
}
/**
* This processor processes the OneMethodAtATime annotated methods, one at a time in the following
* fashion. If the number of annotated methods is more than two, the second annotated method is
* processed and the rest are deferred. Otherwise, the first annotated method is processed.
*/
private static class OneOverloadedMethodAtATimeProcessor extends BaseAnnotationProcessor {
int rejectedRounds;
final ImmutableList.Builder<ImmutableSetMultimap<String, Element>> processArguments =
ImmutableList.builder();
@Override
protected Iterable<? extends Step> steps() {
return ImmutableSet.of(
new Step() {
@Override
public ImmutableSet<? extends Element> process(
ImmutableSetMultimap<String, Element> elementsByAnnotation) {
processArguments.add(ImmutableSetMultimap.copyOf(elementsByAnnotation));
List<Element> annotatedElements = new ArrayList<>(elementsByAnnotation.values());
int numberOfAnnotatedElements = annotatedElements.size();
if (numberOfAnnotatedElements == 0) {
return ImmutableSet.of();
}
if (numberOfAnnotatedElements > 1) {
rejectedRounds++;
}
Name nameOfToBeProcessedElement;
ImmutableSet<? extends Element> rejectedElements;
if (numberOfAnnotatedElements > 2) {
// Skip the first Element
nameOfToBeProcessedElement = annotatedElements.get(1).getSimpleName();
annotatedElements.remove(1);
rejectedElements = ImmutableSet.copyOf(annotatedElements);
} else {
nameOfToBeProcessedElement = annotatedElements.get(0).getSimpleName();
annotatedElements.remove(0);
rejectedElements = ImmutableSet.copyOf(annotatedElements);
}
generateClass(
processingEnv.getFiler(),
String.format(
"GeneratedByOneMethodAtATimeProcessor_%d_%s",
numberOfAnnotatedElements > 1 ? rejectedRounds : rejectedRounds + 1,
Objects.requireNonNull(nameOfToBeProcessedElement)));
return Objects.requireNonNull(rejectedElements);
}
@Override
public ImmutableSet<String> annotations() {
return ImmutableSet.of(ENCLOSING_CLASS_NAME + ".OneMethodAtATime");
}
});
}
ImmutableList<ImmutableSetMultimap<String, Element>> processArguments() {
return processArguments.build();
}
}
@Retention(RetentionPolicy.SOURCE)
public @interface GeneratesCode {}
/** Generates a class called {@code test.SomeGeneratedClass}. */
public static class GeneratesCodeProcessor extends BaseAnnotationProcessor {
@Override
protected Iterable<? extends Step> steps() {
return ImmutableList.of(
new Step() {
@Override
public ImmutableSet<? extends Element> process(
ImmutableSetMultimap<String, Element> elementsByAnnotation) {
generateClass(processingEnv.getFiler(), "SomeGeneratedClass");
return ImmutableSet.of();
}
@Override
public ImmutableSet<String> annotations() {
return ImmutableSet.of(ENCLOSING_CLASS_NAME + ".GeneratesCode");
}
});
}
}
public @interface AnAnnotation {}
/** When annotating a type {@code Foo}, generates a class called {@code FooXYZ}. */
public static class AnAnnotationProcessor extends BaseAnnotationProcessor {
@Override
protected Iterable<? extends Step> steps() {
return ImmutableList.of(
new Step() {
@Override
public ImmutableSet<Element> process(
ImmutableSetMultimap<String, Element> elementsByAnnotation) {
for (Element element : elementsByAnnotation.values()) {
generateClass(processingEnv.getFiler(), element.getSimpleName() + "XYZ");
}
return ImmutableSet.of();
}
@Override
public ImmutableSet<String> annotations() {
return ImmutableSet.of(ENCLOSING_CLASS_NAME + ".AnAnnotation");
}
});
}
}
/** An annotation which causes an annotation processing error. */
public @interface CauseError {}
/** Report an error for any class annotated. */
public static class CauseErrorProcessor extends BaseAnnotationProcessor {
@Override
protected Iterable<? extends Step> steps() {
return ImmutableList.of(
new Step() {
@Override
public ImmutableSet<Element> process(
ImmutableSetMultimap<String, Element> elementsByAnnotation) {
for (Element e : elementsByAnnotation.values()) {
processingEnv.getMessager().printMessage(ERROR, "purposeful error", e);
}
return ImmutableSet.copyOf(elementsByAnnotation.values());
}
@Override
public ImmutableSet<String> annotations() {
return ImmutableSet.of(ENCLOSING_CLASS_NAME + ".CauseError");
}
});
}
}
public static class MissingAnnotationProcessor extends BaseAnnotationProcessor {
private ImmutableSetMultimap<String, Element> elementsByAnnotation;
@Override
protected Iterable<? extends Step> steps() {
return ImmutableList.of(
new Step() {
@Override
public ImmutableSet<Element> process(
ImmutableSetMultimap<String, Element> elementsByAnnotation) {
MissingAnnotationProcessor.this.elementsByAnnotation = elementsByAnnotation;
for (Element element : elementsByAnnotation.values()) {
generateClass(processingEnv.getFiler(), element.getSimpleName() + "XYZ");
}
return ImmutableSet.of();
}
@Override
public ImmutableSet<String> annotations() {
return ImmutableSet.of(
"test.SomeNonExistentClass", ENCLOSING_CLASS_NAME + ".AnAnnotation");
}
});
}
ImmutableSetMultimap<String, Element> getElementsByAnnotation() {
return elementsByAnnotation;
}
}
@SuppressWarnings("deprecation") // Deprecated ProcessingStep is being explicitly tested.
static final class MultiAnnotationProcessingStep implements ProcessingStep {
private SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation;
@Override
public ImmutableSet<? extends Class<? extends Annotation>> annotations() {
return ImmutableSet.of(AnAnnotation.class, ReferencesAClass.class);
}
@Override
public ImmutableSet<? extends Element> process(
SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) {
this.elementsByAnnotation = elementsByAnnotation;
return ImmutableSet.of();
}
SetMultimap<Class<? extends Annotation>, Element> getElementsByAnnotation() {
return elementsByAnnotation;
}
}
@Retention(RetentionPolicy.SOURCE)
public @interface ReferencesAClass {
Class<?> value();
}
@Rule public CompilationRule compilation = new CompilationRule();
private void requiresGeneratedCodeDeferralTest(
JavaFileObject dependentTestFileObject, JavaFileObject generatesCodeFileObject) {
RequiresGeneratedCodeProcessor requiresGeneratedCodeProcessor =
new RequiresGeneratedCodeProcessor();
Compilation compilation =
javac()
.withProcessors(requiresGeneratedCodeProcessor, new GeneratesCodeProcessor())
.compile(dependentTestFileObject, generatesCodeFileObject);
assertThat(compilation).succeeded();
assertThat(compilation).generatedSourceFile("test.GeneratedByRequiresGeneratedCodeProcessor");
assertThat(requiresGeneratedCodeProcessor.rejectedRounds).isEqualTo(0);
}
private void requiresGeneratedCodeDeferralTest(JavaFileObject dependentTestFileObject) {
JavaFileObject generatesCodeFileObject =
JavaFileObjects.forSourceLines(
"test.ClassB",
"package test;",
"",
"@" + GeneratesCode.class.getCanonicalName(),
"public class ClassB {}");
requiresGeneratedCodeDeferralTest(dependentTestFileObject, generatesCodeFileObject);
}
@Test
public void properlyDefersProcessing_typeElement() {
JavaFileObject dependentTestFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"@" + RequiresGeneratedCode.class.getCanonicalName(),
"public class ClassA {",
" SomeGeneratedClass sgc;",
"}");
requiresGeneratedCodeDeferralTest(dependentTestFileObject);
}
@Test
public void properlyDefersProcessing_packageElement() {
JavaFileObject dependentTestFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"@" + GeneratesCode.class.getCanonicalName(),
"public class ClassA {",
"}");
JavaFileObject generatesCodeFileObject =
JavaFileObjects.forSourceLines(
"test.package-info",
"@" + RequiresGeneratedCode.class.getCanonicalName(),
"@" + ReferencesAClass.class.getCanonicalName() + "(SomeGeneratedClass.class)",
"package test;");
requiresGeneratedCodeDeferralTest(dependentTestFileObject, generatesCodeFileObject);
}
@Test
public void properlyDefersProcessing_argumentElement() {
JavaFileObject dependentTestFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"public class ClassA {",
" SomeGeneratedClass sgc;",
" public void myMethod(@"
+ RequiresGeneratedCode.class.getCanonicalName()
+ " int myInt)",
" {}",
"}");
JavaFileObject generatesCodeFileObject =
JavaFileObjects.forSourceLines(
"test.ClassB",
"package test;",
"",
"public class ClassB {",
" public void myMethod(@" + GeneratesCode.class.getCanonicalName() + " int myInt) {}",
"}");
requiresGeneratedCodeDeferralTest(dependentTestFileObject, generatesCodeFileObject);
}
@Test
public void properlyDefersProcessing_recordComponent() {
double version = Double.parseDouble(Objects.requireNonNull(JAVA_SPECIFICATION_VERSION.value()));
assume().that(version).isAtLeast(16.0);
JavaFileObject dependentTestFileObject =
JavaFileObjects.forSourceLines(
"test.RecordA",
"package test;",
"",
"public record RecordA( @"
+ RequiresGeneratedCode.class.getCanonicalName()
+ " SomeGeneratedClass sgc) {",
"}");
requiresGeneratedCodeDeferralTest(dependentTestFileObject);
}
@Test
public void properlyDefersProcessing_typeParameter() {
JavaFileObject dependentTestFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"public class ClassA <@"
+ TypeParameterRequiresGeneratedCode.class.getCanonicalName()
+ " T extends SomeGeneratedClass> {",
"}");
requiresGeneratedCodeDeferralTest(dependentTestFileObject);
}
@Test
public void properlyDefersProcessing_methodTypeParameter() {
JavaFileObject dependentTestFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"public class ClassA {",
" <@"
+ TypeParameterRequiresGeneratedCode.class.getCanonicalName()
+ " T extends SomeGeneratedClass> void foo(T t) {}",
"}");
requiresGeneratedCodeDeferralTest(dependentTestFileObject);
}
@Test
public void properlyDefersProcessing_nestedTypeValidBeforeOuterType() {
JavaFileObject source =
JavaFileObjects.forSourceLines(
"test.ValidInRound2",
"package test;",
"",
"@" + AnAnnotation.class.getCanonicalName(),
"public class ValidInRound2 {",
" ValidInRound1XYZ vir1xyz;",
" @" + AnAnnotation.class.getCanonicalName(),
" static class ValidInRound1 {}",
"}");
Compilation compilation = javac().withProcessors(new AnAnnotationProcessor()).compile(source);
assertThat(compilation).succeeded();
assertThat(compilation).generatedSourceFile("test.ValidInRound2XYZ");
}
@Test
public void properlyDefersProcessing_rejectsTypeElement() {
JavaFileObject classAFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"@" + RequiresGeneratedCode.class.getCanonicalName(),
"public class ClassA {",
" @" + AnAnnotation.class.getCanonicalName(),
" public void method() {}",
"}");
RequiresGeneratedCodeProcessor requiresGeneratedCodeProcessor =
requiresGeneratedCodeRejectionTest(classAFileObject);
// Re b/118372780: Assert that the right deferred elements are passed back, and not any enclosed
// elements annotated with annotations from a different step.
assertThat(requiresGeneratedCodeProcessor.processArguments())
.comparingElementsUsing(setMultimapValuesByString())
.containsExactly(
ImmutableSetMultimap.of(RequiresGeneratedCode.class.getCanonicalName(), "test.ClassA"),
ImmutableSetMultimap.of(RequiresGeneratedCode.class.getCanonicalName(), "test.ClassA"))
.inOrder();
}
@Test
public void properlyDefersProcessing_rejectsTypeParameterElement() {
JavaFileObject classAFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"public class ClassA<@"
+ TypeParameterRequiresGeneratedCode.class.getCanonicalName()
+ " T> {",
" @" + AnAnnotation.class.getCanonicalName(),
" public void method() {}",
"}");
requiresGeneratedCodeRejectionTest(classAFileObject);
}
@Test
public void properlyDefersProcessing_rejectsArgumentElement() {
JavaFileObject classAFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"public class ClassA {",
" public void myMethod(@"
+ RequiresGeneratedCode.class.getCanonicalName()
+ " int myInt)",
" {}",
"}");
requiresGeneratedCodeRejectionTest(classAFileObject);
}
@Test
public void properlyDefersProcessing_rejectsField() {
double version = Double.parseDouble(Objects.requireNonNull(JAVA_SPECIFICATION_VERSION.value()));
assume().that(version).isAtLeast(16.0);
JavaFileObject classAFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"public class ClassA {",
"@" + RequiresGeneratedCode.class.getCanonicalName() + " String s;",
"}");
requiresGeneratedCodeRejectionTest(classAFileObject);
}
@Test
public void properlyDefersProcessing_rejectsRecordComponent() {
double version = Double.parseDouble(Objects.requireNonNull(JAVA_SPECIFICATION_VERSION.value()));
assume().that(version).isAtLeast(16.0);
JavaFileObject classAFileObject =
JavaFileObjects.forSourceLines(
"test.RecordA",
"package test;",
"",
"public record RecordA(@"
+ RequiresGeneratedCode.class.getCanonicalName()
+ " String s) {",
"}");
requiresGeneratedCodeRejectionTest(classAFileObject);
}
@Test
public void properlyDefersProcessing_rejectsTypeParameterElementInMethod() {
JavaFileObject classAFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"public class ClassA {",
" @" + AnAnnotation.class.getCanonicalName(),
" <@"
+ TypeParameterRequiresGeneratedCode.class.getCanonicalName()
+ " T> void method(T t) {}",
"}");
requiresGeneratedCodeRejectionTest(classAFileObject);
}
@CanIgnoreReturnValue
private RequiresGeneratedCodeProcessor requiresGeneratedCodeRejectionTest(
JavaFileObject classAFileObject) {
JavaFileObject classBFileObject =
JavaFileObjects.forSourceLines(
"test.ClassB",
"package test;",
"",
"@" + GeneratesCode.class.getCanonicalName(),
"public class ClassB {}");
RequiresGeneratedCodeProcessor requiresGeneratedCodeProcessor =
new RequiresGeneratedCodeProcessor();
Compilation compilation =
javac()
.withProcessors(requiresGeneratedCodeProcessor, new GeneratesCodeProcessor())
.compile(classAFileObject, classBFileObject);
assertThat(compilation).succeeded();
assertThat(compilation).generatedSourceFile("test.GeneratedByRequiresGeneratedCodeProcessor");
assertThat(requiresGeneratedCodeProcessor.rejectedRounds).isEqualTo(1);
return requiresGeneratedCodeProcessor;
}
private static <K, V>
Correspondence<SetMultimap<K, V>, SetMultimap<K, String>> setMultimapValuesByString() {
return Correspondence.from(
(actual, expected) ->
ImmutableSetMultimap.copyOf(transformValues(actual, Object::toString)).equals(expected),
"is equivalent comparing multimap values by `toString()` to");
}
@Test
public void properlyDefersProcessing_stepRejectingExecutableElements() {
JavaFileObject classAFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"public class ClassA {",
" @" + OneMethodAtATime.class.getCanonicalName(),
" public void method0() {}",
" @" + OneMethodAtATime.class.getCanonicalName(),
" public void method1() {}",
" @" + OneMethodAtATime.class.getCanonicalName(),
" public void method2() {}",
"}");
OneMethodAtATimeProcessor oneMethodAtATimeProcessor = new OneMethodAtATimeProcessor();
Compilation compilation =
javac().withProcessors(oneMethodAtATimeProcessor).compile(classAFileObject);
assertThat(compilation).succeeded();
assertThat(oneMethodAtATimeProcessor.rejectedRounds).isEqualTo(2);
assertThat(oneMethodAtATimeProcessor.processArguments())
.comparingElementsUsing(setMultimapValuesByString())
.containsExactly(
ImmutableSetMultimap.of(
OneMethodAtATime.class.getCanonicalName(), "method0()",
OneMethodAtATime.class.getCanonicalName(), "method1()",
OneMethodAtATime.class.getCanonicalName(), "method2()"),
ImmutableSetMultimap.of(
OneMethodAtATime.class.getCanonicalName(), "method1()",
OneMethodAtATime.class.getCanonicalName(), "method2()"),
ImmutableSetMultimap.of(OneMethodAtATime.class.getCanonicalName(), "method2()"))
.inOrder();
}
@Test
public void properlyDefersProcessing_stepRejectingOverloadedExecutableElements() {
JavaFileObject classAFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"public class ClassA {",
" @" + OneMethodAtATime.class.getCanonicalName(),
" public void overloadedMethod(int x) {}",
" @" + OneMethodAtATime.class.getCanonicalName(),
" public void overloadedMethod(float x) {}",
" @" + OneMethodAtATime.class.getCanonicalName(),
" public void overloadedMethod(double x) {}",
"}");
OneOverloadedMethodAtATimeProcessor oneOverloadedMethodAtATimeProcessor =
new OneOverloadedMethodAtATimeProcessor();
Compilation compilation =
javac().withProcessors(oneOverloadedMethodAtATimeProcessor).compile(classAFileObject);
assertThat(compilation).succeeded();
assertThat(oneOverloadedMethodAtATimeProcessor.rejectedRounds).isEqualTo(2);
assertThat(oneOverloadedMethodAtATimeProcessor.processArguments())
.comparingElementsUsing(setMultimapValuesByString())
.containsExactly(
ImmutableSetMultimap.of(
OneMethodAtATime.class.getCanonicalName(), "overloadedMethod(int)",
OneMethodAtATime.class.getCanonicalName(), "overloadedMethod(float)",
OneMethodAtATime.class.getCanonicalName(), "overloadedMethod(double)"),
ImmutableSetMultimap.of(
OneMethodAtATime.class.getCanonicalName(), "overloadedMethod(int)",
OneMethodAtATime.class.getCanonicalName(), "overloadedMethod(double)"),
ImmutableSetMultimap.of(
OneMethodAtATime.class.getCanonicalName(), "overloadedMethod(double)"))
.inOrder();
}
@Test
public void properlyDefersProcessing_stepAndIllFormedRejectingExecutableElements() {
JavaFileObject testFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"import java.util.Set;",
"import java.util.SortedSet;",
"",
"public class ClassA {",
" @" + OneMethodAtATime.class.getCanonicalName(),
" <C extends Set<String>> void overloadedMethod(C x) {}",
" @" + OneMethodAtATime.class.getCanonicalName(),
" <C extends SortedSet<String>> void overloadedMethod(C c) {}",
" @" + OneMethodAtATime.class.getCanonicalName(),
" void overloadedMethod(SomeGeneratedClass c) {}",
" @" + OneMethodAtATime.class.getCanonicalName(),
" void method0(SomeGeneratedClass c) {}",
"}");
JavaFileObject generatesCodeFileObject =
JavaFileObjects.forSourceLines(
"test.ClassB",
"package test;",
"",
"@" + GeneratesCode.class.getCanonicalName(),
"public class ClassB {}");
OneOverloadedMethodAtATimeProcessor oneOverloadedMethodAtATimeProcessor =
new OneOverloadedMethodAtATimeProcessor();
Compilation compilation =
javac()
.withProcessors(oneOverloadedMethodAtATimeProcessor, new GeneratesCodeProcessor())
.compile(testFileObject, generatesCodeFileObject);
assertThat(compilation).succeeded();
assertThat(oneOverloadedMethodAtATimeProcessor.rejectedRounds).isEqualTo(3);
assertThat(oneOverloadedMethodAtATimeProcessor.processArguments())
.comparingElementsUsing(setMultimapValuesByString())
.containsExactly(
ImmutableSetMultimap.of(
OneMethodAtATime.class.getCanonicalName(), "<C>overloadedMethod(C)",
OneMethodAtATime.class.getCanonicalName(), "<C>overloadedMethod(C)",
OneMethodAtATime.class.getCanonicalName(),
"overloadedMethod(test.SomeGeneratedClass)",
OneMethodAtATime.class.getCanonicalName(), "method0(test.SomeGeneratedClass)"),
ImmutableSetMultimap.of(
OneMethodAtATime.class.getCanonicalName(), "<C>overloadedMethod(C)",
OneMethodAtATime.class.getCanonicalName(),
"overloadedMethod(test.SomeGeneratedClass)",
OneMethodAtATime.class.getCanonicalName(), "method0(test.SomeGeneratedClass)"),
ImmutableSetMultimap.of(
OneMethodAtATime.class.getCanonicalName(), "<C>overloadedMethod(C)",
OneMethodAtATime.class.getCanonicalName(), "method0(test.SomeGeneratedClass)"),
ImmutableSetMultimap.of(
OneMethodAtATime.class.getCanonicalName(), "method0(test.SomeGeneratedClass)"))
.inOrder();
}
/**
* In the following example, at least open-jdk does not report the second method if {@code
* SomeGeneratedClass} references a {@link TypeKind#ERROR} when {@link
* RoundEnvironment#getElementsAnnotatedWith} is called, or even when {@link
* TypeElement#getEnclosedElements()} is called. Therefore, our implementation should be vigilant
* that the second method is captured for processing at some point.
*
* <p>Note that for a method to get "hidden" like this, it should reside after the ERROR
* referencing method, and it should not have any distinguishing characteristic like different
* name, different number of parameter, or a clear parameter type mismatch.
*/
@Test
public void properlyDefersProcessing_errorTypeReferencingOverloadedMethods() {
JavaFileObject testFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"public class ClassA {",
" @" + OneMethodAtATime.class.getCanonicalName(),
" void overloadedMethod(SomeGeneratedClass c) {}",
" @" + OneMethodAtATime.class.getCanonicalName(),
" void overloadedMethod(int c) {}",
"}");
JavaFileObject generatesCodeFileObject =
JavaFileObjects.forSourceLines(
"test.ClassB",
"package test;",
"",
"@" + GeneratesCode.class.getCanonicalName(),
"public class ClassB {}");
OneOverloadedMethodAtATimeProcessor oneOverloadedMethodAtATimeProcessor =
new OneOverloadedMethodAtATimeProcessor();
Compilation compilation =
javac()
.withProcessors(oneOverloadedMethodAtATimeProcessor, new GeneratesCodeProcessor())
.compile(testFileObject, generatesCodeFileObject);
assertThat(compilation).succeeded();
assertThat(oneOverloadedMethodAtATimeProcessor.rejectedRounds).isEqualTo(1);
assertThat(oneOverloadedMethodAtATimeProcessor.processArguments())
.comparingElementsUsing(setMultimapValuesByString())
.containsExactly(
ImmutableSetMultimap.of(
OneMethodAtATime.class.getCanonicalName(),
"overloadedMethod(test.SomeGeneratedClass)",
OneMethodAtATime.class.getCanonicalName(),
"overloadedMethod(int)"),
ImmutableSetMultimap.of(
OneMethodAtATime.class.getCanonicalName(), "overloadedMethod(int)"))
.inOrder();
}
@Test
public void properlySkipsMissingAnnotations_generatesClass() {
JavaFileObject source =
JavaFileObjects.forSourceLines(
"test.ValidInRound2",
"package test;",
"",
"@" + AnAnnotation.class.getCanonicalName(),
"public class ValidInRound2 {",
" ValidInRound1XYZ vir1xyz;",
" @" + AnAnnotation.class.getCanonicalName(),
" static class ValidInRound1 {}",
"}");
Compilation compilation =
javac().withProcessors(new MissingAnnotationProcessor()).compile(source);
assertThat(compilation).succeeded();
assertThat(compilation).generatedSourceFile("test.ValidInRound2XYZ");
}
@Test
public void properlySkipsMissingAnnotations_passesValidAnnotationsToProcess() {
JavaFileObject source =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"@" + AnAnnotation.class.getCanonicalName(),
"public class ClassA {",
"}");
MissingAnnotationProcessor missingAnnotationProcessor = new MissingAnnotationProcessor();
assertThat(javac().withProcessors(missingAnnotationProcessor).compile(source)).succeeded();
assertThat(missingAnnotationProcessor.getElementsByAnnotation().keySet())
.containsExactly(AnAnnotation.class.getCanonicalName());
assertThat(missingAnnotationProcessor.getElementsByAnnotation().values()).hasSize(1);
}
@Test
public void reportsMissingType() {
JavaFileObject classAFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"@" + RequiresGeneratedCode.class.getCanonicalName(),
"public class ClassA {",
" SomeGeneratedClass bar;",
"}");
Compilation compilation =
javac().withProcessors(new RequiresGeneratedCodeProcessor()).compile(classAFileObject);
assertThat(compilation)
.hadErrorContaining(RequiresGeneratedCodeProcessor.class.getCanonicalName())
.inFile(classAFileObject)
.onLineContaining("class ClassA");
}
@Test
public void reportsMissingTypeSuppressedWhenOtherErrors() {
JavaFileObject classAFileObject =
JavaFileObjects.forSourceLines(
"test.ClassA",
"package test;",
"",
"@" + CauseError.class.getCanonicalName(),
"public class ClassA {}");
Compilation compilation =
javac().withProcessors(new CauseErrorProcessor()).compile(classAFileObject);
assertThat(compilation).hadErrorContaining("purposeful");
}
@Test
public void processingStepAsStepAnnotationsNamesMatchClasses() {
Step step = BasicAnnotationProcessor.asStep(new MultiAnnotationProcessingStep());
assertThat(step.annotations())
.containsExactly(
AnAnnotation.class.getCanonicalName(), ReferencesAClass.class.getCanonicalName());
}
/**
* Tests that a {@link ProcessingStep} passed to {@link
* BasicAnnotationProcessor#asStep(ProcessingStep)} still gets passed the correct arguments to
* {@link Step#process(ImmutableSetMultimap)}.
*/
@Test
public void processingStepAsStepProcessElementsMatchClasses() {
Elements elements = compilation.getElements();
String anAnnotationName = AnAnnotation.class.getCanonicalName();
String referencesAClassName = ReferencesAClass.class.getCanonicalName();
TypeElement anAnnotationElement = elements.getTypeElement(anAnnotationName);
TypeElement referencesAClassElement = elements.getTypeElement(referencesAClassName);
MultiAnnotationProcessingStep processingStep = new MultiAnnotationProcessingStep();
BasicAnnotationProcessor.asStep(processingStep)
.process(
ImmutableSetMultimap.of(
anAnnotationName,
anAnnotationElement,
referencesAClassName,
referencesAClassElement));
assertThat(processingStep.getElementsByAnnotation())
.containsExactly(
AnAnnotation.class,
anAnnotationElement,
ReferencesAClass.class,
referencesAClassElement);
}
private static void generateClass(Filer filer, String generatedClassName) {
PrintWriter writer = null;
try {
writer = new PrintWriter(filer.createSourceFile("test." + generatedClassName).openWriter());
writer.println("package test;");
writer.println("public class " + generatedClassName + " {}");
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (writer != null) {
writer.close();
}
}
}
}
|
apache/logging-log4j2
| 38,135
|
log4j-core-test/src/test/java/org/apache/logging/log4j/core/layout/PatternLayoutTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.logging.log4j.core.layout;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.apache.logging.log4j.core.lookup.MainMapLookup;
import org.apache.logging.log4j.core.test.BasicConfigurationFactory;
import org.apache.logging.log4j.message.SimpleMessage;
import org.apache.logging.log4j.test.junit.UsingAnyThreadContext;
import org.apache.logging.log4j.util.Strings;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@UsingAnyThreadContext
class PatternLayoutTest {
public static class FauxLogger {
public String formatEvent(final LogEvent event, final Layout<?> layout) {
return new String(layout.toByteArray(event));
}
}
static ConfigurationFactory cf = new BasicConfigurationFactory();
static String msgPattern = "%m%n";
static String OUTPUT_FILE = "target/output/PatternParser";
static final String regexPattern = "%replace{%logger %msg}{\\.}{/}";
static String WITNESS_FILE = "witness/PatternParser";
public static void cleanupClass() {
ConfigurationFactory.removeConfigurationFactory(cf);
}
@BeforeAll
static void setupClass() {
ConfigurationFactory.setConfigurationFactory(cf);
final LoggerContext ctx = LoggerContext.getContext();
ctx.reconfigure();
}
LoggerContext ctx = LoggerContext.getContext();
Logger root = ctx.getRootLogger();
private static class Destination implements ByteBufferDestination {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[2048]);
@Override
public ByteBuffer getByteBuffer() {
return byteBuffer;
}
@Override
public ByteBuffer drain(final ByteBuffer buf) {
throw new IllegalStateException("Unexpected message larger than 2048 bytes");
}
@Override
public void writeBytes(final ByteBuffer data) {
byteBuffer.put(data);
}
@Override
public void writeBytes(final byte[] data, final int offset, final int length) {
byteBuffer.put(data, offset, length);
}
}
private void assertToByteArray(final String expectedStr, final PatternLayout layout, final LogEvent event) {
final byte[] result = layout.toByteArray(event);
assertEquals(expectedStr, new String(result));
}
private void assertEncode(final String expectedStr, final PatternLayout layout, final LogEvent event) {
final Destination destination = new Destination();
layout.encode(event, destination);
final ByteBuffer byteBuffer = destination.getByteBuffer();
byteBuffer.flip(); // set limit to position, position back to zero
assertEquals(
expectedStr,
new String(
byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining()));
}
@Test
void testEqualsEmptyMarker() {
// replace "[]" with the empty string
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("[%logger]%equals{[%marker]}{[]}{} %msg")
.setConfiguration(ctx.getConfiguration())
.build();
// Not empty marker
final LogEvent event1 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMarker(MarkerManager.getMarker("TestMarker")) //
.setMessage(new SimpleMessage("Hello, world!"))
.build();
assertToByteArray(
"[org.apache.logging.log4j.core.layout.PatternLayoutTest][TestMarker] Hello, world!", layout, event1);
assertEncode(
"[org.apache.logging.log4j.core.layout.PatternLayoutTest][TestMarker] Hello, world!", layout, event1);
// empty marker
final LogEvent event2 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world!"))
.build();
assertToByteArray("[org.apache.logging.log4j.core.layout.PatternLayoutTest] Hello, world!", layout, event2);
assertEncode("[org.apache.logging.log4j.core.layout.PatternLayoutTest] Hello, world!", layout, event2);
}
@Test
void testHeaderFooterJavaLookup() {
// % does not work here.
final String pattern = "%d{UNIX} MyApp%n${java:version}%n${java:runtime}%n${java:vm}%n${java:os}%n${java:hw}";
final PatternLayout layout = PatternLayout.newBuilder()
.setConfiguration(ctx.getConfiguration())
.setHeader("Header: " + pattern)
.setFooter("Footer: " + pattern)
.build();
final byte[] header = layout.getHeader();
assertNotNull(header, "No header");
final String headerStr = new String(header);
assertTrue(headerStr.contains("Header: "), headerStr);
assertTrue(headerStr.contains("Java version "), headerStr);
assertTrue(headerStr.contains("(build "), headerStr);
assertTrue(headerStr.contains(" from "), headerStr);
assertTrue(headerStr.contains(" architecture: "), headerStr);
assertFalse(headerStr.contains("%d{UNIX}"), headerStr);
//
final byte[] footer = layout.getFooter();
assertNotNull(footer, "No footer");
final String footerStr = new String(footer);
assertTrue(footerStr.contains("Footer: "), footerStr);
assertTrue(footerStr.contains("Java version "), footerStr);
assertTrue(footerStr.contains("(build "), footerStr);
assertTrue(footerStr.contains(" from "), footerStr);
assertTrue(footerStr.contains(" architecture: "), footerStr);
assertFalse(footerStr.contains("%d{UNIX}"), footerStr);
}
/**
* Tests LOG4J2-962.
*/
@Test
void testHeaderFooterMainLookup() {
MainMapLookup.setMainArguments("value0", "value1", "value2");
final PatternLayout layout = PatternLayout.newBuilder()
.setConfiguration(ctx.getConfiguration())
.setHeader("${main:0}")
.setFooter("${main:2}")
.build();
final byte[] header = layout.getHeader();
assertNotNull(header, "No header");
final String headerStr = new String(header);
assertTrue(headerStr.contains("value0"), headerStr);
//
final byte[] footer = layout.getFooter();
assertNotNull(footer, "No footer");
final String footerStr = new String(footer);
assertTrue(footerStr.contains("value2"), footerStr);
}
@Test
void testHeaderFooterThreadContext() {
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%d{UNIX} %m")
.setConfiguration(ctx.getConfiguration())
.setHeader("${ctx:header}")
.setFooter("${ctx:footer}")
.build();
ThreadContext.put("header", "Hello world Header");
ThreadContext.put("footer", "Hello world Footer");
final byte[] header = layout.getHeader();
assertNotNull(header, "No header");
assertEquals(
"Hello world Header",
new String(header),
"expected \"Hello world Header\", actual " + Strings.dquote(new String(header)));
}
private void testMdcPattern(final String patternStr, final String expectedStr, final boolean useThreadContext) {
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern(patternStr)
.setConfiguration(ctx.getConfiguration())
.build();
if (useThreadContext) {
ThreadContext.put("key1", "value1");
ThreadContext.put("key2", "value2");
}
final LogEvent event = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello"))
.build();
assertToByteArray(expectedStr, layout, event);
assertEncode(expectedStr, layout, event);
}
@Test
void testMdcPattern0() throws Exception {
testMdcPattern("%m : %X", "Hello : {key1=value1, key2=value2}", true);
}
@Test
void testMdcPattern1() throws Exception {
testMdcPattern("%m : %X", "Hello : {}", false);
}
@Test
void testMdcPattern2() throws Exception {
testMdcPattern("%m : %X{key1}", "Hello : value1", true);
}
@Test
void testMdcPattern3() throws Exception {
testMdcPattern("%m : %X{key2}", "Hello : value2", true);
}
@Test
void testMdcPattern4() throws Exception {
testMdcPattern("%m : %X{key3}", "Hello : ", true);
}
@Test
void testMdcPattern5() throws Exception {
testMdcPattern("%m : %X{key1}, %X{key2}, %X{key3}", "Hello : value1, value2, ", true);
}
@Test
void testPatternSelector() {
final PatternMatch[] patterns = new PatternMatch[1];
patterns[0] = new PatternMatch("FLOW", "%d %-5p [%t]: ====== %C{1}.%M:%L %m ======%n");
final PatternSelector selector = MarkerPatternSelector.createSelector(
patterns, "%d %-5p [%t]: %m%n", true, true, ctx.getConfiguration());
final PatternLayout layout = PatternLayout.newBuilder()
.setPatternSelector(selector)
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.layout.PatternLayoutTest$FauxLogger")
.setMarker(MarkerManager.getMarker("FLOW"))
.setLevel(Level.TRACE) //
.setIncludeLocation(true)
.setMessage(new SimpleMessage("entry"))
.build();
final String result1 = new FauxLogger().formatEvent(event1, layout);
final String expectPattern1 =
String.format(".*====== PatternLayoutTest.testPatternSelector:\\d+ entry ======%n");
assertTrue(result1.matches(expectPattern1), "Unexpected result: " + result1);
final LogEvent event2 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world 1!"))
.build();
final String result2 = new String(layout.toByteArray(event2));
final String expectSuffix2 = String.format("Hello, world 1!%n");
assertTrue(result2.endsWith(expectSuffix2), "Unexpected result: " + result2);
}
@Test
void testRegex() {
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern(regexPattern)
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world!"))
.build();
assertToByteArray("org/apache/logging/log4j/core/layout/PatternLayoutTest Hello, world!", layout, event);
assertEncode("org/apache/logging/log4j/core/layout/PatternLayoutTest Hello, world!", layout, event);
}
@Test
void testRegexEmptyMarker() {
// replace "[]" with the empty string
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("[%logger]%replace{[%marker]}{\\[\\]}{} %msg")
.setConfiguration(ctx.getConfiguration())
.build();
// Not empty marker
final LogEvent event1 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMarker(MarkerManager.getMarker("TestMarker")) //
.setMessage(new SimpleMessage("Hello, world!"))
.build();
assertToByteArray(
"[org.apache.logging.log4j.core.layout.PatternLayoutTest][TestMarker] Hello, world!", layout, event1);
assertEncode(
"[org.apache.logging.log4j.core.layout.PatternLayoutTest][TestMarker] Hello, world!", layout, event1);
// empty marker
final LogEvent event2 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world!"))
.build();
assertToByteArray("[org.apache.logging.log4j.core.layout.PatternLayoutTest] Hello, world!", layout, event2);
assertEncode("[org.apache.logging.log4j.core.layout.PatternLayoutTest] Hello, world!", layout, event2);
}
@Test
void testEqualsMarkerWithMessageSubstitution() {
// replace "[]" with the empty string
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("[%logger]%equals{[%marker]}{[]}{[%msg]}")
.setConfiguration(ctx.getConfiguration())
.build();
// Not empty marker
final LogEvent event1 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMarker(MarkerManager.getMarker("TestMarker"))
.setMessage(new SimpleMessage("Hello, world!"))
.build();
final byte[] result1 = layout.toByteArray(event1);
assertEquals("[org.apache.logging.log4j.core.layout.PatternLayoutTest][TestMarker]", new String(result1));
// empty marker
final LogEvent event2 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world!"))
.build();
final byte[] result2 = layout.toByteArray(event2);
assertEquals("[org.apache.logging.log4j.core.layout.PatternLayoutTest][Hello, world!]", new String(result2));
}
@Test
void testSpecialChars() {
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("\\\\%level\\t%msg\\n\\t%logger\\r\\n\\f")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world!"))
.build();
assertToByteArray(
"\\INFO\tHello, world!\n" + "\torg.apache.logging.log4j.core.layout.PatternLayoutTest\r\n" + "\f",
layout,
event);
assertEncode(
"\\INFO\tHello, world!\n" + "\torg.apache.logging.log4j.core.layout.PatternLayoutTest\r\n" + "\f",
layout,
event);
}
@Test
void testUnixTime() {
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%d{UNIX} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world 1!"))
.build();
final byte[] result1 = layout.toByteArray(event1);
assertEquals(event1.getTimeMillis() / 1000 + " Hello, world 1!", new String(result1));
// System.out.println("event1=" + event1.getTimeMillis() / 1000);
final LogEvent event2 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world 2!"))
.build();
final byte[] result2 = layout.toByteArray(event2);
assertEquals(event2.getTimeMillis() / 1000 + " Hello, world 2!", new String(result2));
// System.out.println("event2=" + event2.getTimeMillis() / 1000);
}
@SuppressWarnings("unused")
private void testUnixTime(final String pattern) {
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern(pattern + " %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world 1!"))
.build();
final byte[] result1 = layout.toByteArray(event1);
assertEquals(event1.getTimeMillis() + " Hello, world 1!", new String(result1));
// System.out.println("event1=" + event1.getMillis());
final LogEvent event2 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world 2!"))
.build();
final byte[] result2 = layout.toByteArray(event2);
assertEquals(event2.getTimeMillis() + " Hello, world 2!", new String(result2));
// System.out.println("event2=" + event2.getMillis());
}
@Test
void testUnixTimeMillis() {
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%d{UNIX_MILLIS} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world 1!"))
.build();
final byte[] result1 = layout.toByteArray(event1);
assertEquals(event1.getTimeMillis() + " Hello, world 1!", new String(result1));
// System.out.println("event1=" + event1.getTimeMillis());
final LogEvent event2 = Log4jLogEvent.newBuilder() //
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger") //
.setLevel(Level.INFO) //
.setMessage(new SimpleMessage("Hello, world 2!"))
.build();
final byte[] result2 = layout.toByteArray(event2);
assertEquals(event2.getTimeMillis() + " Hello, world 2!", new String(result2));
// System.out.println("event2=" + event2.getTimeMillis());
}
@Test
void testUsePlatformDefaultIfNoCharset() {
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%m")
.setConfiguration(ctx.getConfiguration())
.build();
assertEquals(Charset.defaultCharset(), layout.getCharset());
}
@Test
void testUseSpecifiedCharsetIfExists() {
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%m")
.setConfiguration(ctx.getConfiguration())
.setCharset(StandardCharsets.UTF_8)
.build();
assertEquals(StandardCharsets.UTF_8, layout.getCharset());
}
@Test
void testLoggerNameTruncationByRetainingPartsFromEnd() {
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%c{1} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.build();
final String result1 = layout.toSerializable(event1);
assertEquals(
this.getClass()
.getName()
.substring(this.getClass().getName().lastIndexOf(".") + 1) + " Hello, world 1!",
new String(result1));
}
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%c{2} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.build();
final String result1 = layout.toSerializable(event1);
String name = this.getClass()
.getName()
.substring(0, this.getClass().getName().lastIndexOf("."));
name = name.substring(0, name.lastIndexOf("."));
assertEquals(
this.getClass().getName().substring(name.length() + 1) + " Hello, world 1!", new String(result1));
}
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%c{20} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.build();
final String result1 = layout.toSerializable(event1);
assertEquals(this.getClass().getName() + " Hello, world 1!", new String(result1));
}
}
@Test
void testCallersFqcnTruncationByRetainingPartsFromEnd() {
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%C{1} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.setSource(new StackTraceElement(
this.getClass().getName(),
"testCallersFqcnTruncationByRetainingPartsFromEnd",
this.getClass().getCanonicalName() + ".java",
440))
.build();
final String result1 = layout.toSerializable(event1);
assertEquals(
this.getClass()
.getName()
.substring(this.getClass().getName().lastIndexOf(".") + 1) + " Hello, world 1!",
new String(result1));
}
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%C{2} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.setSource(new StackTraceElement(
this.getClass().getName(),
"testCallersFqcnTruncationByRetainingPartsFromEnd",
this.getClass().getCanonicalName() + ".java",
440))
.build();
final String result1 = layout.toSerializable(event1);
String name = this.getClass()
.getName()
.substring(0, this.getClass().getName().lastIndexOf("."));
name = name.substring(0, name.lastIndexOf("."));
assertEquals(
this.getClass().getName().substring(name.length() + 1) + " Hello, world 1!", new String(result1));
}
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%C{20} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.setSource(new StackTraceElement(
this.getClass().getName(),
"testCallersFqcnTruncationByRetainingPartsFromEnd",
this.getClass().getCanonicalName() + ".java",
440))
.build();
final String result1 = layout.toSerializable(event1);
assertEquals(this.getClass().getName() + " Hello, world 1!", new String(result1));
}
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%class{1} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.setSource(new StackTraceElement(
this.getClass().getName(),
"testCallersFqcnTruncationByRetainingPartsFromEnd",
this.getClass().getCanonicalName() + ".java",
440))
.build();
final String result1 = layout.toSerializable(event1);
assertEquals(
this.getClass()
.getName()
.substring(this.getClass().getName().lastIndexOf(".") + 1) + " Hello, world 1!",
new String(result1));
}
}
@Test
void testLoggerNameTruncationByDroppingPartsFromFront() {
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%c{-1} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.build();
final String result1 = layout.toSerializable(event1);
final String name = this.getClass()
.getName()
.substring(this.getClass().getName().indexOf(".") + 1);
assertEquals(name + " Hello, world 1!", new String(result1));
}
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%c{-3} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.build();
final String result1 = layout.toSerializable(event1);
String name = this.getClass()
.getName()
.substring(this.getClass().getName().indexOf(".") + 1);
name = name.substring(name.indexOf(".") + 1);
name = name.substring(name.indexOf(".") + 1);
assertEquals(name + " Hello, world 1!", new String(result1));
}
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%logger{-3} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.build();
final String result1 = layout.toSerializable(event1);
String name = this.getClass()
.getName()
.substring(this.getClass().getName().indexOf(".") + 1);
name = name.substring(name.indexOf(".") + 1);
name = name.substring(name.indexOf(".") + 1);
assertEquals(name + " Hello, world 1!", new String(result1));
}
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%c{-20} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.build();
final String result1 = layout.toSerializable(event1);
assertEquals(this.getClass().getName() + " Hello, world 1!", new String(result1));
}
}
@Test
void testCallersFqcnTruncationByDroppingPartsFromFront() {
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%C{-1} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.setSource(new StackTraceElement(
this.getClass().getName(),
"testCallersFqcnTruncationByDroppingPartsFromFront",
this.getClass().getCanonicalName() + ".java",
546))
.build();
final String result1 = layout.toSerializable(event1);
final String name = this.getClass()
.getName()
.substring(this.getClass().getName().indexOf(".") + 1);
assertEquals(name + " Hello, world 1!", new String(result1));
}
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%C{-3} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.setSource(new StackTraceElement(
this.getClass().getName(),
"testCallersFqcnTruncationByDroppingPartsFromFront",
this.getClass().getCanonicalName() + ".java",
546))
.build();
final String result1 = layout.toSerializable(event1);
String name = this.getClass()
.getName()
.substring(this.getClass().getName().indexOf(".") + 1);
name = name.substring(name.indexOf(".") + 1);
name = name.substring(name.indexOf(".") + 1);
assertEquals(name + " Hello, world 1!", new String(result1));
}
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%class{-3} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.setSource(new StackTraceElement(
this.getClass().getName(),
"testCallersFqcnTruncationByDroppingPartsFromFront",
this.getClass().getCanonicalName() + ".java",
546))
.build();
final String result1 = layout.toSerializable(event1);
String name = this.getClass()
.getName()
.substring(this.getClass().getName().indexOf(".") + 1);
name = name.substring(name.indexOf(".") + 1);
name = name.substring(name.indexOf(".") + 1);
assertEquals(name + " Hello, world 1!", new String(result1));
}
{
final PatternLayout layout = PatternLayout.newBuilder()
.setPattern("%C{-20} %m")
.setConfiguration(ctx.getConfiguration())
.build();
final LogEvent event1 = Log4jLogEvent.newBuilder()
.setLoggerName(this.getClass().getName())
.setLoggerFqcn("org.apache.logging.log4j.core.Logger")
.setLevel(Level.INFO)
.setMessage(new SimpleMessage("Hello, world 1!"))
.setSource(new StackTraceElement(
this.getClass().getName(),
"testCallersFqcnTruncationByDroppingPartsFromFront",
this.getClass().getCanonicalName() + ".java",
546))
.build();
final String result1 = layout.toSerializable(event1);
assertEquals(this.getClass().getName() + " Hello, world 1!", new String(result1));
}
}
}
|
googleapis/google-cloud-java
| 38,424
|
java-gkehub/grpc-google-cloud-gkehub-v1alpha/src/main/java/com/google/cloud/gkehub/v1alpha/GkeHubGrpc.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.gkehub.v1alpha;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
*
*
* <pre>
* The GKE Hub service handles the registration of many Kubernetes clusters to
* Google Cloud, and the management of multi-cluster features over those
* clusters.
* The GKE Hub service operates on the following resources:
* * [Membership][google.cloud.gkehub.v1alpha.Membership]
* * [Feature][google.cloud.gkehub.v1alpha.Feature]
* GKE Hub is currently only available in the global region.
* **Membership management may be non-trivial:** it is recommended to use one
* of the Google-provided client libraries or tools where possible when working
* with Membership resources.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: google/cloud/gkehub/v1alpha/service.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class GkeHubGrpc {
private GkeHubGrpc() {}
public static final java.lang.String SERVICE_NAME = "google.cloud.gkehub.v1alpha.GkeHub";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.ListFeaturesRequest,
com.google.cloud.gkehub.v1alpha.ListFeaturesResponse>
getListFeaturesMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "ListFeatures",
requestType = com.google.cloud.gkehub.v1alpha.ListFeaturesRequest.class,
responseType = com.google.cloud.gkehub.v1alpha.ListFeaturesResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.ListFeaturesRequest,
com.google.cloud.gkehub.v1alpha.ListFeaturesResponse>
getListFeaturesMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.ListFeaturesRequest,
com.google.cloud.gkehub.v1alpha.ListFeaturesResponse>
getListFeaturesMethod;
if ((getListFeaturesMethod = GkeHubGrpc.getListFeaturesMethod) == null) {
synchronized (GkeHubGrpc.class) {
if ((getListFeaturesMethod = GkeHubGrpc.getListFeaturesMethod) == null) {
GkeHubGrpc.getListFeaturesMethod =
getListFeaturesMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.gkehub.v1alpha.ListFeaturesRequest,
com.google.cloud.gkehub.v1alpha.ListFeaturesResponse>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListFeatures"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.gkehub.v1alpha.ListFeaturesRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.gkehub.v1alpha.ListFeaturesResponse
.getDefaultInstance()))
.setSchemaDescriptor(new GkeHubMethodDescriptorSupplier("ListFeatures"))
.build();
}
}
}
return getListFeaturesMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.GetFeatureRequest,
com.google.cloud.gkehub.v1alpha.Feature>
getGetFeatureMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "GetFeature",
requestType = com.google.cloud.gkehub.v1alpha.GetFeatureRequest.class,
responseType = com.google.cloud.gkehub.v1alpha.Feature.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.GetFeatureRequest,
com.google.cloud.gkehub.v1alpha.Feature>
getGetFeatureMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.GetFeatureRequest,
com.google.cloud.gkehub.v1alpha.Feature>
getGetFeatureMethod;
if ((getGetFeatureMethod = GkeHubGrpc.getGetFeatureMethod) == null) {
synchronized (GkeHubGrpc.class) {
if ((getGetFeatureMethod = GkeHubGrpc.getGetFeatureMethod) == null) {
GkeHubGrpc.getGetFeatureMethod =
getGetFeatureMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.gkehub.v1alpha.GetFeatureRequest,
com.google.cloud.gkehub.v1alpha.Feature>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetFeature"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.gkehub.v1alpha.GetFeatureRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.gkehub.v1alpha.Feature.getDefaultInstance()))
.setSchemaDescriptor(new GkeHubMethodDescriptorSupplier("GetFeature"))
.build();
}
}
}
return getGetFeatureMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.CreateFeatureRequest, com.google.longrunning.Operation>
getCreateFeatureMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "CreateFeature",
requestType = com.google.cloud.gkehub.v1alpha.CreateFeatureRequest.class,
responseType = com.google.longrunning.Operation.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.CreateFeatureRequest, com.google.longrunning.Operation>
getCreateFeatureMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.CreateFeatureRequest, com.google.longrunning.Operation>
getCreateFeatureMethod;
if ((getCreateFeatureMethod = GkeHubGrpc.getCreateFeatureMethod) == null) {
synchronized (GkeHubGrpc.class) {
if ((getCreateFeatureMethod = GkeHubGrpc.getCreateFeatureMethod) == null) {
GkeHubGrpc.getCreateFeatureMethod =
getCreateFeatureMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.gkehub.v1alpha.CreateFeatureRequest,
com.google.longrunning.Operation>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "CreateFeature"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.gkehub.v1alpha.CreateFeatureRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.longrunning.Operation.getDefaultInstance()))
.setSchemaDescriptor(new GkeHubMethodDescriptorSupplier("CreateFeature"))
.build();
}
}
}
return getCreateFeatureMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest, com.google.longrunning.Operation>
getDeleteFeatureMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "DeleteFeature",
requestType = com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest.class,
responseType = com.google.longrunning.Operation.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest, com.google.longrunning.Operation>
getDeleteFeatureMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest, com.google.longrunning.Operation>
getDeleteFeatureMethod;
if ((getDeleteFeatureMethod = GkeHubGrpc.getDeleteFeatureMethod) == null) {
synchronized (GkeHubGrpc.class) {
if ((getDeleteFeatureMethod = GkeHubGrpc.getDeleteFeatureMethod) == null) {
GkeHubGrpc.getDeleteFeatureMethod =
getDeleteFeatureMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest,
com.google.longrunning.Operation>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "DeleteFeature"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.longrunning.Operation.getDefaultInstance()))
.setSchemaDescriptor(new GkeHubMethodDescriptorSupplier("DeleteFeature"))
.build();
}
}
}
return getDeleteFeatureMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest, com.google.longrunning.Operation>
getUpdateFeatureMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "UpdateFeature",
requestType = com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest.class,
responseType = com.google.longrunning.Operation.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest, com.google.longrunning.Operation>
getUpdateFeatureMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest, com.google.longrunning.Operation>
getUpdateFeatureMethod;
if ((getUpdateFeatureMethod = GkeHubGrpc.getUpdateFeatureMethod) == null) {
synchronized (GkeHubGrpc.class) {
if ((getUpdateFeatureMethod = GkeHubGrpc.getUpdateFeatureMethod) == null) {
GkeHubGrpc.getUpdateFeatureMethod =
getUpdateFeatureMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest,
com.google.longrunning.Operation>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "UpdateFeature"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.longrunning.Operation.getDefaultInstance()))
.setSchemaDescriptor(new GkeHubMethodDescriptorSupplier("UpdateFeature"))
.build();
}
}
}
return getUpdateFeatureMethod;
}
/** Creates a new async stub that supports all call types for the service */
public static GkeHubStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<GkeHubStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<GkeHubStub>() {
@java.lang.Override
public GkeHubStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GkeHubStub(channel, callOptions);
}
};
return GkeHubStub.newStub(factory, channel);
}
/** Creates a new blocking-style stub that supports all types of calls on the service */
public static GkeHubBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<GkeHubBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<GkeHubBlockingV2Stub>() {
@java.lang.Override
public GkeHubBlockingV2Stub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GkeHubBlockingV2Stub(channel, callOptions);
}
};
return GkeHubBlockingV2Stub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static GkeHubBlockingStub newBlockingStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<GkeHubBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<GkeHubBlockingStub>() {
@java.lang.Override
public GkeHubBlockingStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GkeHubBlockingStub(channel, callOptions);
}
};
return GkeHubBlockingStub.newStub(factory, channel);
}
/** Creates a new ListenableFuture-style stub that supports unary calls on the service */
public static GkeHubFutureStub newFutureStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<GkeHubFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<GkeHubFutureStub>() {
@java.lang.Override
public GkeHubFutureStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GkeHubFutureStub(channel, callOptions);
}
};
return GkeHubFutureStub.newStub(factory, channel);
}
/**
*
*
* <pre>
* The GKE Hub service handles the registration of many Kubernetes clusters to
* Google Cloud, and the management of multi-cluster features over those
* clusters.
* The GKE Hub service operates on the following resources:
* * [Membership][google.cloud.gkehub.v1alpha.Membership]
* * [Feature][google.cloud.gkehub.v1alpha.Feature]
* GKE Hub is currently only available in the global region.
* **Membership management may be non-trivial:** it is recommended to use one
* of the Google-provided client libraries or tools where possible when working
* with Membership resources.
* </pre>
*/
public interface AsyncService {
/**
*
*
* <pre>
* Lists Features in a given project and location.
* </pre>
*/
default void listFeatures(
com.google.cloud.gkehub.v1alpha.ListFeaturesRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.gkehub.v1alpha.ListFeaturesResponse>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getListFeaturesMethod(), responseObserver);
}
/**
*
*
* <pre>
* Gets details of a single Feature.
* </pre>
*/
default void getFeature(
com.google.cloud.gkehub.v1alpha.GetFeatureRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.gkehub.v1alpha.Feature> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(getGetFeatureMethod(), responseObserver);
}
/**
*
*
* <pre>
* Adds a new Feature.
* </pre>
*/
default void createFeature(
com.google.cloud.gkehub.v1alpha.CreateFeatureRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getCreateFeatureMethod(), responseObserver);
}
/**
*
*
* <pre>
* Removes a Feature.
* </pre>
*/
default void deleteFeature(
com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getDeleteFeatureMethod(), responseObserver);
}
/**
*
*
* <pre>
* Updates an existing Feature.
* </pre>
*/
default void updateFeature(
com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getUpdateFeatureMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service GkeHub.
*
* <pre>
* The GKE Hub service handles the registration of many Kubernetes clusters to
* Google Cloud, and the management of multi-cluster features over those
* clusters.
* The GKE Hub service operates on the following resources:
* * [Membership][google.cloud.gkehub.v1alpha.Membership]
* * [Feature][google.cloud.gkehub.v1alpha.Feature]
* GKE Hub is currently only available in the global region.
* **Membership management may be non-trivial:** it is recommended to use one
* of the Google-provided client libraries or tools where possible when working
* with Membership resources.
* </pre>
*/
public abstract static class GkeHubImplBase implements io.grpc.BindableService, AsyncService {
@java.lang.Override
public final io.grpc.ServerServiceDefinition bindService() {
return GkeHubGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service GkeHub.
*
* <pre>
* The GKE Hub service handles the registration of many Kubernetes clusters to
* Google Cloud, and the management of multi-cluster features over those
* clusters.
* The GKE Hub service operates on the following resources:
* * [Membership][google.cloud.gkehub.v1alpha.Membership]
* * [Feature][google.cloud.gkehub.v1alpha.Feature]
* GKE Hub is currently only available in the global region.
* **Membership management may be non-trivial:** it is recommended to use one
* of the Google-provided client libraries or tools where possible when working
* with Membership resources.
* </pre>
*/
public static final class GkeHubStub extends io.grpc.stub.AbstractAsyncStub<GkeHubStub> {
private GkeHubStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected GkeHubStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GkeHubStub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists Features in a given project and location.
* </pre>
*/
public void listFeatures(
com.google.cloud.gkehub.v1alpha.ListFeaturesRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.gkehub.v1alpha.ListFeaturesResponse>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getListFeaturesMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Gets details of a single Feature.
* </pre>
*/
public void getFeature(
com.google.cloud.gkehub.v1alpha.GetFeatureRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.gkehub.v1alpha.Feature> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetFeatureMethod(), getCallOptions()), request, responseObserver);
}
/**
*
*
* <pre>
* Adds a new Feature.
* </pre>
*/
public void createFeature(
com.google.cloud.gkehub.v1alpha.CreateFeatureRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getCreateFeatureMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Removes a Feature.
* </pre>
*/
public void deleteFeature(
com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getDeleteFeatureMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Updates an existing Feature.
* </pre>
*/
public void updateFeature(
com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getUpdateFeatureMethod(), getCallOptions()),
request,
responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service GkeHub.
*
* <pre>
* The GKE Hub service handles the registration of many Kubernetes clusters to
* Google Cloud, and the management of multi-cluster features over those
* clusters.
* The GKE Hub service operates on the following resources:
* * [Membership][google.cloud.gkehub.v1alpha.Membership]
* * [Feature][google.cloud.gkehub.v1alpha.Feature]
* GKE Hub is currently only available in the global region.
* **Membership management may be non-trivial:** it is recommended to use one
* of the Google-provided client libraries or tools where possible when working
* with Membership resources.
* </pre>
*/
public static final class GkeHubBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<GkeHubBlockingV2Stub> {
private GkeHubBlockingV2Stub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected GkeHubBlockingV2Stub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GkeHubBlockingV2Stub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists Features in a given project and location.
* </pre>
*/
public com.google.cloud.gkehub.v1alpha.ListFeaturesResponse listFeatures(
com.google.cloud.gkehub.v1alpha.ListFeaturesRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListFeaturesMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Gets details of a single Feature.
* </pre>
*/
public com.google.cloud.gkehub.v1alpha.Feature getFeature(
com.google.cloud.gkehub.v1alpha.GetFeatureRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetFeatureMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Adds a new Feature.
* </pre>
*/
public com.google.longrunning.Operation createFeature(
com.google.cloud.gkehub.v1alpha.CreateFeatureRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCreateFeatureMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Removes a Feature.
* </pre>
*/
public com.google.longrunning.Operation deleteFeature(
com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeleteFeatureMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Updates an existing Feature.
* </pre>
*/
public com.google.longrunning.Operation updateFeature(
com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUpdateFeatureMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do limited synchronous rpc calls to service GkeHub.
*
* <pre>
* The GKE Hub service handles the registration of many Kubernetes clusters to
* Google Cloud, and the management of multi-cluster features over those
* clusters.
* The GKE Hub service operates on the following resources:
* * [Membership][google.cloud.gkehub.v1alpha.Membership]
* * [Feature][google.cloud.gkehub.v1alpha.Feature]
* GKE Hub is currently only available in the global region.
* **Membership management may be non-trivial:** it is recommended to use one
* of the Google-provided client libraries or tools where possible when working
* with Membership resources.
* </pre>
*/
public static final class GkeHubBlockingStub
extends io.grpc.stub.AbstractBlockingStub<GkeHubBlockingStub> {
private GkeHubBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected GkeHubBlockingStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GkeHubBlockingStub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists Features in a given project and location.
* </pre>
*/
public com.google.cloud.gkehub.v1alpha.ListFeaturesResponse listFeatures(
com.google.cloud.gkehub.v1alpha.ListFeaturesRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListFeaturesMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Gets details of a single Feature.
* </pre>
*/
public com.google.cloud.gkehub.v1alpha.Feature getFeature(
com.google.cloud.gkehub.v1alpha.GetFeatureRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetFeatureMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Adds a new Feature.
* </pre>
*/
public com.google.longrunning.Operation createFeature(
com.google.cloud.gkehub.v1alpha.CreateFeatureRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCreateFeatureMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Removes a Feature.
* </pre>
*/
public com.google.longrunning.Operation deleteFeature(
com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeleteFeatureMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Updates an existing Feature.
* </pre>
*/
public com.google.longrunning.Operation updateFeature(
com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUpdateFeatureMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service GkeHub.
*
* <pre>
* The GKE Hub service handles the registration of many Kubernetes clusters to
* Google Cloud, and the management of multi-cluster features over those
* clusters.
* The GKE Hub service operates on the following resources:
* * [Membership][google.cloud.gkehub.v1alpha.Membership]
* * [Feature][google.cloud.gkehub.v1alpha.Feature]
* GKE Hub is currently only available in the global region.
* **Membership management may be non-trivial:** it is recommended to use one
* of the Google-provided client libraries or tools where possible when working
* with Membership resources.
* </pre>
*/
public static final class GkeHubFutureStub
extends io.grpc.stub.AbstractFutureStub<GkeHubFutureStub> {
private GkeHubFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected GkeHubFutureStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new GkeHubFutureStub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists Features in a given project and location.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.gkehub.v1alpha.ListFeaturesResponse>
listFeatures(com.google.cloud.gkehub.v1alpha.ListFeaturesRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getListFeaturesMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Gets details of a single Feature.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.gkehub.v1alpha.Feature>
getFeature(com.google.cloud.gkehub.v1alpha.GetFeatureRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getGetFeatureMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Adds a new Feature.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation>
createFeature(com.google.cloud.gkehub.v1alpha.CreateFeatureRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getCreateFeatureMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Removes a Feature.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation>
deleteFeature(com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getDeleteFeatureMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Updates an existing Feature.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation>
updateFeature(com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUpdateFeatureMethod(), getCallOptions()), request);
}
}
private static final int METHODID_LIST_FEATURES = 0;
private static final int METHODID_GET_FEATURE = 1;
private static final int METHODID_CREATE_FEATURE = 2;
private static final int METHODID_DELETE_FEATURE = 3;
private static final int METHODID_UPDATE_FEATURE = 4;
private static final class MethodHandlers<Req, Resp>
implements io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AsyncService serviceImpl;
private final int methodId;
MethodHandlers(AsyncService serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_LIST_FEATURES:
serviceImpl.listFeatures(
(com.google.cloud.gkehub.v1alpha.ListFeaturesRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.gkehub.v1alpha.ListFeaturesResponse>)
responseObserver);
break;
case METHODID_GET_FEATURE:
serviceImpl.getFeature(
(com.google.cloud.gkehub.v1alpha.GetFeatureRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.gkehub.v1alpha.Feature>)
responseObserver);
break;
case METHODID_CREATE_FEATURE:
serviceImpl.createFeature(
(com.google.cloud.gkehub.v1alpha.CreateFeatureRequest) request,
(io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver);
break;
case METHODID_DELETE_FEATURE:
serviceImpl.deleteFeature(
(com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest) request,
(io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver);
break;
case METHODID_UPDATE_FEATURE:
serviceImpl.updateFeature(
(com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest) request,
(io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
}
public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getListFeaturesMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.gkehub.v1alpha.ListFeaturesRequest,
com.google.cloud.gkehub.v1alpha.ListFeaturesResponse>(
service, METHODID_LIST_FEATURES)))
.addMethod(
getGetFeatureMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.gkehub.v1alpha.GetFeatureRequest,
com.google.cloud.gkehub.v1alpha.Feature>(service, METHODID_GET_FEATURE)))
.addMethod(
getCreateFeatureMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.gkehub.v1alpha.CreateFeatureRequest,
com.google.longrunning.Operation>(service, METHODID_CREATE_FEATURE)))
.addMethod(
getDeleteFeatureMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.gkehub.v1alpha.DeleteFeatureRequest,
com.google.longrunning.Operation>(service, METHODID_DELETE_FEATURE)))
.addMethod(
getUpdateFeatureMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.gkehub.v1alpha.UpdateFeatureRequest,
com.google.longrunning.Operation>(service, METHODID_UPDATE_FEATURE)))
.build();
}
private abstract static class GkeHubBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier,
io.grpc.protobuf.ProtoServiceDescriptorSupplier {
GkeHubBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.google.cloud.gkehub.v1alpha.ServiceProto.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("GkeHub");
}
}
private static final class GkeHubFileDescriptorSupplier extends GkeHubBaseDescriptorSupplier {
GkeHubFileDescriptorSupplier() {}
}
private static final class GkeHubMethodDescriptorSupplier extends GkeHubBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final java.lang.String methodName;
GkeHubMethodDescriptorSupplier(java.lang.String methodName) {
this.methodName = methodName;
}
@java.lang.Override
public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() {
return getServiceDescriptor().findMethodByName(methodName);
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (GkeHubGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor =
result =
io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new GkeHubFileDescriptorSupplier())
.addMethod(getListFeaturesMethod())
.addMethod(getGetFeatureMethod())
.addMethod(getCreateFeatureMethod())
.addMethod(getDeleteFeatureMethod())
.addMethod(getUpdateFeatureMethod())
.build();
}
}
}
return result;
}
}
|
google/java-photoslibrary
| 38,417
|
photoslibraryapi/src/main/java/com/google/photos/library/v1/proto/BatchGetMediaItemsResponse.java
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/photos/library/v1/photos_library.proto
package com.google.photos.library.v1.proto;
/**
*
*
* <pre>
* Response to retrieve a list of media items.
* </pre>
*
* Protobuf type {@code google.photos.library.v1.BatchGetMediaItemsResponse}
*/
public final class BatchGetMediaItemsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.photos.library.v1.BatchGetMediaItemsResponse)
BatchGetMediaItemsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use BatchGetMediaItemsResponse.newBuilder() to construct.
private BatchGetMediaItemsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private BatchGetMediaItemsResponse() {
mediaItemResults_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new BatchGetMediaItemsResponse();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.photos.library.v1.proto.LibraryServiceProto
.internal_static_google_photos_library_v1_BatchGetMediaItemsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.photos.library.v1.proto.LibraryServiceProto
.internal_static_google_photos_library_v1_BatchGetMediaItemsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.photos.library.v1.proto.BatchGetMediaItemsResponse.class,
com.google.photos.library.v1.proto.BatchGetMediaItemsResponse.Builder.class);
}
public static final int MEDIA_ITEM_RESULTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.photos.library.v1.proto.MediaItemResult> mediaItemResults_;
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.photos.library.v1.proto.MediaItemResult>
getMediaItemResultsList() {
return mediaItemResults_;
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.photos.library.v1.proto.MediaItemResultOrBuilder>
getMediaItemResultsOrBuilderList() {
return mediaItemResults_;
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
@java.lang.Override
public int getMediaItemResultsCount() {
return mediaItemResults_.size();
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
@java.lang.Override
public com.google.photos.library.v1.proto.MediaItemResult getMediaItemResults(int index) {
return mediaItemResults_.get(index);
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
@java.lang.Override
public com.google.photos.library.v1.proto.MediaItemResultOrBuilder getMediaItemResultsOrBuilder(
int index) {
return mediaItemResults_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < mediaItemResults_.size(); i++) {
output.writeMessage(1, mediaItemResults_.get(i));
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < mediaItemResults_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, mediaItemResults_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.photos.library.v1.proto.BatchGetMediaItemsResponse)) {
return super.equals(obj);
}
com.google.photos.library.v1.proto.BatchGetMediaItemsResponse other =
(com.google.photos.library.v1.proto.BatchGetMediaItemsResponse) obj;
if (!getMediaItemResultsList().equals(other.getMediaItemResultsList())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getMediaItemResultsCount() > 0) {
hash = (37 * hash) + MEDIA_ITEM_RESULTS_FIELD_NUMBER;
hash = (53 * hash) + getMediaItemResultsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.photos.library.v1.proto.BatchGetMediaItemsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response to retrieve a list of media items.
* </pre>
*
* Protobuf type {@code google.photos.library.v1.BatchGetMediaItemsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.photos.library.v1.BatchGetMediaItemsResponse)
com.google.photos.library.v1.proto.BatchGetMediaItemsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.photos.library.v1.proto.LibraryServiceProto
.internal_static_google_photos_library_v1_BatchGetMediaItemsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.photos.library.v1.proto.LibraryServiceProto
.internal_static_google_photos_library_v1_BatchGetMediaItemsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.photos.library.v1.proto.BatchGetMediaItemsResponse.class,
com.google.photos.library.v1.proto.BatchGetMediaItemsResponse.Builder.class);
}
// Construct using com.google.photos.library.v1.proto.BatchGetMediaItemsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (mediaItemResultsBuilder_ == null) {
mediaItemResults_ = java.util.Collections.emptyList();
} else {
mediaItemResults_ = null;
mediaItemResultsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.photos.library.v1.proto.LibraryServiceProto
.internal_static_google_photos_library_v1_BatchGetMediaItemsResponse_descriptor;
}
@java.lang.Override
public com.google.photos.library.v1.proto.BatchGetMediaItemsResponse
getDefaultInstanceForType() {
return com.google.photos.library.v1.proto.BatchGetMediaItemsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.photos.library.v1.proto.BatchGetMediaItemsResponse build() {
com.google.photos.library.v1.proto.BatchGetMediaItemsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.photos.library.v1.proto.BatchGetMediaItemsResponse buildPartial() {
com.google.photos.library.v1.proto.BatchGetMediaItemsResponse result =
new com.google.photos.library.v1.proto.BatchGetMediaItemsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.photos.library.v1.proto.BatchGetMediaItemsResponse result) {
if (mediaItemResultsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
mediaItemResults_ = java.util.Collections.unmodifiableList(mediaItemResults_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.mediaItemResults_ = mediaItemResults_;
} else {
result.mediaItemResults_ = mediaItemResultsBuilder_.build();
}
}
private void buildPartial0(
com.google.photos.library.v1.proto.BatchGetMediaItemsResponse result) {
int from_bitField0_ = bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.photos.library.v1.proto.BatchGetMediaItemsResponse) {
return mergeFrom((com.google.photos.library.v1.proto.BatchGetMediaItemsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.photos.library.v1.proto.BatchGetMediaItemsResponse other) {
if (other
== com.google.photos.library.v1.proto.BatchGetMediaItemsResponse.getDefaultInstance())
return this;
if (mediaItemResultsBuilder_ == null) {
if (!other.mediaItemResults_.isEmpty()) {
if (mediaItemResults_.isEmpty()) {
mediaItemResults_ = other.mediaItemResults_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureMediaItemResultsIsMutable();
mediaItemResults_.addAll(other.mediaItemResults_);
}
onChanged();
}
} else {
if (!other.mediaItemResults_.isEmpty()) {
if (mediaItemResultsBuilder_.isEmpty()) {
mediaItemResultsBuilder_.dispose();
mediaItemResultsBuilder_ = null;
mediaItemResults_ = other.mediaItemResults_;
bitField0_ = (bitField0_ & ~0x00000001);
mediaItemResultsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getMediaItemResultsFieldBuilder()
: null;
} else {
mediaItemResultsBuilder_.addAllMessages(other.mediaItemResults_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.photos.library.v1.proto.MediaItemResult m =
input.readMessage(
com.google.photos.library.v1.proto.MediaItemResult.parser(),
extensionRegistry);
if (mediaItemResultsBuilder_ == null) {
ensureMediaItemResultsIsMutable();
mediaItemResults_.add(m);
} else {
mediaItemResultsBuilder_.addMessage(m);
}
break;
} // case 10
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.photos.library.v1.proto.MediaItemResult> mediaItemResults_ =
java.util.Collections.emptyList();
private void ensureMediaItemResultsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
mediaItemResults_ =
new java.util.ArrayList<com.google.photos.library.v1.proto.MediaItemResult>(
mediaItemResults_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.photos.library.v1.proto.MediaItemResult,
com.google.photos.library.v1.proto.MediaItemResult.Builder,
com.google.photos.library.v1.proto.MediaItemResultOrBuilder>
mediaItemResultsBuilder_;
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public java.util.List<com.google.photos.library.v1.proto.MediaItemResult>
getMediaItemResultsList() {
if (mediaItemResultsBuilder_ == null) {
return java.util.Collections.unmodifiableList(mediaItemResults_);
} else {
return mediaItemResultsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public int getMediaItemResultsCount() {
if (mediaItemResultsBuilder_ == null) {
return mediaItemResults_.size();
} else {
return mediaItemResultsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public com.google.photos.library.v1.proto.MediaItemResult getMediaItemResults(int index) {
if (mediaItemResultsBuilder_ == null) {
return mediaItemResults_.get(index);
} else {
return mediaItemResultsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public Builder setMediaItemResults(
int index, com.google.photos.library.v1.proto.MediaItemResult value) {
if (mediaItemResultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMediaItemResultsIsMutable();
mediaItemResults_.set(index, value);
onChanged();
} else {
mediaItemResultsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public Builder setMediaItemResults(
int index, com.google.photos.library.v1.proto.MediaItemResult.Builder builderForValue) {
if (mediaItemResultsBuilder_ == null) {
ensureMediaItemResultsIsMutable();
mediaItemResults_.set(index, builderForValue.build());
onChanged();
} else {
mediaItemResultsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public Builder addMediaItemResults(com.google.photos.library.v1.proto.MediaItemResult value) {
if (mediaItemResultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMediaItemResultsIsMutable();
mediaItemResults_.add(value);
onChanged();
} else {
mediaItemResultsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public Builder addMediaItemResults(
int index, com.google.photos.library.v1.proto.MediaItemResult value) {
if (mediaItemResultsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMediaItemResultsIsMutable();
mediaItemResults_.add(index, value);
onChanged();
} else {
mediaItemResultsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public Builder addMediaItemResults(
com.google.photos.library.v1.proto.MediaItemResult.Builder builderForValue) {
if (mediaItemResultsBuilder_ == null) {
ensureMediaItemResultsIsMutable();
mediaItemResults_.add(builderForValue.build());
onChanged();
} else {
mediaItemResultsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public Builder addMediaItemResults(
int index, com.google.photos.library.v1.proto.MediaItemResult.Builder builderForValue) {
if (mediaItemResultsBuilder_ == null) {
ensureMediaItemResultsIsMutable();
mediaItemResults_.add(index, builderForValue.build());
onChanged();
} else {
mediaItemResultsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public Builder addAllMediaItemResults(
java.lang.Iterable<? extends com.google.photos.library.v1.proto.MediaItemResult> values) {
if (mediaItemResultsBuilder_ == null) {
ensureMediaItemResultsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, mediaItemResults_);
onChanged();
} else {
mediaItemResultsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public Builder clearMediaItemResults() {
if (mediaItemResultsBuilder_ == null) {
mediaItemResults_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
mediaItemResultsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public Builder removeMediaItemResults(int index) {
if (mediaItemResultsBuilder_ == null) {
ensureMediaItemResultsIsMutable();
mediaItemResults_.remove(index);
onChanged();
} else {
mediaItemResultsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public com.google.photos.library.v1.proto.MediaItemResult.Builder getMediaItemResultsBuilder(
int index) {
return getMediaItemResultsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public com.google.photos.library.v1.proto.MediaItemResultOrBuilder getMediaItemResultsOrBuilder(
int index) {
if (mediaItemResultsBuilder_ == null) {
return mediaItemResults_.get(index);
} else {
return mediaItemResultsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public java.util.List<? extends com.google.photos.library.v1.proto.MediaItemResultOrBuilder>
getMediaItemResultsOrBuilderList() {
if (mediaItemResultsBuilder_ != null) {
return mediaItemResultsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(mediaItemResults_);
}
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public com.google.photos.library.v1.proto.MediaItemResult.Builder addMediaItemResultsBuilder() {
return getMediaItemResultsFieldBuilder()
.addBuilder(com.google.photos.library.v1.proto.MediaItemResult.getDefaultInstance());
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public com.google.photos.library.v1.proto.MediaItemResult.Builder addMediaItemResultsBuilder(
int index) {
return getMediaItemResultsFieldBuilder()
.addBuilder(
index, com.google.photos.library.v1.proto.MediaItemResult.getDefaultInstance());
}
/**
*
*
* <pre>
* Output only. List of media items retrieved.
* Note that even if the call to BatchGetMediaItems succeeds, there may have
* been failures for some media items in the batch. These failures are
* indicated in each
* [MediaItemResult.status][google.photos.library.v1.MediaItemResult.status].
* </pre>
*
* <code>repeated .google.photos.library.v1.MediaItemResult media_item_results = 1;</code>
*/
public java.util.List<com.google.photos.library.v1.proto.MediaItemResult.Builder>
getMediaItemResultsBuilderList() {
return getMediaItemResultsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.photos.library.v1.proto.MediaItemResult,
com.google.photos.library.v1.proto.MediaItemResult.Builder,
com.google.photos.library.v1.proto.MediaItemResultOrBuilder>
getMediaItemResultsFieldBuilder() {
if (mediaItemResultsBuilder_ == null) {
mediaItemResultsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.photos.library.v1.proto.MediaItemResult,
com.google.photos.library.v1.proto.MediaItemResult.Builder,
com.google.photos.library.v1.proto.MediaItemResultOrBuilder>(
mediaItemResults_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
mediaItemResults_ = null;
}
return mediaItemResultsBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.photos.library.v1.BatchGetMediaItemsResponse)
}
// @@protoc_insertion_point(class_scope:google.photos.library.v1.BatchGetMediaItemsResponse)
private static final com.google.photos.library.v1.proto.BatchGetMediaItemsResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.photos.library.v1.proto.BatchGetMediaItemsResponse();
}
public static com.google.photos.library.v1.proto.BatchGetMediaItemsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<BatchGetMediaItemsResponse> PARSER =
new com.google.protobuf.AbstractParser<BatchGetMediaItemsResponse>() {
@java.lang.Override
public BatchGetMediaItemsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<BatchGetMediaItemsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<BatchGetMediaItemsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.photos.library.v1.proto.BatchGetMediaItemsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,087
|
java-artifact-registry/proto-google-cloud-artifact-registry-v1beta2/src/main/java/com/google/devtools/artifactregistry/v1beta2/ListVersionsRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/devtools/artifactregistry/v1beta2/version.proto
// Protobuf Java Version: 3.25.8
package com.google.devtools.artifactregistry.v1beta2;
/**
*
*
* <pre>
* The request to list versions.
* </pre>
*
* Protobuf type {@code google.devtools.artifactregistry.v1beta2.ListVersionsRequest}
*/
public final class ListVersionsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.devtools.artifactregistry.v1beta2.ListVersionsRequest)
ListVersionsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListVersionsRequest.newBuilder() to construct.
private ListVersionsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListVersionsRequest() {
parent_ = "";
pageToken_ = "";
view_ = 0;
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListVersionsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.devtools.artifactregistry.v1beta2.VersionProto
.internal_static_google_devtools_artifactregistry_v1beta2_ListVersionsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.devtools.artifactregistry.v1beta2.VersionProto
.internal_static_google_devtools_artifactregistry_v1beta2_ListVersionsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest.class,
com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* The name of the parent resource whose versions will be listed.
* </pre>
*
* <code>string parent = 1;</code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* The name of the parent resource whose versions will be listed.
* </pre>
*
* <code>string parent = 1;</code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* The maximum number of versions to return. Maximum page size is 1,000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request, if any.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request, if any.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VIEW_FIELD_NUMBER = 4;
private int view_ = 0;
/**
*
*
* <pre>
* The view that should be returned in the response.
* </pre>
*
* <code>.google.devtools.artifactregistry.v1beta2.VersionView view = 4;</code>
*
* @return The enum numeric value on the wire for view.
*/
@java.lang.Override
public int getViewValue() {
return view_;
}
/**
*
*
* <pre>
* The view that should be returned in the response.
* </pre>
*
* <code>.google.devtools.artifactregistry.v1beta2.VersionView view = 4;</code>
*
* @return The view.
*/
@java.lang.Override
public com.google.devtools.artifactregistry.v1beta2.VersionView getView() {
com.google.devtools.artifactregistry.v1beta2.VersionView result =
com.google.devtools.artifactregistry.v1beta2.VersionView.forNumber(view_);
return result == null
? com.google.devtools.artifactregistry.v1beta2.VersionView.UNRECOGNIZED
: result;
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Optional. The field to order the results by.
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The field to order the results by.
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (view_
!= com.google.devtools.artifactregistry.v1beta2.VersionView.VERSION_VIEW_UNSPECIFIED
.getNumber()) {
output.writeEnum(4, view_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (view_
!= com.google.devtools.artifactregistry.v1beta2.VersionView.VERSION_VIEW_UNSPECIFIED
.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(4, view_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest)) {
return super.equals(obj);
}
com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest other =
(com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (view_ != other.view_) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + VIEW_FIELD_NUMBER;
hash = (53 * hash) + view_;
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The request to list versions.
* </pre>
*
* Protobuf type {@code google.devtools.artifactregistry.v1beta2.ListVersionsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.devtools.artifactregistry.v1beta2.ListVersionsRequest)
com.google.devtools.artifactregistry.v1beta2.ListVersionsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.devtools.artifactregistry.v1beta2.VersionProto
.internal_static_google_devtools_artifactregistry_v1beta2_ListVersionsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.devtools.artifactregistry.v1beta2.VersionProto
.internal_static_google_devtools_artifactregistry_v1beta2_ListVersionsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest.class,
com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest.Builder.class);
}
// Construct using com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
view_ = 0;
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.devtools.artifactregistry.v1beta2.VersionProto
.internal_static_google_devtools_artifactregistry_v1beta2_ListVersionsRequest_descriptor;
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest
getDefaultInstanceForType() {
return com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest build() {
com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest buildPartial() {
com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest result =
new com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.view_ = view_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest) {
return mergeFrom((com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest other) {
if (other
== com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (other.view_ != 0) {
setViewValue(other.getViewValue());
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 32:
{
view_ = input.readEnum();
bitField0_ |= 0x00000008;
break;
} // case 32
case 42:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* The name of the parent resource whose versions will be listed.
* </pre>
*
* <code>string parent = 1;</code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The name of the parent resource whose versions will be listed.
* </pre>
*
* <code>string parent = 1;</code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The name of the parent resource whose versions will be listed.
* </pre>
*
* <code>string parent = 1;</code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the parent resource whose versions will be listed.
* </pre>
*
* <code>string parent = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the parent resource whose versions will be listed.
* </pre>
*
* <code>string parent = 1;</code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of versions to return. Maximum page size is 1,000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The maximum number of versions to return. Maximum page size is 1,000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The maximum number of versions to return. Maximum page size is 1,000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request, if any.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request, if any.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request, if any.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request, if any.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* The next_page_token value returned from a previous list request, if any.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private int view_ = 0;
/**
*
*
* <pre>
* The view that should be returned in the response.
* </pre>
*
* <code>.google.devtools.artifactregistry.v1beta2.VersionView view = 4;</code>
*
* @return The enum numeric value on the wire for view.
*/
@java.lang.Override
public int getViewValue() {
return view_;
}
/**
*
*
* <pre>
* The view that should be returned in the response.
* </pre>
*
* <code>.google.devtools.artifactregistry.v1beta2.VersionView view = 4;</code>
*
* @param value The enum numeric value on the wire for view to set.
* @return This builder for chaining.
*/
public Builder setViewValue(int value) {
view_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* The view that should be returned in the response.
* </pre>
*
* <code>.google.devtools.artifactregistry.v1beta2.VersionView view = 4;</code>
*
* @return The view.
*/
@java.lang.Override
public com.google.devtools.artifactregistry.v1beta2.VersionView getView() {
com.google.devtools.artifactregistry.v1beta2.VersionView result =
com.google.devtools.artifactregistry.v1beta2.VersionView.forNumber(view_);
return result == null
? com.google.devtools.artifactregistry.v1beta2.VersionView.UNRECOGNIZED
: result;
}
/**
*
*
* <pre>
* The view that should be returned in the response.
* </pre>
*
* <code>.google.devtools.artifactregistry.v1beta2.VersionView view = 4;</code>
*
* @param value The view to set.
* @return This builder for chaining.
*/
public Builder setView(com.google.devtools.artifactregistry.v1beta2.VersionView value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
view_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* The view that should be returned in the response.
* </pre>
*
* <code>.google.devtools.artifactregistry.v1beta2.VersionView view = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearView() {
bitField0_ = (bitField0_ & ~0x00000008);
view_ = 0;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Optional. The field to order the results by.
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The field to order the results by.
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The field to order the results by.
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The field to order the results by.
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The field to order the results by.
* </pre>
*
* <code>string order_by = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.devtools.artifactregistry.v1beta2.ListVersionsRequest)
}
// @@protoc_insertion_point(class_scope:google.devtools.artifactregistry.v1beta2.ListVersionsRequest)
private static final com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest();
}
public static com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListVersionsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListVersionsRequest>() {
@java.lang.Override
public ListVersionsRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListVersionsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListVersionsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1beta2.ListVersionsRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
oracle/graal
| 38,647
|
espresso/src/com.oracle.truffle.espresso/src/com/oracle/truffle/espresso/substitutions/standard/Target_java_lang_reflect_Array.java
|
/*
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.espresso.substitutions.standard;
import java.lang.reflect.Array;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.interop.InteropLibrary;
import com.oracle.truffle.api.interop.InvalidArrayIndexException;
import com.oracle.truffle.api.interop.UnsupportedMessageException;
import com.oracle.truffle.api.interop.UnsupportedTypeException;
import com.oracle.truffle.espresso.EspressoLanguage;
import com.oracle.truffle.espresso.classfile.descriptors.TypeSymbols;
import com.oracle.truffle.espresso.impl.ArrayKlass;
import com.oracle.truffle.espresso.impl.Klass;
import com.oracle.truffle.espresso.meta.EspressoError;
import com.oracle.truffle.espresso.meta.Meta;
import com.oracle.truffle.espresso.runtime.EspressoException;
import com.oracle.truffle.espresso.runtime.GuestAllocator.AllocationChecks;
import com.oracle.truffle.espresso.runtime.staticobject.StaticObject;
import com.oracle.truffle.espresso.substitutions.EspressoSubstitutions;
import com.oracle.truffle.espresso.substitutions.Inject;
import com.oracle.truffle.espresso.substitutions.JavaType;
import com.oracle.truffle.espresso.substitutions.Substitution;
import com.oracle.truffle.espresso.substitutions.SubstitutionProfiler;
import com.oracle.truffle.espresso.substitutions.Throws;
import com.oracle.truffle.espresso.vm.InterpreterToVM;
import com.oracle.truffle.espresso.vm.VM;
@EspressoSubstitutions
public final class Target_java_lang_reflect_Array {
/**
* Creates a new array with the specified component type and length. Invoking this method is
* equivalent to creating an array as follows: <blockquote>
*
* <pre>
* int[] x = {length};
* Array.newInstance(componentType, x);
* </pre>
*
* </blockquote>
*
* <p>
* The number of dimensions of the new array must not exceed 255.
*
* @param componentType the {@code Class} object representing the component type of the new
* array
* @param length the length of the new array
* @return the new array
* @exception NullPointerException if the specified {@code componentType} parameter is null
* @exception IllegalArgumentException if componentType is {@link Void#TYPE} or if the number of
* dimensions of the requested array instance exceed 255.
* @exception NegativeArraySizeException if the specified {@code length} is negative
*/
@Substitution
public static @JavaType(Object.class) StaticObject newArray(@JavaType(Class.class) StaticObject componentType, int length, @Inject Meta meta) {
if (CompilerDirectives.isPartialEvaluationConstant(componentType)) {
// PE-through.
return newArrayImpl(componentType, length, meta);
}
return newArrayBoundary(componentType, length, meta);
}
@TruffleBoundary(allowInlining = true)
static StaticObject newArrayBoundary(@JavaType(Class.class) StaticObject componentType, int length, @Inject Meta meta) {
return newArrayImpl(componentType, length, meta);
}
static StaticObject newArrayImpl(@JavaType(Class.class) StaticObject componentType, int length, @Inject Meta meta) {
if (StaticObject.isNull(componentType)) {
throw meta.throwNullPointerException();
}
Klass component = componentType.getMirrorKlass(meta);
if (component == meta._void || TypeSymbols.getArrayDimensions(component.getType()) >= 255) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
}
AllocationChecks.checkCanAllocateArray(meta, length);
if (component.isPrimitive()) {
return meta.getAllocator().createNewPrimitiveArray(component, length);
}
return meta.getAllocator().createNewReferenceArray(component, length);
}
/**
* Creates a new array with the specified component type and dimensions. If
* {@code componentType} represents a non-array class or interface, the new array has
* {@code dimensions.length} dimensions and {@code componentType} as its component type. If
* {@code componentType} represents an array class, the number of dimensions of the new array is
* equal to the sum of {@code dimensions.length} and the number of dimensions of
* {@code componentType}. In this case, the component type of the new array is the component
* type of {@code componentType}.
*
* <p>
* The number of dimensions of the new array must not exceed 255.
*
* @param componentType the {@code Class} object representing the component type of the new
* array
* @param dimensionsArray an array of {@code int} representing the dimensions of the new array
* @return the new array
* @exception NullPointerException if the specified {@code componentType} argument is null
* @exception IllegalArgumentException if the specified {@code dimensions} argument is a
* zero-dimensional array, if componentType is {@link Void#TYPE}, or if the
* number of dimensions of the requested array instance exceed 255.
* @exception NegativeArraySizeException if any of the components in the specified
* {@code dimensions} argument is negative.
*/
@TruffleBoundary
@Substitution
public static @JavaType(Object.class) StaticObject multiNewArray(@JavaType(Class.class) StaticObject componentType, @JavaType(int[].class) StaticObject dimensionsArray,
@Inject EspressoLanguage language,
@Inject Meta meta) {
if (StaticObject.isNull(componentType) || StaticObject.isNull(dimensionsArray)) {
throw meta.throwNullPointerException();
}
Klass component = componentType.getMirrorKlass(meta);
if (component == meta._void || StaticObject.isNull(dimensionsArray)) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
}
final int[] dimensions = dimensionsArray.unwrap(language);
int finalDimensions = dimensions.length;
if (component.isArray()) {
finalDimensions += TypeSymbols.getArrayDimensions(component.getType());
}
if (dimensions.length == 0 || finalDimensions > 255) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
}
AllocationChecks.checkCanAllocateMultiArray(meta, component, dimensions);
if (dimensions.length == 1) {
return meta.getAllocator().createNewMultiArray(component, dimensions);
}
return meta.getAllocator().createNewMultiArray(component.getArrayKlass(dimensions.length - 1), dimensions);
}
@Substitution
public static boolean getBoolean(@JavaType(Object.class) StaticObject array, int index,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
if (StaticObject.isNull(array)) {
profiler.profile(0);
throw meta.throwNullPointerException();
}
// `getBoolean` should only access boolean arrays
Klass arrayKlass = array.getKlass();
if (arrayKlass != meta._boolean_array) {
profiler.profile(1);
throw meta.throwException(meta.java_lang_IllegalArgumentException);
}
if (array.isForeignObject()) {
try {
InteropLibrary library = InteropLibrary.getUncached();
return library.asBoolean(library.readArrayElement(array.rawForeignObject(language), index));
} catch (UnsupportedMessageException e) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} catch (InvalidArrayIndexException e) {
throw meta.throwException(meta.java_lang_ArrayIndexOutOfBoundsException);
}
} else {
try {
return Array.getByte(array.unwrap(language), index) != 0;
} catch (ArrayIndexOutOfBoundsException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static byte getByte(@JavaType(Object.class) StaticObject array, int index,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
try {
InteropLibrary library = InteropLibrary.getUncached();
return library.asByte(library.readArrayElement(array.rawForeignObject(language), index));
} catch (UnsupportedMessageException e) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} catch (InvalidArrayIndexException e) {
throw meta.throwException(meta.java_lang_ArrayIndexOutOfBoundsException);
}
} else {
try {
return Array.getByte(array.unwrap(language), index);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static char getChar(@JavaType(Object.class) StaticObject array, int index,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
try {
InteropLibrary library = InteropLibrary.getUncached();
String str = library.asString(library.readArrayElement(array.rawForeignObject(language), index));
if (str.isEmpty()) {
return '\u0000';
} else if (str.length() > 1) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} else {
return str.charAt(0);
}
} catch (UnsupportedMessageException e) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} catch (InvalidArrayIndexException e) {
throw meta.throwException(meta.java_lang_ArrayIndexOutOfBoundsException);
}
} else {
try {
return Array.getChar(array.unwrap(language), index);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static short getShort(@JavaType(Object.class) StaticObject array, int index,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
try {
InteropLibrary library = InteropLibrary.getUncached();
return library.asShort(library.readArrayElement(array.rawForeignObject(language), index));
} catch (UnsupportedMessageException e) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} catch (InvalidArrayIndexException e) {
throw meta.throwException(meta.java_lang_ArrayIndexOutOfBoundsException);
}
} else {
try {
return Array.getShort(array.unwrap(language), index);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static int getInt(@JavaType(Object.class) StaticObject array, int index,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
try {
InteropLibrary library = InteropLibrary.getUncached();
return library.asInt(library.readArrayElement(array.rawForeignObject(language), index));
} catch (UnsupportedMessageException e) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} catch (InvalidArrayIndexException e) {
throw meta.throwException(meta.java_lang_ArrayIndexOutOfBoundsException);
}
} else {
try {
return Array.getInt(array.unwrap(language), index);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static float getFloat(@JavaType(Object.class) StaticObject array, int index,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
try {
InteropLibrary library = InteropLibrary.getUncached();
return library.asFloat(library.readArrayElement(array.rawForeignObject(language), index));
} catch (UnsupportedMessageException e) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} catch (InvalidArrayIndexException e) {
throw meta.throwException(meta.java_lang_ArrayIndexOutOfBoundsException);
}
} else {
try {
return Array.getFloat(array.unwrap(language), index);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static double getDouble(@JavaType(Object.class) StaticObject array, int index,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
try {
InteropLibrary library = InteropLibrary.getUncached();
return library.asDouble(library.readArrayElement(array.rawForeignObject(language), index));
} catch (UnsupportedMessageException e) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} catch (InvalidArrayIndexException e) {
throw meta.throwException(meta.java_lang_ArrayIndexOutOfBoundsException);
}
} else {
try {
return Array.getDouble(array.unwrap(language), index);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static long getLong(@JavaType(Object.class) StaticObject array, int index,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
try {
InteropLibrary library = InteropLibrary.getUncached();
return library.asLong(library.readArrayElement(array.rawForeignObject(language), index));
} catch (UnsupportedMessageException e) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} catch (InvalidArrayIndexException e) {
throw meta.throwException(meta.java_lang_ArrayIndexOutOfBoundsException);
}
} else {
try {
return Array.getLong(array.unwrap(language), index);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
private static EspressoException rethrowAsGuestException(RuntimeException e, Meta meta, SubstitutionProfiler profiler) {
assert e instanceof NullPointerException || e instanceof ArrayIndexOutOfBoundsException || e instanceof IllegalArgumentException;
if (e instanceof NullPointerException) {
profiler.profile(2);
throw meta.throwNullPointerException();
}
if (e instanceof ArrayIndexOutOfBoundsException) {
profiler.profile(3);
throw meta.throwExceptionWithMessage(meta.java_lang_ArrayIndexOutOfBoundsException, e.getMessage());
}
if (e instanceof IllegalArgumentException) {
profiler.profile(4);
throw meta.throwExceptionWithMessage(meta.java_lang_IllegalArgumentException, getMessageBoundary(e));
}
CompilerDirectives.transferToInterpreterAndInvalidate();
throw EspressoError.shouldNotReachHere(e);
}
@TruffleBoundary
// Some Subclasses of IllegalArgumentException use String concatenation.
private static String getMessageBoundary(RuntimeException e) {
return e.getMessage();
}
private static void checkNonNullArray(StaticObject array, Meta meta, SubstitutionProfiler profiler) {
if (StaticObject.isNull(array)) {
profiler.profile(0);
throw meta.throwNullPointerException();
}
if (!(array.isArray())) {
profiler.profile(1);
throw meta.throwException(meta.java_lang_IllegalArgumentException);
}
}
@Substitution
public static void setBoolean(@JavaType(Object.class) StaticObject array, int index, boolean value,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
if (StaticObject.isNull(array)) {
profiler.profile(0);
throw meta.throwNullPointerException();
}
// host `setByte` can write in all primitive arrays beside boolean array
// `setBoolean` should only access boolean arrays
Klass arrayKlass = array.getKlass();
if (arrayKlass != meta._boolean_array) {
profiler.profile(1);
throw meta.throwException(meta.java_lang_IllegalArgumentException);
}
if (array.isForeignObject()) {
writeForeignArrayElement(array, language, index, value, meta);
} else {
try {
Array.setByte(array.unwrap(language), index, value ? (byte) 1 : (byte) 0);
} catch (ArrayIndexOutOfBoundsException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static void setByte(@JavaType(Object.class) StaticObject array, int index, byte value,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
writeForeignArrayElement(array, language, index, value, meta);
} else {
try {
Array.setByte(array.unwrap(language), index, value);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static void setChar(@JavaType(Object.class) StaticObject array, int index, char value,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
writeForeignArrayElement(array, language, index, value, meta);
} else {
try {
Array.setChar(array.unwrap(language), index, value);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static void setShort(@JavaType(Object.class) StaticObject array, int index, short value,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
writeForeignArrayElement(array, language, index, value, meta);
} else {
try {
Array.setShort(array.unwrap(language), index, value);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static void setInt(@JavaType(Object.class) StaticObject array, int index, int value,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
writeForeignArrayElement(array, language, index, value, meta);
} else {
try {
Array.setInt(array.unwrap(language), index, value);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static void setFloat(@JavaType(Object.class) StaticObject array, int index, float value,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
writeForeignArrayElement(array, language, index, value, meta);
} else {
try {
Array.setFloat(array.unwrap(language), index, value);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static void setDouble(@JavaType(Object.class) StaticObject array, int index, double value,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
writeForeignArrayElement(array, language, index, value, meta);
} else {
try {
Array.setDouble(array.unwrap(language), index, value);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
@Substitution
public static void setLong(@JavaType(Object.class) StaticObject array, int index, long value,
@Inject EspressoLanguage language,
@Inject Meta meta,
@Inject SubstitutionProfiler profiler) {
checkNonNullArray(array, meta, profiler);
if (array.isForeignObject()) {
writeForeignArrayElement(array, language, index, value, meta);
} else {
try {
Array.setLong(array.unwrap(language), index, value);
} catch (NullPointerException | ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
profiler.profile(5);
throw rethrowAsGuestException(e, meta, profiler);
}
}
}
private static void writeForeignArrayElement(StaticObject array, EspressoLanguage language, int index, Object value, Meta meta) {
try {
InteropLibrary library = InteropLibrary.getUncached();
library.writeArrayElement(array.rawForeignObject(language), index, value);
} catch (UnsupportedMessageException | UnsupportedTypeException e) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} catch (InvalidArrayIndexException e) {
throw meta.throwException(meta.java_lang_ArrayIndexOutOfBoundsException);
}
}
/**
* Sets the value of the indexed component of the specified array object to the specified new
* value. The new value is first automatically unwrapped if the array has a primitive component
* type.
*
* @param array the array
* @param index the index into the array
* @param value the new value of the indexed component
* @exception NullPointerException If the specified object argument is null
* @exception IllegalArgumentException If the specified object argument is not an array, or if
* the array component type is primitive and an unwrapping conversion fails
* @exception ArrayIndexOutOfBoundsException If the specified {@code index} argument is
* negative, or if it is greater than or equal to the length of the specified
* array
*/
@Substitution
public static void set(@JavaType(Object.class) StaticObject array, int index, @JavaType(Object.class) StaticObject value,
@Inject EspressoLanguage language,
@Inject Meta meta) {
InterpreterToVM vm = meta.getInterpreterToVM();
if (StaticObject.isNull(array)) {
throw meta.throwNullPointerException();
}
if (array.isArray()) {
Object widenValue = Target_sun_reflect_NativeMethodAccessorImpl.checkAndWiden(meta, value, ((ArrayKlass) array.getKlass()).getComponentType());
if (array.isForeignObject()) {
try {
InteropLibrary library = InteropLibrary.getUncached();
library.writeArrayElement(array.rawForeignObject(language), index, widenValue);
return;
} catch (UnsupportedMessageException | UnsupportedTypeException e) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} catch (InvalidArrayIndexException e) {
throw meta.throwException(meta.java_lang_ArrayIndexOutOfBoundsException);
}
}
// @formatter:off
switch (((ArrayKlass) array.getKlass()).getComponentType().getJavaKind()) {
case Boolean : vm.setArrayByte(language, ((boolean) widenValue) ? (byte) 1 : (byte) 0, index, array); break;
case Byte : vm.setArrayByte(language, ((byte) widenValue), index, array); break;
case Short : vm.setArrayShort(language, ((short) widenValue), index, array); break;
case Char : vm.setArrayChar(language, ((char) widenValue), index, array); break;
case Int : vm.setArrayInt(language, ((int) widenValue), index, array); break;
case Float : vm.setArrayFloat(language, ((float) widenValue), index, array); break;
case Long : vm.setArrayLong(language, ((long) widenValue), index, array); break;
case Double : vm.setArrayDouble(language, ((double) widenValue), index, array); break;
case Object : vm.setArrayObject(language, value, index, array); break;
default :
CompilerDirectives.transferToInterpreter();
throw EspressoError.shouldNotReachHere("invalid array type: " + array);
}
// @formatter:on
} else {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
}
}
/**
* Returns the value of the indexed component in the specified array object. The value is
* automatically wrapped in an object if it has a primitive type.
*
* @param array the array
* @param index the index
* @return the (possibly wrapped) value of the indexed component in the specified array
* @exception NullPointerException If the specified object is null
* @exception IllegalArgumentException If the specified object is not an array
* @exception ArrayIndexOutOfBoundsException If the specified {@code index} argument is
* negative, or if it is greater than or equal to the length of the specified
* array
*/
@Substitution
public static @JavaType(Object.class) StaticObject get(@JavaType(Object.class) StaticObject array, int index,
@Inject EspressoLanguage language,
@Inject Meta meta) {
InterpreterToVM vm = meta.getInterpreterToVM();
if (StaticObject.isNull(array)) {
throw meta.throwNullPointerException();
}
if (array.isArray()) {
try {
switch (((ArrayKlass) array.getKlass()).getComponentType().getJavaKind()) {
case Boolean: {
boolean result;
if (array.isForeignObject()) {
InteropLibrary library = InteropLibrary.getUncached();
result = library.asBoolean(library.readArrayElement(array.rawForeignObject(language), index));
} else {
result = vm.getArrayByte(language, index, array) != 0;
}
return meta.boxBoolean(result);
}
case Byte: {
byte result;
if (array.isForeignObject()) {
InteropLibrary library = InteropLibrary.getUncached();
result = library.asByte(library.readArrayElement(array.rawForeignObject(language), index));
} else {
result = vm.getArrayByte(language, index, array);
}
return meta.boxByte(result);
}
case Short: {
short result;
if (array.isForeignObject()) {
InteropLibrary library = InteropLibrary.getUncached();
result = library.asShort(library.readArrayElement(array.rawForeignObject(language), index));
} else {
result = vm.getArrayShort(language, index, array);
}
return meta.boxShort(result);
}
case Char: {
char result;
if (array.isForeignObject()) {
InteropLibrary library = InteropLibrary.getUncached();
String str = library.asString(library.readArrayElement(array.rawForeignObject(language), index));
if (str.isEmpty()) {
result = '\u0000';
} else if (str.length() > 1) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} else {
result = str.charAt(0);
}
} else {
result = vm.getArrayChar(language, index, array);
}
return meta.boxCharacter(result);
}
case Int: {
int result;
if (array.isForeignObject()) {
InteropLibrary library = InteropLibrary.getUncached();
result = library.asInt(library.readArrayElement(array.rawForeignObject(language), index));
} else {
result = vm.getArrayInt(language, index, array);
}
return meta.boxInteger(result);
}
case Float: {
float result;
if (array.isForeignObject()) {
InteropLibrary library = InteropLibrary.getUncached();
result = library.asFloat(library.readArrayElement(array.rawForeignObject(language), index));
} else {
result = vm.getArrayFloat(language, index, array);
}
return meta.boxFloat(result);
}
case Long: {
long result;
if (array.isForeignObject()) {
InteropLibrary library = InteropLibrary.getUncached();
result = library.asLong(library.readArrayElement(array.rawForeignObject(language), index));
} else {
result = vm.getArrayLong(language, index, array);
}
return meta.boxLong(result);
}
case Double: {
double result;
if (array.isForeignObject()) {
InteropLibrary library = InteropLibrary.getUncached();
result = library.asDouble(library.readArrayElement(array.rawForeignObject(language), index));
} else {
result = vm.getArrayDouble(language, index, array);
}
return meta.boxDouble(result);
}
case Object: {
if (array.isForeignObject()) {
InteropLibrary library = InteropLibrary.getUncached();
Object result = library.readArrayElement(array.rawForeignObject(language), index);
return StaticObject.createForeign(language, meta.java_lang_Object, result, InteropLibrary.getUncached(result));
} else {
return vm.getArrayObject(language, index, array);
}
}
default:
CompilerDirectives.transferToInterpreter();
throw EspressoError.shouldNotReachHere("invalid array type: " + array);
}
} catch (UnsupportedMessageException e) {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
} catch (InvalidArrayIndexException e) {
int length = getForeignArrayLength(array, language, meta);
throw meta.throwExceptionWithMessage(meta.java_lang_ArrayIndexOutOfBoundsException, InterpreterToVM.outOfBoundsMessage(index, length));
}
} else {
throw meta.throwException(meta.java_lang_IllegalArgumentException);
}
}
@Substitution
@Throws(IllegalArgumentException.class)
public static int getLength(@JavaType(Object.class) StaticObject array, @Inject VM vm, @Inject EspressoLanguage language, @Inject SubstitutionProfiler profiler) {
return vm.JVM_GetArrayLength(array, language, profiler);
}
private static int getForeignArrayLength(StaticObject array, EspressoLanguage language, Meta meta) {
assert array.isForeignObject();
try {
Object foreignObject = array.rawForeignObject(language);
InteropLibrary library = InteropLibrary.getUncached(foreignObject);
long arrayLength = library.getArraySize(foreignObject);
if (arrayLength > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
return (int) arrayLength;
} catch (UnsupportedMessageException e) {
throw meta.throwExceptionWithMessage(meta.java_lang_IllegalArgumentException, "can't get array length because foreign object is not an array");
}
}
}
|
googleapis/google-cloud-java
| 38,091
|
java-tpu/proto-google-cloud-tpu-v2alpha1/src/main/java/com/google/cloud/tpu/v2alpha1/CreateNodeRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/tpu/v2alpha1/cloud_tpu.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.tpu.v2alpha1;
/**
*
*
* <pre>
* Request for [CreateNode][google.cloud.tpu.v2alpha1.Tpu.CreateNode].
* </pre>
*
* Protobuf type {@code google.cloud.tpu.v2alpha1.CreateNodeRequest}
*/
public final class CreateNodeRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.tpu.v2alpha1.CreateNodeRequest)
CreateNodeRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateNodeRequest.newBuilder() to construct.
private CreateNodeRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateNodeRequest() {
parent_ = "";
nodeId_ = "";
requestId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateNodeRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.tpu.v2alpha1.CloudTpuProto
.internal_static_google_cloud_tpu_v2alpha1_CreateNodeRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.tpu.v2alpha1.CloudTpuProto
.internal_static_google_cloud_tpu_v2alpha1_CreateNodeRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.tpu.v2alpha1.CreateNodeRequest.class,
com.google.cloud.tpu.v2alpha1.CreateNodeRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The parent resource name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int NODE_ID_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nodeId_ = "";
/**
*
*
* <pre>
* The unqualified resource name.
* </pre>
*
* <code>string node_id = 2;</code>
*
* @return The nodeId.
*/
@java.lang.Override
public java.lang.String getNodeId() {
java.lang.Object ref = nodeId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nodeId_ = s;
return s;
}
}
/**
*
*
* <pre>
* The unqualified resource name.
* </pre>
*
* <code>string node_id = 2;</code>
*
* @return The bytes for nodeId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNodeIdBytes() {
java.lang.Object ref = nodeId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nodeId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int NODE_FIELD_NUMBER = 3;
private com.google.cloud.tpu.v2alpha1.Node node_;
/**
*
*
* <pre>
* Required. The node.
* </pre>
*
* <code>.google.cloud.tpu.v2alpha1.Node node = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the node field is set.
*/
@java.lang.Override
public boolean hasNode() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The node.
* </pre>
*
* <code>.google.cloud.tpu.v2alpha1.Node node = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The node.
*/
@java.lang.Override
public com.google.cloud.tpu.v2alpha1.Node getNode() {
return node_ == null ? com.google.cloud.tpu.v2alpha1.Node.getDefaultInstance() : node_;
}
/**
*
*
* <pre>
* Required. The node.
* </pre>
*
* <code>.google.cloud.tpu.v2alpha1.Node node = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.tpu.v2alpha1.NodeOrBuilder getNodeOrBuilder() {
return node_ == null ? com.google.cloud.tpu.v2alpha1.Node.getDefaultInstance() : node_;
}
public static final int REQUEST_ID_FIELD_NUMBER = 6;
@SuppressWarnings("serial")
private volatile java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* Idempotent request UUID.
* </pre>
*
* <code>string request_id = 6;</code>
*
* @return The requestId.
*/
@java.lang.Override
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Idempotent request UUID.
* </pre>
*
* <code>string request_id = 6;</code>
*
* @return The bytes for requestId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nodeId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nodeId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(3, getNode());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 6, requestId_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nodeId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nodeId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getNode());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(requestId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, requestId_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.tpu.v2alpha1.CreateNodeRequest)) {
return super.equals(obj);
}
com.google.cloud.tpu.v2alpha1.CreateNodeRequest other =
(com.google.cloud.tpu.v2alpha1.CreateNodeRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getNodeId().equals(other.getNodeId())) return false;
if (hasNode() != other.hasNode()) return false;
if (hasNode()) {
if (!getNode().equals(other.getNode())) return false;
}
if (!getRequestId().equals(other.getRequestId())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + NODE_ID_FIELD_NUMBER;
hash = (53 * hash) + getNodeId().hashCode();
if (hasNode()) {
hash = (37 * hash) + NODE_FIELD_NUMBER;
hash = (53 * hash) + getNode().hashCode();
}
hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER;
hash = (53 * hash) + getRequestId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.tpu.v2alpha1.CreateNodeRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for [CreateNode][google.cloud.tpu.v2alpha1.Tpu.CreateNode].
* </pre>
*
* Protobuf type {@code google.cloud.tpu.v2alpha1.CreateNodeRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.tpu.v2alpha1.CreateNodeRequest)
com.google.cloud.tpu.v2alpha1.CreateNodeRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.tpu.v2alpha1.CloudTpuProto
.internal_static_google_cloud_tpu_v2alpha1_CreateNodeRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.tpu.v2alpha1.CloudTpuProto
.internal_static_google_cloud_tpu_v2alpha1_CreateNodeRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.tpu.v2alpha1.CreateNodeRequest.class,
com.google.cloud.tpu.v2alpha1.CreateNodeRequest.Builder.class);
}
// Construct using com.google.cloud.tpu.v2alpha1.CreateNodeRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getNodeFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
nodeId_ = "";
node_ = null;
if (nodeBuilder_ != null) {
nodeBuilder_.dispose();
nodeBuilder_ = null;
}
requestId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.tpu.v2alpha1.CloudTpuProto
.internal_static_google_cloud_tpu_v2alpha1_CreateNodeRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.tpu.v2alpha1.CreateNodeRequest getDefaultInstanceForType() {
return com.google.cloud.tpu.v2alpha1.CreateNodeRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.tpu.v2alpha1.CreateNodeRequest build() {
com.google.cloud.tpu.v2alpha1.CreateNodeRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.tpu.v2alpha1.CreateNodeRequest buildPartial() {
com.google.cloud.tpu.v2alpha1.CreateNodeRequest result =
new com.google.cloud.tpu.v2alpha1.CreateNodeRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.tpu.v2alpha1.CreateNodeRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nodeId_ = nodeId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.node_ = nodeBuilder_ == null ? node_ : nodeBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.requestId_ = requestId_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.tpu.v2alpha1.CreateNodeRequest) {
return mergeFrom((com.google.cloud.tpu.v2alpha1.CreateNodeRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.tpu.v2alpha1.CreateNodeRequest other) {
if (other == com.google.cloud.tpu.v2alpha1.CreateNodeRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getNodeId().isEmpty()) {
nodeId_ = other.nodeId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasNode()) {
mergeNode(other.getNode());
}
if (!other.getRequestId().isEmpty()) {
requestId_ = other.requestId_;
bitField0_ |= 0x00000008;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
nodeId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getNodeFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 26
case 50:
{
requestId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 50
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The parent resource name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The parent resource name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent resource name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent resource name.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object nodeId_ = "";
/**
*
*
* <pre>
* The unqualified resource name.
* </pre>
*
* <code>string node_id = 2;</code>
*
* @return The nodeId.
*/
public java.lang.String getNodeId() {
java.lang.Object ref = nodeId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nodeId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The unqualified resource name.
* </pre>
*
* <code>string node_id = 2;</code>
*
* @return The bytes for nodeId.
*/
public com.google.protobuf.ByteString getNodeIdBytes() {
java.lang.Object ref = nodeId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nodeId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The unqualified resource name.
* </pre>
*
* <code>string node_id = 2;</code>
*
* @param value The nodeId to set.
* @return This builder for chaining.
*/
public Builder setNodeId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nodeId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The unqualified resource name.
* </pre>
*
* <code>string node_id = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNodeId() {
nodeId_ = getDefaultInstance().getNodeId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The unqualified resource name.
* </pre>
*
* <code>string node_id = 2;</code>
*
* @param value The bytes for nodeId to set.
* @return This builder for chaining.
*/
public Builder setNodeIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nodeId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.cloud.tpu.v2alpha1.Node node_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.tpu.v2alpha1.Node,
com.google.cloud.tpu.v2alpha1.Node.Builder,
com.google.cloud.tpu.v2alpha1.NodeOrBuilder>
nodeBuilder_;
/**
*
*
* <pre>
* Required. The node.
* </pre>
*
* <code>.google.cloud.tpu.v2alpha1.Node node = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the node field is set.
*/
public boolean hasNode() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Required. The node.
* </pre>
*
* <code>.google.cloud.tpu.v2alpha1.Node node = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The node.
*/
public com.google.cloud.tpu.v2alpha1.Node getNode() {
if (nodeBuilder_ == null) {
return node_ == null ? com.google.cloud.tpu.v2alpha1.Node.getDefaultInstance() : node_;
} else {
return nodeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The node.
* </pre>
*
* <code>.google.cloud.tpu.v2alpha1.Node node = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setNode(com.google.cloud.tpu.v2alpha1.Node value) {
if (nodeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
node_ = value;
} else {
nodeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The node.
* </pre>
*
* <code>.google.cloud.tpu.v2alpha1.Node node = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setNode(com.google.cloud.tpu.v2alpha1.Node.Builder builderForValue) {
if (nodeBuilder_ == null) {
node_ = builderForValue.build();
} else {
nodeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The node.
* </pre>
*
* <code>.google.cloud.tpu.v2alpha1.Node node = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeNode(com.google.cloud.tpu.v2alpha1.Node value) {
if (nodeBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& node_ != null
&& node_ != com.google.cloud.tpu.v2alpha1.Node.getDefaultInstance()) {
getNodeBuilder().mergeFrom(value);
} else {
node_ = value;
}
} else {
nodeBuilder_.mergeFrom(value);
}
if (node_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The node.
* </pre>
*
* <code>.google.cloud.tpu.v2alpha1.Node node = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearNode() {
bitField0_ = (bitField0_ & ~0x00000004);
node_ = null;
if (nodeBuilder_ != null) {
nodeBuilder_.dispose();
nodeBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The node.
* </pre>
*
* <code>.google.cloud.tpu.v2alpha1.Node node = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.tpu.v2alpha1.Node.Builder getNodeBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getNodeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The node.
* </pre>
*
* <code>.google.cloud.tpu.v2alpha1.Node node = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.tpu.v2alpha1.NodeOrBuilder getNodeOrBuilder() {
if (nodeBuilder_ != null) {
return nodeBuilder_.getMessageOrBuilder();
} else {
return node_ == null ? com.google.cloud.tpu.v2alpha1.Node.getDefaultInstance() : node_;
}
}
/**
*
*
* <pre>
* Required. The node.
* </pre>
*
* <code>.google.cloud.tpu.v2alpha1.Node node = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.tpu.v2alpha1.Node,
com.google.cloud.tpu.v2alpha1.Node.Builder,
com.google.cloud.tpu.v2alpha1.NodeOrBuilder>
getNodeFieldBuilder() {
if (nodeBuilder_ == null) {
nodeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.tpu.v2alpha1.Node,
com.google.cloud.tpu.v2alpha1.Node.Builder,
com.google.cloud.tpu.v2alpha1.NodeOrBuilder>(
getNode(), getParentForChildren(), isClean());
node_ = null;
}
return nodeBuilder_;
}
private java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* Idempotent request UUID.
* </pre>
*
* <code>string request_id = 6;</code>
*
* @return The requestId.
*/
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Idempotent request UUID.
* </pre>
*
* <code>string request_id = 6;</code>
*
* @return The bytes for requestId.
*/
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Idempotent request UUID.
* </pre>
*
* <code>string request_id = 6;</code>
*
* @param value The requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
requestId_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Idempotent request UUID.
* </pre>
*
* <code>string request_id = 6;</code>
*
* @return This builder for chaining.
*/
public Builder clearRequestId() {
requestId_ = getDefaultInstance().getRequestId();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Idempotent request UUID.
* </pre>
*
* <code>string request_id = 6;</code>
*
* @param value The bytes for requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
requestId_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.tpu.v2alpha1.CreateNodeRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.tpu.v2alpha1.CreateNodeRequest)
private static final com.google.cloud.tpu.v2alpha1.CreateNodeRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.tpu.v2alpha1.CreateNodeRequest();
}
public static com.google.cloud.tpu.v2alpha1.CreateNodeRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateNodeRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateNodeRequest>() {
@java.lang.Override
public CreateNodeRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<CreateNodeRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateNodeRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.tpu.v2alpha1.CreateNodeRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,198
|
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/UrlMapsScopedList.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.UrlMapsScopedList}
*/
public final class UrlMapsScopedList extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.UrlMapsScopedList)
UrlMapsScopedListOrBuilder {
private static final long serialVersionUID = 0L;
// Use UrlMapsScopedList.newBuilder() to construct.
private UrlMapsScopedList(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UrlMapsScopedList() {
urlMaps_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UrlMapsScopedList();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_UrlMapsScopedList_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_UrlMapsScopedList_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.UrlMapsScopedList.class,
com.google.cloud.compute.v1.UrlMapsScopedList.Builder.class);
}
private int bitField0_;
public static final int URL_MAPS_FIELD_NUMBER = 103352167;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.compute.v1.UrlMap> urlMaps_;
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.compute.v1.UrlMap> getUrlMapsList() {
return urlMaps_;
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.compute.v1.UrlMapOrBuilder>
getUrlMapsOrBuilderList() {
return urlMaps_;
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
@java.lang.Override
public int getUrlMapsCount() {
return urlMaps_.size();
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
@java.lang.Override
public com.google.cloud.compute.v1.UrlMap getUrlMaps(int index) {
return urlMaps_.get(index);
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
@java.lang.Override
public com.google.cloud.compute.v1.UrlMapOrBuilder getUrlMapsOrBuilder(int index) {
return urlMaps_.get(index);
}
public static final int WARNING_FIELD_NUMBER = 50704284;
private com.google.cloud.compute.v1.Warning warning_;
/**
*
*
* <pre>
* Informational warning which replaces the list of backend services when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return Whether the warning field is set.
*/
@java.lang.Override
public boolean hasWarning() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Informational warning which replaces the list of backend services when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return The warning.
*/
@java.lang.Override
public com.google.cloud.compute.v1.Warning getWarning() {
return warning_ == null ? com.google.cloud.compute.v1.Warning.getDefaultInstance() : warning_;
}
/**
*
*
* <pre>
* Informational warning which replaces the list of backend services when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
@java.lang.Override
public com.google.cloud.compute.v1.WarningOrBuilder getWarningOrBuilder() {
return warning_ == null ? com.google.cloud.compute.v1.Warning.getDefaultInstance() : warning_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(50704284, getWarning());
}
for (int i = 0; i < urlMaps_.size(); i++) {
output.writeMessage(103352167, urlMaps_.get(i));
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(50704284, getWarning());
}
for (int i = 0; i < urlMaps_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(103352167, urlMaps_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.UrlMapsScopedList)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.UrlMapsScopedList other =
(com.google.cloud.compute.v1.UrlMapsScopedList) obj;
if (!getUrlMapsList().equals(other.getUrlMapsList())) return false;
if (hasWarning() != other.hasWarning()) return false;
if (hasWarning()) {
if (!getWarning().equals(other.getWarning())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getUrlMapsCount() > 0) {
hash = (37 * hash) + URL_MAPS_FIELD_NUMBER;
hash = (53 * hash) + getUrlMapsList().hashCode();
}
if (hasWarning()) {
hash = (37 * hash) + WARNING_FIELD_NUMBER;
hash = (53 * hash) + getWarning().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.UrlMapsScopedList parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.UrlMapsScopedList parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.UrlMapsScopedList parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.UrlMapsScopedList parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.UrlMapsScopedList parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.UrlMapsScopedList parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.UrlMapsScopedList parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.UrlMapsScopedList parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.UrlMapsScopedList parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.UrlMapsScopedList parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.UrlMapsScopedList parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.UrlMapsScopedList parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.compute.v1.UrlMapsScopedList prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.UrlMapsScopedList}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.UrlMapsScopedList)
com.google.cloud.compute.v1.UrlMapsScopedListOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_UrlMapsScopedList_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_UrlMapsScopedList_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.UrlMapsScopedList.class,
com.google.cloud.compute.v1.UrlMapsScopedList.Builder.class);
}
// Construct using com.google.cloud.compute.v1.UrlMapsScopedList.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getUrlMapsFieldBuilder();
getWarningFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (urlMapsBuilder_ == null) {
urlMaps_ = java.util.Collections.emptyList();
} else {
urlMaps_ = null;
urlMapsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
warning_ = null;
if (warningBuilder_ != null) {
warningBuilder_.dispose();
warningBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_UrlMapsScopedList_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.UrlMapsScopedList getDefaultInstanceForType() {
return com.google.cloud.compute.v1.UrlMapsScopedList.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.UrlMapsScopedList build() {
com.google.cloud.compute.v1.UrlMapsScopedList result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.UrlMapsScopedList buildPartial() {
com.google.cloud.compute.v1.UrlMapsScopedList result =
new com.google.cloud.compute.v1.UrlMapsScopedList(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.cloud.compute.v1.UrlMapsScopedList result) {
if (urlMapsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
urlMaps_ = java.util.Collections.unmodifiableList(urlMaps_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.urlMaps_ = urlMaps_;
} else {
result.urlMaps_ = urlMapsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.compute.v1.UrlMapsScopedList result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.warning_ = warningBuilder_ == null ? warning_ : warningBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.UrlMapsScopedList) {
return mergeFrom((com.google.cloud.compute.v1.UrlMapsScopedList) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.UrlMapsScopedList other) {
if (other == com.google.cloud.compute.v1.UrlMapsScopedList.getDefaultInstance()) return this;
if (urlMapsBuilder_ == null) {
if (!other.urlMaps_.isEmpty()) {
if (urlMaps_.isEmpty()) {
urlMaps_ = other.urlMaps_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureUrlMapsIsMutable();
urlMaps_.addAll(other.urlMaps_);
}
onChanged();
}
} else {
if (!other.urlMaps_.isEmpty()) {
if (urlMapsBuilder_.isEmpty()) {
urlMapsBuilder_.dispose();
urlMapsBuilder_ = null;
urlMaps_ = other.urlMaps_;
bitField0_ = (bitField0_ & ~0x00000001);
urlMapsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getUrlMapsFieldBuilder()
: null;
} else {
urlMapsBuilder_.addAllMessages(other.urlMaps_);
}
}
}
if (other.hasWarning()) {
mergeWarning(other.getWarning());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 405634274:
{
input.readMessage(getWarningFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 405634274
case 826817338:
{
com.google.cloud.compute.v1.UrlMap m =
input.readMessage(
com.google.cloud.compute.v1.UrlMap.parser(), extensionRegistry);
if (urlMapsBuilder_ == null) {
ensureUrlMapsIsMutable();
urlMaps_.add(m);
} else {
urlMapsBuilder_.addMessage(m);
}
break;
} // case 826817338
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.compute.v1.UrlMap> urlMaps_ =
java.util.Collections.emptyList();
private void ensureUrlMapsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
urlMaps_ = new java.util.ArrayList<com.google.cloud.compute.v1.UrlMap>(urlMaps_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.compute.v1.UrlMap,
com.google.cloud.compute.v1.UrlMap.Builder,
com.google.cloud.compute.v1.UrlMapOrBuilder>
urlMapsBuilder_;
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public java.util.List<com.google.cloud.compute.v1.UrlMap> getUrlMapsList() {
if (urlMapsBuilder_ == null) {
return java.util.Collections.unmodifiableList(urlMaps_);
} else {
return urlMapsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public int getUrlMapsCount() {
if (urlMapsBuilder_ == null) {
return urlMaps_.size();
} else {
return urlMapsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public com.google.cloud.compute.v1.UrlMap getUrlMaps(int index) {
if (urlMapsBuilder_ == null) {
return urlMaps_.get(index);
} else {
return urlMapsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public Builder setUrlMaps(int index, com.google.cloud.compute.v1.UrlMap value) {
if (urlMapsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureUrlMapsIsMutable();
urlMaps_.set(index, value);
onChanged();
} else {
urlMapsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public Builder setUrlMaps(
int index, com.google.cloud.compute.v1.UrlMap.Builder builderForValue) {
if (urlMapsBuilder_ == null) {
ensureUrlMapsIsMutable();
urlMaps_.set(index, builderForValue.build());
onChanged();
} else {
urlMapsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public Builder addUrlMaps(com.google.cloud.compute.v1.UrlMap value) {
if (urlMapsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureUrlMapsIsMutable();
urlMaps_.add(value);
onChanged();
} else {
urlMapsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public Builder addUrlMaps(int index, com.google.cloud.compute.v1.UrlMap value) {
if (urlMapsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureUrlMapsIsMutable();
urlMaps_.add(index, value);
onChanged();
} else {
urlMapsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public Builder addUrlMaps(com.google.cloud.compute.v1.UrlMap.Builder builderForValue) {
if (urlMapsBuilder_ == null) {
ensureUrlMapsIsMutable();
urlMaps_.add(builderForValue.build());
onChanged();
} else {
urlMapsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public Builder addUrlMaps(
int index, com.google.cloud.compute.v1.UrlMap.Builder builderForValue) {
if (urlMapsBuilder_ == null) {
ensureUrlMapsIsMutable();
urlMaps_.add(index, builderForValue.build());
onChanged();
} else {
urlMapsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public Builder addAllUrlMaps(
java.lang.Iterable<? extends com.google.cloud.compute.v1.UrlMap> values) {
if (urlMapsBuilder_ == null) {
ensureUrlMapsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, urlMaps_);
onChanged();
} else {
urlMapsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public Builder clearUrlMaps() {
if (urlMapsBuilder_ == null) {
urlMaps_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
urlMapsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public Builder removeUrlMaps(int index) {
if (urlMapsBuilder_ == null) {
ensureUrlMapsIsMutable();
urlMaps_.remove(index);
onChanged();
} else {
urlMapsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public com.google.cloud.compute.v1.UrlMap.Builder getUrlMapsBuilder(int index) {
return getUrlMapsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public com.google.cloud.compute.v1.UrlMapOrBuilder getUrlMapsOrBuilder(int index) {
if (urlMapsBuilder_ == null) {
return urlMaps_.get(index);
} else {
return urlMapsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public java.util.List<? extends com.google.cloud.compute.v1.UrlMapOrBuilder>
getUrlMapsOrBuilderList() {
if (urlMapsBuilder_ != null) {
return urlMapsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(urlMaps_);
}
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public com.google.cloud.compute.v1.UrlMap.Builder addUrlMapsBuilder() {
return getUrlMapsFieldBuilder()
.addBuilder(com.google.cloud.compute.v1.UrlMap.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public com.google.cloud.compute.v1.UrlMap.Builder addUrlMapsBuilder(int index) {
return getUrlMapsFieldBuilder()
.addBuilder(index, com.google.cloud.compute.v1.UrlMap.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of UrlMaps contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.UrlMap url_maps = 103352167;</code>
*/
public java.util.List<com.google.cloud.compute.v1.UrlMap.Builder> getUrlMapsBuilderList() {
return getUrlMapsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.compute.v1.UrlMap,
com.google.cloud.compute.v1.UrlMap.Builder,
com.google.cloud.compute.v1.UrlMapOrBuilder>
getUrlMapsFieldBuilder() {
if (urlMapsBuilder_ == null) {
urlMapsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.compute.v1.UrlMap,
com.google.cloud.compute.v1.UrlMap.Builder,
com.google.cloud.compute.v1.UrlMapOrBuilder>(
urlMaps_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
urlMaps_ = null;
}
return urlMapsBuilder_;
}
private com.google.cloud.compute.v1.Warning warning_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.Warning,
com.google.cloud.compute.v1.Warning.Builder,
com.google.cloud.compute.v1.WarningOrBuilder>
warningBuilder_;
/**
*
*
* <pre>
* Informational warning which replaces the list of backend services when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return Whether the warning field is set.
*/
public boolean hasWarning() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Informational warning which replaces the list of backend services when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return The warning.
*/
public com.google.cloud.compute.v1.Warning getWarning() {
if (warningBuilder_ == null) {
return warning_ == null
? com.google.cloud.compute.v1.Warning.getDefaultInstance()
: warning_;
} else {
return warningBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Informational warning which replaces the list of backend services when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public Builder setWarning(com.google.cloud.compute.v1.Warning value) {
if (warningBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
warning_ = value;
} else {
warningBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Informational warning which replaces the list of backend services when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public Builder setWarning(com.google.cloud.compute.v1.Warning.Builder builderForValue) {
if (warningBuilder_ == null) {
warning_ = builderForValue.build();
} else {
warningBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Informational warning which replaces the list of backend services when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public Builder mergeWarning(com.google.cloud.compute.v1.Warning value) {
if (warningBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& warning_ != null
&& warning_ != com.google.cloud.compute.v1.Warning.getDefaultInstance()) {
getWarningBuilder().mergeFrom(value);
} else {
warning_ = value;
}
} else {
warningBuilder_.mergeFrom(value);
}
if (warning_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Informational warning which replaces the list of backend services when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public Builder clearWarning() {
bitField0_ = (bitField0_ & ~0x00000002);
warning_ = null;
if (warningBuilder_ != null) {
warningBuilder_.dispose();
warningBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Informational warning which replaces the list of backend services when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public com.google.cloud.compute.v1.Warning.Builder getWarningBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getWarningFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Informational warning which replaces the list of backend services when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public com.google.cloud.compute.v1.WarningOrBuilder getWarningOrBuilder() {
if (warningBuilder_ != null) {
return warningBuilder_.getMessageOrBuilder();
} else {
return warning_ == null
? com.google.cloud.compute.v1.Warning.getDefaultInstance()
: warning_;
}
}
/**
*
*
* <pre>
* Informational warning which replaces the list of backend services when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.Warning,
com.google.cloud.compute.v1.Warning.Builder,
com.google.cloud.compute.v1.WarningOrBuilder>
getWarningFieldBuilder() {
if (warningBuilder_ == null) {
warningBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.Warning,
com.google.cloud.compute.v1.Warning.Builder,
com.google.cloud.compute.v1.WarningOrBuilder>(
getWarning(), getParentForChildren(), isClean());
warning_ = null;
}
return warningBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.UrlMapsScopedList)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.UrlMapsScopedList)
private static final com.google.cloud.compute.v1.UrlMapsScopedList DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.UrlMapsScopedList();
}
public static com.google.cloud.compute.v1.UrlMapsScopedList getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UrlMapsScopedList> PARSER =
new com.google.protobuf.AbstractParser<UrlMapsScopedList>() {
@java.lang.Override
public UrlMapsScopedList parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<UrlMapsScopedList> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UrlMapsScopedList> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.UrlMapsScopedList getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,326
|
java-orchestration-airflow/proto-google-cloud-orchestration-airflow-v1beta1/src/main/java/com/google/cloud/orchestration/airflow/service/v1beta1/CheckUpgradeRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/orchestration/airflow/service/v1beta1/environments.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.orchestration.airflow.service.v1beta1;
/**
*
*
* <pre>
* Request to check whether image upgrade will succeed.
* </pre>
*
* Protobuf type {@code google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest}
*/
public final class CheckUpgradeRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest)
CheckUpgradeRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CheckUpgradeRequest.newBuilder() to construct.
private CheckUpgradeRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CheckUpgradeRequest() {
environment_ = "";
imageVersion_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CheckUpgradeRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.orchestration.airflow.service.v1beta1.EnvironmentsOuterClass
.internal_static_google_cloud_orchestration_airflow_service_v1beta1_CheckUpgradeRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.orchestration.airflow.service.v1beta1.EnvironmentsOuterClass
.internal_static_google_cloud_orchestration_airflow_service_v1beta1_CheckUpgradeRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest.class,
com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest.Builder
.class);
}
public static final int ENVIRONMENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object environment_ = "";
/**
*
*
* <pre>
* The resource name of the environment to check upgrade for, in the
* form:
* "projects/{projectId}/locations/{locationId}/environments/{environmentId}"
* </pre>
*
* <code>string environment = 1;</code>
*
* @return The environment.
*/
@java.lang.Override
public java.lang.String getEnvironment() {
java.lang.Object ref = environment_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
environment_ = s;
return s;
}
}
/**
*
*
* <pre>
* The resource name of the environment to check upgrade for, in the
* form:
* "projects/{projectId}/locations/{locationId}/environments/{environmentId}"
* </pre>
*
* <code>string environment = 1;</code>
*
* @return The bytes for environment.
*/
@java.lang.Override
public com.google.protobuf.ByteString getEnvironmentBytes() {
java.lang.Object ref = environment_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
environment_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int IMAGE_VERSION_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object imageVersion_ = "";
/**
*
*
* <pre>
* The version of the software running in the environment.
* This encapsulates both the version of Cloud Composer functionality and the
* version of Apache Airflow. It must match the regular expression
* `composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)`.
* When used as input, the server also checks if the provided version is
* supported and denies the request for an unsupported version.
*
* The Cloud Composer portion of the image version is a full
* [semantic version](https://semver.org), or an alias in the form of major
* version number or `latest`. When an alias is provided, the server replaces
* it with the current Cloud Composer version that satisfies the alias.
*
* The Apache Airflow portion of the image version is a full semantic version
* that points to one of the supported Apache Airflow versions, or an alias in
* the form of only major or major.minor versions specified. When an alias is
* provided, the server replaces it with the latest Apache Airflow version
* that satisfies the alias and is supported in the given Cloud Composer
* version.
*
* In all cases, the resolved image version is stored in the same field.
*
* See also [version
* list](/composer/docs/concepts/versioning/composer-versions) and [versioning
* overview](/composer/docs/concepts/versioning/composer-versioning-overview).
* </pre>
*
* <code>string image_version = 2;</code>
*
* @return The imageVersion.
*/
@java.lang.Override
public java.lang.String getImageVersion() {
java.lang.Object ref = imageVersion_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
imageVersion_ = s;
return s;
}
}
/**
*
*
* <pre>
* The version of the software running in the environment.
* This encapsulates both the version of Cloud Composer functionality and the
* version of Apache Airflow. It must match the regular expression
* `composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)`.
* When used as input, the server also checks if the provided version is
* supported and denies the request for an unsupported version.
*
* The Cloud Composer portion of the image version is a full
* [semantic version](https://semver.org), or an alias in the form of major
* version number or `latest`. When an alias is provided, the server replaces
* it with the current Cloud Composer version that satisfies the alias.
*
* The Apache Airflow portion of the image version is a full semantic version
* that points to one of the supported Apache Airflow versions, or an alias in
* the form of only major or major.minor versions specified. When an alias is
* provided, the server replaces it with the latest Apache Airflow version
* that satisfies the alias and is supported in the given Cloud Composer
* version.
*
* In all cases, the resolved image version is stored in the same field.
*
* See also [version
* list](/composer/docs/concepts/versioning/composer-versions) and [versioning
* overview](/composer/docs/concepts/versioning/composer-versioning-overview).
* </pre>
*
* <code>string image_version = 2;</code>
*
* @return The bytes for imageVersion.
*/
@java.lang.Override
public com.google.protobuf.ByteString getImageVersionBytes() {
java.lang.Object ref = imageVersion_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
imageVersion_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(environment_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, environment_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(imageVersion_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, imageVersion_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(environment_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, environment_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(imageVersion_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, imageVersion_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj
instanceof com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest)) {
return super.equals(obj);
}
com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest other =
(com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest) obj;
if (!getEnvironment().equals(other.getEnvironment())) return false;
if (!getImageVersion().equals(other.getImageVersion())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + ENVIRONMENT_FIELD_NUMBER;
hash = (53 * hash) + getEnvironment().hashCode();
hash = (37 * hash) + IMAGE_VERSION_FIELD_NUMBER;
hash = (53 * hash) + getImageVersion().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request to check whether image upgrade will succeed.
* </pre>
*
* Protobuf type {@code google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest)
com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.orchestration.airflow.service.v1beta1.EnvironmentsOuterClass
.internal_static_google_cloud_orchestration_airflow_service_v1beta1_CheckUpgradeRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.orchestration.airflow.service.v1beta1.EnvironmentsOuterClass
.internal_static_google_cloud_orchestration_airflow_service_v1beta1_CheckUpgradeRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest.class,
com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest.Builder
.class);
}
// Construct using
// com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
environment_ = "";
imageVersion_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.orchestration.airflow.service.v1beta1.EnvironmentsOuterClass
.internal_static_google_cloud_orchestration_airflow_service_v1beta1_CheckUpgradeRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
getDefaultInstanceForType() {
return com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest build() {
com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
buildPartial() {
com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest result =
new com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.environment_ = environment_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.imageVersion_ = imageVersion_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other
instanceof com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest) {
return mergeFrom(
(com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest other) {
if (other
== com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
.getDefaultInstance()) return this;
if (!other.getEnvironment().isEmpty()) {
environment_ = other.environment_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getImageVersion().isEmpty()) {
imageVersion_ = other.imageVersion_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
environment_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
imageVersion_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object environment_ = "";
/**
*
*
* <pre>
* The resource name of the environment to check upgrade for, in the
* form:
* "projects/{projectId}/locations/{locationId}/environments/{environmentId}"
* </pre>
*
* <code>string environment = 1;</code>
*
* @return The environment.
*/
public java.lang.String getEnvironment() {
java.lang.Object ref = environment_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
environment_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The resource name of the environment to check upgrade for, in the
* form:
* "projects/{projectId}/locations/{locationId}/environments/{environmentId}"
* </pre>
*
* <code>string environment = 1;</code>
*
* @return The bytes for environment.
*/
public com.google.protobuf.ByteString getEnvironmentBytes() {
java.lang.Object ref = environment_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
environment_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The resource name of the environment to check upgrade for, in the
* form:
* "projects/{projectId}/locations/{locationId}/environments/{environmentId}"
* </pre>
*
* <code>string environment = 1;</code>
*
* @param value The environment to set.
* @return This builder for chaining.
*/
public Builder setEnvironment(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
environment_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The resource name of the environment to check upgrade for, in the
* form:
* "projects/{projectId}/locations/{locationId}/environments/{environmentId}"
* </pre>
*
* <code>string environment = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearEnvironment() {
environment_ = getDefaultInstance().getEnvironment();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The resource name of the environment to check upgrade for, in the
* form:
* "projects/{projectId}/locations/{locationId}/environments/{environmentId}"
* </pre>
*
* <code>string environment = 1;</code>
*
* @param value The bytes for environment to set.
* @return This builder for chaining.
*/
public Builder setEnvironmentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
environment_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object imageVersion_ = "";
/**
*
*
* <pre>
* The version of the software running in the environment.
* This encapsulates both the version of Cloud Composer functionality and the
* version of Apache Airflow. It must match the regular expression
* `composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)`.
* When used as input, the server also checks if the provided version is
* supported and denies the request for an unsupported version.
*
* The Cloud Composer portion of the image version is a full
* [semantic version](https://semver.org), or an alias in the form of major
* version number or `latest`. When an alias is provided, the server replaces
* it with the current Cloud Composer version that satisfies the alias.
*
* The Apache Airflow portion of the image version is a full semantic version
* that points to one of the supported Apache Airflow versions, or an alias in
* the form of only major or major.minor versions specified. When an alias is
* provided, the server replaces it with the latest Apache Airflow version
* that satisfies the alias and is supported in the given Cloud Composer
* version.
*
* In all cases, the resolved image version is stored in the same field.
*
* See also [version
* list](/composer/docs/concepts/versioning/composer-versions) and [versioning
* overview](/composer/docs/concepts/versioning/composer-versioning-overview).
* </pre>
*
* <code>string image_version = 2;</code>
*
* @return The imageVersion.
*/
public java.lang.String getImageVersion() {
java.lang.Object ref = imageVersion_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
imageVersion_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The version of the software running in the environment.
* This encapsulates both the version of Cloud Composer functionality and the
* version of Apache Airflow. It must match the regular expression
* `composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)`.
* When used as input, the server also checks if the provided version is
* supported and denies the request for an unsupported version.
*
* The Cloud Composer portion of the image version is a full
* [semantic version](https://semver.org), or an alias in the form of major
* version number or `latest`. When an alias is provided, the server replaces
* it with the current Cloud Composer version that satisfies the alias.
*
* The Apache Airflow portion of the image version is a full semantic version
* that points to one of the supported Apache Airflow versions, or an alias in
* the form of only major or major.minor versions specified. When an alias is
* provided, the server replaces it with the latest Apache Airflow version
* that satisfies the alias and is supported in the given Cloud Composer
* version.
*
* In all cases, the resolved image version is stored in the same field.
*
* See also [version
* list](/composer/docs/concepts/versioning/composer-versions) and [versioning
* overview](/composer/docs/concepts/versioning/composer-versioning-overview).
* </pre>
*
* <code>string image_version = 2;</code>
*
* @return The bytes for imageVersion.
*/
public com.google.protobuf.ByteString getImageVersionBytes() {
java.lang.Object ref = imageVersion_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
imageVersion_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The version of the software running in the environment.
* This encapsulates both the version of Cloud Composer functionality and the
* version of Apache Airflow. It must match the regular expression
* `composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)`.
* When used as input, the server also checks if the provided version is
* supported and denies the request for an unsupported version.
*
* The Cloud Composer portion of the image version is a full
* [semantic version](https://semver.org), or an alias in the form of major
* version number or `latest`. When an alias is provided, the server replaces
* it with the current Cloud Composer version that satisfies the alias.
*
* The Apache Airflow portion of the image version is a full semantic version
* that points to one of the supported Apache Airflow versions, or an alias in
* the form of only major or major.minor versions specified. When an alias is
* provided, the server replaces it with the latest Apache Airflow version
* that satisfies the alias and is supported in the given Cloud Composer
* version.
*
* In all cases, the resolved image version is stored in the same field.
*
* See also [version
* list](/composer/docs/concepts/versioning/composer-versions) and [versioning
* overview](/composer/docs/concepts/versioning/composer-versioning-overview).
* </pre>
*
* <code>string image_version = 2;</code>
*
* @param value The imageVersion to set.
* @return This builder for chaining.
*/
public Builder setImageVersion(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
imageVersion_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The version of the software running in the environment.
* This encapsulates both the version of Cloud Composer functionality and the
* version of Apache Airflow. It must match the regular expression
* `composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)`.
* When used as input, the server also checks if the provided version is
* supported and denies the request for an unsupported version.
*
* The Cloud Composer portion of the image version is a full
* [semantic version](https://semver.org), or an alias in the form of major
* version number or `latest`. When an alias is provided, the server replaces
* it with the current Cloud Composer version that satisfies the alias.
*
* The Apache Airflow portion of the image version is a full semantic version
* that points to one of the supported Apache Airflow versions, or an alias in
* the form of only major or major.minor versions specified. When an alias is
* provided, the server replaces it with the latest Apache Airflow version
* that satisfies the alias and is supported in the given Cloud Composer
* version.
*
* In all cases, the resolved image version is stored in the same field.
*
* See also [version
* list](/composer/docs/concepts/versioning/composer-versions) and [versioning
* overview](/composer/docs/concepts/versioning/composer-versioning-overview).
* </pre>
*
* <code>string image_version = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearImageVersion() {
imageVersion_ = getDefaultInstance().getImageVersion();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The version of the software running in the environment.
* This encapsulates both the version of Cloud Composer functionality and the
* version of Apache Airflow. It must match the regular expression
* `composer-([0-9]+(\.[0-9]+\.[0-9]+(-preview\.[0-9]+)?)?|latest)-airflow-([0-9]+(\.[0-9]+(\.[0-9]+)?)?)`.
* When used as input, the server also checks if the provided version is
* supported and denies the request for an unsupported version.
*
* The Cloud Composer portion of the image version is a full
* [semantic version](https://semver.org), or an alias in the form of major
* version number or `latest`. When an alias is provided, the server replaces
* it with the current Cloud Composer version that satisfies the alias.
*
* The Apache Airflow portion of the image version is a full semantic version
* that points to one of the supported Apache Airflow versions, or an alias in
* the form of only major or major.minor versions specified. When an alias is
* provided, the server replaces it with the latest Apache Airflow version
* that satisfies the alias and is supported in the given Cloud Composer
* version.
*
* In all cases, the resolved image version is stored in the same field.
*
* See also [version
* list](/composer/docs/concepts/versioning/composer-versions) and [versioning
* overview](/composer/docs/concepts/versioning/composer-versioning-overview).
* </pre>
*
* <code>string image_version = 2;</code>
*
* @param value The bytes for imageVersion to set.
* @return This builder for chaining.
*/
public Builder setImageVersionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
imageVersion_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest)
private static final com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest();
}
public static com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CheckUpgradeRequest> PARSER =
new com.google.protobuf.AbstractParser<CheckUpgradeRequest>() {
@java.lang.Override
public CheckUpgradeRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<CheckUpgradeRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CheckUpgradeRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.orchestration.airflow.service.v1beta1.CheckUpgradeRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,218
|
java-recommendations-ai/proto-google-cloud-recommendations-ai-v1beta1/src/main/java/com/google/cloud/recommendationengine/v1beta1/PurgeUserEventsRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/recommendationengine/v1beta1/user_event_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.recommendationengine.v1beta1;
/**
*
*
* <pre>
* Request message for PurgeUserEvents method.
* </pre>
*
* Protobuf type {@code google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest}
*/
public final class PurgeUserEventsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest)
PurgeUserEventsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use PurgeUserEventsRequest.newBuilder() to construct.
private PurgeUserEventsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private PurgeUserEventsRequest() {
parent_ = "";
filter_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new PurgeUserEventsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.recommendationengine.v1beta1.UserEventServiceOuterClass
.internal_static_google_cloud_recommendationengine_v1beta1_PurgeUserEventsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.recommendationengine.v1beta1.UserEventServiceOuterClass
.internal_static_google_cloud_recommendationengine_v1beta1_PurgeUserEventsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest.class,
com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The resource name of the event_store under which the events are
* created. The format is
* `projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The resource name of the event_store under which the events are
* created. The format is
* `projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Required. The filter string to specify the events to be deleted. Empty
* string filter is not allowed. This filter can also be used with
* ListUserEvents API to list events that will be deleted. The eligible fields
* for filtering are:
* * eventType - UserEvent.eventType field of type string.
* * eventTime - in ISO 8601 "zulu" format.
* * visitorId - field of type string. Specifying this will delete all events
* associated with a visitor.
* * userId - field of type string. Specifying this will delete all events
* associated with a user.
* Example 1: Deleting all events in a time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventTime <
* "2012-04-23T18:30:43.511Z"`
* Example 2: Deleting specific eventType in time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`
* Example 3: Deleting all events for a specific visitor
* `visitorId = visitor1024`
* The filtering fields are assumed to have an implicit AND.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The filter string to specify the events to be deleted. Empty
* string filter is not allowed. This filter can also be used with
* ListUserEvents API to list events that will be deleted. The eligible fields
* for filtering are:
* * eventType - UserEvent.eventType field of type string.
* * eventTime - in ISO 8601 "zulu" format.
* * visitorId - field of type string. Specifying this will delete all events
* associated with a visitor.
* * userId - field of type string. Specifying this will delete all events
* associated with a user.
* Example 1: Deleting all events in a time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventTime <
* "2012-04-23T18:30:43.511Z"`
* Example 2: Deleting specific eventType in time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`
* Example 3: Deleting all events for a specific visitor
* `visitorId = visitor1024`
* The filtering fields are assumed to have an implicit AND.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FORCE_FIELD_NUMBER = 3;
private boolean force_ = false;
/**
*
*
* <pre>
* Optional. The default value is false. Override this flag to true to
* actually perform the purge. If the field is not set to true, a sampling of
* events to be deleted will be returned.
* </pre>
*
* <code>bool force = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The force.
*/
@java.lang.Override
public boolean getForce() {
return force_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, filter_);
}
if (force_ != false) {
output.writeBool(3, force_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, filter_);
}
if (force_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, force_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest)) {
return super.equals(obj);
}
com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest other =
(com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (getForce() != other.getForce()) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + FORCE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getForce());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request message for PurgeUserEvents method.
* </pre>
*
* Protobuf type {@code google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest)
com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.recommendationengine.v1beta1.UserEventServiceOuterClass
.internal_static_google_cloud_recommendationengine_v1beta1_PurgeUserEventsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.recommendationengine.v1beta1.UserEventServiceOuterClass
.internal_static_google_cloud_recommendationengine_v1beta1_PurgeUserEventsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest.class,
com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest.Builder.class);
}
// Construct using
// com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
filter_ = "";
force_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.recommendationengine.v1beta1.UserEventServiceOuterClass
.internal_static_google_cloud_recommendationengine_v1beta1_PurgeUserEventsRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest
getDefaultInstanceForType() {
return com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest build() {
com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest buildPartial() {
com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest result =
new com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.force_ = force_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest) {
return mergeFrom(
(com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest other) {
if (other
== com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest
.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.getForce() != false) {
setForce(other.getForce());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
force_ = input.readBool();
bitField0_ |= 0x00000004;
break;
} // case 24
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The resource name of the event_store under which the events are
* created. The format is
* `projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The resource name of the event_store under which the events are
* created. The format is
* `projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The resource name of the event_store under which the events are
* created. The format is
* `projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource name of the event_store under which the events are
* created. The format is
* `projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The resource name of the event_store under which the events are
* created. The format is
* `projects/${projectId}/locations/global/catalogs/${catalogId}/eventStores/${eventStoreId}`
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Required. The filter string to specify the events to be deleted. Empty
* string filter is not allowed. This filter can also be used with
* ListUserEvents API to list events that will be deleted. The eligible fields
* for filtering are:
* * eventType - UserEvent.eventType field of type string.
* * eventTime - in ISO 8601 "zulu" format.
* * visitorId - field of type string. Specifying this will delete all events
* associated with a visitor.
* * userId - field of type string. Specifying this will delete all events
* associated with a user.
* Example 1: Deleting all events in a time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventTime <
* "2012-04-23T18:30:43.511Z"`
* Example 2: Deleting specific eventType in time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`
* Example 3: Deleting all events for a specific visitor
* `visitorId = visitor1024`
* The filtering fields are assumed to have an implicit AND.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The filter string to specify the events to be deleted. Empty
* string filter is not allowed. This filter can also be used with
* ListUserEvents API to list events that will be deleted. The eligible fields
* for filtering are:
* * eventType - UserEvent.eventType field of type string.
* * eventTime - in ISO 8601 "zulu" format.
* * visitorId - field of type string. Specifying this will delete all events
* associated with a visitor.
* * userId - field of type string. Specifying this will delete all events
* associated with a user.
* Example 1: Deleting all events in a time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventTime <
* "2012-04-23T18:30:43.511Z"`
* Example 2: Deleting specific eventType in time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`
* Example 3: Deleting all events for a specific visitor
* `visitorId = visitor1024`
* The filtering fields are assumed to have an implicit AND.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The filter string to specify the events to be deleted. Empty
* string filter is not allowed. This filter can also be used with
* ListUserEvents API to list events that will be deleted. The eligible fields
* for filtering are:
* * eventType - UserEvent.eventType field of type string.
* * eventTime - in ISO 8601 "zulu" format.
* * visitorId - field of type string. Specifying this will delete all events
* associated with a visitor.
* * userId - field of type string. Specifying this will delete all events
* associated with a user.
* Example 1: Deleting all events in a time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventTime <
* "2012-04-23T18:30:43.511Z"`
* Example 2: Deleting specific eventType in time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`
* Example 3: Deleting all events for a specific visitor
* `visitorId = visitor1024`
* The filtering fields are assumed to have an implicit AND.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The filter string to specify the events to be deleted. Empty
* string filter is not allowed. This filter can also be used with
* ListUserEvents API to list events that will be deleted. The eligible fields
* for filtering are:
* * eventType - UserEvent.eventType field of type string.
* * eventTime - in ISO 8601 "zulu" format.
* * visitorId - field of type string. Specifying this will delete all events
* associated with a visitor.
* * userId - field of type string. Specifying this will delete all events
* associated with a user.
* Example 1: Deleting all events in a time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventTime <
* "2012-04-23T18:30:43.511Z"`
* Example 2: Deleting specific eventType in time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`
* Example 3: Deleting all events for a specific visitor
* `visitorId = visitor1024`
* The filtering fields are assumed to have an implicit AND.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The filter string to specify the events to be deleted. Empty
* string filter is not allowed. This filter can also be used with
* ListUserEvents API to list events that will be deleted. The eligible fields
* for filtering are:
* * eventType - UserEvent.eventType field of type string.
* * eventTime - in ISO 8601 "zulu" format.
* * visitorId - field of type string. Specifying this will delete all events
* associated with a visitor.
* * userId - field of type string. Specifying this will delete all events
* associated with a user.
* Example 1: Deleting all events in a time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventTime <
* "2012-04-23T18:30:43.511Z"`
* Example 2: Deleting specific eventType in time range.
* `eventTime > "2012-04-23T18:25:43.511Z" eventType = "detail-page-view"`
* Example 3: Deleting all events for a specific visitor
* `visitorId = visitor1024`
* The filtering fields are assumed to have an implicit AND.
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private boolean force_;
/**
*
*
* <pre>
* Optional. The default value is false. Override this flag to true to
* actually perform the purge. If the field is not set to true, a sampling of
* events to be deleted will be returned.
* </pre>
*
* <code>bool force = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The force.
*/
@java.lang.Override
public boolean getForce() {
return force_;
}
/**
*
*
* <pre>
* Optional. The default value is false. Override this flag to true to
* actually perform the purge. If the field is not set to true, a sampling of
* events to be deleted will be returned.
* </pre>
*
* <code>bool force = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The force to set.
* @return This builder for chaining.
*/
public Builder setForce(boolean value) {
force_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The default value is false. Override this flag to true to
* actually perform the purge. If the field is not set to true, a sampling of
* events to be deleted will be returned.
* </pre>
*
* <code>bool force = 3 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearForce() {
bitField0_ = (bitField0_ & ~0x00000004);
force_ = false;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest)
private static final com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest();
}
public static com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<PurgeUserEventsRequest> PARSER =
new com.google.protobuf.AbstractParser<PurgeUserEventsRequest>() {
@java.lang.Override
public PurgeUserEventsRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<PurgeUserEventsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<PurgeUserEventsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.recommendationengine.v1beta1.PurgeUserEventsRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,239
|
java-dlp/proto-google-cloud-dlp-v2/src/main/java/com/google/privacy/dlp/v2/ListFileStoreDataProfilesResponse.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/privacy/dlp/v2/dlp.proto
// Protobuf Java Version: 3.25.8
package com.google.privacy.dlp.v2;
/**
*
*
* <pre>
* List of file store data profiles generated for a given organization or
* project.
* </pre>
*
* Protobuf type {@code google.privacy.dlp.v2.ListFileStoreDataProfilesResponse}
*/
public final class ListFileStoreDataProfilesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.privacy.dlp.v2.ListFileStoreDataProfilesResponse)
ListFileStoreDataProfilesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListFileStoreDataProfilesResponse.newBuilder() to construct.
private ListFileStoreDataProfilesResponse(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListFileStoreDataProfilesResponse() {
fileStoreDataProfiles_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListFileStoreDataProfilesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_ListFileStoreDataProfilesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_ListFileStoreDataProfilesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse.class,
com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse.Builder.class);
}
public static final int FILE_STORE_DATA_PROFILES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.privacy.dlp.v2.FileStoreDataProfile> fileStoreDataProfiles_;
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.privacy.dlp.v2.FileStoreDataProfile>
getFileStoreDataProfilesList() {
return fileStoreDataProfiles_;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.privacy.dlp.v2.FileStoreDataProfileOrBuilder>
getFileStoreDataProfilesOrBuilderList() {
return fileStoreDataProfiles_;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;</code>
*/
@java.lang.Override
public int getFileStoreDataProfilesCount() {
return fileStoreDataProfiles_.size();
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;</code>
*/
@java.lang.Override
public com.google.privacy.dlp.v2.FileStoreDataProfile getFileStoreDataProfiles(int index) {
return fileStoreDataProfiles_.get(index);
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;</code>
*/
@java.lang.Override
public com.google.privacy.dlp.v2.FileStoreDataProfileOrBuilder getFileStoreDataProfilesOrBuilder(
int index) {
return fileStoreDataProfiles_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < fileStoreDataProfiles_.size(); i++) {
output.writeMessage(1, fileStoreDataProfiles_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < fileStoreDataProfiles_.size(); i++) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, fileStoreDataProfiles_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse)) {
return super.equals(obj);
}
com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse other =
(com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse) obj;
if (!getFileStoreDataProfilesList().equals(other.getFileStoreDataProfilesList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getFileStoreDataProfilesCount() > 0) {
hash = (37 * hash) + FILE_STORE_DATA_PROFILES_FIELD_NUMBER;
hash = (53 * hash) + getFileStoreDataProfilesList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* List of file store data profiles generated for a given organization or
* project.
* </pre>
*
* Protobuf type {@code google.privacy.dlp.v2.ListFileStoreDataProfilesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.privacy.dlp.v2.ListFileStoreDataProfilesResponse)
com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_ListFileStoreDataProfilesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_ListFileStoreDataProfilesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse.class,
com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse.Builder.class);
}
// Construct using com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (fileStoreDataProfilesBuilder_ == null) {
fileStoreDataProfiles_ = java.util.Collections.emptyList();
} else {
fileStoreDataProfiles_ = null;
fileStoreDataProfilesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.privacy.dlp.v2.DlpProto
.internal_static_google_privacy_dlp_v2_ListFileStoreDataProfilesResponse_descriptor;
}
@java.lang.Override
public com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse getDefaultInstanceForType() {
return com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse build() {
com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse buildPartial() {
com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse result =
new com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse result) {
if (fileStoreDataProfilesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
fileStoreDataProfiles_ = java.util.Collections.unmodifiableList(fileStoreDataProfiles_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.fileStoreDataProfiles_ = fileStoreDataProfiles_;
} else {
result.fileStoreDataProfiles_ = fileStoreDataProfilesBuilder_.build();
}
}
private void buildPartial0(com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse) {
return mergeFrom((com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse other) {
if (other == com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse.getDefaultInstance())
return this;
if (fileStoreDataProfilesBuilder_ == null) {
if (!other.fileStoreDataProfiles_.isEmpty()) {
if (fileStoreDataProfiles_.isEmpty()) {
fileStoreDataProfiles_ = other.fileStoreDataProfiles_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureFileStoreDataProfilesIsMutable();
fileStoreDataProfiles_.addAll(other.fileStoreDataProfiles_);
}
onChanged();
}
} else {
if (!other.fileStoreDataProfiles_.isEmpty()) {
if (fileStoreDataProfilesBuilder_.isEmpty()) {
fileStoreDataProfilesBuilder_.dispose();
fileStoreDataProfilesBuilder_ = null;
fileStoreDataProfiles_ = other.fileStoreDataProfiles_;
bitField0_ = (bitField0_ & ~0x00000001);
fileStoreDataProfilesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getFileStoreDataProfilesFieldBuilder()
: null;
} else {
fileStoreDataProfilesBuilder_.addAllMessages(other.fileStoreDataProfiles_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.privacy.dlp.v2.FileStoreDataProfile m =
input.readMessage(
com.google.privacy.dlp.v2.FileStoreDataProfile.parser(), extensionRegistry);
if (fileStoreDataProfilesBuilder_ == null) {
ensureFileStoreDataProfilesIsMutable();
fileStoreDataProfiles_.add(m);
} else {
fileStoreDataProfilesBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.privacy.dlp.v2.FileStoreDataProfile> fileStoreDataProfiles_ =
java.util.Collections.emptyList();
private void ensureFileStoreDataProfilesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
fileStoreDataProfiles_ =
new java.util.ArrayList<com.google.privacy.dlp.v2.FileStoreDataProfile>(
fileStoreDataProfiles_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.privacy.dlp.v2.FileStoreDataProfile,
com.google.privacy.dlp.v2.FileStoreDataProfile.Builder,
com.google.privacy.dlp.v2.FileStoreDataProfileOrBuilder>
fileStoreDataProfilesBuilder_;
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public java.util.List<com.google.privacy.dlp.v2.FileStoreDataProfile>
getFileStoreDataProfilesList() {
if (fileStoreDataProfilesBuilder_ == null) {
return java.util.Collections.unmodifiableList(fileStoreDataProfiles_);
} else {
return fileStoreDataProfilesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public int getFileStoreDataProfilesCount() {
if (fileStoreDataProfilesBuilder_ == null) {
return fileStoreDataProfiles_.size();
} else {
return fileStoreDataProfilesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public com.google.privacy.dlp.v2.FileStoreDataProfile getFileStoreDataProfiles(int index) {
if (fileStoreDataProfilesBuilder_ == null) {
return fileStoreDataProfiles_.get(index);
} else {
return fileStoreDataProfilesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public Builder setFileStoreDataProfiles(
int index, com.google.privacy.dlp.v2.FileStoreDataProfile value) {
if (fileStoreDataProfilesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFileStoreDataProfilesIsMutable();
fileStoreDataProfiles_.set(index, value);
onChanged();
} else {
fileStoreDataProfilesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public Builder setFileStoreDataProfiles(
int index, com.google.privacy.dlp.v2.FileStoreDataProfile.Builder builderForValue) {
if (fileStoreDataProfilesBuilder_ == null) {
ensureFileStoreDataProfilesIsMutable();
fileStoreDataProfiles_.set(index, builderForValue.build());
onChanged();
} else {
fileStoreDataProfilesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public Builder addFileStoreDataProfiles(com.google.privacy.dlp.v2.FileStoreDataProfile value) {
if (fileStoreDataProfilesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFileStoreDataProfilesIsMutable();
fileStoreDataProfiles_.add(value);
onChanged();
} else {
fileStoreDataProfilesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public Builder addFileStoreDataProfiles(
int index, com.google.privacy.dlp.v2.FileStoreDataProfile value) {
if (fileStoreDataProfilesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFileStoreDataProfilesIsMutable();
fileStoreDataProfiles_.add(index, value);
onChanged();
} else {
fileStoreDataProfilesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public Builder addFileStoreDataProfiles(
com.google.privacy.dlp.v2.FileStoreDataProfile.Builder builderForValue) {
if (fileStoreDataProfilesBuilder_ == null) {
ensureFileStoreDataProfilesIsMutable();
fileStoreDataProfiles_.add(builderForValue.build());
onChanged();
} else {
fileStoreDataProfilesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public Builder addFileStoreDataProfiles(
int index, com.google.privacy.dlp.v2.FileStoreDataProfile.Builder builderForValue) {
if (fileStoreDataProfilesBuilder_ == null) {
ensureFileStoreDataProfilesIsMutable();
fileStoreDataProfiles_.add(index, builderForValue.build());
onChanged();
} else {
fileStoreDataProfilesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public Builder addAllFileStoreDataProfiles(
java.lang.Iterable<? extends com.google.privacy.dlp.v2.FileStoreDataProfile> values) {
if (fileStoreDataProfilesBuilder_ == null) {
ensureFileStoreDataProfilesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, fileStoreDataProfiles_);
onChanged();
} else {
fileStoreDataProfilesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public Builder clearFileStoreDataProfiles() {
if (fileStoreDataProfilesBuilder_ == null) {
fileStoreDataProfiles_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
fileStoreDataProfilesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public Builder removeFileStoreDataProfiles(int index) {
if (fileStoreDataProfilesBuilder_ == null) {
ensureFileStoreDataProfilesIsMutable();
fileStoreDataProfiles_.remove(index);
onChanged();
} else {
fileStoreDataProfilesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public com.google.privacy.dlp.v2.FileStoreDataProfile.Builder getFileStoreDataProfilesBuilder(
int index) {
return getFileStoreDataProfilesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public com.google.privacy.dlp.v2.FileStoreDataProfileOrBuilder
getFileStoreDataProfilesOrBuilder(int index) {
if (fileStoreDataProfilesBuilder_ == null) {
return fileStoreDataProfiles_.get(index);
} else {
return fileStoreDataProfilesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public java.util.List<? extends com.google.privacy.dlp.v2.FileStoreDataProfileOrBuilder>
getFileStoreDataProfilesOrBuilderList() {
if (fileStoreDataProfilesBuilder_ != null) {
return fileStoreDataProfilesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(fileStoreDataProfiles_);
}
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public com.google.privacy.dlp.v2.FileStoreDataProfile.Builder
addFileStoreDataProfilesBuilder() {
return getFileStoreDataProfilesFieldBuilder()
.addBuilder(com.google.privacy.dlp.v2.FileStoreDataProfile.getDefaultInstance());
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public com.google.privacy.dlp.v2.FileStoreDataProfile.Builder addFileStoreDataProfilesBuilder(
int index) {
return getFileStoreDataProfilesFieldBuilder()
.addBuilder(index, com.google.privacy.dlp.v2.FileStoreDataProfile.getDefaultInstance());
}
/**
*
*
* <pre>
* List of data profiles.
* </pre>
*
* <code>repeated .google.privacy.dlp.v2.FileStoreDataProfile file_store_data_profiles = 1;
* </code>
*/
public java.util.List<com.google.privacy.dlp.v2.FileStoreDataProfile.Builder>
getFileStoreDataProfilesBuilderList() {
return getFileStoreDataProfilesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.privacy.dlp.v2.FileStoreDataProfile,
com.google.privacy.dlp.v2.FileStoreDataProfile.Builder,
com.google.privacy.dlp.v2.FileStoreDataProfileOrBuilder>
getFileStoreDataProfilesFieldBuilder() {
if (fileStoreDataProfilesBuilder_ == null) {
fileStoreDataProfilesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.privacy.dlp.v2.FileStoreDataProfile,
com.google.privacy.dlp.v2.FileStoreDataProfile.Builder,
com.google.privacy.dlp.v2.FileStoreDataProfileOrBuilder>(
fileStoreDataProfiles_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
fileStoreDataProfiles_ = null;
}
return fileStoreDataProfilesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The next page token.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.privacy.dlp.v2.ListFileStoreDataProfilesResponse)
}
// @@protoc_insertion_point(class_scope:google.privacy.dlp.v2.ListFileStoreDataProfilesResponse)
private static final com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse();
}
public static com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListFileStoreDataProfilesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListFileStoreDataProfilesResponse>() {
@java.lang.Override
public ListFileStoreDataProfilesResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListFileStoreDataProfilesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListFileStoreDataProfilesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.privacy.dlp.v2.ListFileStoreDataProfilesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
oracle/nosql
| 38,379
|
kvmain/src/main/java/oracle/kv/impl/util/registry/ClientSocketFactory.java
|
/*-
* Copyright (C) 2011, 2025 Oracle and/or its affiliates. All rights reserved.
*
* This file was distributed by Oracle as part of a version of Oracle NoSQL
* Database made available at:
*
* http://www.oracle.com/technetwork/database/database-technologies/nosqldb/downloads/index.html
*
* Please see the LICENSE file included in the top-level directory of the
* appropriate version of Oracle NoSQL Database for a copy of the license and
* additional information.
*/
package oracle.kv.impl.util.registry;
import static oracle.kv.impl.util.ObjectUtil.checkNull;
import static oracle.kv.impl.util.SerializationUtil.readPackedInt;
import static oracle.kv.impl.util.SerializationUtil.readPackedLong;
import static oracle.kv.impl.util.SerializationUtil.readString;
import static oracle.kv.impl.util.SerializationUtil.writePackedInt;
import static oracle.kv.impl.util.SerializationUtil.writePackedLong;
import static oracle.kv.impl.util.SerializationUtil.writeString;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.rmi.server.RMIClientSocketFactory;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import oracle.kv.KVSecurityConstants;
import oracle.kv.KVStoreConfig;
import oracle.kv.impl.api.ClientId;
import oracle.kv.impl.async.AsyncOption;
import oracle.kv.impl.async.EndpointConfig;
import oracle.kv.impl.async.EndpointConfigBuilder;
import oracle.kv.impl.security.ssl.SSLConfig;
import oracle.kv.impl.util.CommonLoggerUtils;
import oracle.kv.impl.util.EmbeddedMode;
import oracle.kv.impl.util.FastExternalizable;
import oracle.kv.impl.util.SerializationUtil;
import oracle.kv.impl.util.client.ClientLoggerUtils;
import oracle.kv.impl.util.registry.RegistryUtils.InterfaceType;
/**
* An implementation of RMIClientSocketFactory that permits configuration of
* the following Socket timeouts:
* <ol>
* <li>Connection timeout</li>
* <li>Read timeout</li>
* </ol>
* These are set to allow clients to become aware of possible network problems
* in a timely manner.
* <p>
* CSFs with the appropriate timeouts for a registry are specified on the
* client side.
* <p>
* CSFs for service requests (unrelated to the registry) have default values
* provided by the server that can be overridden by the client as below:
* <ol>
* <li>Server side timeout parameters are set via the KVS admin as policy
* parameters</li>
* <li>Client side timeout parameters are set via {@link KVStoreConfig}. When
* present, they override the parameters set at the server level.</li>
* </ol>
* <p>
* Currently, read timeouts are implemented using a timer thread and the
* TimeoutTask, which periodically checks open sockets and interrupts any that
* are inactive and have exceeded their timeout period. We replaced the more
* obvious approach of using the Socket.setSoTimeout() method with this manual
* mechanism, because the socket implementation uses a poll system call to
* enforce the timeout, which was too cpu intensive.
* <p>
* The lifetime and data flow of a CSF is complex and worth noting: The CSF is
* created by the server process exporting the service object, serialized and
* sent to the registry (hosted by the SNA) when the exported object is first
* registered by the RMI server. Subsequently, it's serialized and sent out by
* the RMI registry to each RMI client that needs a handle to the exported
* object. This means that properties of the client factory, that are
* client-specific, e.g. connection local address, connection open and read
* timeouts, etc. must be set when the exported object is deserialized at the
* client in the updateAfterDeserialization method.
* <p>
* Much as with the registries recorded by {@link RegistryUtils}, this class
* needs to associate information with particular stores, and sometimes with
* specific services within those stores. The information needed consists of
* client-side parameters, including security parameters, that are used to
* configure client socket factories when they are downloaded from the server
* as part of the service endpoints stored in the registry. Lookups are
* performed using binding names (for service-specific parameters), or store
* names (for security parameters), as well as with client IDs. Both types of
* lookups are used, as well as a global default, for the same reasons
* mentioned for RegistryUtils, primarily to support tests that mix client and
* server facilities in the same process.
* <p>
* TODO: RMI does not make any provisions for request granularity timeouts, but
* now that we have implemented our own timeout mechanism, request granularity
* timeouts could be supported. If request timeouts are implemented, perhaps
* that should encompass and replace connection and request timeouts.
*
* @see #writeFastExternal FastExternalizable format
*/
public class ClientSocketFactory
implements FastExternalizable, RMIClientSocketFactory, Serializable
{
private static final long serialVersionUID = 1L;
private static volatile Logger logger = null;
/*
* Mutual exclusion object for thread-safe synchronized locking, this
* object is used to create synchronize lock for any update on sockets,
* timer and timoutTask.
*/
private static final Object mutex = new Object();
/*
* The list of sockets to check for being active. Access and modification
* of the list are synchronized, which could be a possible bottleneck if
* the list is very large.
* Any update on sockets must be wrapped in synchronized(mutex) block.
*/
private static final List<TimeoutSocket> sockets = new LinkedList<>();
/*
* RMI doesn't let you provide application level context into the
* socket factory, so the timer and timeout tasks which implement socket
* timeouts are static, rather than scoped per NoSQL DB service or per
* RequestDispatcher.
* Only initialize timer and timeoutTask when socket is created. Free
* these two objects when there is no active socket. This prevents the
* JVM from holding an idle thread doing nothing.
* Any update on timer and timeoutTask must be wrapped in
* synchronized(mutex) block.
*/
private static Timer timer = null;
private static volatile TimeoutTask timeoutTask = null;
/*
* The default timer interval in milliseconds.
* This value should only be changed during testing.
*/
private static long defaultTimerIntervalMs =
TimeoutTask.DEFAULT_TIMER_INTERVAL_MS;
/* Counts of the allocated sockets and socket factories, for unit testing */
protected transient volatile AtomicInteger socketCount =
new AtomicInteger(0);
protected static final AtomicInteger socketFactoryCount =
new AtomicInteger(0);
/**
* Map from service name and client ID to any (optional) client side
* overrides of the default timeout period.
*/
private static final Map<ServiceKey, SocketTimeouts> serviceToTimeoutsMap =
new ConcurrentHashMap<>();
/**
* Map from service name and client ID to the local interface to be used
* for communications with the store. If no entry is present, uses the
* default local interface.
*/
private static final Map<ServiceKey, InetSocketAddress>
serviceToLocalAddrMap = new ConcurrentHashMap<>();
/*
* The generation into which new ClientSocketFactories are being born.
*/
private static final AtomicInteger currCsfGeneration = new AtomicInteger(0);
/*
* The ID generator for newly minted ClientSocketFactories.
*/
private static final AtomicLong nextCsfId =
new AtomicLong(System.nanoTime());
/*
* The RMI socket policy used for general client access. Synchronize on
* the class when accessing this field.
*/
private static RMISocketPolicy clientPolicy;
/*
* The SSLConfig used to generate the last SSL socket policy, or null if
* not using SSL. Synchronize on the class when accessing this field.
*/
private static SSLConfig sslConfig;
/**
* The client ID of the caller for use during deserialization, or null if
* called in a server context. The value is specified as a thread local
* because there is no way to pass it directly during deserialization and,
* unlike the store name, the value is not available on the server side
* when the factory is serialized.
*/
private static final ThreadLocal<ClientId> currentClientId =
new ThreadLocal<>();
/**
* A logger to use for debugging, for cases where we don't have access to
* the real logger.
*/
private static final Logger localDebugLogger =
ClientLoggerUtils.getLogger(ClientSocketFactory.class, "debugging");
/* The name associated with the CSF. */
protected final String name;
protected volatile int connectTimeoutMs;
protected volatile int readTimeoutMs;
/**
* The client ID or null in a server context. The value is specified in the
* constructor on the client side or is set during deserialization from
* the value of currentClientId.
*/
protected transient volatile ClientId clientId;
/*
* The "generation" at which this CSF was born, as viewed from the client
* side of the world. ClientSocketFactories of different generation never
* compare equal.
*/
private transient volatile int csfGeneration;
/*
* The "id" at which this CSF as viewed from the server side of the world.
* ClientSocketFactories with different id values never compare equal.
*/
private final long csfId;
/*
* The local address on this machine to which the connection is bound, or
* null for the default. This value is only set when the CSF instance is
* deserialized at the client, since the value is client-specific and
* cannot be a non-transient iv in the CSF itself. The non-null value is
* used to select from among multiple TCP network interfaces.
*/
private transient InetSocketAddress localAddr;
/**
* Creates the client socket factory.
*
* @param name the factory name
* @param connectTimeoutMs the connect timeout. A zero value denotes an
* infinite timeout
* @param readTimeoutMs the read timeout associated with the connection.
* A zero value denotes an infinite timeout
* @param clientId the client ID or null in a server context
*/
public ClientSocketFactory(String name,
int connectTimeoutMs,
int readTimeoutMs,
ClientId clientId) {
this(name, connectTimeoutMs, readTimeoutMs, clientId,
nextCsfId.getAndIncrement());
}
/**
* Create a client socket factory and specify the CSF ID, for testing.
*/
public ClientSocketFactory(String name,
int connectTimeoutMs,
int readTimeoutMs,
ClientId clientId,
long csfId) {
this.name = name;
this.connectTimeoutMs = connectTimeoutMs;
this.readTimeoutMs = readTimeoutMs;
this.clientId = clientId;
this.csfGeneration = currCsfGeneration.get();
this.csfId = csfId;
}
/**
* Creates an instance using data from an input stream.
*/
protected ClientSocketFactory(DataInput in, short serialVersion)
throws IOException {
name = readString(in, serialVersion);
connectTimeoutMs = readPackedInt(in);
readTimeoutMs = readPackedInt(in);
csfId = readPackedLong(in);
updateAfterDeserialization();
}
/*
* Force the start of a new generation on the client side.
*/
public static void newGeneration() {
currCsfGeneration.incrementAndGet();
}
/**
* For testing only. Need to be careful, update on the sockets needs to be
* thread-safe. This not guaranteed when the test code updates the sockets.
*/
static List<TimeoutSocket> getSockets() {
return sockets;
}
/**
* Generates a factory name that is unique for each KVS, component and
* service to facilitate timeouts at service granularity.
*
* @param kvsName the store name
* @param compName the component name, the string sn, rn, etc.
* @param interfaceName the interface name
* {@link InterfaceType#interfaceName()}
*
* @return the name to be used for a factory
*/
public static String factoryName(String kvsName,
String compName,
String interfaceName) {
return kvsName + '|' + compName + '|' + interfaceName;
}
/**
* The factory name associated with the SNA's registry.
*/
public static String registryFactoryName() {
return "registry";
}
public String getBindingName() {
return name;
}
public int getConnectTimeoutMs() {
return connectTimeoutMs;
}
public int getReadTimeoutMs() {
return readTimeoutMs;
}
public ClientId getClientId() {
return clientId;
}
public InetSocketAddress getLocalAddr() {
return localAddr;
}
/**
* Returns the number of sockets that have been allocated so far.
*/
public int getSocketCount() {
return socketCount.get();
}
public static int getSocketFactoryCount() {
return socketFactoryCount.get();
}
public static void setSocketFactoryCount(int count) {
socketFactoryCount.set(count);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result +
((name == null) ? 0 : name.hashCode());
result = prime * result + connectTimeoutMs;
result = prime * result + readTimeoutMs;
result = prime * result +
((localAddr == null) ? 0 : localAddr.hashCode());
result = prime * result + (int) csfId;
result = prime * result + csfGeneration;
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("<");
sb.append(getClass().getSimpleName());
getToStringBody(sb);
sb.append(">");
return sb.toString();
}
protected void getToStringBody(StringBuilder sb) {
sb.append(" name=").append(name);
sb.append(" id=").append(hashCode());
sb.append(" connectMs=").append(connectTimeoutMs);
sb.append(" readMs=").append(readTimeoutMs);
sb.append(" clientId=").append(clientId == null ? "none" : clientId);
sb.append(" localAddr=").append(
(localAddr == null) ? "none" : localAddr);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ClientSocketFactory other = (ClientSocketFactory) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (connectTimeoutMs != other.connectTimeoutMs) {
return false;
}
if (readTimeoutMs != other.readTimeoutMs) {
return false;
}
if (localAddr == null) {
if (other.localAddr != null) {
return false;
}
} else if (!localAddr.equals(other.localAddr)) {
return false;
}
if (csfGeneration != other.csfGeneration) {
return false;
}
if (csfId != other.csfId) {
return false;
}
return true;
}
/**
* Read the object and override the server supplied default timeout values
* with any client side timeouts.
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
updateAfterDeserialization();
}
private void updateAfterDeserialization() {
/* Reset the generation for the client side */
csfGeneration = currCsfGeneration.get();
/* Store the current client ID */
clientId = getCurrentClientId();
if ((name == null) && (clientId == null)) {
/* use the defaults. */
return;
}
/* Override defaults, if necessary, with client side timeout settings.*/
SocketTimeouts timeouts =
getFromServiceMap(name, clientId, serviceToTimeoutsMap);
if (timeouts != null) {
connectTimeoutMs = timeouts.connectTimeoutMs;
readTimeoutMs = timeouts.readTimeoutMs;
}
localAddr = getFromServiceMap(name, clientId, serviceToLocalAddrMap);
socketCount = new AtomicInteger();
socketFactoryCount.incrementAndGet();
}
/*
* Cancel the TimeoutTask and terminate the timer thread
*/
private static void terminateTimer() {
synchronized (mutex) {
if (timeoutTask != null) {
timeoutTask.cancel();
timeoutTask = null;
}
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
/**
* Writes this object to the output stream. Format:
* <ol>
* <li> ({@link SerializationUtil#writeString String}) {@link
* #getBindingName name}
* <li> ({@link SerializationUtil#writePackedInt packed int}) {@link
* #getConnectTimeoutMs connectTimeoutMs}
* <li> ({@link SerializationUtil#writePackedInt packed int}) {@link
* #getReadTimeoutMs readTimeoutMs}
* <li> ({@link SerializationUtil#writePackedLong} packed long}
* <i>csfId</i>
* </ol>
*/
@Override
public void writeFastExternal(DataOutput out, short serialVersion)
throws IOException {
writeString(out, serialVersion, name);
writePackedInt(out, connectTimeoutMs);
writePackedInt(out, readTimeoutMs);
writePackedLong(out, csfId);
}
/**
* @see java.rmi.server.RMIClientSocketFactory#createSocket
*/
@Override
public Socket createSocket(String host, int port)
throws java.net.UnknownHostException, IOException {
return createTimeoutSocket(host, port);
}
protected TimeoutSocket createTimeoutSocket(String host, int port)
throws java.net.UnknownHostException, IOException {
/*
* Use a TimeoutSocket rather than a vanilla socket and
* Socket.setSoTimeout(). The latter is implemented using a poll system
* call, which is too cpu intensive.
*/
final TimeoutSocket sock = new TimeoutSocket(readTimeoutMs);
sock.bind(localAddr);
sock.connect(new InetSocketAddress(host, port), connectTimeoutMs);
/* Disable Nagle's algorithm to minimize request latency. */
sock.setTcpNoDelay(true);
socketCount.incrementAndGet();
synchronized (mutex) {
/*
* Start the timer thread if it's not started yet
*/
if (timeoutTask == null) {
timeoutTask = new TimeoutTask(defaultTimerIntervalMs);
}
/*
* Register the socket regardless of its readTimeoutMS value, because
* the default server supplied timeouts may be overridden in
* readObject() with client side timeouts.
*
* Register only after the connect has been successful to ensure the
* socket object is not leaked.
*/
timeoutTask.register(sock);
}
return sock;
}
/**
* Note this configuration for use by any future client socket factories.
* Existing socket factories cannot be changed, since it would break
* the hash code and equals methods, preventing RMI from locating and using
* socket factories it had cached.
*
* @param bindingName the binding name associated with this interface
* in the registry.
* @param config the store config parameters, a subset of which is relevant
* to the CSF's client side configuration.
* @param clientId the client ID of the caller or null if called in a
* server context
*/
public static void configure(String bindingName,
KVStoreConfig config,
ClientId clientId) {
checkNull("bindingName", bindingName);
final long requestTimeoutMs =
config.getRequestTimeout(TimeUnit.MILLISECONDS);
final long readTimeoutMs =
config.getSocketReadTimeout(TimeUnit.MILLISECONDS);
if (!config.getUseAsync() && (requestTimeoutMs > readTimeoutMs)) {
final String format = "Invalid KVStoreConfig. " +
"Request timeout: %,d ms exceeds " +
"socket read timeout: %,d ms" ;
throw new IllegalArgumentException
(String.format(format, requestTimeoutMs, readTimeoutMs));
}
final int openTimeoutMs =
(int) config.getSocketOpenTimeout(TimeUnit.MILLISECONDS);
putIntoServiceMap(bindingName, clientId,
new SocketTimeouts(openTimeoutMs,
(int) readTimeoutMs),
serviceToTimeoutsMap);
if (config.getLocalAddress() != null) {
putIntoServiceMap(bindingName, clientId, config.getLocalAddress(),
serviceToLocalAddrMap);
}
}
/**
* Clears out the configuration done by {@link #configure}).
*
* This method is for test use only.
*/
public static void clearConfiguration() {
serviceToTimeoutsMap.clear();
serviceToLocalAddrMap.clear();
}
/**
* Returns the size of serviceToTimeoutsMap, for testing.
*/
public static int getServiceToTimeoutsMapSize() {
return serviceToTimeoutsMap.size();
}
/**
* Clears out service entries added by {@link #configure} associated with a
* client ID for a KVStoreImpl that is being shutdown.
*
* @clientId the client ID of the KVStoreImpl
*/
public static void clearConfiguration(ClientId clientId) {
checkNull("clientId", clientId);
clearClientIdFromServiceMap(clientId, serviceToTimeoutsMap);
clearClientIdFromServiceMap(clientId, serviceToLocalAddrMap);
final RMISocketPolicy policy = getRMIPolicy();
if (policy != null) {
policy.clearPreparedClient(clientId);
}
}
/**
* Just a simple struct to hold timeouts.
*/
private static class SocketTimeouts {
private final int connectTimeoutMs;
private final int readTimeoutMs;
SocketTimeouts(int connectTimeoutMs, int readTimeoutMs) {
super();
this.connectTimeoutMs = connectTimeoutMs;
this.readTimeoutMs = readTimeoutMs;
}
}
/**
* Set a logger to be used by the static TimeoutTask, to report socket read
* timeouts.
*/
public static void setTimeoutLogger(Logger logger) {
ClientSocketFactory.logger = logger;
}
/**
* Set transport information for KVStore client access where the client
* does not need to manage connections to multiple stores concurrently.
*
* @throws IllegalStateException if the configuration is bad
* @throws IllegalArgumentException if the transport is not supported
*/
public static void setRMIPolicy(Properties securityProps) {
setRMIPolicy(securityProps, null, null);
}
/**
* Set transport information for KVStore client access.
* @throws IllegalStateException if the configuration is bad
* @throws IllegalArgumentException if the transport is not supported
*/
public static synchronized void setRMIPolicy(Properties securityProps,
String storeName,
ClientId clientId) {
final String transportName = (securityProps == null) ? null :
securityProps.getProperty(KVSecurityConstants.TRANSPORT_PROPERTY);
if ("internal".equals(transportName)) {
/*
* INTERNAL transport is a signal that the currently installed
* transport configuration should be used.
*/
return;
}
sslConfig = null;
if ("ssl".equals(transportName)) {
sslConfig = new SSLConfig(securityProps);
clientPolicy = sslConfig.makeClientSocketPolicy(localDebugLogger);
} else if (transportName == null || "clear".equals(transportName)) {
clientPolicy = new ClearSocketPolicy();
} else {
throw new IllegalArgumentException(
"Transport " + transportName + " is not supported.");
}
clientPolicy.prepareClient(storeName, clientId);
}
/**
* Set transport information for non-KVStore access.
*/
public static synchronized void setRMIPolicy(RMISocketPolicy policy) {
clientPolicy = policy;
clientPolicy.prepareClient(null, null);
}
private static synchronized RMISocketPolicy getRMIPolicy() {
return clientPolicy;
}
public static synchronized RMISocketPolicy ensureRMISocketPolicy() {
RMISocketPolicy policy = getRMIPolicy();
if (policy == null) {
setRMIPolicy(new ClearSocketPolicy());
}
return clientPolicy;
}
/**
* Reset RMI socket policy with current SSL configuration in order to
* reload the entries of keystore and truststore.
*/
public static synchronized RMISocketPolicy resetRMISocketPolicy(
String storeName, ClientId clientId, Logger debugLogger) {
if (sslConfig != null) {
clientPolicy = sslConfig.makeClientSocketPolicy(debugLogger);
clientPolicy.prepareClient(storeName, clientId);
}
return clientPolicy;
}
/**
* Return an {@link EndpointConfig} object that represents the
* configuration of sockets created by this factory.
*
* @return the configuration
* @throws IOException if there is a problem creating the configuration
*/
public final EndpointConfig getEndpointConfig()
throws IOException {
return getEndpointConfigBuilder().build();
}
/**
* Returns a new {@link EndpointConfigBuilder} that can be used to create
* an {@link EndpointConfig} that represents the configuration of sockets
* created by this factory.
*
* @return the configuration
* @throws IOException if there is a problem creating the configuration
* builder
*/
/*
* Suppress warning about unused IOException, since we need it for
* subclasses
*/
@SuppressWarnings("unused")
public EndpointConfigBuilder getEndpointConfigBuilder()
throws IOException {
return getEndpointConfigBuilder(connectTimeoutMs, readTimeoutMs);
}
/**
* Returns a new {@link EndpointConfigBuilder} that can be used to create
* an {@link EndpointConfig} that reflects the specified connect and read
* timeouts. The read timeout value is not currently used.
*
* @param connectTimeoutMs the socket connect timeout in milliseconds
* @param readTimeoutMs the socket read timeout in milliseconds
* @return the configuration
*/
public static EndpointConfigBuilder
getEndpointConfigBuilder(int connectTimeoutMs,
int readTimeoutMs)
{
/* Socket factories use 0 to mean an infinite timeout */
if (connectTimeoutMs <= 0) {
connectTimeoutMs = Integer.MAX_VALUE;
}
/*
* Use the defaults for the heartbeat timeout, heartbeat interval, and
* idle timeout. The values had previously depended on the read
* timeout, which in effect represents the request timeout, but it
* seems better to make them independent. We want to use heartbeats
* even if the read timeout is long, and it's not clear why they should
* be shorter if the read timeout is short.
*/
return new EndpointConfigBuilder()
.option(AsyncOption.DLG_CONNECT_TIMEOUT, connectTimeoutMs);
}
/**
* Change the timer interval -- for testing. If the argument is 0, resets
* to the default interval.
*/
public static void changeTimerInterval(long intervalMs) {
synchronized (mutex) {
if (timeoutTask != null) {
timeoutTask.cancel();
}
defaultTimerIntervalMs = (intervalMs != 0) ?
intervalMs :
TimeoutTask.DEFAULT_TIMER_INTERVAL_MS;
timeoutTask = new TimeoutTask(defaultTimerIntervalMs);
}
}
/**
* The TimeoutTask checks all sockets registered with it to ensure that
* they are active. The period roughly corresponds to a second, although
* intervening GC activity may expand this period considerably. Note that
* elapsedMs used for timeouts is always ticked up in 1 second
* increments. Thus multiple seconds of real time may correspond to a
* single second of "timer time" if the system is particularly busy, or the
* gc has been particularly active.
*
* This property allows the underlying timeout implementation to compensate
* for GC pauses in which activity on the socket at the java level would
* have been suspended and thus reduces the number of false timeouts.
*
* The task maintains a list of all the sockets which it is monitoring.
* Access and modification of the list are synchronized, which
* introduces a possible bottleneck and scalability issue if the list
* becomes large. In that case, a more concurrent data structure could be
* used.
* TODO: TimeoutTask is very similar to
* com.sleepycat.je.rep.impl.node.ChannelTimeoutTask. In the future,
* contemplate refactoring for common code.
*/
private static class TimeoutTask extends TimerTask {
private static final long DEFAULT_TIMER_INTERVAL_MS = 1000L;
private final long intervalMs;
/*
* Elapsed time as measured by the timer task. It's always incremented
* by intervalMs, which defaults to one second.
*/
private long elapsedMs = 0;
/** Creates and schedules the timer task for the specified interval. */
TimeoutTask(final long intervalMs) {
this.intervalMs = intervalMs;
synchronized (mutex) {
if (timer == null) {
timer = new Timer("KVClientSocketTimeout", true);
}
timer.schedule(this, intervalMs, intervalMs);
}
}
/**
* Runs once each interval to check if a socket is still active. Each
* socket establishes its own timeout period using elapsedMs to check
* for timeouts. Inactive sockets are removed from the list of
* registered sockets.
*/
@Override
public void run() {
elapsedMs += intervalMs;
try {
synchronized (mutex) {
/* If there is no active socket, terminate the timer thread
* The socket will be closed when
* 1. read timeout
* 2. socket idle for 15 seconds
* This default value is controlled by
* sun.rmi.transport.connectionTimeout system property
* 3. Other exceptions
*/
if (sockets.isEmpty()) {
/*
* Terminate timer thread within the run function
* guarantees that the ongoing task execution is the
* last task execution that will ever be performed by
* this timer.
*/
terminateTimer();
return;
}
sockets.removeIf(
socket -> !socket.isActive(elapsedMs, logger));
}
} catch (Throwable t) {
/*
* The task is executed by a simple Timer, so this catch
* attempts to act as a sort of unexpected exception handler.
*/
final String message = "ClientSocketFactory.TimerTask: " +
CommonLoggerUtils.getStackTrace(t);
if (logger != null) {
logger.severe(message);
} else if (!EmbeddedMode.isEmbedded()){
System.err.println(message);
}
}
}
/**
* Registers a socket so that the timer can make periodic calls to
* isActive(). Note that closing a socket renders it inactive and
* causes it to be removed from the list by the run()
* method. Consequently, there is no corresponding unregister
* operation.
*
* Registration will block when the actual timeout check, from the run()
* method, are executing. Be aware of this potential bottleneck on
* socket opens.
*
* @param socket the socket being registered.
*/
public void register(TimeoutSocket socket) {
if ((logger != null) && logger.isLoggable(Level.FINE)) {
logger.fine("Registering " + socket +
" onto timeout monitoring list. " +
sockets.size() + " sockets currently registered");
}
synchronized (mutex) {
sockets.add(socket);
}
}
}
/**
* Returns the current client Id.
*/
public static ClientId getCurrentClientId() {
return currentClientId.get();
}
/**
* Sets the current client ID.
*
* @param clientId the client ID
*/
public static void setCurrentClientId(ClientId clientId) {
currentClientId.set(clientId);
}
/**
* Look up a service entry by binding name and client ID.
*/
private static <V> V getFromServiceMap(String name,
ClientId clientId,
Map<ServiceKey, V> map) {
V v = map.get(new ServiceKey(name, clientId));
if (v != null) {
return v;
}
/*
* Unless both fields are non-null, there is only one key that has at
* least one non-null field, so we are done.
*/
if ((name == null) || (clientId == null)) {
return null;
}
/* Client IDs are unique, so look up by client ID before store name */
v = map.get(new ServiceKey(null, clientId));
if (v != null) {
return v;
}
return map.get(new ServiceKey(name, null));
}
/**
* Add a service entry by binding name and client ID.
*/
private static <V> void putIntoServiceMap(String name,
ClientId clientId,
V value,
Map<ServiceKey, V> map) {
map.put(new ServiceKey(name, clientId), value);
if ((name != null) && (clientId != null)) {
map.put(new ServiceKey(name, null), value);
map.put(new ServiceKey(null, clientId), value);
}
}
/**
* Clear service entries associated with the specified client ID.
*/
private static <V> void clearClientIdFromServiceMap(
ClientId clientId, Map<ServiceKey, V> map) {
final Iterator<ServiceKey> keys = map.keySet().iterator();
while (keys.hasNext()) {
final ServiceKey key = keys.next();
if (clientId.equals(key.clientId)) {
keys.remove();
}
}
}
private static class ServiceKey {
final String bindingName;
final ClientId clientId;
ServiceKey(String bindingName, ClientId clientId) {
this.bindingName = bindingName;
this.clientId = clientId;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ServiceKey)) {
return false;
}
final ServiceKey other = (ServiceKey) obj;
return Objects.equals(bindingName, other.bindingName) &&
Objects.equals(clientId, other.clientId);
}
@Override
public int hashCode() {
return Objects.hash(bindingName, clientId);
}
@Override
public String toString() {
return "CSFServiceKey[" + bindingName + "," + clientId + "]";
}
}
}
|
apache/servicemix-bundles
| 37,313
|
xalan-2.7.3/src/main/java/org/apache/xalan/xsltc/compiler/FunctionCall.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: FunctionCall.java 468650 2006-10-28 07:03:30Z minchau $
*/
package org.apache.xalan.xsltc.compiler;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.IFEQ;
import org.apache.bcel.generic.INVOKEINTERFACE;
import org.apache.bcel.generic.INVOKESPECIAL;
import org.apache.bcel.generic.INVOKESTATIC;
import org.apache.bcel.generic.INVOKEVIRTUAL;
import org.apache.bcel.generic.InstructionConstants;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.LocalVariableGen;
import org.apache.bcel.generic.NEW;
import org.apache.bcel.generic.PUSH;
import org.apache.xalan.xsltc.compiler.util.BooleanType;
import org.apache.xalan.xsltc.compiler.util.ClassGenerator;
import org.apache.xalan.xsltc.compiler.util.ErrorMsg;
import org.apache.xalan.xsltc.compiler.util.IntType;
import org.apache.xalan.xsltc.compiler.util.MethodGenerator;
import org.apache.xalan.xsltc.compiler.util.MethodType;
import org.apache.xalan.xsltc.compiler.util.MultiHashtable;
import org.apache.xalan.xsltc.compiler.util.ObjectType;
import org.apache.xalan.xsltc.compiler.util.ReferenceType;
import org.apache.xalan.xsltc.compiler.util.Type;
import org.apache.xalan.xsltc.compiler.util.TypeCheckError;
/**
* @author Jacek Ambroziak
* @author Santiago Pericas-Geertsen
* @author Morten Jorgensen
* @author Erwin Bolwidt <ejb@klomp.org>
* @author Todd Miller
*/
class FunctionCall extends Expression {
// Name of this function call
private QName _fname;
// Arguments to this function call (might not be any)
private final Vector _arguments;
// Empty argument list, used for certain functions
private final static Vector EMPTY_ARG_LIST = new Vector(0);
// Valid namespaces for Java function-call extension
protected final static String EXT_XSLTC =
TRANSLET_URI;
protected final static String JAVA_EXT_XSLTC =
EXT_XSLTC + "/java";
protected final static String EXT_XALAN =
"http://xml.apache.org/xalan";
protected final static String JAVA_EXT_XALAN =
"http://xml.apache.org/xalan/java";
protected final static String JAVA_EXT_XALAN_OLD =
"http://xml.apache.org/xslt/java";
protected final static String EXSLT_COMMON =
"http://exslt.org/common";
protected final static String EXSLT_MATH =
"http://exslt.org/math";
protected final static String EXSLT_SETS =
"http://exslt.org/sets";
protected final static String EXSLT_DATETIME =
"http://exslt.org/dates-and-times";
protected final static String EXSLT_STRINGS =
"http://exslt.org/strings";
// Namespace format constants
protected final static int NAMESPACE_FORMAT_JAVA = 0;
protected final static int NAMESPACE_FORMAT_CLASS = 1;
protected final static int NAMESPACE_FORMAT_PACKAGE = 2;
protected final static int NAMESPACE_FORMAT_CLASS_OR_PACKAGE = 3;
// Namespace format
private int _namespace_format = NAMESPACE_FORMAT_JAVA;
/**
* Stores reference to object for non-static Java calls
*/
Expression _thisArgument = null;
// External Java function's class/method/signature
private String _className;
private Class _clazz;
private Method _chosenMethod;
private Constructor _chosenConstructor;
private MethodType _chosenMethodType;
// Encapsulates all unsupported external function calls
private boolean unresolvedExternal;
// If FunctionCall is a external java constructor
private boolean _isExtConstructor = false;
// If the java method is static
private boolean _isStatic = false;
// Legal conversions between internal and Java types.
private static final MultiHashtable _internal2Java = new MultiHashtable();
// Legal conversions between Java and internal types.
private static final Hashtable _java2Internal = new Hashtable();
// The mappings between EXSLT extension namespaces and implementation classes
private static final Hashtable _extensionNamespaceTable = new Hashtable();
// Extension functions that are implemented in BasisLibrary
private static final Hashtable _extensionFunctionTable = new Hashtable();
/**
* inner class to used in internal2Java mappings, contains
* the Java type and the distance between the internal type and
* the Java type.
*/
static class JavaType {
public Class type;
public int distance;
public JavaType(Class type, int distance){
this.type = type;
this.distance = distance;
}
public boolean equals(Object query){
return query.equals(type);
}
}
/**
* Defines 2 conversion tables:
* 1. From internal types to Java types and
* 2. From Java types to internal types.
* These two tables are used when calling external (Java) functions.
*/
static {
try {
final Class nodeClass = Class.forName("org.w3c.dom.Node");
final Class nodeListClass = Class.forName("org.w3c.dom.NodeList");
// -- Internal to Java --------------------------------------------
// Type.Boolean -> { boolean(0), Boolean(1), Object(2) }
_internal2Java.put(Type.Boolean, new JavaType(Boolean.TYPE, 0));
_internal2Java.put(Type.Boolean, new JavaType(Boolean.class, 1));
_internal2Java.put(Type.Boolean, new JavaType(Object.class, 2));
// Type.Real -> { double(0), Double(1), float(2), long(3), int(4),
// short(5), byte(6), char(7), Object(8) }
_internal2Java.put(Type.Real, new JavaType(Double.TYPE, 0));
_internal2Java.put(Type.Real, new JavaType(Double.class, 1));
_internal2Java.put(Type.Real, new JavaType(Float.TYPE, 2));
_internal2Java.put(Type.Real, new JavaType(Long.TYPE, 3));
_internal2Java.put(Type.Real, new JavaType(Integer.TYPE, 4));
_internal2Java.put(Type.Real, new JavaType(Short.TYPE, 5));
_internal2Java.put(Type.Real, new JavaType(Byte.TYPE, 6));
_internal2Java.put(Type.Real, new JavaType(Character.TYPE, 7));
_internal2Java.put(Type.Real, new JavaType(Object.class, 8));
// Type.Int must be the same as Type.Real
_internal2Java.put(Type.Int, new JavaType(Double.TYPE, 0));
_internal2Java.put(Type.Int, new JavaType(Double.class, 1));
_internal2Java.put(Type.Int, new JavaType(Float.TYPE, 2));
_internal2Java.put(Type.Int, new JavaType(Long.TYPE, 3));
_internal2Java.put(Type.Int, new JavaType(Integer.TYPE, 4));
_internal2Java.put(Type.Int, new JavaType(Short.TYPE, 5));
_internal2Java.put(Type.Int, new JavaType(Byte.TYPE, 6));
_internal2Java.put(Type.Int, new JavaType(Character.TYPE, 7));
_internal2Java.put(Type.Int, new JavaType(Object.class, 8));
// Type.String -> { String(0), Object(1) }
_internal2Java.put(Type.String, new JavaType(String.class, 0));
_internal2Java.put(Type.String, new JavaType(Object.class, 1));
// Type.NodeSet -> { NodeList(0), Node(1), Object(2), String(3) }
_internal2Java.put(Type.NodeSet, new JavaType(nodeListClass, 0));
_internal2Java.put(Type.NodeSet, new JavaType(nodeClass, 1));
_internal2Java.put(Type.NodeSet, new JavaType(Object.class, 2));
_internal2Java.put(Type.NodeSet, new JavaType(String.class, 3));
// Type.Node -> { Node(0), NodeList(1), Object(2), String(3) }
_internal2Java.put(Type.Node, new JavaType(nodeListClass, 0));
_internal2Java.put(Type.Node, new JavaType(nodeClass, 1));
_internal2Java.put(Type.Node, new JavaType(Object.class, 2));
_internal2Java.put(Type.Node, new JavaType(String.class, 3));
// Type.ResultTree -> { NodeList(0), Node(1), Object(2), String(3) }
_internal2Java.put(Type.ResultTree, new JavaType(nodeListClass, 0));
_internal2Java.put(Type.ResultTree, new JavaType(nodeClass, 1));
_internal2Java.put(Type.ResultTree, new JavaType(Object.class, 2));
_internal2Java.put(Type.ResultTree, new JavaType(String.class, 3));
_internal2Java.put(Type.Reference, new JavaType(Object.class, 0));
// Possible conversions between Java and internal types
_java2Internal.put(Boolean.TYPE, Type.Boolean);
_java2Internal.put(Void.TYPE, Type.Void);
_java2Internal.put(Character.TYPE, Type.Real);
_java2Internal.put(Byte.TYPE, Type.Real);
_java2Internal.put(Short.TYPE, Type.Real);
_java2Internal.put(Integer.TYPE, Type.Real);
_java2Internal.put(Long.TYPE, Type.Real);
_java2Internal.put(Float.TYPE, Type.Real);
_java2Internal.put(Double.TYPE, Type.Real);
_java2Internal.put(String.class, Type.String);
_java2Internal.put(Object.class, Type.Reference);
// Conversions from org.w3c.dom.Node/NodeList to internal NodeSet
_java2Internal.put(nodeListClass, Type.NodeSet);
_java2Internal.put(nodeClass, Type.NodeSet);
// Initialize the extension namespace table
_extensionNamespaceTable.put(EXT_XALAN, "org.apache.xalan.lib.Extensions");
_extensionNamespaceTable.put(EXSLT_COMMON, "org.apache.xalan.lib.ExsltCommon");
_extensionNamespaceTable.put(EXSLT_MATH, "org.apache.xalan.lib.ExsltMath");
_extensionNamespaceTable.put(EXSLT_SETS, "org.apache.xalan.lib.ExsltSets");
_extensionNamespaceTable.put(EXSLT_DATETIME, "org.apache.xalan.lib.ExsltDatetime");
_extensionNamespaceTable.put(EXSLT_STRINGS, "org.apache.xalan.lib.ExsltStrings");
// Initialize the extension function table
_extensionFunctionTable.put(EXSLT_COMMON + ":nodeSet", "nodeset");
_extensionFunctionTable.put(EXSLT_COMMON + ":objectType", "objectType");
_extensionFunctionTable.put(EXT_XALAN + ":nodeset", "nodeset");
}
catch (ClassNotFoundException e) {
System.err.println(e);
}
}
public FunctionCall(QName fname, Vector arguments) {
_fname = fname;
_arguments = arguments;
_type = null;
}
public FunctionCall(QName fname) {
this(fname, EMPTY_ARG_LIST);
}
public String getName() {
return(_fname.toString());
}
public void setParser(Parser parser) {
super.setParser(parser);
if (_arguments != null) {
final int n = _arguments.size();
for (int i = 0; i < n; i++) {
final Expression exp = (Expression)_arguments.elementAt(i);
exp.setParser(parser);
exp.setParent(this);
}
}
}
public String getClassNameFromUri(String uri)
{
String className = (String)_extensionNamespaceTable.get(uri);
if (className != null)
return className;
else {
if (uri.startsWith(JAVA_EXT_XSLTC)) {
int length = JAVA_EXT_XSLTC.length() + 1;
return (uri.length() > length) ? uri.substring(length) : EMPTYSTRING;
}
else if (uri.startsWith(JAVA_EXT_XALAN)) {
int length = JAVA_EXT_XALAN.length() + 1;
return (uri.length() > length) ? uri.substring(length) : EMPTYSTRING;
}
else if (uri.startsWith(JAVA_EXT_XALAN_OLD)) {
int length = JAVA_EXT_XALAN_OLD.length() + 1;
return (uri.length() > length) ? uri.substring(length) : EMPTYSTRING;
}
else {
int index = uri.lastIndexOf('/');
return (index > 0) ? uri.substring(index+1) : uri;
}
}
}
/**
* Type check a function call. Since different type conversions apply,
* type checking is different for standard and external (Java) functions.
*/
public Type typeCheck(SymbolTable stable)
throws TypeCheckError
{
if (_type != null) return _type;
final String namespace = _fname.getNamespace();
String local = _fname.getLocalPart();
if (isExtension()) {
_fname = new QName(null, null, local);
return typeCheckStandard(stable);
}
else if (isStandard()) {
return typeCheckStandard(stable);
}
// Handle extension functions (they all have a namespace)
else {
try {
_className = getClassNameFromUri(namespace);
final int pos = local.lastIndexOf('.');
if (pos > 0) {
_isStatic = true;
if (_className != null && _className.length() > 0) {
_namespace_format = NAMESPACE_FORMAT_PACKAGE;
_className = _className + "." + local.substring(0, pos);
}
else {
_namespace_format = NAMESPACE_FORMAT_JAVA;
_className = local.substring(0, pos);
}
_fname = new QName(namespace, null, local.substring(pos + 1));
}
else {
if (_className != null && _className.length() > 0) {
try {
_clazz = ObjectFactory.findProviderClass(
_className, ObjectFactory.findClassLoader(), true);
_namespace_format = NAMESPACE_FORMAT_CLASS;
}
catch (ClassNotFoundException e) {
_namespace_format = NAMESPACE_FORMAT_PACKAGE;
}
}
else
_namespace_format = NAMESPACE_FORMAT_JAVA;
if (local.indexOf('-') > 0) {
local = replaceDash(local);
}
String extFunction = (String)_extensionFunctionTable.get(namespace + ":" + local);
if (extFunction != null) {
_fname = new QName(null, null, extFunction);
return typeCheckStandard(stable);
}
else
_fname = new QName(namespace, null, local);
}
return typeCheckExternal(stable);
}
catch (TypeCheckError e) {
ErrorMsg errorMsg = e.getErrorMsg();
if (errorMsg == null) {
final String name = _fname.getLocalPart();
errorMsg = new ErrorMsg(ErrorMsg.METHOD_NOT_FOUND_ERR, name);
}
getParser().reportError(ERROR, errorMsg);
return _type = Type.Void;
}
}
}
/**
* Type check a call to a standard function. Insert CastExprs when needed.
* If as a result of the insertion of a CastExpr a type check error is
* thrown, then catch it and re-throw it with a new "this".
*/
public Type typeCheckStandard(SymbolTable stable) throws TypeCheckError {
_fname.clearNamespace(); // HACK!!!
final int n = _arguments.size();
final Vector argsType = typeCheckArgs(stable);
final MethodType args = new MethodType(Type.Void, argsType);
final MethodType ptype =
lookupPrimop(stable, _fname.getLocalPart(), args);
if (ptype != null) {
for (int i = 0; i < n; i++) {
final Type argType = (Type) ptype.argsType().elementAt(i);
final Expression exp = (Expression)_arguments.elementAt(i);
if (!argType.identicalTo(exp.getType())) {
try {
_arguments.setElementAt(new CastExpr(exp, argType), i);
}
catch (TypeCheckError e) {
throw new TypeCheckError(this); // invalid conversion
}
}
}
_chosenMethodType = ptype;
return _type = ptype.resultType();
}
throw new TypeCheckError(this);
}
public Type typeCheckConstructor(SymbolTable stable) throws TypeCheckError{
final Vector constructors = findConstructors();
if (constructors == null) {
// Constructor not found in this class
throw new TypeCheckError(ErrorMsg.CONSTRUCTOR_NOT_FOUND,
_className);
}
final int nConstructors = constructors.size();
final int nArgs = _arguments.size();
final Vector argsType = typeCheckArgs(stable);
// Try all constructors
int bestConstrDistance = Integer.MAX_VALUE;
_type = null; // reset
for (int j, i = 0; i < nConstructors; i++) {
// Check if all parameters to this constructor can be converted
final Constructor constructor =
(Constructor)constructors.elementAt(i);
final Class[] paramTypes = constructor.getParameterTypes();
Class extType = null;
int currConstrDistance = 0;
for (j = 0; j < nArgs; j++) {
// Convert from internal (translet) type to external (Java) type
extType = paramTypes[j];
final Type intType = (Type)argsType.elementAt(j);
Object match = _internal2Java.maps(intType, extType);
if (match != null) {
currConstrDistance += ((JavaType)match).distance;
}
else if (intType instanceof ObjectType) {
ObjectType objectType = (ObjectType)intType;
if (objectType.getJavaClass() == extType)
continue;
else if (extType.isAssignableFrom(objectType.getJavaClass()))
currConstrDistance += 1;
else {
currConstrDistance = Integer.MAX_VALUE;
break;
}
}
else {
// no mapping available
currConstrDistance = Integer.MAX_VALUE;
break;
}
}
if (j == nArgs && currConstrDistance < bestConstrDistance ) {
_chosenConstructor = constructor;
_isExtConstructor = true;
bestConstrDistance = currConstrDistance;
_type = (_clazz != null) ? Type.newObjectType(_clazz)
: Type.newObjectType(_className);
}
}
if (_type != null) {
return _type;
}
throw new TypeCheckError(ErrorMsg.ARGUMENT_CONVERSION_ERR, getMethodSignature(argsType));
}
/**
* Type check a call to an external (Java) method.
* The method must be static an public, and a legal type conversion
* must exist for all its arguments and its return type.
* Every method of name <code>_fname</code> is inspected
* as a possible candidate.
*/
public Type typeCheckExternal(SymbolTable stable) throws TypeCheckError {
int nArgs = _arguments.size();
final String name = _fname.getLocalPart();
// check if function is a contructor 'new'
if (_fname.getLocalPart().equals("new")) {
return typeCheckConstructor(stable);
}
// check if we are calling an instance method
else {
boolean hasThisArgument = false;
if (nArgs == 0)
_isStatic = true;
if (!_isStatic) {
if (_namespace_format == NAMESPACE_FORMAT_JAVA
|| _namespace_format == NAMESPACE_FORMAT_PACKAGE)
hasThisArgument = true;
Expression firstArg = (Expression)_arguments.elementAt(0);
Type firstArgType = (Type)firstArg.typeCheck(stable);
if (_namespace_format == NAMESPACE_FORMAT_CLASS
&& firstArgType instanceof ObjectType
&& _clazz != null
&& _clazz.isAssignableFrom(((ObjectType)firstArgType).getJavaClass()))
hasThisArgument = true;
if (hasThisArgument) {
_thisArgument = (Expression) _arguments.elementAt(0);
_arguments.remove(0); nArgs--;
if (firstArgType instanceof ObjectType) {
_className = ((ObjectType) firstArgType).getJavaClassName();
}
else
throw new TypeCheckError(ErrorMsg.NO_JAVA_FUNCT_THIS_REF, name);
}
}
else if (_className.length() == 0) {
/*
* Warn user if external function could not be resolved.
* Warning will _NOT_ be issued is the call is properly
* wrapped in an <xsl:if> or <xsl:when> element. For details
* see If.parserContents() and When.parserContents()
*/
final Parser parser = getParser();
if (parser != null) {
reportWarning(this, parser, ErrorMsg.FUNCTION_RESOLVE_ERR,
_fname.toString());
}
unresolvedExternal = true;
return _type = Type.Int; // use "Int" as "unknown"
}
}
final Vector methods = findMethods();
if (methods == null) {
// Method not found in this class
throw new TypeCheckError(ErrorMsg.METHOD_NOT_FOUND_ERR, _className + "." + name);
}
Class extType = null;
final int nMethods = methods.size();
final Vector argsType = typeCheckArgs(stable);
// Try all methods to identify the best fit
int bestMethodDistance = Integer.MAX_VALUE;
_type = null; // reset internal type
for (int j, i = 0; i < nMethods; i++) {
// Check if all paramteters to this method can be converted
final Method method = (Method)methods.elementAt(i);
final Class[] paramTypes = method.getParameterTypes();
int currMethodDistance = 0;
for (j = 0; j < nArgs; j++) {
// Convert from internal (translet) type to external (Java) type
extType = paramTypes[j];
final Type intType = (Type)argsType.elementAt(j);
Object match = _internal2Java.maps(intType, extType);
if (match != null) {
currMethodDistance += ((JavaType)match).distance;
}
else {
// no mapping available
//
// Allow a Reference type to match any external (Java) type at
// the moment. The real type checking is performed at runtime.
if (intType instanceof ReferenceType) {
currMethodDistance += 1;
}
else if (intType instanceof ObjectType) {
ObjectType object = (ObjectType)intType;
if (extType.getName().equals(object.getJavaClassName()))
currMethodDistance += 0;
else if (extType.isAssignableFrom(object.getJavaClass()))
currMethodDistance += 1;
else {
currMethodDistance = Integer.MAX_VALUE;
break;
}
}
else {
currMethodDistance = Integer.MAX_VALUE;
break;
}
}
}
if (j == nArgs) {
// Check if the return type can be converted
extType = method.getReturnType();
_type = (Type) _java2Internal.get(extType);
if (_type == null) {
_type = Type.newObjectType(extType);
}
// Use this method if all parameters & return type match
if (_type != null && currMethodDistance < bestMethodDistance) {
_chosenMethod = method;
bestMethodDistance = currMethodDistance;
}
}
}
// It is an error if the chosen method is an instance menthod but we don't
// have a this argument.
if (_chosenMethod != null && _thisArgument == null &&
!Modifier.isStatic(_chosenMethod.getModifiers())) {
throw new TypeCheckError(ErrorMsg.NO_JAVA_FUNCT_THIS_REF, getMethodSignature(argsType));
}
if (_type != null) {
if (_type == Type.NodeSet) {
getXSLTC().setMultiDocument(true);
}
return _type;
}
throw new TypeCheckError(ErrorMsg.ARGUMENT_CONVERSION_ERR, getMethodSignature(argsType));
}
/**
* Type check the actual arguments of this function call.
*/
public Vector typeCheckArgs(SymbolTable stable) throws TypeCheckError {
final Vector result = new Vector();
final Enumeration e = _arguments.elements();
while (e.hasMoreElements()) {
final Expression exp = (Expression)e.nextElement();
result.addElement(exp.typeCheck(stable));
}
return result;
}
protected final Expression argument(int i) {
return (Expression)_arguments.elementAt(i);
}
protected final Expression argument() {
return argument(0);
}
protected final int argumentCount() {
return _arguments.size();
}
protected final void setArgument(int i, Expression exp) {
_arguments.setElementAt(exp, i);
}
/**
* Compile the function call and treat as an expression
* Update true/false-lists.
*/
public void translateDesynthesized(ClassGenerator classGen,
MethodGenerator methodGen)
{
Type type = Type.Boolean;
if (_chosenMethodType != null)
type = _chosenMethodType.resultType();
final InstructionList il = methodGen.getInstructionList();
translate(classGen, methodGen);
if ((type instanceof BooleanType) || (type instanceof IntType)) {
_falseList.add(il.append(new IFEQ(null)));
}
}
/**
* Translate a function call. The compiled code will leave the function's
* return value on the JVM's stack.
*/
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
final int n = argumentCount();
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
final boolean isSecureProcessing = classGen.getParser().getXSLTC().isSecureProcessing();
int index;
// Translate calls to methods in the BasisLibrary
if (isStandard() || isExtension()) {
for (int i = 0; i < n; i++) {
final Expression exp = argument(i);
exp.translate(classGen, methodGen);
exp.startIterator(classGen, methodGen);
}
// append "F" to the function's name
final String name = _fname.toString().replace('-', '_') + "F";
String args = Constants.EMPTYSTRING;
// Special precautions for some method calls
if (name.equals("sumF")) {
args = DOM_INTF_SIG;
il.append(methodGen.loadDOM());
}
else if (name.equals("normalize_spaceF")) {
if (_chosenMethodType.toSignature(args).
equals("()Ljava/lang/String;")) {
args = "I"+DOM_INTF_SIG;
il.append(methodGen.loadContextNode());
il.append(methodGen.loadDOM());
}
}
// Invoke the method in the basis library
index = cpg.addMethodref(BASIS_LIBRARY_CLASS, name,
_chosenMethodType.toSignature(args));
il.append(new INVOKESTATIC(index));
}
// Add call to BasisLibrary.unresolved_externalF() to generate
// run-time error message for unsupported external functions
else if (unresolvedExternal) {
index = cpg.addMethodref(BASIS_LIBRARY_CLASS,
"unresolved_externalF",
"(Ljava/lang/String;)V");
il.append(new PUSH(cpg, _fname.toString()));
il.append(new INVOKESTATIC(index));
}
else if (_isExtConstructor) {
if (isSecureProcessing)
translateUnallowedExtension(cpg, il);
final String clazz =
_chosenConstructor.getDeclaringClass().getName();
Class[] paramTypes = _chosenConstructor.getParameterTypes();
LocalVariableGen[] paramTemp = new LocalVariableGen[n];
// Backwards branches are prohibited if an uninitialized object is
// on the stack by section 4.9.4 of the JVM Specification, 2nd Ed.
// We don't know whether this code might contain backwards branches
// so we mustn't create the new object until after we've created
// the suspect arguments to its constructor. Instead we calculate
// the values of the arguments to the constructor first, store them
// in temporary variables, create the object and reload the
// arguments from the temporaries to avoid the problem.
for (int i = 0; i < n; i++) {
final Expression exp = argument(i);
Type expType = exp.getType();
exp.translate(classGen, methodGen);
// Convert the argument to its Java type
exp.startIterator(classGen, methodGen);
expType.translateTo(classGen, methodGen, paramTypes[i]);
paramTemp[i] =
methodGen.addLocalVariable("function_call_tmp"+i,
expType.toJCType(),
null, null);
paramTemp[i].setStart(
il.append(expType.STORE(paramTemp[i].getIndex())));
}
il.append(new NEW(cpg.addClass(_className)));
il.append(InstructionConstants.DUP);
for (int i = 0; i < n; i++) {
final Expression arg = argument(i);
paramTemp[i].setEnd(
il.append(arg.getType().LOAD(paramTemp[i].getIndex())));
}
final StringBuffer buffer = new StringBuffer();
buffer.append('(');
for (int i = 0; i < paramTypes.length; i++) {
buffer.append(getSignature(paramTypes[i]));
}
buffer.append(')');
buffer.append("V");
index = cpg.addMethodref(clazz,
"<init>",
buffer.toString());
il.append(new INVOKESPECIAL(index));
// Convert the return type back to our internal type
(Type.Object).translateFrom(classGen, methodGen,
_chosenConstructor.getDeclaringClass());
}
// Invoke function calls that are handled in separate classes
else {
if (isSecureProcessing)
translateUnallowedExtension(cpg, il);
final String clazz = _chosenMethod.getDeclaringClass().getName();
Class[] paramTypes = _chosenMethod.getParameterTypes();
// Push "this" if it is an instance method
if (_thisArgument != null) {
_thisArgument.translate(classGen, methodGen);
}
for (int i = 0; i < n; i++) {
final Expression exp = argument(i);
exp.translate(classGen, methodGen);
// Convert the argument to its Java type
exp.startIterator(classGen, methodGen);
exp.getType().translateTo(classGen, methodGen, paramTypes[i]);
}
final StringBuffer buffer = new StringBuffer();
buffer.append('(');
for (int i = 0; i < paramTypes.length; i++) {
buffer.append(getSignature(paramTypes[i]));
}
buffer.append(')');
buffer.append(getSignature(_chosenMethod.getReturnType()));
if (_thisArgument != null && _clazz.isInterface()) {
index = cpg.addInterfaceMethodref(clazz,
_fname.getLocalPart(),
buffer.toString());
il.append(new INVOKEINTERFACE(index, n+1));
}
else {
index = cpg.addMethodref(clazz,
_fname.getLocalPart(),
buffer.toString());
il.append(_thisArgument != null ? (InvokeInstruction) new INVOKEVIRTUAL(index) :
(InvokeInstruction) new INVOKESTATIC(index));
}
// Convert the return type back to our internal type
_type.translateFrom(classGen, methodGen,
_chosenMethod.getReturnType());
}
}
public String toString() {
return "funcall(" + _fname + ", " + _arguments + ')';
}
public boolean isStandard() {
final String namespace = _fname.getNamespace();
return (namespace == null) || (namespace.equals(Constants.EMPTYSTRING));
}
public boolean isExtension() {
final String namespace = _fname.getNamespace();
return (namespace != null) && (namespace.equals(EXT_XSLTC));
}
/**
* Returns a vector with all methods named <code>_fname</code>
* after stripping its namespace or <code>null</code>
* if no such methods exist.
*/
private Vector findMethods() {
Vector result = null;
final String namespace = _fname.getNamespace();
if (_className != null && _className.length() > 0) {
final int nArgs = _arguments.size();
try {
if (_clazz == null) {
_clazz = ObjectFactory.findProviderClass(
_className, ObjectFactory.findClassLoader(), true);
if (_clazz == null) {
final ErrorMsg msg =
new ErrorMsg(ErrorMsg.CLASS_NOT_FOUND_ERR, _className);
getParser().reportError(Constants.ERROR, msg);
}
}
final String methodName = _fname.getLocalPart();
final Method[] methods = _clazz.getMethods();
for (int i = 0; i < methods.length; i++) {
final int mods = methods[i].getModifiers();
// Is it public and same number of args ?
if (Modifier.isPublic(mods)
&& methods[i].getName().equals(methodName)
&& methods[i].getParameterTypes().length == nArgs)
{
if (result == null) {
result = new Vector();
}
result.addElement(methods[i]);
}
}
}
catch (ClassNotFoundException e) {
final ErrorMsg msg = new ErrorMsg(ErrorMsg.CLASS_NOT_FOUND_ERR, _className);
getParser().reportError(Constants.ERROR, msg);
}
}
return result;
}
/**
* Returns a vector with all constructors named <code>_fname</code>
* after stripping its namespace or <code>null</code>
* if no such methods exist.
*/
private Vector findConstructors() {
Vector result = null;
final String namespace = _fname.getNamespace();
final int nArgs = _arguments.size();
try {
if (_clazz == null) {
_clazz = ObjectFactory.findProviderClass(
_className, ObjectFactory.findClassLoader(), true);
if (_clazz == null) {
final ErrorMsg msg = new ErrorMsg(ErrorMsg.CLASS_NOT_FOUND_ERR, _className);
getParser().reportError(Constants.ERROR, msg);
}
}
final Constructor[] constructors = _clazz.getConstructors();
for (int i = 0; i < constructors.length; i++) {
final int mods = constructors[i].getModifiers();
// Is it public, static and same number of args ?
if (Modifier.isPublic(mods) &&
constructors[i].getParameterTypes().length == nArgs)
{
if (result == null) {
result = new Vector();
}
result.addElement(constructors[i]);
}
}
}
catch (ClassNotFoundException e) {
final ErrorMsg msg = new ErrorMsg(ErrorMsg.CLASS_NOT_FOUND_ERR, _className);
getParser().reportError(Constants.ERROR, msg);
}
return result;
}
/**
* Compute the JVM signature for the class.
*/
static final String getSignature(Class clazz) {
if (clazz.isArray()) {
final StringBuffer sb = new StringBuffer();
Class cl = clazz;
while (cl.isArray()) {
sb.append("[");
cl = cl.getComponentType();
}
sb.append(getSignature(cl));
return sb.toString();
}
else if (clazz.isPrimitive()) {
if (clazz == Integer.TYPE) {
return "I";
}
else if (clazz == Byte.TYPE) {
return "B";
}
else if (clazz == Long.TYPE) {
return "J";
}
else if (clazz == Float.TYPE) {
return "F";
}
else if (clazz == Double.TYPE) {
return "D";
}
else if (clazz == Short.TYPE) {
return "S";
}
else if (clazz == Character.TYPE) {
return "C";
}
else if (clazz == Boolean.TYPE) {
return "Z";
}
else if (clazz == Void.TYPE) {
return "V";
}
else {
final String name = clazz.toString();
ErrorMsg err = new ErrorMsg(ErrorMsg.UNKNOWN_SIG_TYPE_ERR,name);
throw new Error(err.toString());
}
}
else {
return "L" + clazz.getName().replace('.', '/') + ';';
}
}
/**
* Compute the JVM method descriptor for the method.
*/
static final String getSignature(Method meth) {
final StringBuffer sb = new StringBuffer();
sb.append('(');
final Class[] params = meth.getParameterTypes(); // avoid clone
for (int j = 0; j < params.length; j++) {
sb.append(getSignature(params[j]));
}
return sb.append(')').append(getSignature(meth.getReturnType()))
.toString();
}
/**
* Compute the JVM constructor descriptor for the constructor.
*/
static final String getSignature(Constructor cons) {
final StringBuffer sb = new StringBuffer();
sb.append('(');
final Class[] params = cons.getParameterTypes(); // avoid clone
for (int j = 0; j < params.length; j++) {
sb.append(getSignature(params[j]));
}
return sb.append(")V").toString();
}
/**
* Return the signature of the current method
*/
private String getMethodSignature(Vector argsType) {
final StringBuffer buf = new StringBuffer(_className);
buf.append('.').append(_fname.getLocalPart()).append('(');
int nArgs = argsType.size();
for (int i = 0; i < nArgs; i++) {
final Type intType = (Type)argsType.elementAt(i);
buf.append(intType.toString());
if (i < nArgs - 1) buf.append(", ");
}
buf.append(')');
return buf.toString();
}
/**
* To support EXSLT extensions, convert names with dash to allowable Java names:
* e.g., convert abc-xyz to abcXyz.
* Note: dashes only appear in middle of an EXSLT function or element name.
*/
protected static String replaceDash(String name)
{
char dash = '-';
StringBuffer buff = new StringBuffer("");
for (int i = 0; i < name.length(); i++) {
if (i > 0 && name.charAt(i-1) == dash)
buff.append(Character.toUpperCase(name.charAt(i)));
else if (name.charAt(i) != dash)
buff.append(name.charAt(i));
}
return buff.toString();
}
/**
* Translate code to call the BasisLibrary.unallowed_extensionF(String)
* method.
*/
private void translateUnallowedExtension(ConstantPoolGen cpg,
InstructionList il) {
int index = cpg.addMethodref(BASIS_LIBRARY_CLASS,
"unallowed_extension_functionF",
"(Ljava/lang/String;)V");
il.append(new PUSH(cpg, _fname.toString()));
il.append(new INVOKESTATIC(index));
}
}
|
oracle/fastr
| 38,098
|
com.oracle.truffle.r.test/src/com/oracle/truffle/r/test/builtins/TestBuiltin_match.java
|
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* Copyright (c) 2012-2014, Purdue University
* Copyright (c) 2013, 2020, Oracle and/or its affiliates
*
* All rights reserved.
*/
package com.oracle.truffle.r.test.builtins;
import org.junit.Test;
import com.oracle.truffle.r.test.TestBase;
// Checkstyle: stop line length check
public class TestBuiltin_match extends TestBase {
@Test
public void testmatch1() {
assertEval("argv <- list('corMatrix', c('dpoMatrix', 'dsyMatrix', 'ddenseMatrix', 'symmetricMatrix', 'dMatrix', 'denseMatrix', 'compMatrix', 'Matrix', 'mMatrix'), NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch2() {
assertEval("argv <- list(c('ANY', 'abIndex', 'ddenseMatrix', 'diagonalMatrix', 'dsparseMatrix', 'lMatrix', 'nMatrix', 'nsparseVector', 'pMatrix', 'sparseVector'), 'ANY', NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch3() {
assertEval("argv <- list(character(0), NA_integer_, NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch4() {
assertEval("argv <- list(c('1', '2', NA), NA_real_, NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch5() {
assertEval("argv <- list(c(0.00711247435174189, 0.251292124343149, -0.319172743733056, 5.75733114833721e-05, -0.35788385867217, -0.423873493915367, -0.440922191441033, 0.454737405613056, -0.337349081024889, -0.340540089756868, 0.0142999714851724, -0.337349081024889, 0.16929974943645, 0.0119141094780619, 0.0237947544260095, 0.481799107922823, -0.398620160881439, 0.112296211162227, 0.124500575635478, -0.423873493915367, 0.476631055345105, -0.201544176575946, 0.0504435384277691, 0.0142999714851724, 0.0859627732681778, -0.402191440217491, 0.0237947544260095, -0.35788385867217, 0.131606068222389, -0.328335725283617, -0.366873527650917, 0.855944113774621, 0.0506448607016037, -0.540294711232517, 0.365377890605673, 0.122315677921641, 0.122315677921641, 0.476631055345105, 0.0859627732681778, 0.028962807003728, 0.130710526672205, 0.704128425262244, 0.0119141094780619, 0.0506448607016037, 0.0859627732681778, 0.131606068222389, 0.122315677921641, -0.429041546493085, 0.0506448607016037, -0.35788385867217, 0.746844979419744, -0.158827622418446, -0.340540089756868, 0.130710526672205, -0.429041546493085, 0.126579318324608, 0.0119141094780619, 0.251292124343149, -0.283536551482645, 0.107466982896435, 0.586499858105134, -0.402392762491326, -0.85437461044313, 0.133663557186039, -0.328335725283617, 0.124500575635478, 0.0237947544260095, 0.133663557186039, 0.133663557186039, 0.656149860060726, 0.579415619243703, 0.107466982896435, -0.599127482939288, -0.326256982594487, 0.746844979419744, -0.452778727607612, -0.328335725283617, 0.0119141094780619, -0.340540089756868, -0.319172743733056, -0.725390113737062, 0.503481161620698, -0.661275243349858, -0.402392762491326, 0.476631055345105, 0.126579318324608, 0.251292124343149, -0.0874584103134217, 0.107466982896435, -0.201544176575946, 0.0734191385691725), c(-0.85437461044313, -0.725390113737062, -0.661275243349858, -0.599127482939288, -0.540294711232517, -0.452778727607612, -0.440922191441033, -0.429041546493085, -0.423873493915367, -0.402392762491326, -0.402191440217491, -0.398620160881439, -0.366873527650917, -0.35788385867217, -0.340540089756868, -0.337349081024889, -0.328335725283617, -0.326256982594487, -0.319172743733056, -0.283536551482645, -0.201544176575946, -0.158827622418446, -0.0874584103134217, 5.75733114833721e-05, 0.00711247435174189, 0.0119141094780619, 0.0142999714851724, 0.0237947544260095, 0.028962807003728, 0.0504435384277691, 0.0506448607016037, 0.0734191385691725, 0.0859627732681778, 0.107466982896435, 0.112296211162227, 0.122315677921641, 0.124500575635478, 0.126579318324608, 0.130710526672205, 0.131606068222389, 0.133663557186039, 0.16929974943645, 0.251292124343149, 0.365377890605673, 0.454737405613056, 0.476631055345105, 0.481799107922823, 0.503481161620698, 0.579415619243703, 0.586499858105134, 0.656149860060726, 0.704128425262244, 0.746844979419744, 0.855944113774621), NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch6() {
assertEval("argv <- list(c('1008', '1011', '1013', '1014', '1015', '1016', '1027', '1028', '1030', '1032', '1051', '1052', '1083', '1093', '1095', '1096', '110', '1102', '111', '1117', '112', '113', '116', '117', '1219', '125', '1250', '1251', '126', '127', '128', '1291', '1292', '1293', '1298', '1299', '130', '1308', '135', '1376', '1377', '1383', '1408', '1409', '141', '1410', '1411', '1413', '1418', '1422', '1438', '1445', '1456', '1492', '2001', '2316', '262', '266', '269', '270', '2708', '2714', '2715', '272', '2728', '2734', '280', '283', '286', '290', '3501', '411', '412', '475', '5028', '5042', '5043', '5044', '5045', '5047', '5049', '5050', '5051', '5052', '5053', '5054', '5055', '5056', '5057', '5058', '5059', '5060', '5061', '5062', '5066', '5067', '5068', '5069', '5070', '5072', '5073', '5115', '5160', '5165', '655', '724', '885', '931', '942', '952', '955', '958', 'c118', 'c168', 'c203', 'c204', 'c266'), NA_integer_, NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch7() {
assertEval("argv <- list(character(0), c('methods', 'utils', 'XML', 'RCurl'), 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch8() {
assertEval("argv <- list(c('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15'), NA_real_, NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch9() {
assertEval("argv <- list(c(-1628571, -1628571, -1200000, -1200000, -1057143, -914286, -771429, -771429, -771429, -628571, -628571, -485714, -485714, -485714, -485714, -342857, -342857, -342857, -342857, -2e+05, -2e+05, -2e+05, -2e+05, -57143, -57143, -57143, 85714, 85714, 228571, 228571, 228571, 371429, 371429, 371429, 371429, 514286, 514286, 514286, 657143, 657143, 657143, 657143, 657143, 942857, 1085714, 1228571, 1228571, 1228571, 1228571, 1371429), c(-1628571, -1200000, -1057143, -914286, -771429, -628571, -485714, -342857, -2e+05, -57143, 85714, 228571, 371429, 514286, 657143, 942857, 1085714, 1228571, 1371429), NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch10() {
assertEval("argv <- list(structure(1:27, .Label = c('M16', 'M05', 'M02', 'M11', 'M07', 'M08', 'M03', 'M12', 'M13', 'M14', 'M09', 'M15', 'M06', 'M04', 'M01', 'M10', 'F10', 'F09', 'F06', 'F01', 'F05', 'F07', 'F02', 'F08', 'F03', 'F04', 'F11'), class = c('ordered', 'factor')), structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 14L, 14L, 14L, 14L, 15L, 15L, 15L, 15L, 16L, 16L, 16L, 16L, 17L, 17L, 17L, 17L, 18L, 18L, 18L, 18L, 19L, 19L, 19L, 19L, 20L, 20L, 20L, 20L, 21L, 21L, 21L, 21L, 22L, 22L, 22L, 22L, 23L, 23L, 23L, 23L, 24L, 24L, 24L, 24L, 25L, 25L, 25L, 25L, 26L, 26L, 26L, 26L, 27L, 27L, 27L, 27L), .Label = c('M16', 'M05', 'M02', 'M11', 'M07', 'M08', 'M03', 'M12', 'M13', 'M14', 'M09', 'M15', 'M06', 'M04', 'M01', 'M10', 'F10', 'F09', 'F06', 'F01', 'F05', 'F07', 'F02', 'F08', 'F03', 'F04', 'F11'), class = c('ordered', 'factor')), NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch11() {
assertEval("argv <- list('g', 'l', NA_character_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch12() {
assertEval("argv <- list(1:4, 3L, 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch13() {
assertEval("argv <- list(c('0.5', '0.5', '0.5', '0.5', '0.5'), 0.5, NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch14() {
assertEval("argv <- list(structure(list(c0 = structure(integer(0), .Label = character(0), class = 'factor')), .Names = 'c0', row.names = character(0), class = 'data.frame'), structure(list(c0 = structure(integer(0), .Label = character(0), class = 'factor')), .Names = 'c0', row.names = character(0), class = 'data.frame'), 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch15() {
assertEval("argv <- list(c('May', 'Jun', 'Jul', 'Aug', 'Sep'), c(NA, NaN), 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch16() {
assertEval("argv <- list(c(1L, 2L, 4L, 13L, 14L, 15L, 16L, 17L, 18L, 23L), c(23L, 28L), 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch17() {
assertEval("argv <- list(c('dMatrix', 'nonStructure', 'structure'), c('nonStructure', 'structure'), NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch18() {
assertEval("argv <- list(structure(c(0, 1), .Names = c('Domestic', 'Foreign')), NA_integer_, NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch19() {
assertEval("argv <- list(structure(list(col = 1, cellvp = structure(list(structure(list(x = structure(0.5, unit = 'npc', valid.unit = 0L, class = 'unit'), y = structure(0.5, unit = 'npc', valid.unit = 0L, class = 'unit'), width = structure(1, unit = 'npc', valid.unit = 0L, class = 'unit'), height = structure(1, unit = 'npc', valid.unit = 0L, class = 'unit'), justification = 'centre', gp = structure(list(), class = 'gpar'), clip = FALSE, xscale = c(0, 1), yscale = c(0, 1), angle = 0, layout = NULL, layout.pos.row = c(1L, 1L), layout.pos.col = c(1L, 1L), valid.just = c(0.5, 0.5), valid.pos.row = c(1L, 1L), valid.pos.col = c(1L, 1L), name = 'GRID.VP.8'), .Names = c('x', 'y', 'width', 'height', 'justification', 'gp', 'clip', 'xscale', 'yscale', 'angle', 'layout', 'layout.pos.row', 'layout.pos.col', 'valid.just', 'valid.pos.row', 'valid.pos.col', 'name'), class = 'viewport'), structure(list(x = structure(1, unit = 'lines', valid.unit = 3L, data = list(NULL), class = 'unit'), y = structure(1, unit = 'lines', valid.unit = 3L, data = list( NULL), class = 'unit'), width = structure(list(fname = '-', arg1 = structure(1, unit = 'npc', valid.unit = 0L, class = 'unit'), arg2 = structure(list(fname = 'sum', arg1 = structure(c(1, 1), unit = c('lines', 'lines'), valid.unit = c(3L, 3L), data = list(NULL, NULL), class = 'unit'), arg2 = NULL), .Names = c('fname', 'arg1', 'arg2'), class = c('unit.arithmetic', 'unit'))), .Names = c('fname', 'arg1', 'arg2'), class = c('unit.arithmetic', 'unit')), height = structure(list(fname = '-', arg1 = structure(1, unit = 'npc', valid.unit = 0L, class = 'unit'), arg2 = structure(list(fname = 'sum', arg1 = structure(c(1, 1), unit = c('lines', 'lines'), valid.unit = c(3L, 3L), data = list(NULL, NULL), class = 'unit'), arg2 = NULL), .Names = c('fname', 'arg1', 'arg2'), class = c('unit.arithmetic', 'unit'))), .Names = c('fname', 'arg1', 'arg2'), class = c('unit.arithmetic', 'unit')), justification = c('left', 'bottom'), gp = structure(list(), class = 'gpar'), clip = FALSE, xscale = c(0, 1), yscale = c(0, 1), angle = 0, layout = NULL, layout.pos.row = NULL, layout.pos.col = NULL, valid.just = c(0, 0), valid.pos.row = NULL, valid.pos.col = NULL, name = 'GRID.VP.9'), .Names = c('x', 'y', 'width', 'height', 'justification', 'gp', 'clip', 'xscale', 'yscale', 'angle', 'layout', 'layout.pos.row', 'layout.pos.col', 'valid.just', 'valid.pos.row', 'valid.pos.col', 'name'), class = 'viewport')), class = c('vpStack', 'viewport'))), .Names = c('col', 'cellvp')), c('children', 'childrenOrder'), 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch20() {
assertEval("argv <- list(structure(c(1, 1, 6, 2, 2, 7, 3, 3, 7, 3, 3, 8, 4, 4, 4, 5), .Dim = c(16L, 1L), .Dimnames = list(c('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16'), 'y')), c(1, 2, 3, 4, 5, 6, 7, 8), NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch21() {
assertEval("argv <- list(structure(c(0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3), .Tsp = c(1959, 1997.91666667, 12), class = 'ts'), c(0, 1, 2, 3), NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch22() {
// FIXME docs say "For all types, ‘NA’ matches ‘NA’ and no other value."
// Expected output: [1] 0 0 0 3 4
// FastR output: Error: usage of 'incomparables' in match not implemented
assertEval(Ignored.ImplementationError, "argv <- list(c(NA, NA, 3, 4, 5), c(NA, NA, 4, 5), 0L, NA); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch23() {
assertEval("argv <- list(structure('tools', .Names = 'name'), c('base', 'utils'), 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch24() {
assertEval("argv <- list(structure(list(framevp = structure(list(x = structure(0.5, unit = 'npc', valid.unit = 0L, class = 'unit'), y = structure(0.5, unit = 'npc', valid.unit = 0L, class = 'unit'), width = structure(1, unit = 'npc', valid.unit = 0L, class = 'unit'), height = structure(1, unit = 'npc', valid.unit = 0L, class = 'unit'), justification = 'centre', gp = structure(list(), class = 'gpar'), clip = FALSE, xscale = c(0, 1), yscale = c(0, 1), angle = 0, layout = structure(list(nrow = 1L, ncol = 1L, widths = structure(list( fname = 'sum', arg1 = structure(c(1, 1, 1), unit = c('lines', 'lines', 'lines'), valid.unit = c(3L, 3L, 3L), data = list(NULL, NULL, NULL), class = 'unit'), arg2 = NULL), .Names = c('fname', 'arg1', 'arg2'), class = c('unit.arithmetic', 'unit')), heights = structure(list(fname = 'sum', arg1 = structure(c(1, 1, 1), unit = c('lines', 'lines', 'lines'), valid.unit = c(3L, 3L, 3L), data = list(NULL, NULL, NULL), class = 'unit'), arg2 = NULL), .Names = c('fname', 'arg1', 'arg2'), class = c('unit.arithmetic', 'unit')), respect = FALSE, valid.respect = 0L, respect.mat = structure(0L, .Dim = c(1L, 1L)), just = 'centre', valid.just = c(0.5, 0.5)), .Names = c('nrow', 'ncol', 'widths', 'heights', 'respect', 'valid.respect', 'respect.mat', 'just', 'valid.just'), class = 'layout'), layout.pos.row = NULL, layout.pos.col = NULL, valid.just = c(0.5, 0.5), valid.pos.row = NULL, valid.pos.col = NULL, name = 'GRID.VP.33'), .Names = c('x', 'y', 'width', 'height', 'justification', 'gp', 'clip', 'xscale', 'yscale', 'angle', 'layout', 'layout.pos.row', 'layout.pos.col', 'valid.just', 'valid.pos.row', 'valid.pos.col', 'name'), class = 'viewport')), .Names = 'framevp'), c('children', 'childrenOrder'), 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch25() {
assertEval("argv <- list(' *** Run successfully completed ***', c('', '> ### R code from vignette source \\'Design-issues.Rnw\\'', '> ', '> ###################################################', '> ### code chunk number 1: preliminarie .... [TRUNCATED] ', '', '> ###################################################', '> ### code chunk number 2: diag-class', '> ###################################################', '> li .... [TRUNCATED] ', 'Loading required package: lattice', '', 'Attaching package: ‘Matrix’', '', 'The following object is masked from ‘package:base’:', '', ' det', '', '', '> (D4 <- Diagonal(4, 10*(1:4)))', '4 x 4 diagonal matrix of class \\\'ddiMatrix\\\'', ' [,1] [,2] [,3] [,4]', '[1,] 10 . . .', '[2,] . 20 . .', '[3,] . . 30 .', '[4,] . . . 40', '', '> str(D4)', 'Formal class \\'ddiMatrix\\' [package \\\'Matrix\\\'] with 4 slots', ' ..@ diag : chr \\\'N\\\'', ' ..@ Dim : int [1:2] 4 4', ' ..@ Dimnames:List of 2', ' .. ..$ : NULL', ' .. ..$ : NULL', ' ..@ x : num [1:4] 10 20 30 40', '', '> diag(D4)', '[1] 10 20 30 40', '', '> ###################################################', '> ### code chunk number 3: diag-2', '> ###################################################', '> diag(D .... [TRUNCATED] ', '', '> D4', '4 x 4 diagonal matrix of class \\\'ddiMatrix\\\'', ' [,1] [,2] [,3] [,4]', '[1,] 11 . . .', '[2,] . 22 . .', '[3,] . . 33 .', '[4,] . . . 44', '', '> ###################################################', '> ### code chunk number 4: unit-diag', '> ###################################################', '> str .... [TRUNCATED] ', 'Formal class \\'ddiMatrix\\' [package \\\'Matrix\\\'] with 4 slots', ' ..@ diag : chr \\\'U\\\'', ' ..@ Dim : int [1:2] 3 3', ' ..@ Dimnames:List of 2', ' .. ..$ : NULL', ' .. ..$ : NULL', ' ..@ x : num(0) ', '', '> getClass(\\\'diagonalMatrix\\\') ## extending \\\'denseMatrix\\\'', 'Virtual Class \\\'diagonalMatrix\\\' [package \\\'Matrix\\\']', '', 'Slots:', ' ', 'Name: diag Dim Dimnames', 'Class: character integer list', '', 'Extends: ', 'Class \\\'sparseMatrix\\\', directly', 'Class \\\'Matrix\\\', by class \\\'sparseMatrix\\\', distance 2', 'Class \\\'mMatrix\\\', by class \\\'Matrix\\\', distance 3', '', 'Known Subclasses: \\\'ddiMatrix\\\', \\\'ldiMatrix\\\'', '', '> ###################################################', '> ### code chunk number 5: Matrix-ex', '> ###################################################', '> (M .... [TRUNCATED] ', '4 x 4 sparse Matrix of class \\\'dgTMatrix\\\'', ' ', '[1,] . . 4 .', '[2,] . 1 . .', '[3,] 4 . . .', '[4,] . . . 8', '', '> m <- as(M, \\\'matrix\\\')', '', '> (M. <- Matrix(m)) # dsCMatrix (i.e. *symmetric*)', '4 x 4 sparse Matrix of class \\\'dsCMatrix\\\'', ' ', '[1,] . . 4 .', '[2,] . 1 . .', '[3,] 4 . . .', '[4,] . . . 8', '', '> ###################################################', '> ### code chunk number 6: sessionInfo', '> ###################################################', '> t .... [TRUNCATED] ', '\\\\begin{itemize}\\\\raggedright', ' \\\\item R version 3.0.1 (2013-05-16), \\\\verb|x86_64-unknown-linux-gnu|', ' \\\\item Locale: \\\\verb|LC_CTYPE=en_US.UTF-8|, \\\\verb|LC_NUMERIC=C|, \\\\verb|LC_TIME=en_US.UTF-8|, \\\\verb|LC_COLLATE=C|, \\\\verb|LC_MONETARY=en_US.UTF-8|, \\\\verb|LC_MESSAGES=en_US.UTF-8|, \\\\verb|LC_PAPER=C|, \\\\verb|LC_NAME=C|, \\\\verb|LC_ADDRESS=C|, \\\\verb|LC_TELEPHONE=C|, \\\\verb|LC_MEASUREMENT=en_US.UTF-8|, \\\\verb|LC_IDENTIFICATION=C|', ' \\\\item Base packages: base, datasets, grDevices, graphics,', ' methods, stats, utils', ' \\\\item Other packages: Matrix~1.0-12, lattice~0.20-15', ' \\\\item Loaded via a namespace (and not attached): grid~3.0.1,', ' tools~3.0.1', '\\\\end{itemize}', '', ' *** Run successfully completed ***', '> proc.time()', ' user system elapsed ', '157.417 4.183 161.773 '), 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch26() {
assertEval("argv <- list(c(NA, NA, NA, NA, NA, NA, NA, NA), c('real', 'double'), 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch27() {
assertEval("argv <- list(c('2005-01-01', '2006-01-01', '2007-01-01', '2008-01-01', '2009-01-01'), c(NA, NaN), 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch28() {
assertEval("argv <- list(c(NA, NA), c('real', 'double'), 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch29() {
assertEval("argv <- list(c('TRUE', 'FALSE', 'TRUE', 'FALSE', 'TRUE', 'FALSE', 'TRUE', 'FALSE', 'TRUE', 'FALSE'), c(FALSE, TRUE), NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch30() {
assertEval("argv <- list(c('2005-01-01', '2005-02-01', '2005-03-01', '2005-04-01', '2005-05-01', '2005-06-01', '2005-07-01', '2005-08-01', '2005-09-01', '2005-10-01', '2005-11-01', '2005-12-01', '2006-01-01', '2006-02-01', '2006-03-01', '2006-04-01', '2006-05-01', '2006-06-01', '2006-07-01', '2006-08-01', '2006-09-01', '2006-10-01', '2006-11-01', '2006-12-01', '2007-01-01', '2007-02-01', '2007-03-01', '2007-04-01', '2007-05-01', '2007-06-01', '2007-07-01', '2007-08-01', '2007-09-01', '2007-10-01', '2007-11-01', '2007-12-01', '2008-01-01', '2008-02-01', '2008-03-01', '2008-04-01', '2008-05-01', '2008-06-01', '2008-07-01', '2008-08-01', '2008-09-01', '2008-10-01', '2008-11-01', '2008-12-01', '2009-01-01'), NA_integer_, NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch31() {
assertEval("argv <- list(c(1, 2, 3, 4, 8, 12), c(1, 2, 3, 4, 8, 12), NA_integer_, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testmatch32() {
assertEval("argv <- list(c('.__C__classA', '.__T__$:base', '.__T__$<-:base', '.__T__[:base', '.__T__plot:graphics', 'plot'), c('.__NAMESPACE__.', '.__S3MethodsTable__.', '.packageName', '.First.lib', '.Last.lib', '.onLoad', '.onAttach', '.onDetach', '.conflicts.OK', '.noGenerics'), 0L, NULL); .Internal(match(argv[[1]], argv[[2]], argv[[3]], argv[[4]]))");
}
@Test
public void testMatch() {
assertEval("{ match(2,c(1,2,3)) }");
assertEval("{ match(c(1,2,3,4,5),c(1,2,1,2)) }");
assertEval("{ match(\"hello\",c(\"I\", \"say\", \"hello\", \"world\")) }");
assertEval("{ match(c(\"hello\", \"say\"),c(\"I\", \"say\", \"hello\", \"world\")) }");
assertEval("{ match(\"abc\", c(\"xyz\")) }");
assertEval("{ match(\"abc\", c(\"xyz\"), nomatch=-1) }");
assertEval("{ match(c(1,2,3,\"NA\",NA), c(NA,\"NA\",1,2,3,4,5,6,7,8,9,10)) }");
assertEval("{ match(c(1L,2L,3L,1L,NA), c(NA,1L,1L,2L,3L,4L,5L,6L,7L,8L,9L,10L)) }");
assertEval("{ match(c(1,2,3,NaN,NA,1), c(1,NA,NaN,1,2,3,4,5,6,7,8,9,10)) }");
assertEval("{ match(c(0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,\"NA\",NA), c(NA,\"NA\",1,2,3,4,5,6,7,8,9,10,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9)) }");
assertEval("{ match(c(0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,1L,NA), c(NA,1L,1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,0L,1L,1L,2L,3L,4L,5L,6L,7L,8L,9L,10L,0L,1L,1L,2L,3L,4L,5L,6L)) }");
assertEval("{ match(c(0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,NaN,NA,1), c(1,NA,NaN,1,2,3,4,5,6,7,8,9,10,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9)) }");
assertEval("{ match(factor(c(\"a\", \"b\")), factor(c(\"c\", \"b\", \"a\", \"b\", \"c\", \"a\"))) }");
assertEval("{ match(\"a\", factor(c(\"a\", \"b\", \"a\"))) }");
assertEval("{ match(factor(c(\"a\", \"b\", \"a\")), \"a\") }");
assertEval("{ fa <- structure(1:2, .Label = c('a', NA), class = 'factor'); match(fa, c('a', NA_character_)) }");
assertEval("{ fa <- structure(1:2, .Label = c('a', NA), class = 'factor'); fa2 <- structure(1:3, .Label = c('a', NA, 'b'), class = 'factor'); match(fa, fa2) }");
assertEval("{ match(42, NULL) }");
assertEval("{ match(c(7, 42), NULL) }");
assertEval(Ignored.ImplementationError, "{ match(c(7, 42), NULL, integer()) }");
assertEval("{ match(c(7, 42), NULL, 1L) }");
assertEval("{ match(NULL, NULL) }");
}
@Test
public void testMatch2() {
// logical
assertEval("{ match(T, T) }");
assertEval("{ match(F, c(T,F)) }");
assertEval("{ match(c(T, F), T) }");
assertEval("{ match(c(T, F, NA), c(T,F, NA)) }");
assertEval("{ match(T, 1) }");
assertEval("{ match(T, 1.1) }");
assertEval("{ match(F, c(1, 0)) }");
assertEval("{ match(F, c(1.1, 0)) }");
assertEval("{ match(c(T, F), 1) }");
assertEval("{ match(c(T, F, NA), c(1, 0, NA)) }");
assertEval("{ match(c(T, F, NA), c(1, 0, -1)) }");
assertEval("{ match(T, 1L) }");
assertEval("{ match(F, c(1L, 0L)) }");
assertEval("{ match(T, c(1L,0L)) }");
assertEval("{ match(c(T, F, NA), c(1L,0L, NA_integer_)) }");
assertEval("{ match(c(T, F, NA), c(1L,0L, -1L)) }");
assertEval("{ match(T, 1+0i) }");
assertEval("{ match(F, c(1+0i, 0+0i)) }");
assertEval("{ match(T, c(1+0i,0+0i)) }");
assertEval("{ match(c(T, F, NA), c(1+0i, 0+0i, NA_complex_)) }");
assertEval("{ match(T, as.raw(1)) }");
assertEval("{ match(T, as.raw(c(1, 0))) }");
assertEval("{ match(c(T,F), as.raw(1)) }");
assertEval("{ match(c(T,F), as.raw(c(1, 0))) }");
assertEval("{ match(T, 'TRUE') }");
assertEval("{ match(T, c('TRUE', 'FALSE')) }");
assertEval("{ match(c(T,F), 'TRUE') }");
assertEval("{ match(c(T,F, NA), c('TRUE', 'FALSE', NA_character_)) }");
assertEval("{ match(c(T,F, NA), c('TRUE', 'FALSE', '-1')) }");
// raw
assertEval("{ match(as.raw(1), as.raw(1)) }");
assertEval("{ match(as.raw(1), as.raw(c(1, 0))) }");
assertEval("{ match(as.raw(c(1,0)), as.raw(1)) }");
assertEval("{ match(as.raw(c(1,0)), as.raw(c(1, 0))) }");
assertEval("{ match(as.raw(16), 10) }");
assertEval("{ match(as.raw(16), 10.1) }");
assertEval("{ match(as.raw(c(16, 17)), 10) }");
assertEval("{ match(as.raw(c(16, 17)), 10.1) }");
assertEval("{ match(as.raw(16), c(16, 11)) }");
assertEval("{ match(as.raw(c(16, 17)), c(10,11)) }");
assertEval("{ match(as.raw(16), 10L) }");
assertEval("{ match(as.raw(c(16, 17)), 10L) }");
assertEval("{ match(as.raw(16), c(16, 11L)) }");
assertEval("{ match(as.raw(c(16, 17)), c(10L,11L)) }");
assertEval("{ match(as.raw(1), T) }");
assertEval("{ match(as.raw(c(1, 0)), T) }");
assertEval("{ match(as.raw(1), c(T,F)) }");
assertEval("{ match(as.raw(c(1, 0)), c(T,F)) }");
assertEval("{ match(as.raw(0:255), c(F, T)) }");
assertEval("{ match(as.raw(16), '10') }");
assertEval("{ match(as.raw(c(16, 17)), '10') }");
assertEval("{ match(as.raw(16), c('10', '11')) }");
assertEval("{ match(as.raw(c(16, 17)), c('10', '11')) }");
assertEval("{ match(as.raw(16), 10+0i) }");
assertEval("{ match(as.raw(c(16, 17)), 10+0i) }");
assertEval("{ match(as.raw(16), c(10+0i, 11+0i)) }");
assertEval("{ match(as.raw(c(16, 17)), c(10+0i, 11+0i)) }");
assertEval("{ match(as.raw(0:255), complex(real=0:255, imaginary=0)) }");
// int
assertEval("{ match(1L, 1L) }");
assertEval("{ match(0L, c(1L, 0L)) }");
assertEval("{ match(c(1L, 0L), 1L) }");
assertEval("{ match(c(1L, 0L, NA_integer_), c(1L, 0L, NA_integer_)) }");
assertEval("{ match(1L, T) }");
assertEval("{ match(0L, c(T, F)) }");
assertEval("{ match(c(1L, 0L), T) }");
assertEval("{ match(c(1L, 0L, NA_integer_), c(T, F, NA)) }");
assertEval("{ match(c(1L, 0L, -1L), c(T, F, NA)) }");
assertEval("{ match(10L, as.raw(16)) }");
assertEval("{ match(10L, as.raw(c(16, 17))) }");
assertEval("{ match(c(10L, 11L), as.raw(16)) }");
assertEval("{ match(c(10L, 11L), as.raw(c(16, 17))) }");
assertEval("{ match(1L, 1) }");
assertEval("{ match(1L, c(1, 0)) }");
assertEval("{ match(c(1L,0L), 1) }");
assertEval("{ match(c(1L,0L, NA_integer_), c(1, 0, NA)) }");
assertEval("{ match(c(1L,0L, NA_integer_), c(1, 0, -2147483648)) }");
assertEval("{ match(1L, 1+0i) }");
assertEval("{ match(1L, c(1+0i, 0+0i)) }");
assertEval("{ match(c(1L,0L), 1+0i) }");
assertEval("{ match(c(1L,0L,NA_integer_), c(1+0i, 0+0i, NA_complex_)) }");
assertEval("{ match(1L, '1') }");
assertEval("{ match(1L, c('1', '0')) }");
assertEval("{ match(c(1L,0L), '1') }");
assertEval("{ match(c(1L,0L,NA_integer_), c('1', '0', NA_character_)) }");
// double
assertEval("{ match(1, 1) }");
assertEval("{ match(1.1, 1.1) }");
assertEval("{ match(0, c(1, 0)) }");
assertEval("{ match(c(1, 0), 1) }");
assertEval("{ match(c(1, 0, NA), c(1, 0, NA)) }");
assertEval("{ match(c(1, 1.1, NA), c(1, 1.1, NA)) }");
assertEval("{ match(1, T) }");
assertEval("{ match(1.1, T) }");
assertEval("{ match(0, c(T, F)) }");
assertEval("{ match(c(1, 0), T) }");
assertEval("{ match(c(1, 0, NA), c(T, F, NA)) }");
assertEval("{ match(c(1, 1.1, NA), c(T, F, NA)) }");
assertEval("{ match(c(1, NA, 1), c(T, F, NA)) }");
assertEval("{ match(c(1, 0, 2, 3, NA), c(T, F, NA)) }");
assertEval("{ match(c(1, 0, 2, 3, NA, -1), c(T, T, T, T, NA)) }");
assertEval("{ match(c(1, 1.1, NA, -2147483648), c(T, F, NA)) }");
assertEval("{ match(10, as.raw(16)) }");
assertEval("{ match(10.1, as.raw(16)) }");
assertEval("{ match(10, as.raw(c(16, 17))) }");
assertEval("{ match(c(10, 11), as.raw(16)) }");
assertEval("{ match(c(10.1, 11), as.raw(16)) }");
assertEval("{ match(c(10, 11), as.raw(c(16, 17))) }");
assertEval("{ match(1, 1L) }");
assertEval("{ match(1.1, 1L) }");
assertEval("{ match(0, c(1L, 0L)) }");
assertEval("{ match(c(1, 0), 1L) }");
assertEval("{ match(c(1.1, 0), 1L) }");
assertEval("{ match(c(1, 0, NA), c(1L, 0L, NA_integer_)) }");
assertEval("{ match(c(1, -2147483648), c(1L, 0L, NA_integer_)) }");
assertEval("{ match(1, 1+0i) }");
assertEval("{ match(1.1, 1+0i) }");
assertEval("{ match(0, c(1+0i, 0+0i)) }");
assertEval("{ match(c(1, 0), 1+0i) }");
assertEval("{ match(c(1.1, 0), 1+0i) }");
assertEval("{ match(c(1, 0, NA), c(1+0i, 0+0i, NA_complex_)) }");
assertEval("{ match(1, '1') }");
assertEval("{ match(1.1, '1') }");
assertEval("{ match(0, c('1', '0')) }");
assertEval("{ match(c(1, 0), '1') }");
assertEval("{ match(c(1.1, 0), '1') }");
assertEval("{ match(c(1, 0, NA), c('1', '0', NA_character_)) }");
// complex
assertEval("{ match(1+0i, 1+0i) }");
assertEval("{ match(1+0i, c(1+0i, 0+0i)) }");
assertEval("{ match(c(1+0i,0+0i), 1+0i) }");
assertEval("{ match(c(1+0i,0+0i, NA_complex_), c(1+0i, 0+0i, NA_complex_)) }");
assertEval("{ match(1+0i, T) }");
assertEval("{ match(1+0i, c(T, F)) }");
assertEval("{ match(c(1+0i,0+0i), T) }");
assertEval("{ match(c(1+0i,0+0i, NA_complex_), c(T, F, NA)) }");
assertEval("{ match(10+0i, as.raw(16)) }");
assertEval("{ match(10+0i, as.raw(c(16, 17))) }");
assertEval("{ match(c(10+0i,11+0i), as.raw(16)) }");
assertEval("{ match(c(10+0i,11+0i), as.raw(c(16, 17))) }");
assertEval("{ match(10+0i, 10L) }");
assertEval("{ match(10+0i, c(10L, 11L)) }");
assertEval("{ match(c(10+0i,11+0i), 10L) }");
assertEval("{ match(c(10+0i,11+0i, NA_complex_), c(10L, 11L, NA_integer_)) }");
assertEval("{ match(10+0i, 10) }");
assertEval("{ match(10+0i, 10.1) }");
assertEval("{ match(10+0i, c(10, 11)) }");
assertEval("{ match(10+0i, c(10.1, 11)) }");
assertEval("{ match(c(10+0i,11+0i), 10) }");
assertEval("{ match(c(10+0i,11+0i, NA_complex_), c(10, 11, NA)) }");
assertEval("{ match(10+0i, '10') }");
assertEval("{ match(10+0i, c('10', '11')) }");
assertEval("{ match(c(10+0i,11+0i), '10') }");
assertEval("{ match(c(10+0i,11+0i, NA_complex_), c('10', '11', NA_character_)) }");
// string
assertEval("{ match('a', 'a') }");
assertEval("{ match('a', c('a', 'b')) }");
assertEval("{ match(c('a', 'b'), 'a') }");
assertEval("{ match(c('a', 'b', NA_character_), c('a', 'b', NA_character_)) }");
assertEval("{ match('TRUE', T) }");
assertEval("{ match('TRUE', c(T, F)) }");
assertEval("{ match(c('TRUE', 'FALSE'), T) }");
assertEval("{ match(c('TRUE', 'FALSE', NA_character_), c(T, F, NA)) }");
assertEval("{ match(c('TRUE', 'FALSE', '-2147483648'), c(T, F, NA)) }");
assertEval("{ match('10', as.raw(16)) }");
assertEval("{ match('10', as.raw(c(16, 17))) }");
assertEval("{ match(c('10', '11'), as.raw(16)) }");
assertEval("{ match(c('10', '11'), as.raw(c(16, 17))) }");
assertEval("{ match('1', 1) }");
assertEval("{ match('1', 1.1) }");
assertEval("{ match('1', c(1, 0)) }");
assertEval("{ match('1', c(1.1, 0)) }");
assertEval("{ match(c('1', '0'), 1) }");
assertEval("{ match(c('1', '1',NA_character_), c(1, 0, NA)) }");
assertEval("{ match('1', 1L) }");
assertEval("{ match('1', c(1L, 0L)) }");
assertEval("{ match(c('1', '0'), 1L) }");
assertEval("{ match(c('1', '1', NA_character_), c(1L, 0L, NA_integer_)) }");
assertEval("{ match(c('1', '1', '-2147483648'), c(1L, 0L, NA_integer_)) }");
assertEval("{ match('1+0i', 1+0i) }");
assertEval("{ match('1+0i', c(1+0i, 0+0i)) }");
assertEval("{ match(c('1+0i', '0+0i'), 1+0i) }");
assertEval("{ match(c('1+0i', '0+0i', NA_character_), c(1+0i, 0+0i, NA_complex_)) }");
}
@Test
public void testMatchInSequence() {
assertEval("{ match(c(-2L, -1L, 0L, 1L, 10L, 11L), seq.int(from=-1L, to=10L, by=1L)) }");
assertEval("{ match(c( 1L, 2L, 3L), seq.int(from=1L, to=10L, by=2L)) }");
assertEval("{ match(seq.int(from=1L, to=10L, by=1L), seq.int(from=1L, to=10L, by=4L)) }");
testMatchStringSequence("a", "b");
testMatchStringSequence("", "b");
testMatchStringSequence("", "");
assertEval("match(1:3, 3:1)");
assertEval("match(as.character(1:3), as.character(3:1))");
assertEval("match(1:3, numeric(0))");
}
private void testMatchStringSequence(String preffix, String suffix) {
String x = String.format("c('%1$s-2%2$s', '%1$s-1%2$s', '%1$s0%2$s', '%1$s1%2$s', '%1$s10%2$s', '%1$s11%2$s')", preffix, suffix);
String table = String.format("paste('%1$s', -1:10, '%2$s', sep='')", preffix, suffix);
assertEval("{ match(" + x + "," + table + ")}");
x = String.format("c('%1$s1%2$s', '%1$s2%2$s', '%1$s3%2$s')", preffix, suffix);
table = String.format("paste('%1$s', seq(from=1, to=10, by=2), '%2$s', sep='')", preffix, suffix);
assertEval("{ match(" + x + "," + table + ")}");
x = String.format("paste('%1$s', seq(from=1, to=10, by=1), '%2$s', sep='')", preffix, suffix);
table = String.format("paste('%1$s', seq(from=1, to=10, by=4), '%2$s', sep='')", preffix, suffix);
assertEval("{ match(" + x + "," + table + ")}");
}
}
|
apache/directory-studio
| 38,312
|
plugins/ldapbrowser.common/src/main/java/org/apache/directory/studio/ldapbrowser/common/widgets/search/SearchPageWrapper.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.ldapbrowser.common.widgets.search;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.message.Control;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.message.controls.ManageDsaIT;
import org.apache.directory.api.ldap.model.message.controls.PagedResults;
import org.apache.directory.api.ldap.model.message.controls.PagedResultsImpl;
import org.apache.directory.api.ldap.model.message.controls.Subentries;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.ldap.model.schema.AttributeType;
import org.apache.directory.studio.common.ui.widgets.AbstractWidget;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyEvent;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyListener;
import org.apache.directory.studio.connection.core.Connection;
import org.apache.directory.studio.connection.core.Controls;
import org.apache.directory.studio.ldapbrowser.core.jobs.SearchRunnable;
import org.apache.directory.studio.ldapbrowser.core.jobs.StudioBrowserJob;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.apache.directory.studio.ldapbrowser.core.model.ISearch;
import org.apache.directory.studio.ldapbrowser.core.model.schema.SchemaUtils;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
/**
* The SearchPageWrapper is used to arrange all input elements of a
* search page. It is used by the search page, the search properties page,
* the batch operation wizard and the export wizards.
*
* The style is used to specify the invisible and readonly elements.
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class SearchPageWrapper extends AbstractWidget
{
/** The default style */
public static final int NONE = 0;
/** Style for invisible name field */
public static final int NAME_INVISIBLE = 1 << 1;
/** Style for read-only name field */
public static final int NAME_READONLY = 1 << 2;
/** Style for invisible connection field */
public static final int CONNECTION_INVISIBLE = 1 << 3;
/** Style for read-only connection field */
public static final int CONNECTION_READONLY = 1 << 4;
/** Style for invisible search base field */
public static final int SEARCHBASE_INVISIBLE = 1 << 5;
/** Style for read-only search base field */
public static final int SEARCHBASE_READONLY = 1 << 6;
/** Style for invisible filter field */
public static final int FILTER_INVISIBLE = 1 << 7;
/** Style for read-only filter field */
public static final int FILTER_READONLY = 1 << 8;
/** Style for invisible returning attributes field */
public static final int RETURNINGATTRIBUTES_INVISIBLE = 1 << 9;
/** Style for read-only returning attributes field */
public static final int RETURNINGATTRIBUTES_READONLY = 1 << 10;
/** Style for visible return Dn checkbox */
public static final int RETURN_DN_VISIBLE = 1 << 11;
/** Style for checked return Dn checkbox */
public static final int RETURN_DN_CHECKED = 1 << 12;
/** Style for visible return all attributes checkbox */
public static final int RETURN_ALLATTRIBUTES_VISIBLE = 1 << 13;
/** Style for checked return all attributes checkbox */
public static final int RETURN_ALLATTRIBUTES_CHECKED = 1 << 14;
/** Style for visible return operational attributes checkbox */
public static final int RETURN_OPERATIONALATTRIBUTES_VISIBLE = 1 << 15;
/** Style for checked return operational attributes checkbox */
public static final int RETURN_OPERATIONALATTRIBUTES_CHECKED = 1 << 16;
/** Style for invisible options */
public static final int OPTIONS_INVISIBLE = 1 << 21;
/** Style for read-only scope options */
public static final int SCOPEOPTIONS_READONLY = 1 << 22;
/** Style for read-only limit options */
public static final int LIMITOPTIONS_READONLY = 1 << 23;
/** Style for read-only alias options */
public static final int ALIASOPTIONS_READONLY = 1 << 24;
/** Style for read-only referrals options */
public static final int REFERRALOPTIONS_READONLY = 1 << 25;
/** Style for invisible follow referrals manually*/
public static final int REFERRALOPTIONS_FOLLOW_MANUAL_INVISIBLE = 1 << 26;
/** Style for invisible controls fields */
public static final int CONTROLS_INVISIBLE = 1 << 30;
/** The style. */
protected int style;
/** The search name label. */
protected Label searchNameLabel;
/** The search name text. */
protected Text searchNameText;
/** The connection label. */
protected Label connectionLabel;
/** The browser connection widget. */
protected BrowserConnectionWidget browserConnectionWidget;
/** The search base label. */
protected Label searchBaseLabel;
/** The search base widget. */
protected EntryWidget searchBaseWidget;
/** The filter label. */
protected Label filterLabel;
/** The filter widget. */
protected FilterWidget filterWidget;
/** The returning attributes label. */
protected Label returningAttributesLabel;
/** The returning attributes widget. */
protected ReturningAttributesWidget returningAttributesWidget;
/** The return dn button. */
protected Button returnDnButton;
/** The return all attributes button. */
protected Button returnAllAttributesButton;
/** The return operational attributes button. */
protected Button returnOperationalAttributesButton;
/** The scope widget. */
protected ScopeWidget scopeWidget;
/** The limit widget. */
protected LimitWidget limitWidget;
/** The aliases dereferencing widget. */
protected AliasesDereferencingWidget aliasesDereferencingWidget;
/** The referrals handling widget. */
protected ReferralsHandlingWidget referralsHandlingWidget;
/** The control group. */
protected Group controlGroup;
/** The ManageDsaIT control button. */
protected Button manageDsaItControlButton;
/** The subentries control button. */
protected Button subentriesControlButton;
/** The paged search control button. */
protected Button pagedSearchControlButton;
/** The paged search control size label. */
protected Label pagedSearchControlSizeLabel;
/** The paged search control size text. */
protected Text pagedSearchControlSizeText;
/** The paged search control scroll button. */
protected Button pagedSearchControlScrollButton;
/**
* Creates a new instance of SearchPageWrapper.
*
* @param style the style
*/
public SearchPageWrapper( int style )
{
this.style = style;
}
/**
* Creates the contents.
*
* @param composite the composite
*/
public void createContents( final Composite composite )
{
// Search Name
createSearchNameLine( composite );
// Connection
createConnectionLine( composite );
// Search Base
createSearchBaseLine( composite );
// Filter
createFilterLine( composite );
// Returning Attributes
createReturningAttributesLine( composite );
// control
createControlComposite( composite );
// scope, limit, alias, referral
createOptionsComposite( composite );
}
/**
* Checks if the given style is active.
*
* @param requiredStyle the required style to check
*
* @return true, if the required style is active
*/
protected boolean isActive( int requiredStyle )
{
return ( style & requiredStyle ) != 0;
}
/**
* Creates the search name line.
*
* @param composite the composite
*/
protected void createSearchNameLine( final Composite composite )
{
if ( isActive( NAME_INVISIBLE ) )
{
return;
}
searchNameLabel = BaseWidgetUtils.createLabel( composite,
Messages.getString( "SearchPageWrapper.SearchName" ), 1 ); //$NON-NLS-1$
if ( isActive( NAME_READONLY ) )
{
searchNameText = BaseWidgetUtils.createReadonlyText( composite, "", 2 ); //$NON-NLS-1$
}
else
{
searchNameText = BaseWidgetUtils.createText( composite, "", 2 ); //$NON-NLS-1$
}
searchNameText.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
validate();
}
} );
searchNameText.setFocus();
BaseWidgetUtils.createSpacer( composite, 3 );
}
/**
* Creates the connection line.
*
* @param composite the composite
*/
protected void createConnectionLine( final Composite composite )
{
if ( isActive( CONNECTION_INVISIBLE ) )
{
return;
}
connectionLabel = BaseWidgetUtils.createLabel( composite,
Messages.getString( "SearchPageWrapper.Connection" ), 1 ); //$NON-NLS-1$
browserConnectionWidget = new BrowserConnectionWidget();
browserConnectionWidget.createWidget( composite );
browserConnectionWidget.setEnabled( !isActive( CONNECTION_READONLY ) );
browserConnectionWidget.addWidgetModifyListener( new WidgetModifyListener()
{
public void widgetModified( WidgetModifyEvent event )
{
validate();
}
} );
BaseWidgetUtils.createSpacer( composite, 3 );
}
/**
* Creates the search base line.
*
* @param composite the composite
*/
protected void createSearchBaseLine( final Composite composite )
{
if ( isActive( SEARCHBASE_INVISIBLE ) )
{
return;
}
searchBaseLabel = BaseWidgetUtils.createLabel( composite,
Messages.getString( "SearchPageWrapper.SearchBase" ), 1 ); //$NON-NLS-1$
searchBaseWidget = new EntryWidget();
searchBaseWidget.createWidget( composite );
searchBaseWidget.setEnabled( !isActive( SEARCHBASE_READONLY ) );
searchBaseWidget.addWidgetModifyListener( new WidgetModifyListener()
{
public void widgetModified( WidgetModifyEvent event )
{
validate();
}
} );
BaseWidgetUtils.createSpacer( composite, 3 );
}
/**
* Creates the filter line.
*
* @param composite the composite
*/
protected void createFilterLine( final Composite composite )
{
if ( isActive( FILTER_INVISIBLE ) )
{
return;
}
filterLabel = BaseWidgetUtils.createLabel( composite, Messages.getString( "SearchPageWrapper.Filter" ), 1 ); //$NON-NLS-1$
filterWidget = new FilterWidget();
filterWidget.createWidget( composite );
filterWidget.setEnabled( !isActive( FILTER_READONLY ) );
filterWidget.addWidgetModifyListener( new WidgetModifyListener()
{
public void widgetModified( WidgetModifyEvent event )
{
validate();
}
} );
BaseWidgetUtils.createSpacer( composite, 3 );
}
/**
* Creates the returning attributes line.
*
* @param composite the composite
*/
protected void createReturningAttributesLine( final Composite composite )
{
if ( isActive( RETURNINGATTRIBUTES_INVISIBLE ) )
{
return;
}
BaseWidgetUtils.createLabel( composite, Messages.getString( "SearchPageWrapper.ReturningAttributes" ), 1 ); //$NON-NLS-1$
Composite retComposite = BaseWidgetUtils.createColumnContainer( composite, 1, 2 );
returningAttributesWidget = new ReturningAttributesWidget();
returningAttributesWidget.createWidget( retComposite );
returningAttributesWidget.setEnabled( !isActive( RETURNINGATTRIBUTES_READONLY ) );
returningAttributesWidget.addWidgetModifyListener( new WidgetModifyListener()
{
public void widgetModified( WidgetModifyEvent event )
{
validate();
}
} );
// special returning attributes options
if ( isActive( RETURN_DN_VISIBLE ) || isActive( RETURN_ALLATTRIBUTES_VISIBLE )
|| isActive( RETURN_OPERATIONALATTRIBUTES_VISIBLE ) )
{
BaseWidgetUtils.createSpacer( composite, 1 );
Composite buttonComposite = BaseWidgetUtils.createColumnContainer( composite, 3, 2 );
if ( isActive( RETURN_DN_VISIBLE ) )
{
returnDnButton = BaseWidgetUtils.createCheckbox( buttonComposite, Messages
.getString( "SearchPageWrapper.ExportDN" ), 1 ); //$NON-NLS-1$
returnDnButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
validate();
}
} );
returnDnButton.setSelection( isActive( RETURN_DN_CHECKED ) );
}
if ( isActive( RETURN_ALLATTRIBUTES_VISIBLE ) )
{
returnAllAttributesButton = BaseWidgetUtils.createCheckbox( buttonComposite, Messages
.getString( "SearchPageWrapper.AllUserAttributes" ), 1 ); //$NON-NLS-1$
returnAllAttributesButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
validate();
}
} );
returnAllAttributesButton.setSelection( isActive( RETURN_ALLATTRIBUTES_CHECKED ) );
}
if ( isActive( RETURN_OPERATIONALATTRIBUTES_VISIBLE ) )
{
returnOperationalAttributesButton = BaseWidgetUtils.createCheckbox( buttonComposite, Messages
.getString( "SearchPageWrapper.OperationalAttributes" ), 1 ); //$NON-NLS-1$
returnOperationalAttributesButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
validate();
}
} );
returnOperationalAttributesButton.setSelection( isActive( RETURN_OPERATIONALATTRIBUTES_CHECKED ) );
}
}
BaseWidgetUtils.createSpacer( composite, 3 );
}
/**
* Creates the options composite, this includes the
* scope, limit, alias and referral widgets.
*
* @param composite the composite
*/
protected void createOptionsComposite( final Composite composite )
{
if ( isActive( OPTIONS_INVISIBLE ) )
{
return;
}
Composite optionsComposite = BaseWidgetUtils.createColumnContainer( composite, 2, 3 );
scopeWidget = new ScopeWidget();
scopeWidget.createWidget( optionsComposite );
scopeWidget.setEnabled( !isActive( SCOPEOPTIONS_READONLY ) );
scopeWidget.addWidgetModifyListener( new WidgetModifyListener()
{
public void widgetModified( WidgetModifyEvent event )
{
validate();
}
} );
limitWidget = new LimitWidget();
limitWidget.createWidget( optionsComposite );
limitWidget.setEnabled( !isActive( LIMITOPTIONS_READONLY ) );
limitWidget.addWidgetModifyListener( new WidgetModifyListener()
{
public void widgetModified( WidgetModifyEvent event )
{
validate();
}
} );
aliasesDereferencingWidget = new AliasesDereferencingWidget();
aliasesDereferencingWidget.createWidget( optionsComposite );
aliasesDereferencingWidget.setEnabled( !isActive( ALIASOPTIONS_READONLY ) );
aliasesDereferencingWidget.addWidgetModifyListener( new WidgetModifyListener()
{
public void widgetModified( WidgetModifyEvent event )
{
validate();
}
} );
referralsHandlingWidget = new ReferralsHandlingWidget();
referralsHandlingWidget.createWidget( optionsComposite, !isActive( REFERRALOPTIONS_FOLLOW_MANUAL_INVISIBLE ) );
referralsHandlingWidget.setEnabled( !isActive( REFERRALOPTIONS_READONLY ) );
referralsHandlingWidget.addWidgetModifyListener( new WidgetModifyListener()
{
public void widgetModified( WidgetModifyEvent event )
{
validate();
}
} );
}
/**
* Creates the control composite.
*
* @param composite the composite
*/
protected void createControlComposite( final Composite composite )
{
if ( isActive( CONTROLS_INVISIBLE ) )
{
return;
}
Composite controlComposite = BaseWidgetUtils.createColumnContainer( composite, 1, 3 );
controlGroup = BaseWidgetUtils.createGroup( controlComposite,
Messages.getString( "SearchPageWrapper.Controls" ), 1 ); //$NON-NLS-1$
// ManageDsaIT control
manageDsaItControlButton = BaseWidgetUtils.createCheckbox( controlGroup, Messages
.getString( "SearchPageWrapper.ManageDsaIt" ), 1 ); //$NON-NLS-1$
manageDsaItControlButton.setToolTipText( Messages.getString( "SearchPageWrapper.ManageDsaItTooltip" ) ); //$NON-NLS-1$
manageDsaItControlButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
validate();
}
} );
// subentries control
subentriesControlButton = BaseWidgetUtils.createCheckbox( controlGroup, Messages
.getString( "SearchPageWrapper.Subentries" ), 1 ); //$NON-NLS-1$
subentriesControlButton.setToolTipText( Messages.getString( "SearchPageWrapper.SubentriesTooltip" ) ); //$NON-NLS-1$
subentriesControlButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
validate();
}
} );
// simple paged results control
Composite sprcComposite = BaseWidgetUtils.createColumnContainer( controlGroup, 4, 1 );
pagedSearchControlButton = BaseWidgetUtils.createCheckbox( sprcComposite, Messages
.getString( "SearchPageWrapper.PagedSearch" ), 1 ); //$NON-NLS-1$
pagedSearchControlButton.setToolTipText( Messages.getString( "SearchPageWrapper.PagedSearchToolTip" ) ); //$NON-NLS-1$
pagedSearchControlButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
validate();
}
} );
pagedSearchControlSizeLabel = BaseWidgetUtils.createLabel( sprcComposite, Messages
.getString( "SearchPageWrapper.PageSize" ), 1 ); //$NON-NLS-1$
pagedSearchControlSizeText = BaseWidgetUtils.createText( sprcComposite, "100", 5, 1 ); //$NON-NLS-1$
pagedSearchControlSizeText.addVerifyListener( new VerifyListener()
{
public void verifyText( VerifyEvent e )
{
if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$
{
e.doit = false;
}
}
} );
pagedSearchControlSizeText.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
validate();
}
} );
pagedSearchControlScrollButton = BaseWidgetUtils.createCheckbox( sprcComposite, Messages
.getString( "SearchPageWrapper.ScrollMode" ), 1 ); //$NON-NLS-1$
pagedSearchControlScrollButton.setToolTipText( Messages.getString( "SearchPageWrapper.ScrollModeToolTip" ) ); //$NON-NLS-1$
pagedSearchControlScrollButton.setSelection( true );
pagedSearchControlScrollButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
validate();
}
} );
}
/**
* Validates all elements.
*/
protected void validate()
{
if ( browserConnectionWidget.getBrowserConnection() != null )
{
if ( searchBaseWidget.getDn() == null
|| searchBaseWidget.getBrowserConnection() != browserConnectionWidget.getBrowserConnection() )
{
searchBaseWidget.setInput( browserConnectionWidget.getBrowserConnection(), null );
}
}
filterWidget.setBrowserConnection( browserConnectionWidget.getBrowserConnection() );
pagedSearchControlSizeLabel.setEnabled( pagedSearchControlButton.getSelection() );
pagedSearchControlSizeText.setEnabled( pagedSearchControlButton.getSelection() );
pagedSearchControlScrollButton.setEnabled( pagedSearchControlButton.getSelection() );
super.notifyListeners();
}
/**
* Checks if the DNs should be returned/exported.
*
* @return true, if DNs should be returnde/exported
*/
public boolean isReturnDn()
{
return returnDnButton != null && returnDnButton.getSelection();
}
/**
* Initializes all search page widgets from the given search.
*
* @param search the search
*/
public void loadFromSearch( ISearch search )
{
if ( searchNameText != null )
{
searchNameText.setText( search.getName() );
}
if ( search.getBrowserConnection() != null )
{
IBrowserConnection browserConnection = search.getBrowserConnection();
Dn searchBase = search.getSearchBase();
if ( browserConnectionWidget != null )
{
browserConnectionWidget.setBrowserConnection( browserConnection );
}
if ( searchBase != null )
{
searchBaseWidget.setInput( browserConnection, searchBase );
}
if ( filterWidget != null )
{
filterWidget.setBrowserConnection( browserConnection );
filterWidget.setFilter( search.getFilter() );
}
if ( returningAttributesWidget != null )
{
returningAttributesWidget.setBrowserConnection( browserConnection );
returningAttributesWidget.setInitialReturningAttributes( search.getReturningAttributes() );
}
if ( scopeWidget != null )
{
scopeWidget.setScope( search.getScope() );
}
if ( limitWidget != null )
{
limitWidget.setCountLimit( search.getCountLimit() );
limitWidget.setTimeLimit( search.getTimeLimit() );
}
if ( aliasesDereferencingWidget != null )
{
aliasesDereferencingWidget.setAliasesDereferencingMethod( search.getAliasesDereferencingMethod() );
}
if ( referralsHandlingWidget != null )
{
referralsHandlingWidget.setReferralsHandlingMethod( search.getReferralsHandlingMethod() );
}
if ( subentriesControlButton != null )
{
List<Control> searchControls = search.getControls();
if ( searchControls != null && searchControls.size() > 0 )
{
for ( Control c : searchControls )
{
if ( c instanceof ManageDsaIT )
{
manageDsaItControlButton.setSelection( true );
}
else if ( c instanceof Subentries )
{
subentriesControlButton.setSelection( true );
}
else if ( c instanceof PagedResults )
{
pagedSearchControlButton.setSelection( true );
pagedSearchControlSizeText.setText( "" + ( ( PagedResults ) c ).getSize() ); //$NON-NLS-1$
pagedSearchControlScrollButton.setSelection( search.isPagedSearchScrollMode() );
}
}
}
}
}
}
/**
* Saves all search pages element to the given search.
*
* @param search the search
*
* @return true, if the given search has been modified.
*/
public boolean saveToSearch( ISearch search )
{
boolean searchModified = false;
if ( searchNameText != null && !searchNameText.getText().equals( search.getName() ) )
{
search.getSearchParameter().setName( searchNameText.getText() );
searchModified = true;
}
if ( browserConnectionWidget != null && browserConnectionWidget.getBrowserConnection() != null
&& browserConnectionWidget.getBrowserConnection() != search.getBrowserConnection() )
{
search.setBrowserConnection( browserConnectionWidget.getBrowserConnection() );
searchModified = true;
}
if ( searchBaseWidget != null && searchBaseWidget.getDn() != null
&& !searchBaseWidget.getDn().equals( search.getSearchBase() ) )
{
search.getSearchParameter().setSearchBase( searchBaseWidget.getDn() );
searchModified = true;
searchBaseWidget.saveDialogSettings();
}
if ( filterWidget != null && filterWidget.getFilter() != null )
{
if ( !filterWidget.getFilter().equals( search.getFilter() ) )
{
search.getSearchParameter().setFilter( filterWidget.getFilter() );
searchModified = true;
}
filterWidget.saveDialogSettings();
}
if ( returningAttributesWidget != null )
{
if ( !Arrays.equals( returningAttributesWidget.getReturningAttributes(), search.getReturningAttributes() ) )
{
search.getSearchParameter().setReturningAttributes( returningAttributesWidget.getReturningAttributes() );
searchModified = true;
}
returningAttributesWidget.saveDialogSettings();
if ( returnAllAttributesButton != null || returnOperationalAttributesButton != null )
{
List<String> raList = new ArrayList<String>();
raList.addAll( Arrays.asList( search.getReturningAttributes() ) );
if ( returnAllAttributesButton != null )
{
if ( returnAllAttributesButton.getSelection() )
{
raList.add( SchemaConstants.ALL_USER_ATTRIBUTES );
}
if ( returnAllAttributesButton.getSelection() != isActive( RETURN_ALLATTRIBUTES_CHECKED ) )
{
searchModified = true;
}
}
if ( returnOperationalAttributesButton != null )
{
if ( returnOperationalAttributesButton.getSelection() )
{
Collection<AttributeType> opAtds = SchemaUtils
.getOperationalAttributeDescriptions( browserConnectionWidget.getBrowserConnection()
.getSchema() );
Collection<String> opAtdNames = SchemaUtils.getNames( opAtds );
raList.addAll( opAtdNames );
raList.add( SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES );
}
if ( returnOperationalAttributesButton.getSelection() != isActive( RETURN_OPERATIONALATTRIBUTES_CHECKED ) )
{
searchModified = true;
}
}
String[] returningAttributes = raList.toArray( new String[raList.size()] );
search.getSearchParameter().setReturningAttributes( returningAttributes );
}
}
if ( scopeWidget != null )
{
SearchScope scope = scopeWidget.getScope();
if ( scope != search.getScope() )
{
search.getSearchParameter().setScope( scope );
searchModified = true;
}
}
if ( limitWidget != null )
{
int countLimit = limitWidget.getCountLimit();
int timeLimit = limitWidget.getTimeLimit();
if ( countLimit != search.getCountLimit() )
{
search.getSearchParameter().setCountLimit( countLimit );
searchModified = true;
}
if ( timeLimit != search.getTimeLimit() )
{
search.getSearchParameter().setTimeLimit( timeLimit );
searchModified = true;
}
}
if ( aliasesDereferencingWidget != null )
{
Connection.AliasDereferencingMethod aliasesDereferencingMethod = aliasesDereferencingWidget
.getAliasesDereferencingMethod();
if ( aliasesDereferencingMethod != search.getAliasesDereferencingMethod() )
{
search.getSearchParameter().setAliasesDereferencingMethod( aliasesDereferencingMethod );
searchModified = true;
}
}
if ( referralsHandlingWidget != null )
{
Connection.ReferralHandlingMethod referralsHandlingMethod = referralsHandlingWidget
.getReferralsHandlingMethod();
if ( referralsHandlingMethod != search.getReferralsHandlingMethod() )
{
search.getSearchParameter().setReferralsHandlingMethod( referralsHandlingMethod );
searchModified = true;
}
}
if ( subentriesControlButton != null )
{
Set<Control> oldControls = new HashSet<>();
oldControls.addAll( search.getSearchParameter().getControls() );
search.getSearchParameter().getControls().clear();
if ( manageDsaItControlButton.getSelection() )
{
search.getSearchParameter().getControls().add( Controls.MANAGEDSAIT_CONTROL );
}
if ( subentriesControlButton.getSelection() )
{
search.getSearchParameter().getControls().add( Controls.SUBENTRIES_CONTROL );
}
if ( pagedSearchControlButton.getSelection() )
{
int pageSize;
try
{
pageSize = Integer.valueOf( pagedSearchControlSizeText.getText() );
}
catch ( NumberFormatException e )
{
pageSize = 100;
}
boolean isScrollMode = pagedSearchControlScrollButton.getSelection();
PagedResults control = Controls.newPagedResultsControl(pageSize);
search.getSearchParameter().getControls().add( control );
search.getSearchParameter().setPagedSearchScrollMode( isScrollMode );
}
Set<Control> newControls = new HashSet<>();
newControls.addAll( search.getSearchParameter().getControls() );
if ( !oldControls.equals( newControls ) )
{
searchModified = true;
}
}
return searchModified;
}
/**
* Performs the search.
*
* @param search the search
*
* @return true, if perform search
*/
public boolean performSearch( final ISearch search )
{
if ( search.getBrowserConnection() != null )
{
search.setSearchResults( null );
new StudioBrowserJob( new SearchRunnable( new ISearch[]
{ search } ) ).execute();
return true;
}
else
{
return false;
}
}
/**
* Checks if the search page parameters are valid.
*
* @return true, it the search page parameters are valid
*/
public boolean isValid()
{
if ( browserConnectionWidget != null && browserConnectionWidget.getBrowserConnection() == null )
{
return false;
}
if ( searchBaseWidget != null && searchBaseWidget.getDn() == null )
{
return false;
}
if ( searchNameText != null && "".equals( searchNameText.getText() ) ) //$NON-NLS-1$
{
return false;
}
if ( filterWidget != null && filterWidget.getFilter() == null )
{
return false;
}
if ( pagedSearchControlButton != null && pagedSearchControlButton.isEnabled()
&& "".equals( pagedSearchControlButton.getText() ) ) //$NON-NLS-1$
{
return false;
}
return true;
}
/**
* Gets the error message or null if the search page is valid.
*
* @return the error message or null if the search page is valid
*/
public String getErrorMessage()
{
if ( browserConnectionWidget != null && browserConnectionWidget.getBrowserConnection() == null )
{
return Messages.getString( "SearchPageWrapper.SelectConnection" ); //$NON-NLS-1$
}
if ( searchBaseWidget != null && searchBaseWidget.getDn() == null )
{
return Messages.getString( "SearchPageWrapper.EnterValidSearchBase" ); //$NON-NLS-1$
}
if ( searchNameText != null && "".equals( searchNameText.getText() ) ) //$NON-NLS-1$
{
return Messages.getString( "SearchPageWrapper.EnterSearchName" ); //$NON-NLS-1$
}
if ( filterWidget != null && filterWidget.getFilter() == null )
{
return Messages.getString( "SearchPageWrapper.EnterValidFilter" ); //$NON-NLS-1$
}
return null;
}
/**
* Sets the enabled state of the widget.
*
* @param b true to enable the widget, false to disable the widget
*/
public void setEnabled( boolean b )
{
if ( searchNameText != null )
{
searchNameLabel.setEnabled( b );
searchNameText.setEnabled( b );
}
if ( browserConnectionWidget != null )
{
connectionLabel.setEnabled( b );
browserConnectionWidget.setEnabled( b && !isActive( CONNECTION_READONLY ) );
}
if ( searchBaseWidget != null )
{
searchBaseLabel.setEnabled( b );
searchBaseWidget.setEnabled( b && !isActive( SEARCHBASE_READONLY ) );
}
if ( filterWidget != null )
{
filterLabel.setEnabled( b );
filterWidget.setEnabled( b && !isActive( FILTER_READONLY ) );
}
if ( returningAttributesWidget != null )
{
returningAttributesLabel.setEnabled( b );
returningAttributesWidget.setEnabled( b && !isActive( RETURNINGATTRIBUTES_READONLY ) );
}
if ( returnDnButton != null )
{
returnDnButton.setEnabled( b );
}
if ( returnAllAttributesButton != null )
{
returnAllAttributesButton.setEnabled( b );
}
if ( returnOperationalAttributesButton != null )
{
returnOperationalAttributesButton.setEnabled( b );
}
if ( scopeWidget != null )
{
scopeWidget.setEnabled( b && !isActive( SCOPEOPTIONS_READONLY ) );
}
if ( limitWidget != null )
{
limitWidget.setEnabled( b && !isActive( LIMITOPTIONS_READONLY ) );
}
if ( aliasesDereferencingWidget != null )
{
aliasesDereferencingWidget.setEnabled( b && !isActive( ALIASOPTIONS_READONLY ) );
}
if ( referralsHandlingWidget != null )
{
referralsHandlingWidget.setEnabled( b && !isActive( REFERRALOPTIONS_READONLY ) );
}
if ( controlGroup != null )
{
controlGroup.setEnabled( b );
manageDsaItControlButton.setEnabled( b );
subentriesControlButton.setEnabled( b );
}
}
}
|
googleapis/google-cloud-java
| 38,185
|
java-eventarc/proto-google-cloud-eventarc-v1/src/main/java/com/google/cloud/eventarc/v1/UpdateTriggerRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/eventarc/v1/eventarc.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.eventarc.v1;
/**
*
*
* <pre>
* The request message for the UpdateTrigger method.
* </pre>
*
* Protobuf type {@code google.cloud.eventarc.v1.UpdateTriggerRequest}
*/
public final class UpdateTriggerRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.eventarc.v1.UpdateTriggerRequest)
UpdateTriggerRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateTriggerRequest.newBuilder() to construct.
private UpdateTriggerRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateTriggerRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateTriggerRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.eventarc.v1.EventarcProto
.internal_static_google_cloud_eventarc_v1_UpdateTriggerRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.eventarc.v1.EventarcProto
.internal_static_google_cloud_eventarc_v1_UpdateTriggerRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.eventarc.v1.UpdateTriggerRequest.class,
com.google.cloud.eventarc.v1.UpdateTriggerRequest.Builder.class);
}
private int bitField0_;
public static final int TRIGGER_FIELD_NUMBER = 1;
private com.google.cloud.eventarc.v1.Trigger trigger_;
/**
*
*
* <pre>
* The trigger to be updated.
* </pre>
*
* <code>.google.cloud.eventarc.v1.Trigger trigger = 1;</code>
*
* @return Whether the trigger field is set.
*/
@java.lang.Override
public boolean hasTrigger() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The trigger to be updated.
* </pre>
*
* <code>.google.cloud.eventarc.v1.Trigger trigger = 1;</code>
*
* @return The trigger.
*/
@java.lang.Override
public com.google.cloud.eventarc.v1.Trigger getTrigger() {
return trigger_ == null ? com.google.cloud.eventarc.v1.Trigger.getDefaultInstance() : trigger_;
}
/**
*
*
* <pre>
* The trigger to be updated.
* </pre>
*
* <code>.google.cloud.eventarc.v1.Trigger trigger = 1;</code>
*/
@java.lang.Override
public com.google.cloud.eventarc.v1.TriggerOrBuilder getTriggerOrBuilder() {
return trigger_ == null ? com.google.cloud.eventarc.v1.Trigger.getDefaultInstance() : trigger_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* The fields to be updated; only fields explicitly provided are updated.
* If no field mask is provided, all provided fields in the request are
* updated. To update all fields, provide a field mask of "*".
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The fields to be updated; only fields explicitly provided are updated.
* If no field mask is provided, all provided fields in the request are
* updated. To update all fields, provide a field mask of "*".
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* The fields to be updated; only fields explicitly provided are updated.
* If no field mask is provided, all provided fields in the request are
* updated. To update all fields, provide a field mask of "*".
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
public static final int ALLOW_MISSING_FIELD_NUMBER = 3;
private boolean allowMissing_ = false;
/**
*
*
* <pre>
* If set to true, and the trigger is not found, a new trigger will be
* created. In this situation, `update_mask` is ignored.
* </pre>
*
* <code>bool allow_missing = 3;</code>
*
* @return The allowMissing.
*/
@java.lang.Override
public boolean getAllowMissing() {
return allowMissing_;
}
public static final int VALIDATE_ONLY_FIELD_NUMBER = 4;
private boolean validateOnly_ = false;
/**
*
*
* <pre>
* Optional. If set, validate the request and preview the review, but do not
* post it.
* </pre>
*
* <code>bool validate_only = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getTrigger());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getUpdateMask());
}
if (allowMissing_ != false) {
output.writeBool(3, allowMissing_);
}
if (validateOnly_ != false) {
output.writeBool(4, validateOnly_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getTrigger());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
if (allowMissing_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, allowMissing_);
}
if (validateOnly_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(4, validateOnly_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.eventarc.v1.UpdateTriggerRequest)) {
return super.equals(obj);
}
com.google.cloud.eventarc.v1.UpdateTriggerRequest other =
(com.google.cloud.eventarc.v1.UpdateTriggerRequest) obj;
if (hasTrigger() != other.hasTrigger()) return false;
if (hasTrigger()) {
if (!getTrigger().equals(other.getTrigger())) return false;
}
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (getAllowMissing() != other.getAllowMissing()) return false;
if (getValidateOnly() != other.getValidateOnly()) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasTrigger()) {
hash = (37 * hash) + TRIGGER_FIELD_NUMBER;
hash = (53 * hash) + getTrigger().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (37 * hash) + ALLOW_MISSING_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getAllowMissing());
hash = (37 * hash) + VALIDATE_ONLY_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValidateOnly());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.eventarc.v1.UpdateTriggerRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The request message for the UpdateTrigger method.
* </pre>
*
* Protobuf type {@code google.cloud.eventarc.v1.UpdateTriggerRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.eventarc.v1.UpdateTriggerRequest)
com.google.cloud.eventarc.v1.UpdateTriggerRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.eventarc.v1.EventarcProto
.internal_static_google_cloud_eventarc_v1_UpdateTriggerRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.eventarc.v1.EventarcProto
.internal_static_google_cloud_eventarc_v1_UpdateTriggerRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.eventarc.v1.UpdateTriggerRequest.class,
com.google.cloud.eventarc.v1.UpdateTriggerRequest.Builder.class);
}
// Construct using com.google.cloud.eventarc.v1.UpdateTriggerRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getTriggerFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
trigger_ = null;
if (triggerBuilder_ != null) {
triggerBuilder_.dispose();
triggerBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
allowMissing_ = false;
validateOnly_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.eventarc.v1.EventarcProto
.internal_static_google_cloud_eventarc_v1_UpdateTriggerRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.eventarc.v1.UpdateTriggerRequest getDefaultInstanceForType() {
return com.google.cloud.eventarc.v1.UpdateTriggerRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.eventarc.v1.UpdateTriggerRequest build() {
com.google.cloud.eventarc.v1.UpdateTriggerRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.eventarc.v1.UpdateTriggerRequest buildPartial() {
com.google.cloud.eventarc.v1.UpdateTriggerRequest result =
new com.google.cloud.eventarc.v1.UpdateTriggerRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.eventarc.v1.UpdateTriggerRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.trigger_ = triggerBuilder_ == null ? trigger_ : triggerBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.allowMissing_ = allowMissing_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.validateOnly_ = validateOnly_;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.eventarc.v1.UpdateTriggerRequest) {
return mergeFrom((com.google.cloud.eventarc.v1.UpdateTriggerRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.eventarc.v1.UpdateTriggerRequest other) {
if (other == com.google.cloud.eventarc.v1.UpdateTriggerRequest.getDefaultInstance())
return this;
if (other.hasTrigger()) {
mergeTrigger(other.getTrigger());
}
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
if (other.getAllowMissing() != false) {
setAllowMissing(other.getAllowMissing());
}
if (other.getValidateOnly() != false) {
setValidateOnly(other.getValidateOnly());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(getTriggerFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
allowMissing_ = input.readBool();
bitField0_ |= 0x00000004;
break;
} // case 24
case 32:
{
validateOnly_ = input.readBool();
bitField0_ |= 0x00000008;
break;
} // case 32
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.eventarc.v1.Trigger trigger_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.eventarc.v1.Trigger,
com.google.cloud.eventarc.v1.Trigger.Builder,
com.google.cloud.eventarc.v1.TriggerOrBuilder>
triggerBuilder_;
/**
*
*
* <pre>
* The trigger to be updated.
* </pre>
*
* <code>.google.cloud.eventarc.v1.Trigger trigger = 1;</code>
*
* @return Whether the trigger field is set.
*/
public boolean hasTrigger() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The trigger to be updated.
* </pre>
*
* <code>.google.cloud.eventarc.v1.Trigger trigger = 1;</code>
*
* @return The trigger.
*/
public com.google.cloud.eventarc.v1.Trigger getTrigger() {
if (triggerBuilder_ == null) {
return trigger_ == null
? com.google.cloud.eventarc.v1.Trigger.getDefaultInstance()
: trigger_;
} else {
return triggerBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The trigger to be updated.
* </pre>
*
* <code>.google.cloud.eventarc.v1.Trigger trigger = 1;</code>
*/
public Builder setTrigger(com.google.cloud.eventarc.v1.Trigger value) {
if (triggerBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
trigger_ = value;
} else {
triggerBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The trigger to be updated.
* </pre>
*
* <code>.google.cloud.eventarc.v1.Trigger trigger = 1;</code>
*/
public Builder setTrigger(com.google.cloud.eventarc.v1.Trigger.Builder builderForValue) {
if (triggerBuilder_ == null) {
trigger_ = builderForValue.build();
} else {
triggerBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The trigger to be updated.
* </pre>
*
* <code>.google.cloud.eventarc.v1.Trigger trigger = 1;</code>
*/
public Builder mergeTrigger(com.google.cloud.eventarc.v1.Trigger value) {
if (triggerBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& trigger_ != null
&& trigger_ != com.google.cloud.eventarc.v1.Trigger.getDefaultInstance()) {
getTriggerBuilder().mergeFrom(value);
} else {
trigger_ = value;
}
} else {
triggerBuilder_.mergeFrom(value);
}
if (trigger_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The trigger to be updated.
* </pre>
*
* <code>.google.cloud.eventarc.v1.Trigger trigger = 1;</code>
*/
public Builder clearTrigger() {
bitField0_ = (bitField0_ & ~0x00000001);
trigger_ = null;
if (triggerBuilder_ != null) {
triggerBuilder_.dispose();
triggerBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The trigger to be updated.
* </pre>
*
* <code>.google.cloud.eventarc.v1.Trigger trigger = 1;</code>
*/
public com.google.cloud.eventarc.v1.Trigger.Builder getTriggerBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getTriggerFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The trigger to be updated.
* </pre>
*
* <code>.google.cloud.eventarc.v1.Trigger trigger = 1;</code>
*/
public com.google.cloud.eventarc.v1.TriggerOrBuilder getTriggerOrBuilder() {
if (triggerBuilder_ != null) {
return triggerBuilder_.getMessageOrBuilder();
} else {
return trigger_ == null
? com.google.cloud.eventarc.v1.Trigger.getDefaultInstance()
: trigger_;
}
}
/**
*
*
* <pre>
* The trigger to be updated.
* </pre>
*
* <code>.google.cloud.eventarc.v1.Trigger trigger = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.eventarc.v1.Trigger,
com.google.cloud.eventarc.v1.Trigger.Builder,
com.google.cloud.eventarc.v1.TriggerOrBuilder>
getTriggerFieldBuilder() {
if (triggerBuilder_ == null) {
triggerBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.eventarc.v1.Trigger,
com.google.cloud.eventarc.v1.Trigger.Builder,
com.google.cloud.eventarc.v1.TriggerOrBuilder>(
getTrigger(), getParentForChildren(), isClean());
trigger_ = null;
}
return triggerBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* The fields to be updated; only fields explicitly provided are updated.
* If no field mask is provided, all provided fields in the request are
* updated. To update all fields, provide a field mask of "*".
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The fields to be updated; only fields explicitly provided are updated.
* If no field mask is provided, all provided fields in the request are
* updated. To update all fields, provide a field mask of "*".
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The fields to be updated; only fields explicitly provided are updated.
* If no field mask is provided, all provided fields in the request are
* updated. To update all fields, provide a field mask of "*".
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The fields to be updated; only fields explicitly provided are updated.
* If no field mask is provided, all provided fields in the request are
* updated. To update all fields, provide a field mask of "*".
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The fields to be updated; only fields explicitly provided are updated.
* If no field mask is provided, all provided fields in the request are
* updated. To update all fields, provide a field mask of "*".
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The fields to be updated; only fields explicitly provided are updated.
* If no field mask is provided, all provided fields in the request are
* updated. To update all fields, provide a field mask of "*".
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The fields to be updated; only fields explicitly provided are updated.
* If no field mask is provided, all provided fields in the request are
* updated. To update all fields, provide a field mask of "*".
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The fields to be updated; only fields explicitly provided are updated.
* If no field mask is provided, all provided fields in the request are
* updated. To update all fields, provide a field mask of "*".
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* The fields to be updated; only fields explicitly provided are updated.
* If no field mask is provided, all provided fields in the request are
* updated. To update all fields, provide a field mask of "*".
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
private boolean allowMissing_;
/**
*
*
* <pre>
* If set to true, and the trigger is not found, a new trigger will be
* created. In this situation, `update_mask` is ignored.
* </pre>
*
* <code>bool allow_missing = 3;</code>
*
* @return The allowMissing.
*/
@java.lang.Override
public boolean getAllowMissing() {
return allowMissing_;
}
/**
*
*
* <pre>
* If set to true, and the trigger is not found, a new trigger will be
* created. In this situation, `update_mask` is ignored.
* </pre>
*
* <code>bool allow_missing = 3;</code>
*
* @param value The allowMissing to set.
* @return This builder for chaining.
*/
public Builder setAllowMissing(boolean value) {
allowMissing_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* If set to true, and the trigger is not found, a new trigger will be
* created. In this situation, `update_mask` is ignored.
* </pre>
*
* <code>bool allow_missing = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearAllowMissing() {
bitField0_ = (bitField0_ & ~0x00000004);
allowMissing_ = false;
onChanged();
return this;
}
private boolean validateOnly_;
/**
*
*
* <pre>
* Optional. If set, validate the request and preview the review, but do not
* post it.
* </pre>
*
* <code>bool validate_only = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
/**
*
*
* <pre>
* Optional. If set, validate the request and preview the review, but do not
* post it.
* </pre>
*
* <code>bool validate_only = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The validateOnly to set.
* @return This builder for chaining.
*/
public Builder setValidateOnly(boolean value) {
validateOnly_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. If set, validate the request and preview the review, but do not
* post it.
* </pre>
*
* <code>bool validate_only = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearValidateOnly() {
bitField0_ = (bitField0_ & ~0x00000008);
validateOnly_ = false;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.eventarc.v1.UpdateTriggerRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.eventarc.v1.UpdateTriggerRequest)
private static final com.google.cloud.eventarc.v1.UpdateTriggerRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.eventarc.v1.UpdateTriggerRequest();
}
public static com.google.cloud.eventarc.v1.UpdateTriggerRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateTriggerRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateTriggerRequest>() {
@java.lang.Override
public UpdateTriggerRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<UpdateTriggerRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateTriggerRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.eventarc.v1.UpdateTriggerRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,211
|
java-datastream/proto-google-cloud-datastream-v1alpha1/src/main/java/com/google/cloud/datastream/v1alpha1/OracleTable.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/datastream/v1alpha1/datastream_resources.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.datastream.v1alpha1;
/**
*
*
* <pre>
* Oracle table.
* </pre>
*
* Protobuf type {@code google.cloud.datastream.v1alpha1.OracleTable}
*/
public final class OracleTable extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.datastream.v1alpha1.OracleTable)
OracleTableOrBuilder {
private static final long serialVersionUID = 0L;
// Use OracleTable.newBuilder() to construct.
private OracleTable(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private OracleTable() {
tableName_ = "";
oracleColumns_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new OracleTable();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datastream.v1alpha1.CloudDatastreamResourcesProto
.internal_static_google_cloud_datastream_v1alpha1_OracleTable_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datastream.v1alpha1.CloudDatastreamResourcesProto
.internal_static_google_cloud_datastream_v1alpha1_OracleTable_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datastream.v1alpha1.OracleTable.class,
com.google.cloud.datastream.v1alpha1.OracleTable.Builder.class);
}
public static final int TABLE_NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object tableName_ = "";
/**
*
*
* <pre>
* Table name.
* </pre>
*
* <code>string table_name = 1;</code>
*
* @return The tableName.
*/
@java.lang.Override
public java.lang.String getTableName() {
java.lang.Object ref = tableName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
tableName_ = s;
return s;
}
}
/**
*
*
* <pre>
* Table name.
* </pre>
*
* <code>string table_name = 1;</code>
*
* @return The bytes for tableName.
*/
@java.lang.Override
public com.google.protobuf.ByteString getTableNameBytes() {
java.lang.Object ref = tableName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
tableName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORACLE_COLUMNS_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.datastream.v1alpha1.OracleColumn> oracleColumns_;
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.datastream.v1alpha1.OracleColumn> getOracleColumnsList() {
return oracleColumns_;
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.datastream.v1alpha1.OracleColumnOrBuilder>
getOracleColumnsOrBuilderList() {
return oracleColumns_;
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
@java.lang.Override
public int getOracleColumnsCount() {
return oracleColumns_.size();
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
@java.lang.Override
public com.google.cloud.datastream.v1alpha1.OracleColumn getOracleColumns(int index) {
return oracleColumns_.get(index);
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
@java.lang.Override
public com.google.cloud.datastream.v1alpha1.OracleColumnOrBuilder getOracleColumnsOrBuilder(
int index) {
return oracleColumns_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(tableName_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, tableName_);
}
for (int i = 0; i < oracleColumns_.size(); i++) {
output.writeMessage(2, oracleColumns_.get(i));
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(tableName_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, tableName_);
}
for (int i = 0; i < oracleColumns_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, oracleColumns_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.datastream.v1alpha1.OracleTable)) {
return super.equals(obj);
}
com.google.cloud.datastream.v1alpha1.OracleTable other =
(com.google.cloud.datastream.v1alpha1.OracleTable) obj;
if (!getTableName().equals(other.getTableName())) return false;
if (!getOracleColumnsList().equals(other.getOracleColumnsList())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + TABLE_NAME_FIELD_NUMBER;
hash = (53 * hash) + getTableName().hashCode();
if (getOracleColumnsCount() > 0) {
hash = (37 * hash) + ORACLE_COLUMNS_FIELD_NUMBER;
hash = (53 * hash) + getOracleColumnsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.datastream.v1alpha1.OracleTable parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datastream.v1alpha1.OracleTable parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datastream.v1alpha1.OracleTable parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datastream.v1alpha1.OracleTable parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datastream.v1alpha1.OracleTable parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datastream.v1alpha1.OracleTable parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datastream.v1alpha1.OracleTable parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datastream.v1alpha1.OracleTable parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datastream.v1alpha1.OracleTable parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.datastream.v1alpha1.OracleTable parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.datastream.v1alpha1.OracleTable parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datastream.v1alpha1.OracleTable parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.datastream.v1alpha1.OracleTable prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Oracle table.
* </pre>
*
* Protobuf type {@code google.cloud.datastream.v1alpha1.OracleTable}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.datastream.v1alpha1.OracleTable)
com.google.cloud.datastream.v1alpha1.OracleTableOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datastream.v1alpha1.CloudDatastreamResourcesProto
.internal_static_google_cloud_datastream_v1alpha1_OracleTable_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datastream.v1alpha1.CloudDatastreamResourcesProto
.internal_static_google_cloud_datastream_v1alpha1_OracleTable_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datastream.v1alpha1.OracleTable.class,
com.google.cloud.datastream.v1alpha1.OracleTable.Builder.class);
}
// Construct using com.google.cloud.datastream.v1alpha1.OracleTable.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
tableName_ = "";
if (oracleColumnsBuilder_ == null) {
oracleColumns_ = java.util.Collections.emptyList();
} else {
oracleColumns_ = null;
oracleColumnsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.datastream.v1alpha1.CloudDatastreamResourcesProto
.internal_static_google_cloud_datastream_v1alpha1_OracleTable_descriptor;
}
@java.lang.Override
public com.google.cloud.datastream.v1alpha1.OracleTable getDefaultInstanceForType() {
return com.google.cloud.datastream.v1alpha1.OracleTable.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.datastream.v1alpha1.OracleTable build() {
com.google.cloud.datastream.v1alpha1.OracleTable result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.datastream.v1alpha1.OracleTable buildPartial() {
com.google.cloud.datastream.v1alpha1.OracleTable result =
new com.google.cloud.datastream.v1alpha1.OracleTable(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.datastream.v1alpha1.OracleTable result) {
if (oracleColumnsBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)) {
oracleColumns_ = java.util.Collections.unmodifiableList(oracleColumns_);
bitField0_ = (bitField0_ & ~0x00000002);
}
result.oracleColumns_ = oracleColumns_;
} else {
result.oracleColumns_ = oracleColumnsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.datastream.v1alpha1.OracleTable result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.tableName_ = tableName_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.datastream.v1alpha1.OracleTable) {
return mergeFrom((com.google.cloud.datastream.v1alpha1.OracleTable) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.datastream.v1alpha1.OracleTable other) {
if (other == com.google.cloud.datastream.v1alpha1.OracleTable.getDefaultInstance())
return this;
if (!other.getTableName().isEmpty()) {
tableName_ = other.tableName_;
bitField0_ |= 0x00000001;
onChanged();
}
if (oracleColumnsBuilder_ == null) {
if (!other.oracleColumns_.isEmpty()) {
if (oracleColumns_.isEmpty()) {
oracleColumns_ = other.oracleColumns_;
bitField0_ = (bitField0_ & ~0x00000002);
} else {
ensureOracleColumnsIsMutable();
oracleColumns_.addAll(other.oracleColumns_);
}
onChanged();
}
} else {
if (!other.oracleColumns_.isEmpty()) {
if (oracleColumnsBuilder_.isEmpty()) {
oracleColumnsBuilder_.dispose();
oracleColumnsBuilder_ = null;
oracleColumns_ = other.oracleColumns_;
bitField0_ = (bitField0_ & ~0x00000002);
oracleColumnsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getOracleColumnsFieldBuilder()
: null;
} else {
oracleColumnsBuilder_.addAllMessages(other.oracleColumns_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
tableName_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
com.google.cloud.datastream.v1alpha1.OracleColumn m =
input.readMessage(
com.google.cloud.datastream.v1alpha1.OracleColumn.parser(),
extensionRegistry);
if (oracleColumnsBuilder_ == null) {
ensureOracleColumnsIsMutable();
oracleColumns_.add(m);
} else {
oracleColumnsBuilder_.addMessage(m);
}
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object tableName_ = "";
/**
*
*
* <pre>
* Table name.
* </pre>
*
* <code>string table_name = 1;</code>
*
* @return The tableName.
*/
public java.lang.String getTableName() {
java.lang.Object ref = tableName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
tableName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Table name.
* </pre>
*
* <code>string table_name = 1;</code>
*
* @return The bytes for tableName.
*/
public com.google.protobuf.ByteString getTableNameBytes() {
java.lang.Object ref = tableName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
tableName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Table name.
* </pre>
*
* <code>string table_name = 1;</code>
*
* @param value The tableName to set.
* @return This builder for chaining.
*/
public Builder setTableName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
tableName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Table name.
* </pre>
*
* <code>string table_name = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearTableName() {
tableName_ = getDefaultInstance().getTableName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Table name.
* </pre>
*
* <code>string table_name = 1;</code>
*
* @param value The bytes for tableName to set.
* @return This builder for chaining.
*/
public Builder setTableNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
tableName_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.util.List<com.google.cloud.datastream.v1alpha1.OracleColumn> oracleColumns_ =
java.util.Collections.emptyList();
private void ensureOracleColumnsIsMutable() {
if (!((bitField0_ & 0x00000002) != 0)) {
oracleColumns_ =
new java.util.ArrayList<com.google.cloud.datastream.v1alpha1.OracleColumn>(
oracleColumns_);
bitField0_ |= 0x00000002;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datastream.v1alpha1.OracleColumn,
com.google.cloud.datastream.v1alpha1.OracleColumn.Builder,
com.google.cloud.datastream.v1alpha1.OracleColumnOrBuilder>
oracleColumnsBuilder_;
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public java.util.List<com.google.cloud.datastream.v1alpha1.OracleColumn>
getOracleColumnsList() {
if (oracleColumnsBuilder_ == null) {
return java.util.Collections.unmodifiableList(oracleColumns_);
} else {
return oracleColumnsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public int getOracleColumnsCount() {
if (oracleColumnsBuilder_ == null) {
return oracleColumns_.size();
} else {
return oracleColumnsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public com.google.cloud.datastream.v1alpha1.OracleColumn getOracleColumns(int index) {
if (oracleColumnsBuilder_ == null) {
return oracleColumns_.get(index);
} else {
return oracleColumnsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public Builder setOracleColumns(
int index, com.google.cloud.datastream.v1alpha1.OracleColumn value) {
if (oracleColumnsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOracleColumnsIsMutable();
oracleColumns_.set(index, value);
onChanged();
} else {
oracleColumnsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public Builder setOracleColumns(
int index, com.google.cloud.datastream.v1alpha1.OracleColumn.Builder builderForValue) {
if (oracleColumnsBuilder_ == null) {
ensureOracleColumnsIsMutable();
oracleColumns_.set(index, builderForValue.build());
onChanged();
} else {
oracleColumnsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public Builder addOracleColumns(com.google.cloud.datastream.v1alpha1.OracleColumn value) {
if (oracleColumnsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOracleColumnsIsMutable();
oracleColumns_.add(value);
onChanged();
} else {
oracleColumnsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public Builder addOracleColumns(
int index, com.google.cloud.datastream.v1alpha1.OracleColumn value) {
if (oracleColumnsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOracleColumnsIsMutable();
oracleColumns_.add(index, value);
onChanged();
} else {
oracleColumnsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public Builder addOracleColumns(
com.google.cloud.datastream.v1alpha1.OracleColumn.Builder builderForValue) {
if (oracleColumnsBuilder_ == null) {
ensureOracleColumnsIsMutable();
oracleColumns_.add(builderForValue.build());
onChanged();
} else {
oracleColumnsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public Builder addOracleColumns(
int index, com.google.cloud.datastream.v1alpha1.OracleColumn.Builder builderForValue) {
if (oracleColumnsBuilder_ == null) {
ensureOracleColumnsIsMutable();
oracleColumns_.add(index, builderForValue.build());
onChanged();
} else {
oracleColumnsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public Builder addAllOracleColumns(
java.lang.Iterable<? extends com.google.cloud.datastream.v1alpha1.OracleColumn> values) {
if (oracleColumnsBuilder_ == null) {
ensureOracleColumnsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, oracleColumns_);
onChanged();
} else {
oracleColumnsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public Builder clearOracleColumns() {
if (oracleColumnsBuilder_ == null) {
oracleColumns_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
} else {
oracleColumnsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public Builder removeOracleColumns(int index) {
if (oracleColumnsBuilder_ == null) {
ensureOracleColumnsIsMutable();
oracleColumns_.remove(index);
onChanged();
} else {
oracleColumnsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public com.google.cloud.datastream.v1alpha1.OracleColumn.Builder getOracleColumnsBuilder(
int index) {
return getOracleColumnsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public com.google.cloud.datastream.v1alpha1.OracleColumnOrBuilder getOracleColumnsOrBuilder(
int index) {
if (oracleColumnsBuilder_ == null) {
return oracleColumns_.get(index);
} else {
return oracleColumnsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public java.util.List<? extends com.google.cloud.datastream.v1alpha1.OracleColumnOrBuilder>
getOracleColumnsOrBuilderList() {
if (oracleColumnsBuilder_ != null) {
return oracleColumnsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(oracleColumns_);
}
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public com.google.cloud.datastream.v1alpha1.OracleColumn.Builder addOracleColumnsBuilder() {
return getOracleColumnsFieldBuilder()
.addBuilder(com.google.cloud.datastream.v1alpha1.OracleColumn.getDefaultInstance());
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public com.google.cloud.datastream.v1alpha1.OracleColumn.Builder addOracleColumnsBuilder(
int index) {
return getOracleColumnsFieldBuilder()
.addBuilder(
index, com.google.cloud.datastream.v1alpha1.OracleColumn.getDefaultInstance());
}
/**
*
*
* <pre>
* Oracle columns in the schema.
* When unspecified as part of inclue/exclude lists, includes/excludes
* everything.
* </pre>
*
* <code>repeated .google.cloud.datastream.v1alpha1.OracleColumn oracle_columns = 2;</code>
*/
public java.util.List<com.google.cloud.datastream.v1alpha1.OracleColumn.Builder>
getOracleColumnsBuilderList() {
return getOracleColumnsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datastream.v1alpha1.OracleColumn,
com.google.cloud.datastream.v1alpha1.OracleColumn.Builder,
com.google.cloud.datastream.v1alpha1.OracleColumnOrBuilder>
getOracleColumnsFieldBuilder() {
if (oracleColumnsBuilder_ == null) {
oracleColumnsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datastream.v1alpha1.OracleColumn,
com.google.cloud.datastream.v1alpha1.OracleColumn.Builder,
com.google.cloud.datastream.v1alpha1.OracleColumnOrBuilder>(
oracleColumns_,
((bitField0_ & 0x00000002) != 0),
getParentForChildren(),
isClean());
oracleColumns_ = null;
}
return oracleColumnsBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.datastream.v1alpha1.OracleTable)
}
// @@protoc_insertion_point(class_scope:google.cloud.datastream.v1alpha1.OracleTable)
private static final com.google.cloud.datastream.v1alpha1.OracleTable DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.datastream.v1alpha1.OracleTable();
}
public static com.google.cloud.datastream.v1alpha1.OracleTable getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<OracleTable> PARSER =
new com.google.protobuf.AbstractParser<OracleTable>() {
@java.lang.Override
public OracleTable parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<OracleTable> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<OracleTable> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.datastream.v1alpha1.OracleTable getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
google/j2objc
| 38,140
|
jre_emul/android/platform/libcore/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterTest.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.tests.java.util.zip;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.zip.Adler32;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/* J2ObjC removed: not supported by Junit 4.11 (https://github.com/google/j2objc/issues/1318).
import libcore.junit.junit3.TestCaseWithRules;
import libcore.junit.util.ResourceLeakageDetector; */
import org.junit.Rule;
import org.junit.rules.TestRule;
import tests.support.resource.Support_Resources;
public class DeflaterTest extends junit.framework.TestCase /* J2ObjC removed: TestCaseWithRules */ {
/* J2ObjC removed: not supported by Junit 4.11 (https://github.com/google/j2objc/issues/1318).
@Rule
public TestRule guardRule = ResourceLeakageDetector.getRule(); */
class MyDeflater extends Deflater {
MyDeflater() {
super();
}
MyDeflater(int lvl) {
super(lvl);
}
void myFinalize() {
finalize();
}
int getDefCompression() {
return DEFAULT_COMPRESSION;
}
int getDefStrategy() {
return DEFAULT_STRATEGY;
}
int getHuffman() {
return HUFFMAN_ONLY;
}
int getFiltered() {
return FILTERED;
}
}
/**
* java.util.zip.Deflater#deflate(byte[])
*/
public void test_deflate$B() {
byte outPutBuf[] = new byte[50];
byte byteArray[] = { 1, 3, 4, 7, 8 };
byte outPutInf[] = new byte[50];
int x = 0;
Deflater defl = new Deflater();
defl.setInput(byteArray);
defl.finish();
while (!defl.finished()) {
x += defl.deflate(outPutBuf);
}
assertEquals("Deflater at end of stream, should return 0", 0, defl
.deflate(outPutBuf));
int totalOut = defl.getTotalOut();
int totalIn = defl.getTotalIn();
assertEquals(x, totalOut);
assertEquals(byteArray.length, totalIn);
defl.end();
Inflater infl = new Inflater();
try {
infl.setInput(outPutBuf);
while (!infl.finished()) {
infl.inflate(outPutInf);
}
} catch (DataFormatException e) {
fail("Invalid input to be decompressed");
}
assertEquals(totalIn, infl.getTotalOut());
assertEquals(totalOut, infl.getTotalIn());
for (int i = 0; i < byteArray.length; i++) {
assertEquals(byteArray[i], outPutInf[i]);
}
assertEquals("Final decompressed data contained more bytes than original",
0, outPutInf[byteArray.length]);
infl.end();
}
/**
* java.util.zip.Deflater#deflate(byte[], int, int)
*/
public void test_deflate$BII() {
byte outPutBuf[] = new byte[50];
byte byteArray[] = { 5, 2, 3, 7, 8 };
byte outPutInf[] = new byte[50];
int offSet = 1;
int length = outPutBuf.length - 1;
int x = 0;
Deflater defl = new Deflater();
defl.setInput(byteArray);
defl.finish();
while (!defl.finished()) {
x += defl.deflate(outPutBuf, offSet, length);
}
assertEquals("Deflater at end of stream, should return 0", 0, defl.deflate(
outPutBuf, offSet, length));
int totalOut = defl.getTotalOut();
int totalIn = defl.getTotalIn();
assertEquals(x, totalOut);
assertEquals(byteArray.length, totalIn);
defl.end();
Inflater infl = new Inflater();
try {
infl.setInput(outPutBuf, offSet, length);
while (!infl.finished()) {
infl.inflate(outPutInf);
}
} catch (DataFormatException e) {
fail("Invalid input to be decompressed");
}
assertEquals(totalIn, infl.getTotalOut());
assertEquals(totalOut, infl.getTotalIn());
for (int i = 0; i < byteArray.length; i++) {
assertEquals(byteArray[i], outPutInf[i]);
}
assertEquals("Final decompressed data contained more bytes than original",
0, outPutInf[byteArray.length]);
infl.end();
// Set of tests testing the boundaries of the offSet/length
defl = new Deflater();
outPutBuf = new byte[100];
defl.setInput(byteArray);
for (int i = 0; i < 2; i++) {
if (i == 0) {
offSet = outPutBuf.length + 1;
length = outPutBuf.length;
} else {
offSet = 0;
length = outPutBuf.length + 1;
}
try {
defl.deflate(outPutBuf, offSet, length);
fail("Test " + i
+ ": ArrayIndexOutOfBoundsException not thrown");
} catch (ArrayIndexOutOfBoundsException e) {
}
}
defl.end();
}
/**
* java.util.zip.Deflater#end()
*/
public void test_end() {
byte byteArray[] = { 5, 2, 3, 7, 8 };
byte outPutBuf[] = new byte[100];
Deflater defl = new Deflater();
defl.setInput(byteArray);
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
defl.end();
helper_end_test(defl, "end");
}
/**
* java.util.zip.Deflater#finalize()
*/
public void test_finalize() {
MyDeflater mdefl = new MyDeflater();
mdefl.myFinalize();
System.gc();
helper_end_test(mdefl, "finalize");
}
/**
* java.util.zip.Deflater#finish()
*/
public void test_finish() throws Exception {
// This test already here, its the same as test_deflate()
byte byteArray[] = { 5, 2, 3, 7, 8 };
byte outPutBuf[] = new byte[100];
byte outPutInf[] = new byte[100];
int x = 0;
Deflater defl = new Deflater();
defl.setInput(byteArray);
defl.finish();
// needsInput should never return true after finish() is called
if (System.getProperty("java.vendor").startsWith("IBM")) {
assertFalse("needsInput() should return false after finish() is called", defl
.needsInput());
}
while (!defl.finished()) {
x += defl.deflate(outPutBuf);
}
int totalOut = defl.getTotalOut();
int totalIn = defl.getTotalIn();
assertEquals(x, totalOut);
assertEquals(byteArray.length, totalIn);
defl.end();
Inflater infl = new Inflater();
infl.setInput(outPutBuf);
while (!infl.finished()) {
infl.inflate(outPutInf);
}
assertEquals(totalIn, infl.getTotalOut());
assertEquals(totalOut, infl.getTotalIn());
for (int i = 0; i < byteArray.length; i++) {
assertEquals(byteArray[i], outPutInf[i]);
}
assertEquals("Final decompressed data contained more bytes than original",
0, outPutInf[byteArray.length]);
infl.end();
}
/**
* java.util.zip.Deflater#finished()
*/
public void test_finished() {
byte byteArray[] = { 5, 2, 3, 7, 8 };
byte outPutBuf[] = new byte[100];
Deflater defl = new Deflater();
assertTrue("Test 1: Deflater should not be finished.", !defl.finished());
defl.setInput(byteArray);
assertTrue("Test 2: Deflater should not be finished.", !defl.finished());
defl.finish();
assertTrue("Test 3: Deflater should not be finished.", !defl.finished());
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
assertTrue("Test 4: Deflater should be finished.", defl.finished());
defl.end();
assertTrue("Test 5: Deflater should be finished.", defl.finished());
}
/**
* java.util.zip.Deflater#getAdler()
*/
public void test_getAdler() {
byte byteArray[] = { 'a', 'b', 'c', 1, 2, 3 };
byte outPutBuf[] = new byte[100];
Deflater defl = new Deflater();
// getting the checkSum value using the Adler
defl.setInput(byteArray);
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
long checkSumD = defl.getAdler();
defl.end();
// getting the checkSum value through the Adler32 class
Adler32 adl = new Adler32();
adl.update(byteArray);
long checkSumR = adl.getValue();
assertEquals(
"The checksum value returned by getAdler() is not the same as the checksum returned by creating the adler32 instance",
checkSumD, checkSumR);
}
/**
* java.util.zip.Deflater#getTotalIn()
*/
public void test_getTotalIn() {
byte outPutBuf[] = new byte[5];
byte byteArray[] = { 1, 3, 4, 7, 8 };
Deflater defl = new Deflater();
defl.setInput(byteArray);
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
assertEquals(byteArray.length, defl.getTotalIn());
defl.end();
defl = new Deflater();
int offSet = 2;
int length = 3;
outPutBuf = new byte[5];
defl.setInput(byteArray, offSet, length);
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
assertEquals(length, defl.getTotalIn());
defl.end();
}
/**
* java.util.zip.Deflater#getTotalOut()
*/
public void test_getTotalOut() {
// the getTotalOut should equal the sum of value returned by deflate()
byte outPutBuf[] = new byte[5];
byte byteArray[] = { 5, 2, 3, 7, 8 };
int x = 0;
Deflater defl = new Deflater();
defl.setInput(byteArray);
defl.finish();
while (!defl.finished()) {
x += defl.deflate(outPutBuf);
}
assertEquals(x, defl.getTotalOut());
defl.end();
x = 0;
int offSet = 2;
int length = 3;
defl = new Deflater();
outPutBuf = new byte[5];
defl.setInput(byteArray, offSet, length);
defl.finish();
while (!defl.finished()) {
x += defl.deflate(outPutBuf);
}
assertEquals(x, defl.getTotalOut());
defl.end();
}
/**
* java.util.zip.Deflater#needsInput()
*/
public void test_needsInput() {
Deflater defl = new Deflater();
assertTrue(
"needsInput give the wrong boolean value as a result of no input buffer",
defl.needsInput());
byte byteArray[] = { 1, 2, 3 };
defl.setInput(byteArray);
assertFalse(
"needsInput give wrong boolean value as a result of a full input buffer",
defl.needsInput());
byte[] outPutBuf = new byte[50];
while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
byte emptyByteArray[] = new byte[0];
defl.setInput(emptyByteArray);
assertTrue(
"needsInput give wrong boolean value as a result of an empty input buffer",
defl.needsInput());
defl.setInput(byteArray);
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
// needsInput should NOT return true after finish() has been
// called.
if (System.getProperty("java.vendor").startsWith("IBM")) {
assertFalse(
"needsInput gave wrong boolean value as a result of finish() being called",
defl.needsInput());
}
defl.end();
}
/**
* java.util.zip.Deflater#reset()
*/
public void test_reset() {
byte outPutBuf[] = new byte[100];
byte outPutInf[] = new byte[100];
byte curArray[] = new byte[5];
byte byteArray[] = { 1, 3, 4, 7, 8 };
byte byteArray2[] = { 8, 7, 4, 3, 1 };
int x = 0;
int orgValue = 0;
Deflater defl = new Deflater();
for (int i = 0; i < 3; i++) {
if (i == 0) {
curArray = byteArray;
} else if (i == 1) {
curArray = byteArray2;
} else {
defl.reset();
}
defl.setInput(curArray);
defl.finish();
while (!defl.finished()) {
x += defl.deflate(outPutBuf);
}
if (i == 0) {
assertEquals(x, defl.getTotalOut());
} else if (i == 1) {
assertEquals(x, orgValue);
} else {
assertEquals(x, orgValue * 2);
}
if (i == 0) {
orgValue = x;
}
try {
Inflater infl = new Inflater();
infl.setInput(outPutBuf);
while (!infl.finished()) {
infl.inflate(outPutInf);
}
infl.end();
} catch (DataFormatException e) {
fail("Test " + i + ": Invalid input to be decompressed");
}
if (i == 1) {
curArray = byteArray;
}
for (int j = 0; j < curArray.length; j++) {
assertEquals(curArray[j], outPutInf[j]);
}
assertEquals(0, outPutInf[curArray.length]);
}
defl.end();
}
/**
* java.util.zip.Deflater#setDictionary(byte[])
*/
public void test_setDictionary$B() {
// This test is very close to getAdler()
byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3 };
byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
'w', 'r' };
byte outPutBuf[] = new byte[100];
Deflater defl = new Deflater();
long deflAdler = defl.getAdler();
assertEquals("No dictionary set, no data deflated, getAdler should return 1",
1, deflAdler);
defl.setDictionary(dictionaryArray);
deflAdler = defl.getAdler();
// getting the checkSum value through the Adler32 class
Adler32 adl = new Adler32();
adl.update(dictionaryArray);
long realAdler = adl.getValue();
assertEquals(deflAdler, realAdler);
defl.setInput(byteArray);
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
deflAdler = defl.getAdler();
adl = new Adler32();
adl.update(byteArray);
realAdler = adl.getValue();
// Deflate is finished and there were bytes deflated that did not occur
// in the dictionaryArray, therefore a new dictionary was automatically
// set.
assertEquals(realAdler, deflAdler);
defl.end();
}
/**
* java.util.zip.Deflater#setDictionary(byte[], int, int)
*/
public void test_setDictionary$BII() {
// This test is very close to getAdler()
byte dictionaryArray[] = { 'e', 'r', 't', 'a', 'b', 2, 3, 'o', 't' };
byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
'w', 'r', 't', 'u', 'i', 'o', 4, 5, 6, 7 };
byte outPutBuf[] = new byte[500];
int offSet = 4;
int length = 5;
Deflater defl = new Deflater();
long deflAdler = defl.getAdler();
assertEquals("No dictionary set, no data deflated, getAdler should return 1",
1, deflAdler);
defl.setDictionary(dictionaryArray, offSet, length);
deflAdler = defl.getAdler();
// getting the checkSum value through the Adler32 class
Adler32 adl = new Adler32();
adl.update(dictionaryArray, offSet, length);
long realAdler = adl.getValue();
assertEquals(deflAdler, realAdler);
defl.setInput(byteArray);
while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
deflAdler = defl.getAdler();
adl = new Adler32();
adl.update(byteArray);
realAdler = adl.getValue();
// Deflate is finished and there were bytes deflated that did not occur
// in the dictionaryArray, therefore a new dictionary was automatically
// set.
assertEquals(realAdler, deflAdler);
defl.end();
// boundary check
defl = new Deflater();
for (int i = 0; i < 2; i++) {
if (i == 0) {
offSet = 0;
length = dictionaryArray.length + 1;
} else {
offSet = dictionaryArray.length + 1;
length = 1;
}
try {
defl.setDictionary(dictionaryArray, offSet, length);
fail(
"Test "
+ i
+ ": boundary check for setDictionary failed for offset "
+ offSet + " and length " + length);
} catch (ArrayIndexOutOfBoundsException e) {
}
}
defl.end();
}
/**
* java.util.zip.Deflater#setInput(byte[])
*/
public void test_setInput$B() {
byte[] byteArray = { 1, 2, 3 };
byte[] outPutBuf = new byte[50];
byte[] outPutInf = new byte[50];
Deflater defl = new Deflater();
defl.setInput(byteArray);
assertTrue("the array buffer in setInput() is empty", !defl
.needsInput());
// The second setInput() should be ignored since needsInput() return
// false
defl.setInput(byteArray);
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
defl.end();
Inflater infl = new Inflater();
try {
infl.setInput(outPutBuf);
while (!infl.finished()) {
infl.inflate(outPutInf);
}
} catch (DataFormatException e) {
fail("Invalid input to be decompressed");
}
for (int i = 0; i < byteArray.length; i++) {
assertEquals(byteArray[i], outPutInf[i]);
}
assertEquals(byteArray.length, infl.getTotalOut());
infl.end();
}
/**
* java.util.zip.Deflater#setInput(byte[], int, int)
*/
public void test_setInput$BII() throws Exception {
byte[] byteArray = { 1, 2, 3, 4, 5 };
byte[] outPutBuf = new byte[50];
byte[] outPutInf = new byte[50];
int offSet = 1;
int length = 3;
Deflater defl = new Deflater();
defl.setInput(byteArray, offSet, length);
assertFalse("the array buffer in setInput() is empty", defl.needsInput());
// The second setInput() should be ignored since needsInput() return
// false
defl.setInput(byteArray, offSet, length);
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
defl.end();
Inflater infl = new Inflater();
infl.setInput(outPutBuf);
while (!infl.finished()) {
infl.inflate(outPutInf);
}
for (int i = 0; i < length; i++) {
assertEquals(byteArray[i + offSet], outPutInf[i]);
}
assertEquals(length, infl.getTotalOut());
infl.end();
// boundary check
defl = new Deflater();
for (int i = 0; i < 2; i++) {
if (i == 0) {
offSet = 0;
length = byteArray.length + 1;
} else {
offSet = byteArray.length + 1;
length = 1;
}
try {
defl.setInput(byteArray, offSet, length);
fail("Test " + i
+ ": boundary check for setInput failed for offset "
+ offSet + " and length " + length);
} catch (ArrayIndexOutOfBoundsException e) {
}
}
defl.end();
}
/**
* java.util.zip.Deflater#setLevel(int)
*/
public void test_setLevelI() throws Exception {
// Very similar to test_Constructor(int)
byte[] byteArray = new byte[100];
InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
inFile.read(byteArray);
inFile.close();
byte[] outPutBuf;
int totalOut;
for (int i = 0; i < 10; i++) {
Deflater defl = new Deflater();
defl.setLevel(i);
outPutBuf = new byte[500];
defl.setInput(byteArray);
while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
totalOut = defl.getTotalOut();
defl.end();
outPutBuf = new byte[500];
defl = new Deflater(i);
defl.setInput(byteArray);
while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
assertEquals(totalOut, defl.getTotalOut());
defl.end();
}
// testing boundaries
Deflater boundDefl = new Deflater();
try {
// Level must be between 0-9
boundDefl.setLevel(-2);
fail(
"IllegalArgumentException not thrown when setting level to a number < 0.");
} catch (IllegalArgumentException e) {
}
try {
boundDefl.setLevel(10);
fail(
"IllegalArgumentException not thrown when setting level to a number > 9.");
} catch (IllegalArgumentException e) {
}
boundDefl.end();
}
/**
* java.util.zip.Deflater#setStrategy(int)
*/
public void test_setStrategyI() throws Exception {
byte[] byteArray = new byte[100];
InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
inFile.read(byteArray);
inFile.close();
for (int i = 0; i < 3; i++) {
byte outPutBuf[] = new byte[500];
MyDeflater mdefl = new MyDeflater();
if (i == 0) {
mdefl.setStrategy(mdefl.getDefStrategy());
} else if (i == 1) {
mdefl.setStrategy(mdefl.getHuffman());
} else {
mdefl.setStrategy(mdefl.getFiltered());
}
mdefl.setInput(byteArray);
while (!mdefl.needsInput()) {
mdefl.deflate(outPutBuf);
}
mdefl.finish();
while (!mdefl.finished()) {
mdefl.deflate(outPutBuf);
}
if (i == 0) {
// System.out.println(mdefl.getTotalOut());
// ran JDK and found that getTotalOut() = 86 for this particular
// file
assertEquals("getTotalOut() for the default strategy did not correspond with JDK",
86, mdefl.getTotalOut());
} else if (i == 1) {
// System.out.println(mdefl.getTotalOut());
// ran JDK and found that getTotalOut() = 100 for this
// particular file
assertEquals("getTotalOut() for the Huffman strategy did not correspond with JDK",
100, mdefl.getTotalOut());
} else {
// System.out.println(mdefl.getTotalOut());
// ran JDK and found that totalOut = 93 for this particular file
assertEquals("Total Out for the Filtered strategy did not correspond with JDK",
93, mdefl.getTotalOut());
}
mdefl.end();
}
// Attempting to setStrategy to an invalid value
Deflater defl = new Deflater();
try {
defl.setStrategy(-412);
fail("IllegalArgumentException not thrown when setting strategy to an invalid value.");
} catch (IllegalArgumentException e) {
}
defl.end();
}
/**
* java.util.zip.Deflater#Deflater()
*/
public void test_Constructor() throws Exception {
byte[] byteArray = new byte[100];
InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
inFile.read(byteArray);
inFile.close();
Deflater defl = new Deflater();
byte[] outPutBuf = new byte[500];
defl.setInput(byteArray);
while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
int totalOut = defl.getTotalOut();
defl.end();
// creating a Deflater using the DEFAULT_COMPRESSION as the int
MyDeflater mdefl = new MyDeflater();
mdefl.end();
mdefl = new MyDeflater(mdefl.getDefCompression());
outPutBuf = new byte[500];
mdefl.setInput(byteArray);
while (!mdefl.needsInput()) {
mdefl.deflate(outPutBuf);
}
mdefl.finish();
while (!mdefl.finished()) {
mdefl.deflate(outPutBuf);
}
assertEquals(totalOut, mdefl.getTotalOut());
mdefl.end();
}
/**
* java.util.zip.Deflater#Deflater(int, boolean)
*/
public void test_ConstructorIZ() throws Exception {
byte byteArray[] = { 4, 5, 3, 2, 'a', 'b', 6, 7, 8, 9, 0, 's', '3',
'w', 'r' };
Deflater defl = new Deflater();
byte outPutBuf[] = new byte[500];
defl.setLevel(2);
defl.setInput(byteArray);
while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
int totalOut = defl.getTotalOut();
defl.end();
outPutBuf = new byte[500];
defl = new Deflater(2, false);
defl.setInput(byteArray);
while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
assertEquals(totalOut, defl.getTotalOut());
defl.end();
outPutBuf = new byte[500];
defl = new Deflater(2, true);
defl.setInput(byteArray);
while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
assertTrue(
"getTotalOut() should not be equal comparing two Deflaters with different header options.",
defl.getTotalOut() != totalOut);
defl.end();
byte outPutInf[] = new byte[500];
Inflater infl = new Inflater(true);
while (!infl.finished()) {
if (infl.needsInput()) {
infl.setInput(outPutBuf);
}
infl.inflate(outPutInf);
}
for (int i = 0; i < byteArray.length; i++) {
assertEquals(byteArray[i], outPutInf[i]);
}
assertEquals("final decompressed data contained more bytes than original - constructorIZ",
0, outPutInf[byteArray.length]);
infl.end();
infl = new Inflater(false);
outPutInf = new byte[500];
int r = 0;
try {
while (!infl.finished()) {
if (infl.needsInput()) {
infl.setInput(outPutBuf);
}
infl.inflate(outPutInf);
}
} catch (DataFormatException e) {
r = 1;
}
infl.end();
assertEquals("header option did not correspond", 1, r);
// testing boundaries
Deflater boundDefl = new Deflater();
try {
// Level must be between 0-9
boundDefl.setLevel(-2);
fail("IllegalArgumentException not thrown when setting level to a number < 0.");
} catch (IllegalArgumentException e) {
}
try {
boundDefl.setLevel(10);
fail("IllegalArgumentException not thrown when setting level to a number > 9.");
} catch (IllegalArgumentException e) {
}
boundDefl.end();
try {
new Deflater(-2, true).end();
fail("IllegalArgumentException not thrown when passing level to a number < 0.");
} catch (IllegalArgumentException e) {
}
try {
new Deflater(10, true).end();
fail("IllegalArgumentException not thrown when passing level to a number > 9.");
} catch (IllegalArgumentException e) {
}
}
/**
* java.util.zip.Deflater#Deflater(int)
*/
public void test_ConstructorI() throws Exception {
byte[] byteArray = new byte[100];
InputStream inFile = Support_Resources.getStream("hyts_checkInput.txt");
inFile.read(byteArray);
inFile.close();
byte outPutBuf[] = new byte[500];
Deflater defl = new Deflater(3);
defl.setInput(byteArray);
while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
int totalOut = defl.getTotalOut();
defl.end();
// test to see if the compression ratio is the same as setting the level
// on a deflater
outPutBuf = new byte[500];
defl = new Deflater();
defl.setLevel(3);
defl.setInput(byteArray);
while (!defl.needsInput()) {
defl.deflate(outPutBuf);
}
defl.finish();
while (!defl.finished()) {
defl.deflate(outPutBuf);
}
assertEquals(totalOut, defl.getTotalOut());
defl.end();
// testing boundaries
Deflater boundDefl = new Deflater();
try {
// Level must be between 0-9
boundDefl.setLevel(-2);
fail("IllegalArgumentException not thrown when setting level to a number < 0.");
} catch (IllegalArgumentException e) {
}
try {
boundDefl.setLevel(10);
fail("IllegalArgumentException not thrown when setting level to a number > 9.");
} catch (IllegalArgumentException e) {
}
boundDefl.end();
}
private void helper_end_test(Deflater defl, String desc) {
// Help tests for test_end() and test_reset().
byte byteArray[] = { 5, 2, 3, 7, 8 };
// Methods where we expect IllegalStateException or NullPointerException
// to be thrown
try {
defl.getTotalOut();
fail("defl.getTotalOut() can still be used after " + desc
+ " is called in test_" + desc);
} catch (IllegalStateException e) {
} catch (NullPointerException e) {
}
try {
defl.getTotalIn();
fail("defl.getTotalIn() can still be used after " + desc
+ " is called in test_" + desc);
} catch (IllegalStateException e) {
} catch (NullPointerException e) {
}
try {
defl.getAdler();
fail("defl.getAdler() can still be used after " + desc
+ " is called in test_" + desc);
} catch (IllegalStateException e) {
} catch (NullPointerException e) {
}
try {
byte[] dict = { 'a', 'b', 'c' };
defl.setDictionary(dict);
fail("defl.setDictionary() can still be used after " + desc
+ " is called in test_" + desc);
} catch (IllegalStateException e) {
} catch (NullPointerException e) {
}
try {
defl.getTotalIn();
fail("defl.getTotalIn() can still be used after " + desc
+ " is called in test_" + desc);
} catch (IllegalStateException e) {
} catch (NullPointerException e) {
}
try {
defl.getTotalIn();
fail("defl.getTotalIn() can still be used after " + desc
+ " is called in test_" + desc);
} catch (IllegalStateException e) {
} catch (NullPointerException e) {
}
try {
defl.deflate(byteArray);
fail("defl.deflate() can still be used after " + desc
+ " is called in test_" + desc);
} catch (IllegalStateException e) {
} catch (NullPointerException e) {
}
// Methods where we expect NullPointerException to be thrown
try {
defl.reset();
fail("defl.reset() can still be used after " + desc
+ " is called in test_" + desc);
} catch (NullPointerException expected) {
} catch (IllegalStateException expected) {
}
// Methods where we expect NullPointerException to be thrown
try {
defl.getBytesRead();
fail("defl.reset() can still be used after " + desc
+ " is called in test_" + desc);
} catch (NullPointerException expected) {
} catch (IllegalStateException expected) {
}
// Methods where we expect NullPointerException to be thrown
try {
defl.getBytesWritten();
fail("defl.getBytesWritten() can still be used after " + desc
+ " is called in test_" + desc);
} catch (NullPointerException expected) {
} catch (IllegalStateException expected) {
}
// Methods that should be allowed to be called after end() is called
defl.needsInput();
defl.setStrategy(1);
defl.setLevel(1);
defl.end();
// Methods where exceptions should be thrown
String vendor = System.getProperty("java.vendor");
if (vendor.indexOf("IBM") != -1) {
try {
defl.setInput(byteArray);
fail("defl.setInput() can still be used after " + desc
+ " is called in test_" + desc);
} catch (IllegalStateException e) {
}
}
}
/**
* java.util.zip.Deflater()
*/
public void test_needsDictionary() {
Deflater inf = new Deflater();
assertEquals(0, inf.getTotalIn());
assertEquals(0, inf.getTotalOut());
assertEquals(0, inf.getBytesRead());
assertEquals(0, inf.getBytesWritten());
inf.end();
}
/**
* @throws DataFormatException
* @throws UnsupportedEncodingException
* java.util.zip.Deflater#getBytesRead()
*/
public void test_getBytesRead() throws DataFormatException,
UnsupportedEncodingException {
// Regression test for HARMONY-158
Deflater def = new Deflater();
assertEquals(0, def.getTotalIn());
assertEquals(0, def.getTotalOut());
assertEquals(0, def.getBytesRead());
// Encode a String into bytes
String inputString = "blahblahblah??";
byte[] input = inputString.getBytes("UTF-8");
// Compress the bytes
byte[] output = new byte[100];
def.setInput(input);
def.finish();
int compressedDataLength = def.deflate(output);
assertEquals(14, def.getTotalIn());
assertEquals(compressedDataLength, def.getTotalOut());
assertEquals(14, def.getBytesRead());
def.end();
}
/**
* @throws DataFormatException
* @throws UnsupportedEncodingException
* java.util.zip.Deflater#getBytesRead()
*/
public void test_getBytesWritten() throws DataFormatException,
UnsupportedEncodingException {
// Regression test for HARMONY-158
Deflater def = new Deflater();
assertEquals(0, def.getTotalIn());
assertEquals(0, def.getTotalOut());
assertEquals(0, def.getBytesWritten());
// Encode a String into bytes
String inputString = "blahblahblah??";
byte[] input = inputString.getBytes("UTF-8");
// Compress the bytes
byte[] output = new byte[100];
def.setInput(input);
def.finish();
int compressedDataLength = def.deflate(output);
assertEquals(14, def.getTotalIn());
assertEquals(compressedDataLength, def.getTotalOut());
assertEquals(compressedDataLength, def.getBytesWritten());
def.end();
}
//Regression Test for HARMONY-2481
public void test_deflate_beforeSetInput() throws Exception {
Deflater deflater = new Deflater();
deflater.finish();
byte[] buffer = new byte[1024];
assertEquals(8, deflater.deflate(buffer));
byte[] expectedBytes = { 120, -100, 3, 0, 0, 0, 0, 1 };
for (int i = 0; i < expectedBytes.length; i++) {
assertEquals(expectedBytes[i], buffer[i]);
}
deflater.end();
}
}
|
googleapis/google-api-java-client-services
| 38,365
|
clients/google-api-services-language/v1/2.0.0/com/google/api/services/language/v1/CloudNaturalLanguage.java
|
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.language.v1;
/**
* Service definition for CloudNaturalLanguage (v1).
*
* <p>
* Provides natural language understanding technologies, such as sentiment analysis, entity recognition, entity sentiment analysis, and other text annotations, to developers.
* </p>
*
* <p>
* For more information about this service, see the
* <a href="https://cloud.google.com/natural-language/" target="_blank">API Documentation</a>
* </p>
*
* <p>
* This service uses {@link CloudNaturalLanguageRequestInitializer} to initialize global parameters via its
* {@link Builder}.
* </p>
*
* @since 1.3
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public class CloudNaturalLanguage extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient {
// Note: Leave this static initializer at the top of the file.
static {
com.google.api.client.util.Preconditions.checkState(
(com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 &&
(com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 32 ||
(com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION == 31 &&
com.google.api.client.googleapis.GoogleUtils.BUGFIX_VERSION >= 1))) ||
com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION >= 2,
"You are currently running with version %s of google-api-client. " +
"You need at least version 1.31.1 of google-api-client to run version " +
"2.0.0 of the Cloud Natural Language API library.", com.google.api.client.googleapis.GoogleUtils.VERSION);
}
/**
* The default encoded root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_ROOT_URL = "https://language.googleapis.com/";
/**
* The default encoded mTLS root URL of the service. This is determined when the library is generated
* and normally should not be changed.
*
* @since 1.31
*/
public static final String DEFAULT_MTLS_ROOT_URL = "https://language.mtls.googleapis.com/";
/**
* The default encoded service path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.7
*/
public static final String DEFAULT_SERVICE_PATH = "";
/**
* The default encoded batch path of the service. This is determined when the library is
* generated and normally should not be changed.
*
* @since 1.23
*/
public static final String DEFAULT_BATCH_PATH = "batch";
/**
* The default encoded base URL of the service. This is determined when the library is generated
* and normally should not be changed.
*/
public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH;
/**
* Constructor.
*
* <p>
* Use {@link Builder} if you need to specify any of the optional parameters.
* </p>
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public CloudNaturalLanguage(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
this(new Builder(transport, jsonFactory, httpRequestInitializer));
}
/**
* @param builder builder
*/
CloudNaturalLanguage(Builder builder) {
super(builder);
}
@Override
protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException {
super.initialize(httpClientRequest);
}
/**
* An accessor for creating requests from the Documents collection.
*
* <p>The typical use is:</p>
* <pre>
* {@code CloudNaturalLanguage language = new CloudNaturalLanguage(...);}
* {@code CloudNaturalLanguage.Documents.List request = language.documents().list(parameters ...)}
* </pre>
*
* @return the resource collection
*/
public Documents documents() {
return new Documents();
}
/**
* The "documents" collection of methods.
*/
public class Documents {
/**
* Finds named entities (currently proper names and common nouns) in the text along with entity
* types, salience, mentions for each entity, and other properties.
*
* Create a request for the method "documents.analyzeEntities".
*
* This request holds the parameters needed by the language server. After setting any optional
* parameters, call the {@link AnalyzeEntities#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.language.v1.model.AnalyzeEntitiesRequest}
* @return the request
*/
public AnalyzeEntities analyzeEntities(com.google.api.services.language.v1.model.AnalyzeEntitiesRequest content) throws java.io.IOException {
AnalyzeEntities result = new AnalyzeEntities(content);
initialize(result);
return result;
}
public class AnalyzeEntities extends CloudNaturalLanguageRequest<com.google.api.services.language.v1.model.AnalyzeEntitiesResponse> {
private static final String REST_PATH = "v1/documents:analyzeEntities";
/**
* Finds named entities (currently proper names and common nouns) in the text along with entity
* types, salience, mentions for each entity, and other properties.
*
* Create a request for the method "documents.analyzeEntities".
*
* This request holds the parameters needed by the the language server. After setting any
* optional parameters, call the {@link AnalyzeEntities#execute()} method to invoke the remote
* operation. <p> {@link AnalyzeEntities#initialize(com.google.api.client.googleapis.services.Abst
* ractGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param content the {@link com.google.api.services.language.v1.model.AnalyzeEntitiesRequest}
* @since 1.13
*/
protected AnalyzeEntities(com.google.api.services.language.v1.model.AnalyzeEntitiesRequest content) {
super(CloudNaturalLanguage.this, "POST", REST_PATH, content, com.google.api.services.language.v1.model.AnalyzeEntitiesResponse.class);
}
@Override
public AnalyzeEntities set$Xgafv(java.lang.String $Xgafv) {
return (AnalyzeEntities) super.set$Xgafv($Xgafv);
}
@Override
public AnalyzeEntities setAccessToken(java.lang.String accessToken) {
return (AnalyzeEntities) super.setAccessToken(accessToken);
}
@Override
public AnalyzeEntities setAlt(java.lang.String alt) {
return (AnalyzeEntities) super.setAlt(alt);
}
@Override
public AnalyzeEntities setCallback(java.lang.String callback) {
return (AnalyzeEntities) super.setCallback(callback);
}
@Override
public AnalyzeEntities setFields(java.lang.String fields) {
return (AnalyzeEntities) super.setFields(fields);
}
@Override
public AnalyzeEntities setKey(java.lang.String key) {
return (AnalyzeEntities) super.setKey(key);
}
@Override
public AnalyzeEntities setOauthToken(java.lang.String oauthToken) {
return (AnalyzeEntities) super.setOauthToken(oauthToken);
}
@Override
public AnalyzeEntities setPrettyPrint(java.lang.Boolean prettyPrint) {
return (AnalyzeEntities) super.setPrettyPrint(prettyPrint);
}
@Override
public AnalyzeEntities setQuotaUser(java.lang.String quotaUser) {
return (AnalyzeEntities) super.setQuotaUser(quotaUser);
}
@Override
public AnalyzeEntities setUploadType(java.lang.String uploadType) {
return (AnalyzeEntities) super.setUploadType(uploadType);
}
@Override
public AnalyzeEntities setUploadProtocol(java.lang.String uploadProtocol) {
return (AnalyzeEntities) super.setUploadProtocol(uploadProtocol);
}
@Override
public AnalyzeEntities set(String parameterName, Object value) {
return (AnalyzeEntities) super.set(parameterName, value);
}
}
/**
* Finds entities, similar to AnalyzeEntities in the text and analyzes sentiment associated with
* each entity and its mentions.
*
* Create a request for the method "documents.analyzeEntitySentiment".
*
* This request holds the parameters needed by the language server. After setting any optional
* parameters, call the {@link AnalyzeEntitySentiment#execute()} method to invoke the remote
* operation.
*
* @param content the {@link com.google.api.services.language.v1.model.AnalyzeEntitySentimentRequest}
* @return the request
*/
public AnalyzeEntitySentiment analyzeEntitySentiment(com.google.api.services.language.v1.model.AnalyzeEntitySentimentRequest content) throws java.io.IOException {
AnalyzeEntitySentiment result = new AnalyzeEntitySentiment(content);
initialize(result);
return result;
}
public class AnalyzeEntitySentiment extends CloudNaturalLanguageRequest<com.google.api.services.language.v1.model.AnalyzeEntitySentimentResponse> {
private static final String REST_PATH = "v1/documents:analyzeEntitySentiment";
/**
* Finds entities, similar to AnalyzeEntities in the text and analyzes sentiment associated with
* each entity and its mentions.
*
* Create a request for the method "documents.analyzeEntitySentiment".
*
* This request holds the parameters needed by the the language server. After setting any
* optional parameters, call the {@link AnalyzeEntitySentiment#execute()} method to invoke the
* remote operation. <p> {@link AnalyzeEntitySentiment#initialize(com.google.api.client.googleapis
* .services.AbstractGoogleClientRequest)} must be called to initialize this instance immediately
* after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.language.v1.model.AnalyzeEntitySentimentRequest}
* @since 1.13
*/
protected AnalyzeEntitySentiment(com.google.api.services.language.v1.model.AnalyzeEntitySentimentRequest content) {
super(CloudNaturalLanguage.this, "POST", REST_PATH, content, com.google.api.services.language.v1.model.AnalyzeEntitySentimentResponse.class);
}
@Override
public AnalyzeEntitySentiment set$Xgafv(java.lang.String $Xgafv) {
return (AnalyzeEntitySentiment) super.set$Xgafv($Xgafv);
}
@Override
public AnalyzeEntitySentiment setAccessToken(java.lang.String accessToken) {
return (AnalyzeEntitySentiment) super.setAccessToken(accessToken);
}
@Override
public AnalyzeEntitySentiment setAlt(java.lang.String alt) {
return (AnalyzeEntitySentiment) super.setAlt(alt);
}
@Override
public AnalyzeEntitySentiment setCallback(java.lang.String callback) {
return (AnalyzeEntitySentiment) super.setCallback(callback);
}
@Override
public AnalyzeEntitySentiment setFields(java.lang.String fields) {
return (AnalyzeEntitySentiment) super.setFields(fields);
}
@Override
public AnalyzeEntitySentiment setKey(java.lang.String key) {
return (AnalyzeEntitySentiment) super.setKey(key);
}
@Override
public AnalyzeEntitySentiment setOauthToken(java.lang.String oauthToken) {
return (AnalyzeEntitySentiment) super.setOauthToken(oauthToken);
}
@Override
public AnalyzeEntitySentiment setPrettyPrint(java.lang.Boolean prettyPrint) {
return (AnalyzeEntitySentiment) super.setPrettyPrint(prettyPrint);
}
@Override
public AnalyzeEntitySentiment setQuotaUser(java.lang.String quotaUser) {
return (AnalyzeEntitySentiment) super.setQuotaUser(quotaUser);
}
@Override
public AnalyzeEntitySentiment setUploadType(java.lang.String uploadType) {
return (AnalyzeEntitySentiment) super.setUploadType(uploadType);
}
@Override
public AnalyzeEntitySentiment setUploadProtocol(java.lang.String uploadProtocol) {
return (AnalyzeEntitySentiment) super.setUploadProtocol(uploadProtocol);
}
@Override
public AnalyzeEntitySentiment set(String parameterName, Object value) {
return (AnalyzeEntitySentiment) super.set(parameterName, value);
}
}
/**
* Analyzes the sentiment of the provided text.
*
* Create a request for the method "documents.analyzeSentiment".
*
* This request holds the parameters needed by the language server. After setting any optional
* parameters, call the {@link AnalyzeSentiment#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.language.v1.model.AnalyzeSentimentRequest}
* @return the request
*/
public AnalyzeSentiment analyzeSentiment(com.google.api.services.language.v1.model.AnalyzeSentimentRequest content) throws java.io.IOException {
AnalyzeSentiment result = new AnalyzeSentiment(content);
initialize(result);
return result;
}
public class AnalyzeSentiment extends CloudNaturalLanguageRequest<com.google.api.services.language.v1.model.AnalyzeSentimentResponse> {
private static final String REST_PATH = "v1/documents:analyzeSentiment";
/**
* Analyzes the sentiment of the provided text.
*
* Create a request for the method "documents.analyzeSentiment".
*
* This request holds the parameters needed by the the language server. After setting any
* optional parameters, call the {@link AnalyzeSentiment#execute()} method to invoke the remote
* operation. <p> {@link AnalyzeSentiment#initialize(com.google.api.client.googleapis.services.Abs
* tractGoogleClientRequest)} must be called to initialize this instance immediately after
* invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.language.v1.model.AnalyzeSentimentRequest}
* @since 1.13
*/
protected AnalyzeSentiment(com.google.api.services.language.v1.model.AnalyzeSentimentRequest content) {
super(CloudNaturalLanguage.this, "POST", REST_PATH, content, com.google.api.services.language.v1.model.AnalyzeSentimentResponse.class);
}
@Override
public AnalyzeSentiment set$Xgafv(java.lang.String $Xgafv) {
return (AnalyzeSentiment) super.set$Xgafv($Xgafv);
}
@Override
public AnalyzeSentiment setAccessToken(java.lang.String accessToken) {
return (AnalyzeSentiment) super.setAccessToken(accessToken);
}
@Override
public AnalyzeSentiment setAlt(java.lang.String alt) {
return (AnalyzeSentiment) super.setAlt(alt);
}
@Override
public AnalyzeSentiment setCallback(java.lang.String callback) {
return (AnalyzeSentiment) super.setCallback(callback);
}
@Override
public AnalyzeSentiment setFields(java.lang.String fields) {
return (AnalyzeSentiment) super.setFields(fields);
}
@Override
public AnalyzeSentiment setKey(java.lang.String key) {
return (AnalyzeSentiment) super.setKey(key);
}
@Override
public AnalyzeSentiment setOauthToken(java.lang.String oauthToken) {
return (AnalyzeSentiment) super.setOauthToken(oauthToken);
}
@Override
public AnalyzeSentiment setPrettyPrint(java.lang.Boolean prettyPrint) {
return (AnalyzeSentiment) super.setPrettyPrint(prettyPrint);
}
@Override
public AnalyzeSentiment setQuotaUser(java.lang.String quotaUser) {
return (AnalyzeSentiment) super.setQuotaUser(quotaUser);
}
@Override
public AnalyzeSentiment setUploadType(java.lang.String uploadType) {
return (AnalyzeSentiment) super.setUploadType(uploadType);
}
@Override
public AnalyzeSentiment setUploadProtocol(java.lang.String uploadProtocol) {
return (AnalyzeSentiment) super.setUploadProtocol(uploadProtocol);
}
@Override
public AnalyzeSentiment set(String parameterName, Object value) {
return (AnalyzeSentiment) super.set(parameterName, value);
}
}
/**
* Analyzes the syntax of the text and provides sentence boundaries and tokenization along with part
* of speech tags, dependency trees, and other properties.
*
* Create a request for the method "documents.analyzeSyntax".
*
* This request holds the parameters needed by the language server. After setting any optional
* parameters, call the {@link AnalyzeSyntax#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.language.v1.model.AnalyzeSyntaxRequest}
* @return the request
*/
public AnalyzeSyntax analyzeSyntax(com.google.api.services.language.v1.model.AnalyzeSyntaxRequest content) throws java.io.IOException {
AnalyzeSyntax result = new AnalyzeSyntax(content);
initialize(result);
return result;
}
public class AnalyzeSyntax extends CloudNaturalLanguageRequest<com.google.api.services.language.v1.model.AnalyzeSyntaxResponse> {
private static final String REST_PATH = "v1/documents:analyzeSyntax";
/**
* Analyzes the syntax of the text and provides sentence boundaries and tokenization along with
* part of speech tags, dependency trees, and other properties.
*
* Create a request for the method "documents.analyzeSyntax".
*
* This request holds the parameters needed by the the language server. After setting any
* optional parameters, call the {@link AnalyzeSyntax#execute()} method to invoke the remote
* operation. <p> {@link AnalyzeSyntax#initialize(com.google.api.client.googleapis.services.Abstra
* ctGoogleClientRequest)} must be called to initialize this instance immediately after invoking
* the constructor. </p>
*
* @param content the {@link com.google.api.services.language.v1.model.AnalyzeSyntaxRequest}
* @since 1.13
*/
protected AnalyzeSyntax(com.google.api.services.language.v1.model.AnalyzeSyntaxRequest content) {
super(CloudNaturalLanguage.this, "POST", REST_PATH, content, com.google.api.services.language.v1.model.AnalyzeSyntaxResponse.class);
}
@Override
public AnalyzeSyntax set$Xgafv(java.lang.String $Xgafv) {
return (AnalyzeSyntax) super.set$Xgafv($Xgafv);
}
@Override
public AnalyzeSyntax setAccessToken(java.lang.String accessToken) {
return (AnalyzeSyntax) super.setAccessToken(accessToken);
}
@Override
public AnalyzeSyntax setAlt(java.lang.String alt) {
return (AnalyzeSyntax) super.setAlt(alt);
}
@Override
public AnalyzeSyntax setCallback(java.lang.String callback) {
return (AnalyzeSyntax) super.setCallback(callback);
}
@Override
public AnalyzeSyntax setFields(java.lang.String fields) {
return (AnalyzeSyntax) super.setFields(fields);
}
@Override
public AnalyzeSyntax setKey(java.lang.String key) {
return (AnalyzeSyntax) super.setKey(key);
}
@Override
public AnalyzeSyntax setOauthToken(java.lang.String oauthToken) {
return (AnalyzeSyntax) super.setOauthToken(oauthToken);
}
@Override
public AnalyzeSyntax setPrettyPrint(java.lang.Boolean prettyPrint) {
return (AnalyzeSyntax) super.setPrettyPrint(prettyPrint);
}
@Override
public AnalyzeSyntax setQuotaUser(java.lang.String quotaUser) {
return (AnalyzeSyntax) super.setQuotaUser(quotaUser);
}
@Override
public AnalyzeSyntax setUploadType(java.lang.String uploadType) {
return (AnalyzeSyntax) super.setUploadType(uploadType);
}
@Override
public AnalyzeSyntax setUploadProtocol(java.lang.String uploadProtocol) {
return (AnalyzeSyntax) super.setUploadProtocol(uploadProtocol);
}
@Override
public AnalyzeSyntax set(String parameterName, Object value) {
return (AnalyzeSyntax) super.set(parameterName, value);
}
}
/**
* A convenience method that provides all the features that analyzeSentiment, analyzeEntities, and
* analyzeSyntax provide in one call.
*
* Create a request for the method "documents.annotateText".
*
* This request holds the parameters needed by the language server. After setting any optional
* parameters, call the {@link AnnotateText#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.language.v1.model.AnnotateTextRequest}
* @return the request
*/
public AnnotateText annotateText(com.google.api.services.language.v1.model.AnnotateTextRequest content) throws java.io.IOException {
AnnotateText result = new AnnotateText(content);
initialize(result);
return result;
}
public class AnnotateText extends CloudNaturalLanguageRequest<com.google.api.services.language.v1.model.AnnotateTextResponse> {
private static final String REST_PATH = "v1/documents:annotateText";
/**
* A convenience method that provides all the features that analyzeSentiment, analyzeEntities, and
* analyzeSyntax provide in one call.
*
* Create a request for the method "documents.annotateText".
*
* This request holds the parameters needed by the the language server. After setting any
* optional parameters, call the {@link AnnotateText#execute()} method to invoke the remote
* operation. <p> {@link
* AnnotateText#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.language.v1.model.AnnotateTextRequest}
* @since 1.13
*/
protected AnnotateText(com.google.api.services.language.v1.model.AnnotateTextRequest content) {
super(CloudNaturalLanguage.this, "POST", REST_PATH, content, com.google.api.services.language.v1.model.AnnotateTextResponse.class);
}
@Override
public AnnotateText set$Xgafv(java.lang.String $Xgafv) {
return (AnnotateText) super.set$Xgafv($Xgafv);
}
@Override
public AnnotateText setAccessToken(java.lang.String accessToken) {
return (AnnotateText) super.setAccessToken(accessToken);
}
@Override
public AnnotateText setAlt(java.lang.String alt) {
return (AnnotateText) super.setAlt(alt);
}
@Override
public AnnotateText setCallback(java.lang.String callback) {
return (AnnotateText) super.setCallback(callback);
}
@Override
public AnnotateText setFields(java.lang.String fields) {
return (AnnotateText) super.setFields(fields);
}
@Override
public AnnotateText setKey(java.lang.String key) {
return (AnnotateText) super.setKey(key);
}
@Override
public AnnotateText setOauthToken(java.lang.String oauthToken) {
return (AnnotateText) super.setOauthToken(oauthToken);
}
@Override
public AnnotateText setPrettyPrint(java.lang.Boolean prettyPrint) {
return (AnnotateText) super.setPrettyPrint(prettyPrint);
}
@Override
public AnnotateText setQuotaUser(java.lang.String quotaUser) {
return (AnnotateText) super.setQuotaUser(quotaUser);
}
@Override
public AnnotateText setUploadType(java.lang.String uploadType) {
return (AnnotateText) super.setUploadType(uploadType);
}
@Override
public AnnotateText setUploadProtocol(java.lang.String uploadProtocol) {
return (AnnotateText) super.setUploadProtocol(uploadProtocol);
}
@Override
public AnnotateText set(String parameterName, Object value) {
return (AnnotateText) super.set(parameterName, value);
}
}
/**
* Classifies a document into categories.
*
* Create a request for the method "documents.classifyText".
*
* This request holds the parameters needed by the language server. After setting any optional
* parameters, call the {@link ClassifyText#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.language.v1.model.ClassifyTextRequest}
* @return the request
*/
public ClassifyText classifyText(com.google.api.services.language.v1.model.ClassifyTextRequest content) throws java.io.IOException {
ClassifyText result = new ClassifyText(content);
initialize(result);
return result;
}
public class ClassifyText extends CloudNaturalLanguageRequest<com.google.api.services.language.v1.model.ClassifyTextResponse> {
private static final String REST_PATH = "v1/documents:classifyText";
/**
* Classifies a document into categories.
*
* Create a request for the method "documents.classifyText".
*
* This request holds the parameters needed by the the language server. After setting any
* optional parameters, call the {@link ClassifyText#execute()} method to invoke the remote
* operation. <p> {@link
* ClassifyText#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.language.v1.model.ClassifyTextRequest}
* @since 1.13
*/
protected ClassifyText(com.google.api.services.language.v1.model.ClassifyTextRequest content) {
super(CloudNaturalLanguage.this, "POST", REST_PATH, content, com.google.api.services.language.v1.model.ClassifyTextResponse.class);
}
@Override
public ClassifyText set$Xgafv(java.lang.String $Xgafv) {
return (ClassifyText) super.set$Xgafv($Xgafv);
}
@Override
public ClassifyText setAccessToken(java.lang.String accessToken) {
return (ClassifyText) super.setAccessToken(accessToken);
}
@Override
public ClassifyText setAlt(java.lang.String alt) {
return (ClassifyText) super.setAlt(alt);
}
@Override
public ClassifyText setCallback(java.lang.String callback) {
return (ClassifyText) super.setCallback(callback);
}
@Override
public ClassifyText setFields(java.lang.String fields) {
return (ClassifyText) super.setFields(fields);
}
@Override
public ClassifyText setKey(java.lang.String key) {
return (ClassifyText) super.setKey(key);
}
@Override
public ClassifyText setOauthToken(java.lang.String oauthToken) {
return (ClassifyText) super.setOauthToken(oauthToken);
}
@Override
public ClassifyText setPrettyPrint(java.lang.Boolean prettyPrint) {
return (ClassifyText) super.setPrettyPrint(prettyPrint);
}
@Override
public ClassifyText setQuotaUser(java.lang.String quotaUser) {
return (ClassifyText) super.setQuotaUser(quotaUser);
}
@Override
public ClassifyText setUploadType(java.lang.String uploadType) {
return (ClassifyText) super.setUploadType(uploadType);
}
@Override
public ClassifyText setUploadProtocol(java.lang.String uploadProtocol) {
return (ClassifyText) super.setUploadProtocol(uploadProtocol);
}
@Override
public ClassifyText set(String parameterName, Object value) {
return (ClassifyText) super.set(parameterName, value);
}
}
/**
* Moderates a document for harmful and sensitive categories.
*
* Create a request for the method "documents.moderateText".
*
* This request holds the parameters needed by the language server. After setting any optional
* parameters, call the {@link ModerateText#execute()} method to invoke the remote operation.
*
* @param content the {@link com.google.api.services.language.v1.model.ModerateTextRequest}
* @return the request
*/
public ModerateText moderateText(com.google.api.services.language.v1.model.ModerateTextRequest content) throws java.io.IOException {
ModerateText result = new ModerateText(content);
initialize(result);
return result;
}
public class ModerateText extends CloudNaturalLanguageRequest<com.google.api.services.language.v1.model.ModerateTextResponse> {
private static final String REST_PATH = "v1/documents:moderateText";
/**
* Moderates a document for harmful and sensitive categories.
*
* Create a request for the method "documents.moderateText".
*
* This request holds the parameters needed by the the language server. After setting any
* optional parameters, call the {@link ModerateText#execute()} method to invoke the remote
* operation. <p> {@link
* ModerateText#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)}
* must be called to initialize this instance immediately after invoking the constructor. </p>
*
* @param content the {@link com.google.api.services.language.v1.model.ModerateTextRequest}
* @since 1.13
*/
protected ModerateText(com.google.api.services.language.v1.model.ModerateTextRequest content) {
super(CloudNaturalLanguage.this, "POST", REST_PATH, content, com.google.api.services.language.v1.model.ModerateTextResponse.class);
}
@Override
public ModerateText set$Xgafv(java.lang.String $Xgafv) {
return (ModerateText) super.set$Xgafv($Xgafv);
}
@Override
public ModerateText setAccessToken(java.lang.String accessToken) {
return (ModerateText) super.setAccessToken(accessToken);
}
@Override
public ModerateText setAlt(java.lang.String alt) {
return (ModerateText) super.setAlt(alt);
}
@Override
public ModerateText setCallback(java.lang.String callback) {
return (ModerateText) super.setCallback(callback);
}
@Override
public ModerateText setFields(java.lang.String fields) {
return (ModerateText) super.setFields(fields);
}
@Override
public ModerateText setKey(java.lang.String key) {
return (ModerateText) super.setKey(key);
}
@Override
public ModerateText setOauthToken(java.lang.String oauthToken) {
return (ModerateText) super.setOauthToken(oauthToken);
}
@Override
public ModerateText setPrettyPrint(java.lang.Boolean prettyPrint) {
return (ModerateText) super.setPrettyPrint(prettyPrint);
}
@Override
public ModerateText setQuotaUser(java.lang.String quotaUser) {
return (ModerateText) super.setQuotaUser(quotaUser);
}
@Override
public ModerateText setUploadType(java.lang.String uploadType) {
return (ModerateText) super.setUploadType(uploadType);
}
@Override
public ModerateText setUploadProtocol(java.lang.String uploadProtocol) {
return (ModerateText) super.setUploadProtocol(uploadProtocol);
}
@Override
public ModerateText set(String parameterName, Object value) {
return (ModerateText) super.set(parameterName, value);
}
}
}
/**
* Builder for {@link CloudNaturalLanguage}.
*
* <p>
* Implementation is not thread-safe.
* </p>
*
* @since 1.3.0
*/
public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder {
private static String chooseEndpoint(com.google.api.client.http.HttpTransport transport) {
// If the GOOGLE_API_USE_MTLS_ENDPOINT environment variable value is "always", use mTLS endpoint.
// If the env variable is "auto", use mTLS endpoint if and only if the transport is mTLS.
// Use the regular endpoint for all other cases.
String useMtlsEndpoint = System.getenv("GOOGLE_API_USE_MTLS_ENDPOINT");
useMtlsEndpoint = useMtlsEndpoint == null ? "auto" : useMtlsEndpoint;
if ("always".equals(useMtlsEndpoint) || ("auto".equals(useMtlsEndpoint) && transport != null && transport.isMtls())) {
return DEFAULT_MTLS_ROOT_URL;
}
return DEFAULT_ROOT_URL;
}
/**
* Returns an instance of a new builder.
*
* @param transport HTTP transport, which should normally be:
* <ul>
* <li>Google App Engine:
* {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li>
* <li>Android: {@code newCompatibleTransport} from
* {@code com.google.api.client.extensions.android.http.AndroidHttp}</li>
* <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()}
* </li>
* </ul>
* @param jsonFactory JSON factory, which may be:
* <ul>
* <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li>
* <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li>
* <li>Android Honeycomb or higher:
* {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li>
* </ul>
* @param httpRequestInitializer HTTP request initializer or {@code null} for none
* @since 1.7
*/
public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory,
com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
super(
transport,
jsonFactory,
Builder.chooseEndpoint(transport),
DEFAULT_SERVICE_PATH,
httpRequestInitializer,
false);
setBatchPath(DEFAULT_BATCH_PATH);
}
/** Builds a new instance of {@link CloudNaturalLanguage}. */
@Override
public CloudNaturalLanguage build() {
return new CloudNaturalLanguage(this);
}
@Override
public Builder setRootUrl(String rootUrl) {
return (Builder) super.setRootUrl(rootUrl);
}
@Override
public Builder setServicePath(String servicePath) {
return (Builder) super.setServicePath(servicePath);
}
@Override
public Builder setBatchPath(String batchPath) {
return (Builder) super.setBatchPath(batchPath);
}
@Override
public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) {
return (Builder) super.setHttpRequestInitializer(httpRequestInitializer);
}
@Override
public Builder setApplicationName(String applicationName) {
return (Builder) super.setApplicationName(applicationName);
}
@Override
public Builder setSuppressPatternChecks(boolean suppressPatternChecks) {
return (Builder) super.setSuppressPatternChecks(suppressPatternChecks);
}
@Override
public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) {
return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks);
}
@Override
public Builder setSuppressAllChecks(boolean suppressAllChecks) {
return (Builder) super.setSuppressAllChecks(suppressAllChecks);
}
/**
* Set the {@link CloudNaturalLanguageRequestInitializer}.
*
* @since 1.12
*/
public Builder setCloudNaturalLanguageRequestInitializer(
CloudNaturalLanguageRequestInitializer cloudnaturallanguageRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(cloudnaturallanguageRequestInitializer);
}
@Override
public Builder setGoogleClientRequestInitializer(
com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) {
return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer);
}
@Override
public Builder setUniverseDomain(String universeDomain) {
return (Builder) super.setUniverseDomain(universeDomain);
}
}
}
|
googleapis/google-cloud-java
| 38,333
|
java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/DeleteMachineImageRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* A request message for MachineImages.Delete. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.DeleteMachineImageRequest}
*/
public final class DeleteMachineImageRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.DeleteMachineImageRequest)
DeleteMachineImageRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use DeleteMachineImageRequest.newBuilder() to construct.
private DeleteMachineImageRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeleteMachineImageRequest() {
machineImage_ = "";
project_ = "";
requestId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DeleteMachineImageRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteMachineImageRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteMachineImageRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.DeleteMachineImageRequest.class,
com.google.cloud.compute.v1.DeleteMachineImageRequest.Builder.class);
}
private int bitField0_;
public static final int MACHINE_IMAGE_FIELD_NUMBER = 69189475;
@SuppressWarnings("serial")
private volatile java.lang.Object machineImage_ = "";
/**
*
*
* <pre>
* The name of the machine image to delete.
* </pre>
*
* <code>string machine_image = 69189475 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The machineImage.
*/
@java.lang.Override
public java.lang.String getMachineImage() {
java.lang.Object ref = machineImage_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
machineImage_ = s;
return s;
}
}
/**
*
*
* <pre>
* The name of the machine image to delete.
* </pre>
*
* <code>string machine_image = 69189475 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for machineImage.
*/
@java.lang.Override
public com.google.protobuf.ByteString getMachineImageBytes() {
java.lang.Object ref = machineImage_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
machineImage_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PROJECT_FIELD_NUMBER = 227560217;
@SuppressWarnings("serial")
private volatile java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
@java.lang.Override
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
@java.lang.Override
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int REQUEST_ID_FIELD_NUMBER = 37109963;
@SuppressWarnings("serial")
private volatile java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return Whether the requestId field is set.
*/
@java.lang.Override
public boolean hasRequestId() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The requestId.
*/
@java.lang.Override
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The bytes for requestId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 37109963, requestId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(machineImage_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 69189475, machineImage_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(37109963, requestId_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(machineImage_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(69189475, machineImage_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.DeleteMachineImageRequest)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.DeleteMachineImageRequest other =
(com.google.cloud.compute.v1.DeleteMachineImageRequest) obj;
if (!getMachineImage().equals(other.getMachineImage())) return false;
if (!getProject().equals(other.getProject())) return false;
if (hasRequestId() != other.hasRequestId()) return false;
if (hasRequestId()) {
if (!getRequestId().equals(other.getRequestId())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + MACHINE_IMAGE_FIELD_NUMBER;
hash = (53 * hash) + getMachineImage().hashCode();
hash = (37 * hash) + PROJECT_FIELD_NUMBER;
hash = (53 * hash) + getProject().hashCode();
if (hasRequestId()) {
hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER;
hash = (53 * hash) + getRequestId().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.compute.v1.DeleteMachineImageRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A request message for MachineImages.Delete. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.DeleteMachineImageRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.DeleteMachineImageRequest)
com.google.cloud.compute.v1.DeleteMachineImageRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteMachineImageRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteMachineImageRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.DeleteMachineImageRequest.class,
com.google.cloud.compute.v1.DeleteMachineImageRequest.Builder.class);
}
// Construct using com.google.cloud.compute.v1.DeleteMachineImageRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
machineImage_ = "";
project_ = "";
requestId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_DeleteMachineImageRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteMachineImageRequest getDefaultInstanceForType() {
return com.google.cloud.compute.v1.DeleteMachineImageRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteMachineImageRequest build() {
com.google.cloud.compute.v1.DeleteMachineImageRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteMachineImageRequest buildPartial() {
com.google.cloud.compute.v1.DeleteMachineImageRequest result =
new com.google.cloud.compute.v1.DeleteMachineImageRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.compute.v1.DeleteMachineImageRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.machineImage_ = machineImage_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.project_ = project_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.requestId_ = requestId_;
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.DeleteMachineImageRequest) {
return mergeFrom((com.google.cloud.compute.v1.DeleteMachineImageRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.DeleteMachineImageRequest other) {
if (other == com.google.cloud.compute.v1.DeleteMachineImageRequest.getDefaultInstance())
return this;
if (!other.getMachineImage().isEmpty()) {
machineImage_ = other.machineImage_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getProject().isEmpty()) {
project_ = other.project_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasRequestId()) {
requestId_ = other.requestId_;
bitField0_ |= 0x00000004;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 296879706:
{
requestId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 296879706
case 553515802:
{
machineImage_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 553515802
case 1820481738:
{
project_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 1820481738
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object machineImage_ = "";
/**
*
*
* <pre>
* The name of the machine image to delete.
* </pre>
*
* <code>string machine_image = 69189475 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The machineImage.
*/
public java.lang.String getMachineImage() {
java.lang.Object ref = machineImage_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
machineImage_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The name of the machine image to delete.
* </pre>
*
* <code>string machine_image = 69189475 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for machineImage.
*/
public com.google.protobuf.ByteString getMachineImageBytes() {
java.lang.Object ref = machineImage_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
machineImage_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The name of the machine image to delete.
* </pre>
*
* <code>string machine_image = 69189475 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The machineImage to set.
* @return This builder for chaining.
*/
public Builder setMachineImage(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
machineImage_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the machine image to delete.
* </pre>
*
* <code>string machine_image = 69189475 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearMachineImage() {
machineImage_ = getDefaultInstance().getMachineImage();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the machine image to delete.
* </pre>
*
* <code>string machine_image = 69189475 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for machineImage to set.
* @return This builder for chaining.
*/
public Builder setMachineImageBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
machineImage_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The project.
*/
public java.lang.String getProject() {
java.lang.Object ref = project_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
project_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return The bytes for project.
*/
public com.google.protobuf.ByteString getProjectBytes() {
java.lang.Object ref = project_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
project_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @param value The project to set.
* @return This builder for chaining.
*/
public Builder setProject(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearProject() {
project_ = getDefaultInstance().getProject();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>
* string project = 227560217 [(.google.api.field_behavior) = REQUIRED, (.google.cloud.operation_request_field) = "project"];
* </code>
*
* @param value The bytes for project to set.
* @return This builder for chaining.
*/
public Builder setProjectBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
project_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object requestId_ = "";
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return Whether the requestId field is set.
*/
public boolean hasRequestId() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The requestId.
*/
public java.lang.String getRequestId() {
java.lang.Object ref = requestId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
requestId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return The bytes for requestId.
*/
public com.google.protobuf.ByteString getRequestIdBytes() {
java.lang.Object ref = requestId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
requestId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @param value The requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
requestId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @return This builder for chaining.
*/
public Builder clearRequestId() {
requestId_ = getDefaultInstance().getRequestId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. The request ID must be a valid UUID with the exception that zero UUID is not supported ( 00000000-0000-0000-0000-000000000000).
* </pre>
*
* <code>optional string request_id = 37109963;</code>
*
* @param value The bytes for requestId to set.
* @return This builder for chaining.
*/
public Builder setRequestIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
requestId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.DeleteMachineImageRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.DeleteMachineImageRequest)
private static final com.google.cloud.compute.v1.DeleteMachineImageRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.DeleteMachineImageRequest();
}
public static com.google.cloud.compute.v1.DeleteMachineImageRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeleteMachineImageRequest> PARSER =
new com.google.protobuf.AbstractParser<DeleteMachineImageRequest>() {
@java.lang.Override
public DeleteMachineImageRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<DeleteMachineImageRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeleteMachineImageRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.DeleteMachineImageRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,207
|
java-asset/proto-google-cloud-asset-v1/src/main/java/com/google/cloud/asset/v1/CreateFeedRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/asset/v1/asset_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.asset.v1;
/**
*
*
* <pre>
* Create asset feed request.
* </pre>
*
* Protobuf type {@code google.cloud.asset.v1.CreateFeedRequest}
*/
public final class CreateFeedRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.asset.v1.CreateFeedRequest)
CreateFeedRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateFeedRequest.newBuilder() to construct.
private CreateFeedRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateFeedRequest() {
parent_ = "";
feedId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateFeedRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.asset.v1.AssetServiceProto
.internal_static_google_cloud_asset_v1_CreateFeedRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.asset.v1.AssetServiceProto
.internal_static_google_cloud_asset_v1_CreateFeedRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.asset.v1.CreateFeedRequest.class,
com.google.cloud.asset.v1.CreateFeedRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The name of the project/folder/organization where this feed
* should be created in. It can only be an organization number (such as
* "organizations/123"), a folder number (such as "folders/123"), a project ID
* (such as "projects/my-project-id"), or a project number (such as
* "projects/12345").
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The name of the project/folder/organization where this feed
* should be created in. It can only be an organization number (such as
* "organizations/123"), a folder number (such as "folders/123"), a project ID
* (such as "projects/my-project-id"), or a project number (such as
* "projects/12345").
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FEED_ID_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object feedId_ = "";
/**
*
*
* <pre>
* Required. This is the client-assigned asset feed identifier and it needs to
* be unique under a specific parent project/folder/organization.
* </pre>
*
* <code>string feed_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The feedId.
*/
@java.lang.Override
public java.lang.String getFeedId() {
java.lang.Object ref = feedId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
feedId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. This is the client-assigned asset feed identifier and it needs to
* be unique under a specific parent project/folder/organization.
* </pre>
*
* <code>string feed_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for feedId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFeedIdBytes() {
java.lang.Object ref = feedId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
feedId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FEED_FIELD_NUMBER = 3;
private com.google.cloud.asset.v1.Feed feed_;
/**
*
*
* <pre>
* Required. The feed details. The field `name` must be empty and it will be
* generated in the format of: projects/project_number/feeds/feed_id
* folders/folder_number/feeds/feed_id
* organizations/organization_number/feeds/feed_id
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return Whether the feed field is set.
*/
@java.lang.Override
public boolean hasFeed() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The feed details. The field `name` must be empty and it will be
* generated in the format of: projects/project_number/feeds/feed_id
* folders/folder_number/feeds/feed_id
* organizations/organization_number/feeds/feed_id
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The feed.
*/
@java.lang.Override
public com.google.cloud.asset.v1.Feed getFeed() {
return feed_ == null ? com.google.cloud.asset.v1.Feed.getDefaultInstance() : feed_;
}
/**
*
*
* <pre>
* Required. The feed details. The field `name` must be empty and it will be
* generated in the format of: projects/project_number/feeds/feed_id
* folders/folder_number/feeds/feed_id
* organizations/organization_number/feeds/feed_id
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.cloud.asset.v1.FeedOrBuilder getFeedOrBuilder() {
return feed_ == null ? com.google.cloud.asset.v1.Feed.getDefaultInstance() : feed_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(feedId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, feedId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(3, getFeed());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(feedId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, feedId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getFeed());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.asset.v1.CreateFeedRequest)) {
return super.equals(obj);
}
com.google.cloud.asset.v1.CreateFeedRequest other =
(com.google.cloud.asset.v1.CreateFeedRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getFeedId().equals(other.getFeedId())) return false;
if (hasFeed() != other.hasFeed()) return false;
if (hasFeed()) {
if (!getFeed().equals(other.getFeed())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + FEED_ID_FIELD_NUMBER;
hash = (53 * hash) + getFeedId().hashCode();
if (hasFeed()) {
hash = (37 * hash) + FEED_FIELD_NUMBER;
hash = (53 * hash) + getFeed().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.asset.v1.CreateFeedRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.asset.v1.CreateFeedRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.asset.v1.CreateFeedRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.asset.v1.CreateFeedRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.asset.v1.CreateFeedRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.asset.v1.CreateFeedRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.asset.v1.CreateFeedRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.asset.v1.CreateFeedRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.asset.v1.CreateFeedRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.asset.v1.CreateFeedRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.asset.v1.CreateFeedRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.asset.v1.CreateFeedRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.asset.v1.CreateFeedRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Create asset feed request.
* </pre>
*
* Protobuf type {@code google.cloud.asset.v1.CreateFeedRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.asset.v1.CreateFeedRequest)
com.google.cloud.asset.v1.CreateFeedRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.asset.v1.AssetServiceProto
.internal_static_google_cloud_asset_v1_CreateFeedRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.asset.v1.AssetServiceProto
.internal_static_google_cloud_asset_v1_CreateFeedRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.asset.v1.CreateFeedRequest.class,
com.google.cloud.asset.v1.CreateFeedRequest.Builder.class);
}
// Construct using com.google.cloud.asset.v1.CreateFeedRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getFeedFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
feedId_ = "";
feed_ = null;
if (feedBuilder_ != null) {
feedBuilder_.dispose();
feedBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.asset.v1.AssetServiceProto
.internal_static_google_cloud_asset_v1_CreateFeedRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.asset.v1.CreateFeedRequest getDefaultInstanceForType() {
return com.google.cloud.asset.v1.CreateFeedRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.asset.v1.CreateFeedRequest build() {
com.google.cloud.asset.v1.CreateFeedRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.asset.v1.CreateFeedRequest buildPartial() {
com.google.cloud.asset.v1.CreateFeedRequest result =
new com.google.cloud.asset.v1.CreateFeedRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.asset.v1.CreateFeedRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.feedId_ = feedId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.feed_ = feedBuilder_ == null ? feed_ : feedBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.asset.v1.CreateFeedRequest) {
return mergeFrom((com.google.cloud.asset.v1.CreateFeedRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.asset.v1.CreateFeedRequest other) {
if (other == com.google.cloud.asset.v1.CreateFeedRequest.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getFeedId().isEmpty()) {
feedId_ = other.feedId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasFeed()) {
mergeFeed(other.getFeed());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
feedId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getFeedFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The name of the project/folder/organization where this feed
* should be created in. It can only be an organization number (such as
* "organizations/123"), a folder number (such as "folders/123"), a project ID
* (such as "projects/my-project-id"), or a project number (such as
* "projects/12345").
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the project/folder/organization where this feed
* should be created in. It can only be an organization number (such as
* "organizations/123"), a folder number (such as "folders/123"), a project ID
* (such as "projects/my-project-id"), or a project number (such as
* "projects/12345").
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the project/folder/organization where this feed
* should be created in. It can only be an organization number (such as
* "organizations/123"), a folder number (such as "folders/123"), a project ID
* (such as "projects/my-project-id"), or a project number (such as
* "projects/12345").
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the project/folder/organization where this feed
* should be created in. It can only be an organization number (such as
* "organizations/123"), a folder number (such as "folders/123"), a project ID
* (such as "projects/my-project-id"), or a project number (such as
* "projects/12345").
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the project/folder/organization where this feed
* should be created in. It can only be an organization number (such as
* "organizations/123"), a folder number (such as "folders/123"), a project ID
* (such as "projects/my-project-id"), or a project number (such as
* "projects/12345").
* </pre>
*
* <code>string parent = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object feedId_ = "";
/**
*
*
* <pre>
* Required. This is the client-assigned asset feed identifier and it needs to
* be unique under a specific parent project/folder/organization.
* </pre>
*
* <code>string feed_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The feedId.
*/
public java.lang.String getFeedId() {
java.lang.Object ref = feedId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
feedId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. This is the client-assigned asset feed identifier and it needs to
* be unique under a specific parent project/folder/organization.
* </pre>
*
* <code>string feed_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for feedId.
*/
public com.google.protobuf.ByteString getFeedIdBytes() {
java.lang.Object ref = feedId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
feedId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. This is the client-assigned asset feed identifier and it needs to
* be unique under a specific parent project/folder/organization.
* </pre>
*
* <code>string feed_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The feedId to set.
* @return This builder for chaining.
*/
public Builder setFeedId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
feedId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. This is the client-assigned asset feed identifier and it needs to
* be unique under a specific parent project/folder/organization.
* </pre>
*
* <code>string feed_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearFeedId() {
feedId_ = getDefaultInstance().getFeedId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. This is the client-assigned asset feed identifier and it needs to
* be unique under a specific parent project/folder/organization.
* </pre>
*
* <code>string feed_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for feedId to set.
* @return This builder for chaining.
*/
public Builder setFeedIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
feedId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.cloud.asset.v1.Feed feed_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.asset.v1.Feed,
com.google.cloud.asset.v1.Feed.Builder,
com.google.cloud.asset.v1.FeedOrBuilder>
feedBuilder_;
/**
*
*
* <pre>
* Required. The feed details. The field `name` must be empty and it will be
* generated in the format of: projects/project_number/feeds/feed_id
* folders/folder_number/feeds/feed_id
* organizations/organization_number/feeds/feed_id
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return Whether the feed field is set.
*/
public boolean hasFeed() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Required. The feed details. The field `name` must be empty and it will be
* generated in the format of: projects/project_number/feeds/feed_id
* folders/folder_number/feeds/feed_id
* organizations/organization_number/feeds/feed_id
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The feed.
*/
public com.google.cloud.asset.v1.Feed getFeed() {
if (feedBuilder_ == null) {
return feed_ == null ? com.google.cloud.asset.v1.Feed.getDefaultInstance() : feed_;
} else {
return feedBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The feed details. The field `name` must be empty and it will be
* generated in the format of: projects/project_number/feeds/feed_id
* folders/folder_number/feeds/feed_id
* organizations/organization_number/feeds/feed_id
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setFeed(com.google.cloud.asset.v1.Feed value) {
if (feedBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
feed_ = value;
} else {
feedBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The feed details. The field `name` must be empty and it will be
* generated in the format of: projects/project_number/feeds/feed_id
* folders/folder_number/feeds/feed_id
* organizations/organization_number/feeds/feed_id
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setFeed(com.google.cloud.asset.v1.Feed.Builder builderForValue) {
if (feedBuilder_ == null) {
feed_ = builderForValue.build();
} else {
feedBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The feed details. The field `name` must be empty and it will be
* generated in the format of: projects/project_number/feeds/feed_id
* folders/folder_number/feeds/feed_id
* organizations/organization_number/feeds/feed_id
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder mergeFeed(com.google.cloud.asset.v1.Feed value) {
if (feedBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& feed_ != null
&& feed_ != com.google.cloud.asset.v1.Feed.getDefaultInstance()) {
getFeedBuilder().mergeFrom(value);
} else {
feed_ = value;
}
} else {
feedBuilder_.mergeFrom(value);
}
if (feed_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The feed details. The field `name` must be empty and it will be
* generated in the format of: projects/project_number/feeds/feed_id
* folders/folder_number/feeds/feed_id
* organizations/organization_number/feeds/feed_id
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearFeed() {
bitField0_ = (bitField0_ & ~0x00000004);
feed_ = null;
if (feedBuilder_ != null) {
feedBuilder_.dispose();
feedBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The feed details. The field `name` must be empty and it will be
* generated in the format of: projects/project_number/feeds/feed_id
* folders/folder_number/feeds/feed_id
* organizations/organization_number/feeds/feed_id
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.cloud.asset.v1.Feed.Builder getFeedBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getFeedFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The feed details. The field `name` must be empty and it will be
* generated in the format of: projects/project_number/feeds/feed_id
* folders/folder_number/feeds/feed_id
* organizations/organization_number/feeds/feed_id
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.cloud.asset.v1.FeedOrBuilder getFeedOrBuilder() {
if (feedBuilder_ != null) {
return feedBuilder_.getMessageOrBuilder();
} else {
return feed_ == null ? com.google.cloud.asset.v1.Feed.getDefaultInstance() : feed_;
}
}
/**
*
*
* <pre>
* Required. The feed details. The field `name` must be empty and it will be
* generated in the format of: projects/project_number/feeds/feed_id
* folders/folder_number/feeds/feed_id
* organizations/organization_number/feeds/feed_id
* </pre>
*
* <code>.google.cloud.asset.v1.Feed feed = 3 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.asset.v1.Feed,
com.google.cloud.asset.v1.Feed.Builder,
com.google.cloud.asset.v1.FeedOrBuilder>
getFeedFieldBuilder() {
if (feedBuilder_ == null) {
feedBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.asset.v1.Feed,
com.google.cloud.asset.v1.Feed.Builder,
com.google.cloud.asset.v1.FeedOrBuilder>(
getFeed(), getParentForChildren(), isClean());
feed_ = null;
}
return feedBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.asset.v1.CreateFeedRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.asset.v1.CreateFeedRequest)
private static final com.google.cloud.asset.v1.CreateFeedRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.asset.v1.CreateFeedRequest();
}
public static com.google.cloud.asset.v1.CreateFeedRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateFeedRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateFeedRequest>() {
@java.lang.Override
public CreateFeedRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<CreateFeedRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateFeedRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.asset.v1.CreateFeedRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
google/schemaorg-java
| 38,293
|
src/main/java/com/google/schemaorg/core/CreativeWork.java
|
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.schemaorg.core;
import com.google.common.collect.ImmutableList;
import com.google.schemaorg.JsonLdContext;
import com.google.schemaorg.SchemaOrgType;
import com.google.schemaorg.core.datatype.Date;
import com.google.schemaorg.core.datatype.DateTime;
import com.google.schemaorg.core.datatype.Integer;
import com.google.schemaorg.core.datatype.Number;
import com.google.schemaorg.core.datatype.Text;
import com.google.schemaorg.core.datatype.URL;
import com.google.schemaorg.goog.PopularityScoreSpecification;
import javax.annotation.Nullable;
/** Interface of <a href="http://schema.org/CreativeWork}">http://schema.org/CreativeWork}</a>. */
public interface CreativeWork extends Thing {
/**
* Builder interface of <a
* href="http://schema.org/CreativeWork}">http://schema.org/CreativeWork}</a>.
*/
public interface Builder extends Thing.Builder {
@Override
Builder addJsonLdContext(@Nullable JsonLdContext context);
@Override
Builder addJsonLdContext(@Nullable JsonLdContext.Builder context);
@Override
Builder setJsonLdId(@Nullable String value);
@Override
Builder setJsonLdReverse(String property, Thing obj);
@Override
Builder setJsonLdReverse(String property, Thing.Builder builder);
/** Add a value to property about. */
Builder addAbout(Thing value);
/** Add a value to property about. */
Builder addAbout(Thing.Builder value);
/** Add a value to property about. */
Builder addAbout(String value);
/** Add a value to property accessibilityAPI. */
Builder addAccessibilityAPI(Text value);
/** Add a value to property accessibilityAPI. */
Builder addAccessibilityAPI(String value);
/** Add a value to property accessibilityControl. */
Builder addAccessibilityControl(Text value);
/** Add a value to property accessibilityControl. */
Builder addAccessibilityControl(String value);
/** Add a value to property accessibilityFeature. */
Builder addAccessibilityFeature(Text value);
/** Add a value to property accessibilityFeature. */
Builder addAccessibilityFeature(String value);
/** Add a value to property accessibilityHazard. */
Builder addAccessibilityHazard(Text value);
/** Add a value to property accessibilityHazard. */
Builder addAccessibilityHazard(String value);
/** Add a value to property accountablePerson. */
Builder addAccountablePerson(Person value);
/** Add a value to property accountablePerson. */
Builder addAccountablePerson(Person.Builder value);
/** Add a value to property accountablePerson. */
Builder addAccountablePerson(String value);
/** Add a value to property additionalType. */
Builder addAdditionalType(URL value);
/** Add a value to property additionalType. */
Builder addAdditionalType(String value);
/** Add a value to property aggregateRating. */
Builder addAggregateRating(AggregateRating value);
/** Add a value to property aggregateRating. */
Builder addAggregateRating(AggregateRating.Builder value);
/** Add a value to property aggregateRating. */
Builder addAggregateRating(String value);
/** Add a value to property alternateName. */
Builder addAlternateName(Text value);
/** Add a value to property alternateName. */
Builder addAlternateName(String value);
/** Add a value to property alternativeHeadline. */
Builder addAlternativeHeadline(Text value);
/** Add a value to property alternativeHeadline. */
Builder addAlternativeHeadline(String value);
/** Add a value to property associatedMedia. */
Builder addAssociatedMedia(MediaObject value);
/** Add a value to property associatedMedia. */
Builder addAssociatedMedia(MediaObject.Builder value);
/** Add a value to property associatedMedia. */
Builder addAssociatedMedia(String value);
/** Add a value to property audience. */
Builder addAudience(Audience value);
/** Add a value to property audience. */
Builder addAudience(Audience.Builder value);
/** Add a value to property audience. */
Builder addAudience(String value);
/** Add a value to property audio. */
Builder addAudio(AudioObject value);
/** Add a value to property audio. */
Builder addAudio(AudioObject.Builder value);
/** Add a value to property audio. */
Builder addAudio(String value);
/** Add a value to property author. */
Builder addAuthor(Organization value);
/** Add a value to property author. */
Builder addAuthor(Organization.Builder value);
/** Add a value to property author. */
Builder addAuthor(Person value);
/** Add a value to property author. */
Builder addAuthor(Person.Builder value);
/** Add a value to property author. */
Builder addAuthor(String value);
/** Add a value to property award. */
Builder addAward(Text value);
/** Add a value to property award. */
Builder addAward(String value);
/** Add a value to property awards. */
Builder addAwards(Text value);
/** Add a value to property awards. */
Builder addAwards(String value);
/** Add a value to property character. */
Builder addCharacter(Person value);
/** Add a value to property character. */
Builder addCharacter(Person.Builder value);
/** Add a value to property character. */
Builder addCharacter(String value);
/** Add a value to property citation. */
Builder addCitation(CreativeWork value);
/** Add a value to property citation. */
Builder addCitation(CreativeWork.Builder value);
/** Add a value to property citation. */
Builder addCitation(Text value);
/** Add a value to property citation. */
Builder addCitation(String value);
/** Add a value to property comment. */
Builder addComment(Comment value);
/** Add a value to property comment. */
Builder addComment(Comment.Builder value);
/** Add a value to property comment. */
Builder addComment(String value);
/** Add a value to property commentCount. */
Builder addCommentCount(Integer value);
/** Add a value to property commentCount. */
Builder addCommentCount(String value);
/** Add a value to property contentLocation. */
Builder addContentLocation(Place value);
/** Add a value to property contentLocation. */
Builder addContentLocation(Place.Builder value);
/** Add a value to property contentLocation. */
Builder addContentLocation(String value);
/** Add a value to property contentRating. */
Builder addContentRating(Text value);
/** Add a value to property contentRating. */
Builder addContentRating(String value);
/** Add a value to property contributor. */
Builder addContributor(Organization value);
/** Add a value to property contributor. */
Builder addContributor(Organization.Builder value);
/** Add a value to property contributor. */
Builder addContributor(Person value);
/** Add a value to property contributor. */
Builder addContributor(Person.Builder value);
/** Add a value to property contributor. */
Builder addContributor(String value);
/** Add a value to property copyrightHolder. */
Builder addCopyrightHolder(Organization value);
/** Add a value to property copyrightHolder. */
Builder addCopyrightHolder(Organization.Builder value);
/** Add a value to property copyrightHolder. */
Builder addCopyrightHolder(Person value);
/** Add a value to property copyrightHolder. */
Builder addCopyrightHolder(Person.Builder value);
/** Add a value to property copyrightHolder. */
Builder addCopyrightHolder(String value);
/** Add a value to property copyrightYear. */
Builder addCopyrightYear(Number value);
/** Add a value to property copyrightYear. */
Builder addCopyrightYear(String value);
/** Add a value to property creator. */
Builder addCreator(Organization value);
/** Add a value to property creator. */
Builder addCreator(Organization.Builder value);
/** Add a value to property creator. */
Builder addCreator(Person value);
/** Add a value to property creator. */
Builder addCreator(Person.Builder value);
/** Add a value to property creator. */
Builder addCreator(String value);
/** Add a value to property dateCreated. */
Builder addDateCreated(Date value);
/** Add a value to property dateCreated. */
Builder addDateCreated(DateTime value);
/** Add a value to property dateCreated. */
Builder addDateCreated(String value);
/** Add a value to property dateModified. */
Builder addDateModified(Date value);
/** Add a value to property dateModified. */
Builder addDateModified(DateTime value);
/** Add a value to property dateModified. */
Builder addDateModified(String value);
/** Add a value to property datePublished. */
Builder addDatePublished(Date value);
/** Add a value to property datePublished. */
Builder addDatePublished(String value);
/** Add a value to property description. */
Builder addDescription(Text value);
/** Add a value to property description. */
Builder addDescription(String value);
/** Add a value to property discussionUrl. */
Builder addDiscussionUrl(URL value);
/** Add a value to property discussionUrl. */
Builder addDiscussionUrl(String value);
/** Add a value to property editor. */
Builder addEditor(Person value);
/** Add a value to property editor. */
Builder addEditor(Person.Builder value);
/** Add a value to property editor. */
Builder addEditor(String value);
/** Add a value to property educationalAlignment. */
Builder addEducationalAlignment(AlignmentObject value);
/** Add a value to property educationalAlignment. */
Builder addEducationalAlignment(AlignmentObject.Builder value);
/** Add a value to property educationalAlignment. */
Builder addEducationalAlignment(String value);
/** Add a value to property educationalUse. */
Builder addEducationalUse(Text value);
/** Add a value to property educationalUse. */
Builder addEducationalUse(String value);
/** Add a value to property encoding. */
Builder addEncoding(MediaObject value);
/** Add a value to property encoding. */
Builder addEncoding(MediaObject.Builder value);
/** Add a value to property encoding. */
Builder addEncoding(String value);
/** Add a value to property encodings. */
Builder addEncodings(MediaObject value);
/** Add a value to property encodings. */
Builder addEncodings(MediaObject.Builder value);
/** Add a value to property encodings. */
Builder addEncodings(String value);
/** Add a value to property exampleOfWork. */
Builder addExampleOfWork(CreativeWork value);
/** Add a value to property exampleOfWork. */
Builder addExampleOfWork(CreativeWork.Builder value);
/** Add a value to property exampleOfWork. */
Builder addExampleOfWork(String value);
/** Add a value to property fileFormat. */
Builder addFileFormat(Text value);
/** Add a value to property fileFormat. */
Builder addFileFormat(String value);
/** Add a value to property genre. */
Builder addGenre(Text value);
/** Add a value to property genre. */
Builder addGenre(URL value);
/** Add a value to property genre. */
Builder addGenre(String value);
/** Add a value to property hasPart. */
Builder addHasPart(CreativeWork value);
/** Add a value to property hasPart. */
Builder addHasPart(CreativeWork.Builder value);
/** Add a value to property hasPart. */
Builder addHasPart(String value);
/** Add a value to property headline. */
Builder addHeadline(Text value);
/** Add a value to property headline. */
Builder addHeadline(String value);
/** Add a value to property image. */
Builder addImage(ImageObject value);
/** Add a value to property image. */
Builder addImage(ImageObject.Builder value);
/** Add a value to property image. */
Builder addImage(URL value);
/** Add a value to property image. */
Builder addImage(String value);
/** Add a value to property inLanguage. */
Builder addInLanguage(Language value);
/** Add a value to property inLanguage. */
Builder addInLanguage(Language.Builder value);
/** Add a value to property inLanguage. */
Builder addInLanguage(Text value);
/** Add a value to property inLanguage. */
Builder addInLanguage(String value);
/** Add a value to property interactionStatistic. */
Builder addInteractionStatistic(InteractionCounter value);
/** Add a value to property interactionStatistic. */
Builder addInteractionStatistic(InteractionCounter.Builder value);
/** Add a value to property interactionStatistic. */
Builder addInteractionStatistic(String value);
/** Add a value to property interactivityType. */
Builder addInteractivityType(Text value);
/** Add a value to property interactivityType. */
Builder addInteractivityType(String value);
/** Add a value to property isBasedOnUrl. */
Builder addIsBasedOnUrl(URL value);
/** Add a value to property isBasedOnUrl. */
Builder addIsBasedOnUrl(String value);
/** Add a value to property isFamilyFriendly. */
Builder addIsFamilyFriendly(Boolean value);
/** Add a value to property isFamilyFriendly. */
Builder addIsFamilyFriendly(String value);
/** Add a value to property isPartOf. */
Builder addIsPartOf(CreativeWork value);
/** Add a value to property isPartOf. */
Builder addIsPartOf(CreativeWork.Builder value);
/** Add a value to property isPartOf. */
Builder addIsPartOf(String value);
/** Add a value to property keywords. */
Builder addKeywords(Text value);
/** Add a value to property keywords. */
Builder addKeywords(String value);
/** Add a value to property learningResourceType. */
Builder addLearningResourceType(Text value);
/** Add a value to property learningResourceType. */
Builder addLearningResourceType(String value);
/** Add a value to property license. */
Builder addLicense(CreativeWork value);
/** Add a value to property license. */
Builder addLicense(CreativeWork.Builder value);
/** Add a value to property license. */
Builder addLicense(URL value);
/** Add a value to property license. */
Builder addLicense(String value);
/** Add a value to property locationCreated. */
Builder addLocationCreated(Place value);
/** Add a value to property locationCreated. */
Builder addLocationCreated(Place.Builder value);
/** Add a value to property locationCreated. */
Builder addLocationCreated(String value);
/** Add a value to property mainEntity. */
Builder addMainEntity(Thing value);
/** Add a value to property mainEntity. */
Builder addMainEntity(Thing.Builder value);
/** Add a value to property mainEntity. */
Builder addMainEntity(String value);
/** Add a value to property mainEntityOfPage. */
Builder addMainEntityOfPage(CreativeWork value);
/** Add a value to property mainEntityOfPage. */
Builder addMainEntityOfPage(CreativeWork.Builder value);
/** Add a value to property mainEntityOfPage. */
Builder addMainEntityOfPage(URL value);
/** Add a value to property mainEntityOfPage. */
Builder addMainEntityOfPage(String value);
/** Add a value to property mentions. */
Builder addMentions(Thing value);
/** Add a value to property mentions. */
Builder addMentions(Thing.Builder value);
/** Add a value to property mentions. */
Builder addMentions(String value);
/** Add a value to property name. */
Builder addName(Text value);
/** Add a value to property name. */
Builder addName(String value);
/** Add a value to property offers. */
Builder addOffers(Offer value);
/** Add a value to property offers. */
Builder addOffers(Offer.Builder value);
/** Add a value to property offers. */
Builder addOffers(String value);
/** Add a value to property position. */
Builder addPosition(Integer value);
/** Add a value to property position. */
Builder addPosition(Text value);
/** Add a value to property position. */
Builder addPosition(String value);
/** Add a value to property potentialAction. */
Builder addPotentialAction(Action value);
/** Add a value to property potentialAction. */
Builder addPotentialAction(Action.Builder value);
/** Add a value to property potentialAction. */
Builder addPotentialAction(String value);
/** Add a value to property producer. */
Builder addProducer(Organization value);
/** Add a value to property producer. */
Builder addProducer(Organization.Builder value);
/** Add a value to property producer. */
Builder addProducer(Person value);
/** Add a value to property producer. */
Builder addProducer(Person.Builder value);
/** Add a value to property producer. */
Builder addProducer(String value);
/** Add a value to property provider. */
Builder addProvider(Organization value);
/** Add a value to property provider. */
Builder addProvider(Organization.Builder value);
/** Add a value to property provider. */
Builder addProvider(Person value);
/** Add a value to property provider. */
Builder addProvider(Person.Builder value);
/** Add a value to property provider. */
Builder addProvider(String value);
/** Add a value to property publication. */
Builder addPublication(PublicationEvent value);
/** Add a value to property publication. */
Builder addPublication(PublicationEvent.Builder value);
/** Add a value to property publication. */
Builder addPublication(String value);
/** Add a value to property publisher. */
Builder addPublisher(Organization value);
/** Add a value to property publisher. */
Builder addPublisher(Organization.Builder value);
/** Add a value to property publisher. */
Builder addPublisher(Person value);
/** Add a value to property publisher. */
Builder addPublisher(Person.Builder value);
/** Add a value to property publisher. */
Builder addPublisher(String value);
/** Add a value to property publishingPrinciples. */
Builder addPublishingPrinciples(URL value);
/** Add a value to property publishingPrinciples. */
Builder addPublishingPrinciples(String value);
/** Add a value to property recordedAt. */
Builder addRecordedAt(Event value);
/** Add a value to property recordedAt. */
Builder addRecordedAt(Event.Builder value);
/** Add a value to property recordedAt. */
Builder addRecordedAt(String value);
/** Add a value to property releasedEvent. */
Builder addReleasedEvent(PublicationEvent value);
/** Add a value to property releasedEvent. */
Builder addReleasedEvent(PublicationEvent.Builder value);
/** Add a value to property releasedEvent. */
Builder addReleasedEvent(String value);
/** Add a value to property review. */
Builder addReview(Review value);
/** Add a value to property review. */
Builder addReview(Review.Builder value);
/** Add a value to property review. */
Builder addReview(String value);
/** Add a value to property reviews. */
Builder addReviews(Review value);
/** Add a value to property reviews. */
Builder addReviews(Review.Builder value);
/** Add a value to property reviews. */
Builder addReviews(String value);
/** Add a value to property sameAs. */
Builder addSameAs(URL value);
/** Add a value to property sameAs. */
Builder addSameAs(String value);
/** Add a value to property schemaVersion. */
Builder addSchemaVersion(Text value);
/** Add a value to property schemaVersion. */
Builder addSchemaVersion(URL value);
/** Add a value to property schemaVersion. */
Builder addSchemaVersion(String value);
/** Add a value to property sourceOrganization. */
Builder addSourceOrganization(Organization value);
/** Add a value to property sourceOrganization. */
Builder addSourceOrganization(Organization.Builder value);
/** Add a value to property sourceOrganization. */
Builder addSourceOrganization(String value);
/** Add a value to property text. */
Builder addText(Text value);
/** Add a value to property text. */
Builder addText(String value);
/** Add a value to property thumbnailUrl. */
Builder addThumbnailUrl(URL value);
/** Add a value to property thumbnailUrl. */
Builder addThumbnailUrl(String value);
/** Add a value to property timeRequired. */
Builder addTimeRequired(Duration value);
/** Add a value to property timeRequired. */
Builder addTimeRequired(Duration.Builder value);
/** Add a value to property timeRequired. */
Builder addTimeRequired(String value);
/** Add a value to property translator. */
Builder addTranslator(Organization value);
/** Add a value to property translator. */
Builder addTranslator(Organization.Builder value);
/** Add a value to property translator. */
Builder addTranslator(Person value);
/** Add a value to property translator. */
Builder addTranslator(Person.Builder value);
/** Add a value to property translator. */
Builder addTranslator(String value);
/** Add a value to property typicalAgeRange. */
Builder addTypicalAgeRange(Text value);
/** Add a value to property typicalAgeRange. */
Builder addTypicalAgeRange(String value);
/** Add a value to property url. */
Builder addUrl(URL value);
/** Add a value to property url. */
Builder addUrl(String value);
/** Add a value to property version. */
Builder addVersion(Number value);
/** Add a value to property version. */
Builder addVersion(String value);
/** Add a value to property video. */
Builder addVideo(VideoObject value);
/** Add a value to property video. */
Builder addVideo(VideoObject.Builder value);
/** Add a value to property video. */
Builder addVideo(String value);
/** Add a value to property workExample. */
Builder addWorkExample(CreativeWork value);
/** Add a value to property workExample. */
Builder addWorkExample(CreativeWork.Builder value);
/** Add a value to property workExample. */
Builder addWorkExample(String value);
/** Add a value to property detailedDescription. */
Builder addDetailedDescription(Article value);
/** Add a value to property detailedDescription. */
Builder addDetailedDescription(Article.Builder value);
/** Add a value to property detailedDescription. */
Builder addDetailedDescription(String value);
/** Add a value to property popularityScore. */
Builder addPopularityScore(PopularityScoreSpecification value);
/** Add a value to property popularityScore. */
Builder addPopularityScore(PopularityScoreSpecification.Builder value);
/** Add a value to property popularityScore. */
Builder addPopularityScore(String value);
/**
* Add a value to property.
*
* @param name The property name.
* @param value The value of the property.
*/
Builder addProperty(String name, SchemaOrgType value);
/**
* Add a value to property.
*
* @param name The property name.
* @param builder The schema.org object builder for the property value.
*/
Builder addProperty(String name, Thing.Builder builder);
/**
* Add a value to property.
*
* @param name The property name.
* @param value The string value of the property.
*/
Builder addProperty(String name, String value);
/** Build a {@link CreativeWork} object. */
CreativeWork build();
}
/**
* Returns the value list of property about. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getAboutList();
/**
* Returns the value list of property accessibilityAPI. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getAccessibilityAPIList();
/**
* Returns the value list of property accessibilityControl. Empty list is returned if the property
* not set in current object.
*/
ImmutableList<SchemaOrgType> getAccessibilityControlList();
/**
* Returns the value list of property accessibilityFeature. Empty list is returned if the property
* not set in current object.
*/
ImmutableList<SchemaOrgType> getAccessibilityFeatureList();
/**
* Returns the value list of property accessibilityHazard. Empty list is returned if the property
* not set in current object.
*/
ImmutableList<SchemaOrgType> getAccessibilityHazardList();
/**
* Returns the value list of property accountablePerson. Empty list is returned if the property
* not set in current object.
*/
ImmutableList<SchemaOrgType> getAccountablePersonList();
/**
* Returns the value list of property aggregateRating. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getAggregateRatingList();
/**
* Returns the value list of property alternativeHeadline. Empty list is returned if the property
* not set in current object.
*/
ImmutableList<SchemaOrgType> getAlternativeHeadlineList();
/**
* Returns the value list of property associatedMedia. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getAssociatedMediaList();
/**
* Returns the value list of property audience. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getAudienceList();
/**
* Returns the value list of property audio. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getAudioList();
/**
* Returns the value list of property author. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getAuthorList();
/**
* Returns the value list of property award. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getAwardList();
/**
* Returns the value list of property awards. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getAwardsList();
/**
* Returns the value list of property character. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getCharacterList();
/**
* Returns the value list of property citation. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getCitationList();
/**
* Returns the value list of property comment. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getCommentList();
/**
* Returns the value list of property commentCount. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getCommentCountList();
/**
* Returns the value list of property contentLocation. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getContentLocationList();
/**
* Returns the value list of property contentRating. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getContentRatingList();
/**
* Returns the value list of property contributor. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getContributorList();
/**
* Returns the value list of property copyrightHolder. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getCopyrightHolderList();
/**
* Returns the value list of property copyrightYear. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getCopyrightYearList();
/**
* Returns the value list of property creator. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getCreatorList();
/**
* Returns the value list of property dateCreated. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getDateCreatedList();
/**
* Returns the value list of property dateModified. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getDateModifiedList();
/**
* Returns the value list of property datePublished. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getDatePublishedList();
/**
* Returns the value list of property discussionUrl. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getDiscussionUrlList();
/**
* Returns the value list of property editor. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getEditorList();
/**
* Returns the value list of property educationalAlignment. Empty list is returned if the property
* not set in current object.
*/
ImmutableList<SchemaOrgType> getEducationalAlignmentList();
/**
* Returns the value list of property educationalUse. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getEducationalUseList();
/**
* Returns the value list of property encoding. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getEncodingList();
/**
* Returns the value list of property encodings. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getEncodingsList();
/**
* Returns the value list of property exampleOfWork. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getExampleOfWorkList();
/**
* Returns the value list of property fileFormat. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getFileFormatList();
/**
* Returns the value list of property genre. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getGenreList();
/**
* Returns the value list of property hasPart. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getHasPartList();
/**
* Returns the value list of property headline. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getHeadlineList();
/**
* Returns the value list of property inLanguage. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getInLanguageList();
/**
* Returns the value list of property interactionStatistic. Empty list is returned if the property
* not set in current object.
*/
ImmutableList<SchemaOrgType> getInteractionStatisticList();
/**
* Returns the value list of property interactivityType. Empty list is returned if the property
* not set in current object.
*/
ImmutableList<SchemaOrgType> getInteractivityTypeList();
/**
* Returns the value list of property isBasedOnUrl. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getIsBasedOnUrlList();
/**
* Returns the value list of property isFamilyFriendly. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getIsFamilyFriendlyList();
/**
* Returns the value list of property isPartOf. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getIsPartOfList();
/**
* Returns the value list of property keywords. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getKeywordsList();
/**
* Returns the value list of property learningResourceType. Empty list is returned if the property
* not set in current object.
*/
ImmutableList<SchemaOrgType> getLearningResourceTypeList();
/**
* Returns the value list of property license. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getLicenseList();
/**
* Returns the value list of property locationCreated. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getLocationCreatedList();
/**
* Returns the value list of property mainEntity. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getMainEntityList();
/**
* Returns the value list of property mentions. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getMentionsList();
/**
* Returns the value list of property offers. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getOffersList();
/**
* Returns the value list of property position. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getPositionList();
/**
* Returns the value list of property producer. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getProducerList();
/**
* Returns the value list of property provider. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getProviderList();
/**
* Returns the value list of property publication. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getPublicationList();
/**
* Returns the value list of property publisher. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getPublisherList();
/**
* Returns the value list of property publishingPrinciples. Empty list is returned if the property
* not set in current object.
*/
ImmutableList<SchemaOrgType> getPublishingPrinciplesList();
/**
* Returns the value list of property recordedAt. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getRecordedAtList();
/**
* Returns the value list of property releasedEvent. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getReleasedEventList();
/**
* Returns the value list of property review. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getReviewList();
/**
* Returns the value list of property reviews. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getReviewsList();
/**
* Returns the value list of property schemaVersion. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getSchemaVersionList();
/**
* Returns the value list of property sourceOrganization. Empty list is returned if the property
* not set in current object.
*/
ImmutableList<SchemaOrgType> getSourceOrganizationList();
/**
* Returns the value list of property text. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getTextList();
/**
* Returns the value list of property thumbnailUrl. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getThumbnailUrlList();
/**
* Returns the value list of property timeRequired. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getTimeRequiredList();
/**
* Returns the value list of property translator. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getTranslatorList();
/**
* Returns the value list of property typicalAgeRange. Empty list is returned if the property not
* set in current object.
*/
ImmutableList<SchemaOrgType> getTypicalAgeRangeList();
/**
* Returns the value list of property version. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getVersionList();
/**
* Returns the value list of property video. Empty list is returned if the property not set in
* current object.
*/
ImmutableList<SchemaOrgType> getVideoList();
/**
* Returns the value list of property workExample. Empty list is returned if the property not set
* in current object.
*/
ImmutableList<SchemaOrgType> getWorkExampleList();
}
|
googleapis/google-cloud-java
| 38,211
|
java-websecurityscanner/proto-google-cloud-websecurityscanner-v1alpha/src/main/java/com/google/cloud/websecurityscanner/v1alpha/ListCrawledUrlsResponse.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/websecurityscanner/v1alpha/web_security_scanner.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.websecurityscanner.v1alpha;
/**
*
*
* <pre>
* Response for the `ListCrawledUrls` method.
* </pre>
*
* Protobuf type {@code google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse}
*/
public final class ListCrawledUrlsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse)
ListCrawledUrlsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListCrawledUrlsResponse.newBuilder() to construct.
private ListCrawledUrlsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListCrawledUrlsResponse() {
crawledUrls_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListCrawledUrlsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListCrawledUrlsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListCrawledUrlsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse.class,
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse.Builder.class);
}
public static final int CRAWLED_URLS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.websecurityscanner.v1alpha.CrawledUrl> crawledUrls_;
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.websecurityscanner.v1alpha.CrawledUrl>
getCrawledUrlsList() {
return crawledUrls_;
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.websecurityscanner.v1alpha.CrawledUrlOrBuilder>
getCrawledUrlsOrBuilderList() {
return crawledUrls_;
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
@java.lang.Override
public int getCrawledUrlsCount() {
return crawledUrls_.size();
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.CrawledUrl getCrawledUrls(int index) {
return crawledUrls_.get(index);
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.CrawledUrlOrBuilder getCrawledUrlsOrBuilder(
int index) {
return crawledUrls_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < crawledUrls_.size(); i++) {
output.writeMessage(1, crawledUrls_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < crawledUrls_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, crawledUrls_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse)) {
return super.equals(obj);
}
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse other =
(com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse) obj;
if (!getCrawledUrlsList().equals(other.getCrawledUrlsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getCrawledUrlsCount() > 0) {
hash = (37 * hash) + CRAWLED_URLS_FIELD_NUMBER;
hash = (53 * hash) + getCrawledUrlsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response for the `ListCrawledUrls` method.
* </pre>
*
* Protobuf type {@code google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse)
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListCrawledUrlsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListCrawledUrlsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse.class,
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse.Builder.class);
}
// Construct using
// com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (crawledUrlsBuilder_ == null) {
crawledUrls_ = java.util.Collections.emptyList();
} else {
crawledUrls_ = null;
crawledUrlsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListCrawledUrlsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse
getDefaultInstanceForType() {
return com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse build() {
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse buildPartial() {
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse result =
new com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse result) {
if (crawledUrlsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
crawledUrls_ = java.util.Collections.unmodifiableList(crawledUrls_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.crawledUrls_ = crawledUrls_;
} else {
result.crawledUrls_ = crawledUrlsBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse) {
return mergeFrom(
(com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse other) {
if (other
== com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse
.getDefaultInstance()) return this;
if (crawledUrlsBuilder_ == null) {
if (!other.crawledUrls_.isEmpty()) {
if (crawledUrls_.isEmpty()) {
crawledUrls_ = other.crawledUrls_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureCrawledUrlsIsMutable();
crawledUrls_.addAll(other.crawledUrls_);
}
onChanged();
}
} else {
if (!other.crawledUrls_.isEmpty()) {
if (crawledUrlsBuilder_.isEmpty()) {
crawledUrlsBuilder_.dispose();
crawledUrlsBuilder_ = null;
crawledUrls_ = other.crawledUrls_;
bitField0_ = (bitField0_ & ~0x00000001);
crawledUrlsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getCrawledUrlsFieldBuilder()
: null;
} else {
crawledUrlsBuilder_.addAllMessages(other.crawledUrls_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.websecurityscanner.v1alpha.CrawledUrl m =
input.readMessage(
com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.parser(),
extensionRegistry);
if (crawledUrlsBuilder_ == null) {
ensureCrawledUrlsIsMutable();
crawledUrls_.add(m);
} else {
crawledUrlsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.websecurityscanner.v1alpha.CrawledUrl> crawledUrls_ =
java.util.Collections.emptyList();
private void ensureCrawledUrlsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
crawledUrls_ =
new java.util.ArrayList<com.google.cloud.websecurityscanner.v1alpha.CrawledUrl>(
crawledUrls_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.websecurityscanner.v1alpha.CrawledUrl,
com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.Builder,
com.google.cloud.websecurityscanner.v1alpha.CrawledUrlOrBuilder>
crawledUrlsBuilder_;
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public java.util.List<com.google.cloud.websecurityscanner.v1alpha.CrawledUrl>
getCrawledUrlsList() {
if (crawledUrlsBuilder_ == null) {
return java.util.Collections.unmodifiableList(crawledUrls_);
} else {
return crawledUrlsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public int getCrawledUrlsCount() {
if (crawledUrlsBuilder_ == null) {
return crawledUrls_.size();
} else {
return crawledUrlsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1alpha.CrawledUrl getCrawledUrls(int index) {
if (crawledUrlsBuilder_ == null) {
return crawledUrls_.get(index);
} else {
return crawledUrlsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public Builder setCrawledUrls(
int index, com.google.cloud.websecurityscanner.v1alpha.CrawledUrl value) {
if (crawledUrlsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCrawledUrlsIsMutable();
crawledUrls_.set(index, value);
onChanged();
} else {
crawledUrlsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public Builder setCrawledUrls(
int index, com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.Builder builderForValue) {
if (crawledUrlsBuilder_ == null) {
ensureCrawledUrlsIsMutable();
crawledUrls_.set(index, builderForValue.build());
onChanged();
} else {
crawledUrlsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public Builder addCrawledUrls(com.google.cloud.websecurityscanner.v1alpha.CrawledUrl value) {
if (crawledUrlsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCrawledUrlsIsMutable();
crawledUrls_.add(value);
onChanged();
} else {
crawledUrlsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public Builder addCrawledUrls(
int index, com.google.cloud.websecurityscanner.v1alpha.CrawledUrl value) {
if (crawledUrlsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCrawledUrlsIsMutable();
crawledUrls_.add(index, value);
onChanged();
} else {
crawledUrlsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public Builder addCrawledUrls(
com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.Builder builderForValue) {
if (crawledUrlsBuilder_ == null) {
ensureCrawledUrlsIsMutable();
crawledUrls_.add(builderForValue.build());
onChanged();
} else {
crawledUrlsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public Builder addCrawledUrls(
int index, com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.Builder builderForValue) {
if (crawledUrlsBuilder_ == null) {
ensureCrawledUrlsIsMutable();
crawledUrls_.add(index, builderForValue.build());
onChanged();
} else {
crawledUrlsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public Builder addAllCrawledUrls(
java.lang.Iterable<? extends com.google.cloud.websecurityscanner.v1alpha.CrawledUrl>
values) {
if (crawledUrlsBuilder_ == null) {
ensureCrawledUrlsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, crawledUrls_);
onChanged();
} else {
crawledUrlsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public Builder clearCrawledUrls() {
if (crawledUrlsBuilder_ == null) {
crawledUrls_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
crawledUrlsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public Builder removeCrawledUrls(int index) {
if (crawledUrlsBuilder_ == null) {
ensureCrawledUrlsIsMutable();
crawledUrls_.remove(index);
onChanged();
} else {
crawledUrlsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.Builder getCrawledUrlsBuilder(
int index) {
return getCrawledUrlsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1alpha.CrawledUrlOrBuilder getCrawledUrlsOrBuilder(
int index) {
if (crawledUrlsBuilder_ == null) {
return crawledUrls_.get(index);
} else {
return crawledUrlsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public java.util.List<? extends com.google.cloud.websecurityscanner.v1alpha.CrawledUrlOrBuilder>
getCrawledUrlsOrBuilderList() {
if (crawledUrlsBuilder_ != null) {
return crawledUrlsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(crawledUrls_);
}
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.Builder addCrawledUrlsBuilder() {
return getCrawledUrlsFieldBuilder()
.addBuilder(com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.Builder addCrawledUrlsBuilder(
int index) {
return getCrawledUrlsFieldBuilder()
.addBuilder(
index, com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of CrawledUrls returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.CrawledUrl crawled_urls = 1;</code>
*/
public java.util.List<com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.Builder>
getCrawledUrlsBuilderList() {
return getCrawledUrlsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.websecurityscanner.v1alpha.CrawledUrl,
com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.Builder,
com.google.cloud.websecurityscanner.v1alpha.CrawledUrlOrBuilder>
getCrawledUrlsFieldBuilder() {
if (crawledUrlsBuilder_ == null) {
crawledUrlsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.websecurityscanner.v1alpha.CrawledUrl,
com.google.cloud.websecurityscanner.v1alpha.CrawledUrl.Builder,
com.google.cloud.websecurityscanner.v1alpha.CrawledUrlOrBuilder>(
crawledUrls_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
crawledUrls_ = null;
}
return crawledUrlsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse)
private static final com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse();
}
public static com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListCrawledUrlsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListCrawledUrlsResponse>() {
@java.lang.Override
public ListCrawledUrlsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListCrawledUrlsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListCrawledUrlsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ListCrawledUrlsResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,211
|
java-websecurityscanner/proto-google-cloud-websecurityscanner-v1alpha/src/main/java/com/google/cloud/websecurityscanner/v1alpha/ListScanConfigsResponse.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/websecurityscanner/v1alpha/web_security_scanner.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.websecurityscanner.v1alpha;
/**
*
*
* <pre>
* Response for the `ListScanConfigs` method.
* </pre>
*
* Protobuf type {@code google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse}
*/
public final class ListScanConfigsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse)
ListScanConfigsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListScanConfigsResponse.newBuilder() to construct.
private ListScanConfigsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListScanConfigsResponse() {
scanConfigs_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListScanConfigsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListScanConfigsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListScanConfigsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse.class,
com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse.Builder.class);
}
public static final int SCAN_CONFIGS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.websecurityscanner.v1alpha.ScanConfig> scanConfigs_;
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.websecurityscanner.v1alpha.ScanConfig>
getScanConfigsList() {
return scanConfigs_;
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.websecurityscanner.v1alpha.ScanConfigOrBuilder>
getScanConfigsOrBuilderList() {
return scanConfigs_;
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
@java.lang.Override
public int getScanConfigsCount() {
return scanConfigs_.size();
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ScanConfig getScanConfigs(int index) {
return scanConfigs_.get(index);
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ScanConfigOrBuilder getScanConfigsOrBuilder(
int index) {
return scanConfigs_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
@java.lang.Override
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < scanConfigs_.size(); i++) {
output.writeMessage(1, scanConfigs_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, nextPageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < scanConfigs_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, scanConfigs_.get(i));
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(nextPageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, nextPageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse)) {
return super.equals(obj);
}
com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse other =
(com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse) obj;
if (!getScanConfigsList().equals(other.getScanConfigsList())) return false;
if (!getNextPageToken().equals(other.getNextPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getScanConfigsCount() > 0) {
hash = (37 * hash) + SCAN_CONFIGS_FIELD_NUMBER;
hash = (53 * hash) + getScanConfigsList().hashCode();
}
hash = (37 * hash) + NEXT_PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getNextPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Response for the `ListScanConfigs` method.
* </pre>
*
* Protobuf type {@code google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse)
com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListScanConfigsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListScanConfigsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse.class,
com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse.Builder.class);
}
// Construct using
// com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (scanConfigsBuilder_ == null) {
scanConfigs_ = java.util.Collections.emptyList();
} else {
scanConfigs_ = null;
scanConfigsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.websecurityscanner.v1alpha.WebSecurityScannerProto
.internal_static_google_cloud_websecurityscanner_v1alpha_ListScanConfigsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse
getDefaultInstanceForType() {
return com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse build() {
com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse buildPartial() {
com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse result =
new com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse result) {
if (scanConfigsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
scanConfigs_ = java.util.Collections.unmodifiableList(scanConfigs_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.scanConfigs_ = scanConfigs_;
} else {
result.scanConfigs_ = scanConfigsBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.nextPageToken_ = nextPageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse) {
return mergeFrom(
(com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse other) {
if (other
== com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse
.getDefaultInstance()) return this;
if (scanConfigsBuilder_ == null) {
if (!other.scanConfigs_.isEmpty()) {
if (scanConfigs_.isEmpty()) {
scanConfigs_ = other.scanConfigs_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureScanConfigsIsMutable();
scanConfigs_.addAll(other.scanConfigs_);
}
onChanged();
}
} else {
if (!other.scanConfigs_.isEmpty()) {
if (scanConfigsBuilder_.isEmpty()) {
scanConfigsBuilder_.dispose();
scanConfigsBuilder_ = null;
scanConfigs_ = other.scanConfigs_;
bitField0_ = (bitField0_ & ~0x00000001);
scanConfigsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getScanConfigsFieldBuilder()
: null;
} else {
scanConfigsBuilder_.addAllMessages(other.scanConfigs_);
}
}
}
if (!other.getNextPageToken().isEmpty()) {
nextPageToken_ = other.nextPageToken_;
bitField0_ |= 0x00000002;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.websecurityscanner.v1alpha.ScanConfig m =
input.readMessage(
com.google.cloud.websecurityscanner.v1alpha.ScanConfig.parser(),
extensionRegistry);
if (scanConfigsBuilder_ == null) {
ensureScanConfigsIsMutable();
scanConfigs_.add(m);
} else {
scanConfigsBuilder_.addMessage(m);
}
break;
} // case 10
case 18:
{
nextPageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.websecurityscanner.v1alpha.ScanConfig> scanConfigs_ =
java.util.Collections.emptyList();
private void ensureScanConfigsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
scanConfigs_ =
new java.util.ArrayList<com.google.cloud.websecurityscanner.v1alpha.ScanConfig>(
scanConfigs_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.websecurityscanner.v1alpha.ScanConfig,
com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder,
com.google.cloud.websecurityscanner.v1alpha.ScanConfigOrBuilder>
scanConfigsBuilder_;
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public java.util.List<com.google.cloud.websecurityscanner.v1alpha.ScanConfig>
getScanConfigsList() {
if (scanConfigsBuilder_ == null) {
return java.util.Collections.unmodifiableList(scanConfigs_);
} else {
return scanConfigsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public int getScanConfigsCount() {
if (scanConfigsBuilder_ == null) {
return scanConfigs_.size();
} else {
return scanConfigsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1alpha.ScanConfig getScanConfigs(int index) {
if (scanConfigsBuilder_ == null) {
return scanConfigs_.get(index);
} else {
return scanConfigsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public Builder setScanConfigs(
int index, com.google.cloud.websecurityscanner.v1alpha.ScanConfig value) {
if (scanConfigsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureScanConfigsIsMutable();
scanConfigs_.set(index, value);
onChanged();
} else {
scanConfigsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public Builder setScanConfigs(
int index, com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder builderForValue) {
if (scanConfigsBuilder_ == null) {
ensureScanConfigsIsMutable();
scanConfigs_.set(index, builderForValue.build());
onChanged();
} else {
scanConfigsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public Builder addScanConfigs(com.google.cloud.websecurityscanner.v1alpha.ScanConfig value) {
if (scanConfigsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureScanConfigsIsMutable();
scanConfigs_.add(value);
onChanged();
} else {
scanConfigsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public Builder addScanConfigs(
int index, com.google.cloud.websecurityscanner.v1alpha.ScanConfig value) {
if (scanConfigsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureScanConfigsIsMutable();
scanConfigs_.add(index, value);
onChanged();
} else {
scanConfigsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public Builder addScanConfigs(
com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder builderForValue) {
if (scanConfigsBuilder_ == null) {
ensureScanConfigsIsMutable();
scanConfigs_.add(builderForValue.build());
onChanged();
} else {
scanConfigsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public Builder addScanConfigs(
int index, com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder builderForValue) {
if (scanConfigsBuilder_ == null) {
ensureScanConfigsIsMutable();
scanConfigs_.add(index, builderForValue.build());
onChanged();
} else {
scanConfigsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public Builder addAllScanConfigs(
java.lang.Iterable<? extends com.google.cloud.websecurityscanner.v1alpha.ScanConfig>
values) {
if (scanConfigsBuilder_ == null) {
ensureScanConfigsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, scanConfigs_);
onChanged();
} else {
scanConfigsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public Builder clearScanConfigs() {
if (scanConfigsBuilder_ == null) {
scanConfigs_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
scanConfigsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public Builder removeScanConfigs(int index) {
if (scanConfigsBuilder_ == null) {
ensureScanConfigsIsMutable();
scanConfigs_.remove(index);
onChanged();
} else {
scanConfigsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder getScanConfigsBuilder(
int index) {
return getScanConfigsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1alpha.ScanConfigOrBuilder getScanConfigsOrBuilder(
int index) {
if (scanConfigsBuilder_ == null) {
return scanConfigs_.get(index);
} else {
return scanConfigsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public java.util.List<? extends com.google.cloud.websecurityscanner.v1alpha.ScanConfigOrBuilder>
getScanConfigsOrBuilderList() {
if (scanConfigsBuilder_ != null) {
return scanConfigsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(scanConfigs_);
}
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder addScanConfigsBuilder() {
return getScanConfigsFieldBuilder()
.addBuilder(com.google.cloud.websecurityscanner.v1alpha.ScanConfig.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder addScanConfigsBuilder(
int index) {
return getScanConfigsFieldBuilder()
.addBuilder(
index, com.google.cloud.websecurityscanner.v1alpha.ScanConfig.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of ScanConfigs returned.
* </pre>
*
* <code>repeated .google.cloud.websecurityscanner.v1alpha.ScanConfig scan_configs = 1;</code>
*/
public java.util.List<com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder>
getScanConfigsBuilderList() {
return getScanConfigsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.websecurityscanner.v1alpha.ScanConfig,
com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder,
com.google.cloud.websecurityscanner.v1alpha.ScanConfigOrBuilder>
getScanConfigsFieldBuilder() {
if (scanConfigsBuilder_ == null) {
scanConfigsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.websecurityscanner.v1alpha.ScanConfig,
com.google.cloud.websecurityscanner.v1alpha.ScanConfig.Builder,
com.google.cloud.websecurityscanner.v1alpha.ScanConfigOrBuilder>(
scanConfigs_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
scanConfigs_ = null;
}
return scanConfigsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The nextPageToken.
*/
public java.lang.String getNextPageToken() {
java.lang.Object ref = nextPageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
nextPageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return The bytes for nextPageToken.
*/
public com.google.protobuf.ByteString getNextPageTokenBytes() {
java.lang.Object ref = nextPageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
nextPageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearNextPageToken() {
nextPageToken_ = getDefaultInstance().getNextPageToken();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Token to retrieve the next page of results, or empty if there are no
* more results in the list.
* </pre>
*
* <code>string next_page_token = 2;</code>
*
* @param value The bytes for nextPageToken to set.
* @return This builder for chaining.
*/
public Builder setNextPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
nextPageToken_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse)
private static final com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse();
}
public static com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListScanConfigsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListScanConfigsResponse>() {
@java.lang.Override
public ListScanConfigsResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListScanConfigsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListScanConfigsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.websecurityscanner.v1alpha.ListScanConfigsResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 37,368
|
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/FeatureRegistryServiceProto.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1beta1/feature_registry_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
public final class FeatureRegistryServiceProto {
private FeatureRegistryServiceProto() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureGroupRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureGroupRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureGroupRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureGroupRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureGroupsRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureGroupsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureGroupsResponse_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureGroupsResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureGroupRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureGroupRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_DeleteFeatureGroupRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_DeleteFeatureGroupRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureMonitorRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureMonitorRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorsRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureMonitorRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureMonitorRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_DeleteFeatureMonitorRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_DeleteFeatureMonitorRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorsResponse_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorsResponse_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureGroupOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureGroupOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureGroupOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureGroupOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_CreateRegistryFeatureOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_CreateRegistryFeatureOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureMonitorOperationMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureMonitorOperationMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorJobRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorJobRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureMonitorJobRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureMonitorJobRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorJobsRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorJobsRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorJobsResponse_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorJobsResponse_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\n"
+ ">google/cloud/aiplatform/v1beta1/feature_registry_service.proto\022\037google.cloud.a"
+ "iplatform.v1beta1\032\034google/api/annotation"
+ "s.proto\032\027google/api/client.proto\032\037google"
+ "/api/field_behavior.proto\032\031google/api/re"
+ "source.proto\032-google/cloud/aiplatform/v1beta1/feature.proto\0323google/cloud/aiplat"
+ "form/v1beta1/feature_group.proto\0325google/cloud/aiplatform/v1beta1/feature_monito"
+ "r.proto\0329google/cloud/aiplatform/v1beta1/feature_monitor_job.proto\032:google/cloud"
+ "/aiplatform/v1beta1/featurestore_service.proto\032/google/cloud/aiplatform/v1beta1/"
+ "operation.proto\032#google/longrunning/oper"
+ "ations.proto\032\033google/protobuf/empty.proto\032"
+ " google/protobuf/field_mask.proto\"\305\001\n"
+ "\031CreateFeatureGroupRequest\022>\n"
+ "\006parent\030\001 \001("
+ "\tB.\340A\002\372A(\022&aiplatform.googleapis.com/FeatureGroup\022I\n\r"
+ "feature_group\030\002 \001(\0132-.googl"
+ "e.cloud.aiplatform.v1beta1.FeatureGroupB\003\340A\002\022\035\n"
+ "\020feature_group_id\030\003 \001(\tB\003\340A\002\"V\n"
+ "\026GetFeatureGroupRequest\022<\n"
+ "\004name\030\001 \001(\tB.\340A\002\372A(\n"
+ "&aiplatform.googleapis.com/FeatureGroup\"\243\001\n"
+ "\030ListFeatureGroupsRequest\022>\n"
+ "\006parent\030\001 \001("
+ "\tB.\340A\002\372A(\022&aiplatform.googleapis.com/FeatureGroup\022\016\n"
+ "\006filter\030\002 \001(\t\022\021\n"
+ "\tpage_size\030\003 \001(\005\022\022\n\n"
+ "page_token\030\004 \001(\t\022\020\n"
+ "\010order_by\030\005 \001(\t\"{\n"
+ "\031ListFeatureGroupsResponse\022E\n"
+ "\016feature_groups\030\001"
+ " \003(\0132-.google.cloud.aiplatform.v1beta1.FeatureGroup\022\027\n"
+ "\017next_page_token\030\002 \001(\t\"\227\001\n"
+ "\031UpdateFeatureGroupRequest\022I\n\r"
+ "feature_group\030\001 \001(\0132-.google.clo"
+ "ud.aiplatform.v1beta1.FeatureGroupB\003\340A\002\022/\n"
+ "\013update_mask\030\002 \001(\0132\032.google.protobuf.FieldMask\"h\n"
+ "\031DeleteFeatureGroupRequest\022<\n"
+ "\004name\030\001 \001(\tB.\340A\002\372A(\n"
+ "&aiplatform.googleapis.com/FeatureGroup\022\r\n"
+ "\005force\030\002 \001(\010\"\317\001\n"
+ "\033CreateFeatureMonitorRequest\022@\n"
+ "\006parent\030\001 \001("
+ "\tB0\340A\002\372A*\022(aiplatform.googleapis.com/FeatureMonitor\022M\n"
+ "\017feature_monitor\030\002 \001(\0132/."
+ "google.cloud.aiplatform.v1beta1.FeatureMonitorB\003\340A\002\022\037\n"
+ "\022feature_monitor_id\030\003 \001(\tB\003\340A\002\"Z\n"
+ "\030GetFeatureMonitorRequest\022>\n"
+ "\004name\030\001 \001(\tB0\340A\002\372A*\n"
+ "(aiplatform.googleapis.com/FeatureMonitor\"\273\001\n"
+ "\032ListFeatureMonitorsRequest\022@\n"
+ "\006parent\030\001 \001("
+ "\tB0\340A\002\372A*\022(aiplatform.googleapis.com/FeatureMonitor\022\023\n"
+ "\006filter\030\002 \001(\tB\003\340A\001\022\026\n"
+ "\tpage_size\030\003 \001(\005B\003\340A\001\022\027\n\n"
+ "page_token\030\004 \001(\tB\003\340A\001\022\025\n"
+ "\010order_by\030\005 \001(\tB\003\340A\001\"\242\001\n"
+ "\033UpdateFeatureMonitorRequest\022M\n"
+ "\017feature_monitor\030\001"
+ " \001(\0132/.google.cloud.aiplatform.v1beta1.FeatureMonitorB\003\340A\002\0224\n"
+ "\013update_mask\030\002 \001(\0132\032.google.protobuf.FieldMaskB\003\340A\001\"]\n"
+ "\033DeleteFeatureMonitorRequest\022>\n"
+ "\004name\030\001 \001(\tB0\340A\002\372A*\n"
+ "(aiplatform.googleapis.com/FeatureMonitor\"\201\001\n"
+ "\033ListFeatureMonitorsResponse\022I\n"
+ "\020feature_monitors\030\001"
+ " \003(\0132/.google.cloud.aiplatform.v1beta1.FeatureMonitor\022\027\n"
+ "\017next_page_token\030\002 \001(\t\"z\n"
+ "#CreateFeatureGroupOperationMetadata\022S\n"
+ "\020generic_metadata\030\001 \001(\01329.google.cloud.a"
+ "iplatform.v1beta1.GenericOperationMetadata\"z\n"
+ "#UpdateFeatureGroupOperationMetadata\022S\n"
+ "\020generic_metadata\030\001 \001(\01329.google.clo"
+ "ud.aiplatform.v1beta1.GenericOperationMetadata\"}\n"
+ "&CreateRegistryFeatureOperationMetadata\022S\n"
+ "\020generic_metadata\030\001 \001(\01329.goo"
+ "gle.cloud.aiplatform.v1beta1.GenericOperationMetadata\"u\n"
+ "\036UpdateFeatureOperationMetadata\022S\n"
+ "\020generic_metadata\030\001 \001(\01329.goog"
+ "le.cloud.aiplatform.v1beta1.GenericOperationMetadata\"|\n"
+ "%CreateFeatureMonitorOperationMetadata\022S\n"
+ "\020generic_metadata\030\001 \001(\0132"
+ "9.google.cloud.aiplatform.v1beta1.GenericOperationMetadata\"|\n"
+ "%UpdateFeatureMonitorOperationMetadata\022S\n"
+ "\020generic_metadata\030\001"
+ " \001(\01329.google.cloud.aiplatform.v1beta1.GenericOperationMetadata\"\343\001\n"
+ "\036CreateFeatureMonitorJobRequest\022C\n"
+ "\006parent\030\001 \001(\tB3\340A\002"
+ "\372A-\022+aiplatform.googleapis.com/FeatureMonitorJob\022T\n"
+ "\023feature_monitor_job\030\002 \001(\01322."
+ "google.cloud.aiplatform.v1beta1.FeatureMonitorJobB\003\340A\002\022&\n"
+ "\026feature_monitor_job_id\030\003 \001(\003B\006\340A\001\340A\003\"`\n"
+ "\033GetFeatureMonitorJobRequest\022A\n"
+ "\004name\030\001 \001(\tB3\340A\002\372A-\n"
+ "+aiplatform.googleapis.com/FeatureMonitorJob\"\301\001\n"
+ "\035ListFeatureMonitorJobsRequest\022C\n"
+ "\006parent\030\001 \001("
+ "\tB3\340A\002\372A-\022+aiplatform.googleapis.com/FeatureMonitorJob\022\023\n"
+ "\006filter\030\002 \001(\tB\003\340A\001\022\026\n"
+ "\tpage_size\030\003 \001(\005B\003\340A\001\022\027\n\n"
+ "page_token\030\004 \001(\tB\003\340A\001\022\025\n"
+ "\010order_by\030\005 \001(\tB\003\340A\001\"\213\001\n"
+ "\036ListFeatureMonitorJobsResponse\022P\n"
+ "\024feature_monitor_jobs\030\001"
+ " \003(\01322.google.cloud.aiplatform.v1beta1.FeatureMonitorJob\022\027\n"
+ "\017next_page_token\030\002 \001(\t2\373&\n"
+ "\026FeatureRegistryService\022\235\002\n"
+ "\022CreateFeatureGroup\022:.google.cloud.aipl"
+ "atform.v1beta1.CreateFeatureGroupRequest\032\035.google.longrunning.Operation\"\253\001\312A3\n"
+ "\014FeatureGroup\022#CreateFeatureGroupOperation"
+ "Metadata\332A%parent,feature_group,feature_"
+ "group_id\202\323\344\223\002G\"6/v1beta1/{parent=projects/*/locations/*}/featureGroups:\r"
+ "feature_group\022\300\001\n"
+ "\017GetFeatureGroup\0227.google.cloud.aiplatform.v1beta1.GetFeatureGroupReque"
+ "st\032-.google.cloud.aiplatform.v1beta1.Fea"
+ "tureGroup\"E\332A\004name\202\323\344\223\0028\0226/v1beta1/{name"
+ "=projects/*/locations/*/featureGroups/*}\022\323\001\n"
+ "\021ListFeatureGroups\0229.google.cloud.aiplatform.v1beta1.ListFeatureGroupsReques"
+ "t\032:.google.cloud.aiplatform.v1beta1.List"
+ "FeatureGroupsResponse\"G\332A\006parent\202\323\344\223\0028\0226"
+ "/v1beta1/{parent=projects/*/locations/*}/featureGroups\022\237\002\n"
+ "\022UpdateFeatureGroup\022:.google.cloud.aiplatform.v1beta1.UpdateFe"
+ "atureGroupRequest\032\035.google.longrunning.Operation\"\255\001\312A3\n"
+ "\014FeatureGroup\022#UpdateFeatureGroupOperationMetadata\332A\031feature_grou"
+ "p,update_mask\202\323\344\223\002U2D/v1beta1/{feature_g"
+ "roup.name=projects/*/locations/*/featureGroups/*}:\r"
+ "feature_group\022\357\001\n"
+ "\022DeleteFeatureGroup\022:.google.cloud.aiplatform.v1beta"
+ "1.DeleteFeatureGroupRequest\032\035.google.longrunning.Operation\"~\312A0\n"
+ "\025google.protobuf.Empty\022\027DeleteOperationMetadata\332A\n"
+ "name,f"
+ "orce\202\323\344\223\0028*6/v1beta1/{name=projects/*/locations/*/featureGroups/*}\022\202\002\n\r"
+ "CreateFeature\0225.google.cloud.aiplatform.v1beta1.C"
+ "reateFeatureRequest\032\035.google.longrunning.Operation\"\232\001\312A)\n"
+ "\007Feature\022\036CreateFeatureOperationMetadata\332A\031parent,feature,featu"
+ "re_id\202\323\344\223\002L\"A/v1beta1/{parent=projects/*"
+ "/locations/*/featureGroups/*}/features:\007feature\022\244\002\n"
+ "\023BatchCreateFeatures\022;.google.cloud.aiplatform.v1beta1.BatchCreateFea"
+ "turesRequest\032\035.google.longrunning.Operation\"\260\001\312AC\n"
+ "\033BatchCreateFeaturesResponse\022$BatchCreateFeaturesOperationMetadata\332A\017p"
+ "arent,requests\202\323\344\223\002R\"M/v1beta1/{parent=p"
+ "rojects/*/locations/*/featureGroups/*}/features:batchCreate:\001*\022\274\001\n\n"
+ "GetFeature\0222.google.cloud.aiplatform.v1beta1.GetFeatu"
+ "reRequest\032(.google.cloud.aiplatform.v1be"
+ "ta1.Feature\"P\332A\004name\202\323\344\223\002C\022A/v1beta1/{na"
+ "me=projects/*/locations/*/featureGroups/*/features/*}\022\317\001\n"
+ "\014ListFeatures\0224.google.cloud.aiplatform.v1beta1.ListFeaturesReq"
+ "uest\0325.google.cloud.aiplatform.v1beta1.L"
+ "istFeaturesResponse\"R\332A\006parent\202\323\344\223\002C\022A/v"
+ "1beta1/{parent=projects/*/locations/*/featureGroups/*}/features\022\204\002\n\r"
+ "UpdateFeature\0225.google.cloud.aiplatform.v1beta1.Upda"
+ "teFeatureRequest\032\035.google.longrunning.Operation\"\234\001\312A)\n"
+ "\007Feature\022\036UpdateFeatureOpe"
+ "rationMetadata\332A\023feature,update_mask\202\323\344\223"
+ "\002T2I/v1beta1/{feature.name=projects/*/lo"
+ "cations/*/featureGroups/*/features/*}:\007feature\022\353\001\n\r"
+ "DeleteFeature\0225.google.cloud."
+ "aiplatform.v1beta1.DeleteFeatureRequest\032\035.google.longrunning.Operation\"\203\001\312A0\n"
+ "\025google.protobuf.Empty\022\027DeleteOperationMeta"
+ "data\332A\004name\202\323\344\223\002C*A/v1beta1/{name=projec"
+ "ts/*/locations/*/featureGroups/*/features/*}\022\275\002\n"
+ "\024CreateFeatureMonitor\022<.google.cloud.aiplatform.v1beta1.CreateFeatureMon"
+ "itorRequest\032\035.google.longrunning.Operation\"\307\001\312A7\n"
+ "\016FeatureMonitor\022%CreateFeatureMonitorOperationMetadata\332A)parent,feature"
+ "_monitor,feature_monitor_id\202\323\344\223\002[\"H/v1be"
+ "ta1/{parent=projects/*/locations/*/featu"
+ "reGroups/*}/featureMonitors:\017feature_monitor\022\330\001\n"
+ "\021GetFeatureMonitor\0229.google.cloud.aiplatform.v1beta1.GetFeatureMonitorRe"
+ "quest\032/.google.cloud.aiplatform.v1beta1."
+ "FeatureMonitor\"W\332A\004name\202\323\344\223\002J\022H/v1beta1/"
+ "{name=projects/*/locations/*/featureGroups/*/featureMonitors/*}\022\353\001\n"
+ "\023ListFeatureMonitors\022;.google.cloud.aiplatform.v1beta"
+ "1.ListFeatureMonitorsRequest\032<.google.cloud.aiplatform.v1beta1.ListFeatureMonito"
+ "rsResponse\"Y\332A\006parent\202\323\344\223\002J\022H/v1beta1/{p"
+ "arent=projects/*/locations/*/featureGroups/*}/featureMonitors\022\277\002\n"
+ "\024UpdateFeatureMonitor\022<.google.cloud.aiplatform.v1beta1"
+ ".UpdateFeatureMonitorRequest\032\035.google.longrunning.Operation\"\311\001\312A7\n"
+ "\016FeatureMonitor\022%UpdateFeatureMonitorOperationMetadata"
+ "\332A\033feature_monitor,update_mask\202\323\344\223\002k2X/v"
+ "1beta1/{feature_monitor.name=projects/*/"
+ "locations/*/featureGroups/*/featureMonitors/*}:\017feature_monitor\022\200\002\n"
+ "\024DeleteFeatureMonitor\022<.google.cloud.aiplatform.v1bet"
+ "a1.DeleteFeatureMonitorRequest\032\035.google.longrunning.Operation\"\212\001\312A0\n"
+ "\025google.protobuf.Empty\022\027DeleteOperationMetadata\332A\004na"
+ "me\202\323\344\223\002J*H/v1beta1/{name=projects/*/loca"
+ "tions/*/featureGroups/*/featureMonitors/*}\022\277\002\n"
+ "\027CreateFeatureMonitorJob\022?.google.cloud.aiplatform.v1beta1.CreateFeatureMo"
+ "nitorJobRequest\0322.google.cloud.aiplatfor"
+ "m.v1beta1.FeatureMonitorJob\"\256\001\332A1parent,"
+ "feature_monitor_job,feature_monitor_job_"
+ "id\202\323\344\223\002t\"]/v1beta1/{parent=projects/*/lo"
+ "cations/*/featureGroups/*/featureMonitor"
+ "s/*}/featureMonitorJobs:\023feature_monitor_job\022\366\001\n"
+ "\024GetFeatureMonitorJob\022<.google.cloud.aiplatform.v1beta1.GetFeatureMonito"
+ "rJobRequest\0322.google.cloud.aiplatform.v1"
+ "beta1.FeatureMonitorJob\"l\332A\004name\202\323\344\223\002_\022]"
+ "/v1beta1/{name=projects/*/locations/*/fe"
+ "atureGroups/*/featureMonitors/*/featureMonitorJobs/*}\022\211\002\n"
+ "\026ListFeatureMonitorJobs\022>.google.cloud.aiplatform.v1beta1.ListF"
+ "eatureMonitorJobsRequest\032?.google.cloud.aiplatform.v1beta1.ListFeatureMonitorJob"
+ "sResponse\"n\332A\006parent\202\323\344\223\002_\022]/v1beta1/{pa"
+ "rent=projects/*/locations/*/featureGroups/*/featureMonitors/*}/featureMonitorJob"
+ "s\032M\312A\031aiplatform.googleapis.com\322A.https:"
+ "//www.googleapis.com/auth/cloud-platformB\362\001\n"
+ "#com.google.cloud.aiplatform.v1beta1B\033FeatureRegistryServiceProtoP\001ZCcloud.g"
+ "oogle.com/go/aiplatform/apiv1beta1/aipla"
+ "tformpb;aiplatformpb\252\002\037Google.Cloud.AIPl"
+ "atform.V1Beta1\312\002\037Google\\Cloud\\AIPlatform"
+ "\\V1beta1\352\002\"Google::Cloud::AIPlatform::V1beta1b\006proto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.AnnotationsProto.getDescriptor(),
com.google.api.ClientProto.getDescriptor(),
com.google.api.FieldBehaviorProto.getDescriptor(),
com.google.api.ResourceProto.getDescriptor(),
com.google.cloud.aiplatform.v1beta1.FeatureProto.getDescriptor(),
com.google.cloud.aiplatform.v1beta1.FeatureGroupProto.getDescriptor(),
com.google.cloud.aiplatform.v1beta1.FeatureMonitorProto.getDescriptor(),
com.google.cloud.aiplatform.v1beta1.FeatureMonitorJobProto.getDescriptor(),
com.google.cloud.aiplatform.v1beta1.FeaturestoreServiceProto.getDescriptor(),
com.google.cloud.aiplatform.v1beta1.OperationProto.getDescriptor(),
com.google.longrunning.OperationsProto.getDescriptor(),
com.google.protobuf.EmptyProto.getDescriptor(),
com.google.protobuf.FieldMaskProto.getDescriptor(),
});
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureGroupRequest_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureGroupRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureGroupRequest_descriptor,
new java.lang.String[] {
"Parent", "FeatureGroup", "FeatureGroupId",
});
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureGroupRequest_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureGroupRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureGroupRequest_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureGroupsRequest_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureGroupsRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureGroupsRequest_descriptor,
new java.lang.String[] {
"Parent", "Filter", "PageSize", "PageToken", "OrderBy",
});
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureGroupsResponse_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureGroupsResponse_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureGroupsResponse_descriptor,
new java.lang.String[] {
"FeatureGroups", "NextPageToken",
});
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureGroupRequest_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureGroupRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureGroupRequest_descriptor,
new java.lang.String[] {
"FeatureGroup", "UpdateMask",
});
internal_static_google_cloud_aiplatform_v1beta1_DeleteFeatureGroupRequest_descriptor =
getDescriptor().getMessageTypes().get(5);
internal_static_google_cloud_aiplatform_v1beta1_DeleteFeatureGroupRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_DeleteFeatureGroupRequest_descriptor,
new java.lang.String[] {
"Name", "Force",
});
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorRequest_descriptor =
getDescriptor().getMessageTypes().get(6);
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorRequest_descriptor,
new java.lang.String[] {
"Parent", "FeatureMonitor", "FeatureMonitorId",
});
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureMonitorRequest_descriptor =
getDescriptor().getMessageTypes().get(7);
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureMonitorRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureMonitorRequest_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorsRequest_descriptor =
getDescriptor().getMessageTypes().get(8);
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorsRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorsRequest_descriptor,
new java.lang.String[] {
"Parent", "Filter", "PageSize", "PageToken", "OrderBy",
});
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureMonitorRequest_descriptor =
getDescriptor().getMessageTypes().get(9);
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureMonitorRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureMonitorRequest_descriptor,
new java.lang.String[] {
"FeatureMonitor", "UpdateMask",
});
internal_static_google_cloud_aiplatform_v1beta1_DeleteFeatureMonitorRequest_descriptor =
getDescriptor().getMessageTypes().get(10);
internal_static_google_cloud_aiplatform_v1beta1_DeleteFeatureMonitorRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_DeleteFeatureMonitorRequest_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorsResponse_descriptor =
getDescriptor().getMessageTypes().get(11);
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorsResponse_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorsResponse_descriptor,
new java.lang.String[] {
"FeatureMonitors", "NextPageToken",
});
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureGroupOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(12);
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureGroupOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureGroupOperationMetadata_descriptor,
new java.lang.String[] {
"GenericMetadata",
});
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureGroupOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(13);
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureGroupOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureGroupOperationMetadata_descriptor,
new java.lang.String[] {
"GenericMetadata",
});
internal_static_google_cloud_aiplatform_v1beta1_CreateRegistryFeatureOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(14);
internal_static_google_cloud_aiplatform_v1beta1_CreateRegistryFeatureOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_CreateRegistryFeatureOperationMetadata_descriptor,
new java.lang.String[] {
"GenericMetadata",
});
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(15);
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureOperationMetadata_descriptor,
new java.lang.String[] {
"GenericMetadata",
});
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(16);
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorOperationMetadata_descriptor,
new java.lang.String[] {
"GenericMetadata",
});
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureMonitorOperationMetadata_descriptor =
getDescriptor().getMessageTypes().get(17);
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureMonitorOperationMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_UpdateFeatureMonitorOperationMetadata_descriptor,
new java.lang.String[] {
"GenericMetadata",
});
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorJobRequest_descriptor =
getDescriptor().getMessageTypes().get(18);
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorJobRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_CreateFeatureMonitorJobRequest_descriptor,
new java.lang.String[] {
"Parent", "FeatureMonitorJob", "FeatureMonitorJobId",
});
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureMonitorJobRequest_descriptor =
getDescriptor().getMessageTypes().get(19);
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureMonitorJobRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_GetFeatureMonitorJobRequest_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorJobsRequest_descriptor =
getDescriptor().getMessageTypes().get(20);
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorJobsRequest_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorJobsRequest_descriptor,
new java.lang.String[] {
"Parent", "Filter", "PageSize", "PageToken", "OrderBy",
});
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorJobsResponse_descriptor =
getDescriptor().getMessageTypes().get(21);
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorJobsResponse_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1beta1_ListFeatureMonitorJobsResponse_descriptor,
new java.lang.String[] {
"FeatureMonitorJobs", "NextPageToken",
});
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.ClientProto.defaultHost);
registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
registry.add(com.google.api.AnnotationsProto.http);
registry.add(com.google.api.ClientProto.methodSignature);
registry.add(com.google.api.ClientProto.oauthScopes);
registry.add(com.google.api.ResourceProto.resourceReference);
registry.add(com.google.longrunning.OperationsProto.operationInfo);
com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor(
descriptor, registry);
com.google.api.AnnotationsProto.getDescriptor();
com.google.api.ClientProto.getDescriptor();
com.google.api.FieldBehaviorProto.getDescriptor();
com.google.api.ResourceProto.getDescriptor();
com.google.cloud.aiplatform.v1beta1.FeatureProto.getDescriptor();
com.google.cloud.aiplatform.v1beta1.FeatureGroupProto.getDescriptor();
com.google.cloud.aiplatform.v1beta1.FeatureMonitorProto.getDescriptor();
com.google.cloud.aiplatform.v1beta1.FeatureMonitorJobProto.getDescriptor();
com.google.cloud.aiplatform.v1beta1.FeaturestoreServiceProto.getDescriptor();
com.google.cloud.aiplatform.v1beta1.OperationProto.getDescriptor();
com.google.longrunning.OperationsProto.getDescriptor();
com.google.protobuf.EmptyProto.getDescriptor();
com.google.protobuf.FieldMaskProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
apache/hadoop-common
| 37,942
|
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/fs/FSMainOperationsBaseTest.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Options.Rename;
import org.apache.hadoop.fs.permission.FsPermission;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mortbay.log.Log;
/**
* <p>
* A collection of tests for the {@link FileSystem}.
* This test should be used for testing an instance of FileSystem
* that has been initialized to a specific default FileSystem such a
* LocalFileSystem, HDFS,S3, etc.
* </p>
* <p>
* To test a given {@link FileSystem} implementation create a subclass of this
* test and override {@link #setUp()} to initialize the <code>fSys</code>
* {@link FileSystem} instance variable.
*
* Since this a junit 4 you can also do a single setup before
* the start of any tests.
* E.g.
* @BeforeClass public static void clusterSetupAtBegining()
* @AfterClass public static void ClusterShutdownAtEnd()
* </p>
*/
public abstract class FSMainOperationsBaseTest extends FileSystemTestHelper {
private static String TEST_DIR_AAA2 = "test/hadoop2/aaa";
private static String TEST_DIR_AAA = "test/hadoop/aaa";
private static String TEST_DIR_AXA = "test/hadoop/axa";
private static String TEST_DIR_AXX = "test/hadoop/axx";
private static int numBlocks = 2;
protected FileSystem fSys;
final private static PathFilter DEFAULT_FILTER = new PathFilter() {
@Override
public boolean accept(final Path file) {
return true;
}
};
//A test filter with returns any path containing an "x" or "X"
final private static PathFilter TEST_X_FILTER = new PathFilter() {
@Override
public boolean accept(Path file) {
if(file.getName().contains("x") || file.getName().contains("X"))
return true;
else
return false;
}
};
protected static final byte[] data = getFileData(numBlocks,
getDefaultBlockSize());
abstract protected FileSystem createFileSystem() throws Exception;
public FSMainOperationsBaseTest() {
}
public FSMainOperationsBaseTest(String testRootDir) {
super(testRootDir);
}
@Before
public void setUp() throws Exception {
fSys = createFileSystem();
fSys.mkdirs(getTestRootPath(fSys, "test"));
}
@After
public void tearDown() throws Exception {
fSys.delete(new Path(getAbsoluteTestRootPath(fSys), new Path("test")), true);
}
protected Path getDefaultWorkingDirectory() throws IOException {
return getTestRootPath(fSys,
"/user/" + System.getProperty("user.name")).makeQualified(
fSys.getUri(), fSys.getWorkingDirectory());
}
protected boolean renameSupported() {
return true;
}
protected IOException unwrapException(IOException e) {
return e;
}
@Test
public void testFsStatus() throws Exception {
FsStatus fsStatus = fSys.getStatus(null);
Assert.assertNotNull(fsStatus);
//used, free and capacity are non-negative longs
Assert.assertTrue(fsStatus.getUsed() >= 0);
Assert.assertTrue(fsStatus.getRemaining() >= 0);
Assert.assertTrue(fsStatus.getCapacity() >= 0);
}
@Test
public void testWorkingDirectory() throws Exception {
// First we cd to our test root
Path workDir = new Path(getAbsoluteTestRootPath(fSys), new Path("test"));
fSys.setWorkingDirectory(workDir);
Assert.assertEquals(workDir, fSys.getWorkingDirectory());
fSys.setWorkingDirectory(new Path("."));
Assert.assertEquals(workDir, fSys.getWorkingDirectory());
fSys.setWorkingDirectory(new Path(".."));
Assert.assertEquals(workDir.getParent(), fSys.getWorkingDirectory());
// cd using a relative path
// Go back to our test root
workDir = new Path(getAbsoluteTestRootPath(fSys), new Path("test"));
fSys.setWorkingDirectory(workDir);
Assert.assertEquals(workDir, fSys.getWorkingDirectory());
Path relativeDir = new Path("existingDir1");
Path absoluteDir = new Path(workDir,"existingDir1");
fSys.mkdirs(absoluteDir);
fSys.setWorkingDirectory(relativeDir);
Assert.assertEquals(absoluteDir, fSys.getWorkingDirectory());
// cd using a absolute path
absoluteDir = getTestRootPath(fSys, "test/existingDir2");
fSys.mkdirs(absoluteDir);
fSys.setWorkingDirectory(absoluteDir);
Assert.assertEquals(absoluteDir, fSys.getWorkingDirectory());
// Now open a file relative to the wd we just set above.
Path absolutePath = new Path(absoluteDir, "foo");
createFile(fSys, absolutePath);
fSys.open(new Path("foo")).close();
// Now mkdir relative to the dir we cd'ed to
fSys.mkdirs(new Path("newDir"));
Assert.assertTrue(isDir(fSys, new Path(absoluteDir, "newDir")));
/**
* We cannot test this because FileSystem has never checked for
* existence of working dir - fixing this would break compatibility,
*
absoluteDir = getTestRootPath(fSys, "nonexistingPath");
try {
fSys.setWorkingDirectory(absoluteDir);
Assert.fail("cd to non existing dir should have failed");
} catch (Exception e) {
// Exception as expected
}
*/
}
// Try a URI
@Test
public void testWDAbsolute() throws IOException {
Path absoluteDir = new Path(fSys.getUri() + "/test/existingDir");
fSys.mkdirs(absoluteDir);
fSys.setWorkingDirectory(absoluteDir);
Assert.assertEquals(absoluteDir, fSys.getWorkingDirectory());
}
@Test
public void testMkdirs() throws Exception {
Path testDir = getTestRootPath(fSys, "test/hadoop");
Assert.assertFalse(exists(fSys, testDir));
Assert.assertFalse(isFile(fSys, testDir));
fSys.mkdirs(testDir);
Assert.assertTrue(exists(fSys, testDir));
Assert.assertFalse(isFile(fSys, testDir));
fSys.mkdirs(testDir);
Assert.assertTrue(exists(fSys, testDir));
Assert.assertFalse(isFile(fSys, testDir));
Path parentDir = testDir.getParent();
Assert.assertTrue(exists(fSys, parentDir));
Assert.assertFalse(isFile(fSys, parentDir));
Path grandparentDir = parentDir.getParent();
Assert.assertTrue(exists(fSys, grandparentDir));
Assert.assertFalse(isFile(fSys, grandparentDir));
}
@Test
public void testMkdirsFailsForSubdirectoryOfExistingFile() throws Exception {
Path testDir = getTestRootPath(fSys, "test/hadoop");
Assert.assertFalse(exists(fSys, testDir));
fSys.mkdirs(testDir);
Assert.assertTrue(exists(fSys, testDir));
createFile(getTestRootPath(fSys, "test/hadoop/file"));
Path testSubDir = getTestRootPath(fSys, "test/hadoop/file/subdir");
try {
fSys.mkdirs(testSubDir);
Assert.fail("Should throw IOException.");
} catch (IOException e) {
// expected
}
Assert.assertFalse(exists(fSys, testSubDir));
Path testDeepSubDir = getTestRootPath(fSys, "test/hadoop/file/deep/sub/dir");
try {
fSys.mkdirs(testDeepSubDir);
Assert.fail("Should throw IOException.");
} catch (IOException e) {
// expected
}
Assert.assertFalse(exists(fSys, testDeepSubDir));
}
@Test
public void testGetFileStatusThrowsExceptionForNonExistentFile()
throws Exception {
try {
fSys.getFileStatus(getTestRootPath(fSys, "test/hadoop/file"));
Assert.fail("Should throw FileNotFoundException");
} catch (FileNotFoundException e) {
// expected
}
}
@Test
public void testListStatusThrowsExceptionForNonExistentFile()
throws Exception {
try {
fSys.listStatus(getTestRootPath(fSys, "test/hadoop/file"));
Assert.fail("Should throw FileNotFoundException");
} catch (FileNotFoundException fnfe) {
// expected
}
}
// TODO: update after fixing HADOOP-7352
@Test
public void testListStatusThrowsExceptionForUnreadableDir()
throws Exception {
Path testRootDir = getTestRootPath(fSys, "test/hadoop/dir");
Path obscuredDir = new Path(testRootDir, "foo");
Path subDir = new Path(obscuredDir, "bar"); //so foo is non-empty
fSys.mkdirs(subDir);
fSys.setPermission(obscuredDir, new FsPermission((short)0)); //no access
try {
fSys.listStatus(obscuredDir);
Assert.fail("Should throw IOException");
} catch (IOException ioe) {
// expected
} finally {
// make sure the test directory can be deleted
fSys.setPermission(obscuredDir, new FsPermission((short)0755)); //default
}
}
@Test
public void testListStatus() throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, "test/hadoop/a"),
getTestRootPath(fSys, "test/hadoop/b"),
getTestRootPath(fSys, "test/hadoop/c/1"), };
Assert.assertFalse(exists(fSys, testDirs[0]));
for (Path path : testDirs) {
fSys.mkdirs(path);
}
// test listStatus that returns an array
FileStatus[] paths = fSys.listStatus(getTestRootPath(fSys, "test"));
Assert.assertEquals(1, paths.length);
Assert.assertEquals(getTestRootPath(fSys, "test/hadoop"), paths[0].getPath());
paths = fSys.listStatus(getTestRootPath(fSys, "test/hadoop"));
Assert.assertEquals(3, paths.length);
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys, "test/hadoop/a"),
paths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys, "test/hadoop/b"),
paths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys, "test/hadoop/c"),
paths));
paths = fSys.listStatus(getTestRootPath(fSys, "test/hadoop/a"));
Assert.assertEquals(0, paths.length);
}
@Test
public void testListStatusFilterWithNoMatches() throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, TEST_DIR_AAA2),
getTestRootPath(fSys, TEST_DIR_AAA),
getTestRootPath(fSys, TEST_DIR_AXA),
getTestRootPath(fSys, TEST_DIR_AXX), };
if (exists(fSys, testDirs[0]) == false) {
for (Path path : testDirs) {
fSys.mkdirs(path);
}
}
// listStatus with filters returns empty correctly
FileStatus[] filteredPaths = fSys.listStatus(
getTestRootPath(fSys, "test"), TEST_X_FILTER);
Assert.assertEquals(0,filteredPaths.length);
}
@Test
public void testListStatusFilterWithSomeMatches() throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, TEST_DIR_AAA),
getTestRootPath(fSys, TEST_DIR_AXA),
getTestRootPath(fSys, TEST_DIR_AXX),
getTestRootPath(fSys, TEST_DIR_AAA2), };
if (exists(fSys, testDirs[0]) == false) {
for (Path path : testDirs) {
fSys.mkdirs(path);
}
}
// should return 2 paths ("/test/hadoop/axa" and "/test/hadoop/axx")
FileStatus[] filteredPaths = fSys.listStatus(
getTestRootPath(fSys, "test/hadoop"), TEST_X_FILTER);
Assert.assertEquals(2,filteredPaths.length);
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys,
TEST_DIR_AXA), filteredPaths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys,
TEST_DIR_AXX), filteredPaths));
}
@Test
public void testGlobStatusNonExistentFile() throws Exception {
FileStatus[] paths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoopfsdf"));
Assert.assertNull(paths);
paths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoopfsdf/?"));
Assert.assertEquals(0, paths.length);
paths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoopfsdf/xyz*/?"));
Assert.assertEquals(0, paths.length);
}
@Test
public void testGlobStatusWithNoMatchesInPath() throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, TEST_DIR_AAA),
getTestRootPath(fSys, TEST_DIR_AXA),
getTestRootPath(fSys, TEST_DIR_AXX),
getTestRootPath(fSys, TEST_DIR_AAA2), };
if (exists(fSys, testDirs[0]) == false) {
for (Path path : testDirs) {
fSys.mkdirs(path);
}
}
// should return nothing
FileStatus[] paths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoop/?"));
Assert.assertEquals(0, paths.length);
}
@Test
public void testGlobStatusSomeMatchesInDirectories() throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, TEST_DIR_AAA),
getTestRootPath(fSys, TEST_DIR_AXA),
getTestRootPath(fSys, TEST_DIR_AXX),
getTestRootPath(fSys, TEST_DIR_AAA2), };
if (exists(fSys, testDirs[0]) == false) {
for (Path path : testDirs) {
fSys.mkdirs(path);
}
}
// Should return two items ("/test/hadoop" and "/test/hadoop2")
FileStatus[] paths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoop*"));
Assert.assertEquals(2, paths.length);
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys,
"test/hadoop"), paths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys,
"test/hadoop2"), paths));
}
@Test
public void testGlobStatusWithMultipleWildCardMatches() throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, TEST_DIR_AAA),
getTestRootPath(fSys, TEST_DIR_AXA),
getTestRootPath(fSys, TEST_DIR_AXX),
getTestRootPath(fSys, TEST_DIR_AAA2), };
if (exists(fSys, testDirs[0]) == false) {
for (Path path : testDirs) {
fSys.mkdirs(path);
}
}
//Should return all 4 items ("/test/hadoop/aaa", "/test/hadoop/axa"
//"/test/hadoop/axx", and "/test/hadoop2/axx")
FileStatus[] paths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoop*/*"));
Assert.assertEquals(4, paths.length);
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys, TEST_DIR_AAA), paths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys, TEST_DIR_AXA), paths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys, TEST_DIR_AXX), paths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys, TEST_DIR_AAA2), paths));
}
@Test
public void testGlobStatusWithMultipleMatchesOfSingleChar() throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, TEST_DIR_AAA),
getTestRootPath(fSys, TEST_DIR_AXA),
getTestRootPath(fSys, TEST_DIR_AXX),
getTestRootPath(fSys, TEST_DIR_AAA2), };
if (exists(fSys, testDirs[0]) == false) {
for (Path path : testDirs) {
fSys.mkdirs(path);
}
}
//Should return only 2 items ("/test/hadoop/axa", "/test/hadoop/axx")
FileStatus[] paths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoop/ax?"));
Assert.assertEquals(2, paths.length);
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys,
TEST_DIR_AXA), paths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys,
TEST_DIR_AXX), paths));
}
@Test
public void testGlobStatusFilterWithEmptyPathResults() throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, TEST_DIR_AAA),
getTestRootPath(fSys, TEST_DIR_AXA),
getTestRootPath(fSys, TEST_DIR_AXX),
getTestRootPath(fSys, TEST_DIR_AXX), };
if (exists(fSys, testDirs[0]) == false) {
for (Path path : testDirs) {
fSys.mkdirs(path);
}
}
//This should return an empty set
FileStatus[] filteredPaths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoop/?"),
DEFAULT_FILTER);
Assert.assertEquals(0,filteredPaths.length);
}
@Test
public void testGlobStatusFilterWithSomePathMatchesAndTrivialFilter()
throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, TEST_DIR_AAA),
getTestRootPath(fSys, TEST_DIR_AXA),
getTestRootPath(fSys, TEST_DIR_AXX),
getTestRootPath(fSys, TEST_DIR_AXX), };
if (exists(fSys, testDirs[0]) == false) {
for (Path path : testDirs) {
fSys.mkdirs(path);
}
}
//This should return all three (aaa, axa, axx)
FileStatus[] filteredPaths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoop/*"),
DEFAULT_FILTER);
Assert.assertEquals(3, filteredPaths.length);
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys,
TEST_DIR_AAA), filteredPaths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys,
TEST_DIR_AXA), filteredPaths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys,
TEST_DIR_AXX), filteredPaths));
}
@Test
public void testGlobStatusFilterWithMultipleWildCardMatchesAndTrivialFilter()
throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, TEST_DIR_AAA),
getTestRootPath(fSys, TEST_DIR_AXA),
getTestRootPath(fSys, TEST_DIR_AXX),
getTestRootPath(fSys, TEST_DIR_AXX), };
if (exists(fSys, testDirs[0]) == false) {
for (Path path : testDirs) {
fSys.mkdirs(path);
}
}
//This should return all three (aaa, axa, axx)
FileStatus[] filteredPaths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoop/a??"),
DEFAULT_FILTER);
Assert.assertEquals(3, filteredPaths.length);
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys, TEST_DIR_AAA),
filteredPaths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys, TEST_DIR_AXA),
filteredPaths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys, TEST_DIR_AXX),
filteredPaths));
}
@Test
public void testGlobStatusFilterWithMultiplePathMatchesAndNonTrivialFilter()
throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, TEST_DIR_AAA),
getTestRootPath(fSys, TEST_DIR_AXA),
getTestRootPath(fSys, TEST_DIR_AXX),
getTestRootPath(fSys, TEST_DIR_AXX), };
if (exists(fSys, testDirs[0]) == false) {
for (Path path : testDirs) {
fSys.mkdirs(path);
}
}
//This should return two (axa, axx)
FileStatus[] filteredPaths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoop/*"),
TEST_X_FILTER);
Assert.assertEquals(2, filteredPaths.length);
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys,
TEST_DIR_AXA), filteredPaths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys,
TEST_DIR_AXX), filteredPaths));
}
@Test
public void testGlobStatusFilterWithNoMatchingPathsAndNonTrivialFilter()
throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, TEST_DIR_AAA),
getTestRootPath(fSys, TEST_DIR_AXA),
getTestRootPath(fSys, TEST_DIR_AXX),
getTestRootPath(fSys, TEST_DIR_AXX), };
if (exists(fSys, testDirs[0]) == false) {
for (Path path : testDirs) {
fSys.mkdirs(path);
}
}
//This should return an empty set
FileStatus[] filteredPaths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoop/?"),
TEST_X_FILTER);
Assert.assertEquals(0,filteredPaths.length);
}
@Test
public void testGlobStatusFilterWithMultiplePathWildcardsAndNonTrivialFilter()
throws Exception {
Path[] testDirs = {
getTestRootPath(fSys, TEST_DIR_AAA),
getTestRootPath(fSys, TEST_DIR_AXA),
getTestRootPath(fSys, TEST_DIR_AXX),
getTestRootPath(fSys, TEST_DIR_AXX), };
if (exists(fSys, testDirs[0]) == false) {
for (Path path : testDirs) {
fSys.mkdirs(path);
}
}
//This should return two (axa, axx)
FileStatus[] filteredPaths = fSys.globStatus(
getTestRootPath(fSys, "test/hadoop/a??"),
TEST_X_FILTER);
Assert.assertEquals(2, filteredPaths.length);
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys, TEST_DIR_AXA),
filteredPaths));
Assert.assertTrue(containsTestRootPath(getTestRootPath(fSys, TEST_DIR_AXX),
filteredPaths));
}
@Test
public void testWriteReadAndDeleteEmptyFile() throws Exception {
writeReadAndDelete(0);
}
@Test
public void testWriteReadAndDeleteHalfABlock() throws Exception {
writeReadAndDelete(getDefaultBlockSize() / 2);
}
@Test
public void testWriteReadAndDeleteOneBlock() throws Exception {
writeReadAndDelete(getDefaultBlockSize());
}
@Test
public void testWriteReadAndDeleteOneAndAHalfBlocks() throws Exception {
int blockSize = getDefaultBlockSize();
writeReadAndDelete(blockSize + (blockSize / 2));
}
@Test
public void testWriteReadAndDeleteTwoBlocks() throws Exception {
writeReadAndDelete(getDefaultBlockSize() * 2);
}
protected void writeReadAndDelete(int len) throws IOException {
Path path = getTestRootPath(fSys, "test/hadoop/file");
fSys.mkdirs(path.getParent());
FSDataOutputStream out =
fSys.create(path, false, 4096, (short) 1, getDefaultBlockSize() );
out.write(data, 0, len);
out.close();
Assert.assertTrue("Exists", exists(fSys, path));
Assert.assertEquals("Length", len, fSys.getFileStatus(path).getLen());
FSDataInputStream in = fSys.open(path);
byte[] buf = new byte[len];
in.readFully(0, buf);
in.close();
Assert.assertEquals(len, buf.length);
for (int i = 0; i < buf.length; i++) {
Assert.assertEquals("Position " + i, data[i], buf[i]);
}
Assert.assertTrue("Deleted", fSys.delete(path, false));
Assert.assertFalse("No longer exists", exists(fSys, path));
}
@Test
public void testOverwrite() throws IOException {
Path path = getTestRootPath(fSys, "test/hadoop/file");
fSys.mkdirs(path.getParent());
createFile(path);
Assert.assertTrue("Exists", exists(fSys, path));
Assert.assertEquals("Length", data.length, fSys.getFileStatus(path).getLen());
try {
createFile(path);
Assert.fail("Should throw IOException.");
} catch (IOException e) {
// Expected
}
FSDataOutputStream out = fSys.create(path, true, 4096);
out.write(data, 0, data.length);
out.close();
Assert.assertTrue("Exists", exists(fSys, path));
Assert.assertEquals("Length", data.length, fSys.getFileStatus(path).getLen());
}
@Test
public void testWriteInNonExistentDirectory() throws IOException {
Path path = getTestRootPath(fSys, "test/hadoop/file");
Assert.assertFalse("Parent doesn't exist", exists(fSys, path.getParent()));
createFile(path);
Assert.assertTrue("Exists", exists(fSys, path));
Assert.assertEquals("Length", data.length, fSys.getFileStatus(path).getLen());
Assert.assertTrue("Parent exists", exists(fSys, path.getParent()));
}
@Test
public void testDeleteNonExistentFile() throws IOException {
Path path = getTestRootPath(fSys, "test/hadoop/file");
Assert.assertFalse("Doesn't exist", exists(fSys, path));
Assert.assertFalse("No deletion", fSys.delete(path, true));
}
@Test
public void testDeleteRecursively() throws IOException {
Path dir = getTestRootPath(fSys, "test/hadoop");
Path file = getTestRootPath(fSys, "test/hadoop/file");
Path subdir = getTestRootPath(fSys, "test/hadoop/subdir");
createFile(file);
fSys.mkdirs(subdir);
Assert.assertTrue("File exists", exists(fSys, file));
Assert.assertTrue("Dir exists", exists(fSys, dir));
Assert.assertTrue("Subdir exists", exists(fSys, subdir));
try {
fSys.delete(dir, false);
Assert.fail("Should throw IOException.");
} catch (IOException e) {
// expected
}
Assert.assertTrue("File still exists", exists(fSys, file));
Assert.assertTrue("Dir still exists", exists(fSys, dir));
Assert.assertTrue("Subdir still exists", exists(fSys, subdir));
Assert.assertTrue("Deleted", fSys.delete(dir, true));
Assert.assertFalse("File doesn't exist", exists(fSys, file));
Assert.assertFalse("Dir doesn't exist", exists(fSys, dir));
Assert.assertFalse("Subdir doesn't exist", exists(fSys, subdir));
}
@Test
public void testDeleteEmptyDirectory() throws IOException {
Path dir = getTestRootPath(fSys, "test/hadoop");
fSys.mkdirs(dir);
Assert.assertTrue("Dir exists", exists(fSys, dir));
Assert.assertTrue("Deleted", fSys.delete(dir, false));
Assert.assertFalse("Dir doesn't exist", exists(fSys, dir));
}
@Test
public void testRenameNonExistentPath() throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/nonExistent");
Path dst = getTestRootPath(fSys, "test/new/newpath");
try {
rename(src, dst, false, false, false, Rename.NONE);
Assert.fail("Should throw FileNotFoundException");
} catch (IOException e) {
Log.info("XXX", e);
Assert.assertTrue(unwrapException(e) instanceof FileNotFoundException);
}
try {
rename(src, dst, false, false, false, Rename.OVERWRITE);
Assert.fail("Should throw FileNotFoundException");
} catch (IOException e) {
Assert.assertTrue(unwrapException(e) instanceof FileNotFoundException);
}
}
@Test
public void testRenameFileToNonExistentDirectory() throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/file");
createFile(src);
Path dst = getTestRootPath(fSys, "test/nonExistent/newfile");
try {
rename(src, dst, false, true, false, Rename.NONE);
Assert.fail("Expected exception was not thrown");
} catch (IOException e) {
Assert.assertTrue(unwrapException(e) instanceof FileNotFoundException);
}
try {
rename(src, dst, false, true, false, Rename.OVERWRITE);
Assert.fail("Expected exception was not thrown");
} catch (IOException e) {
Assert.assertTrue(unwrapException(e) instanceof FileNotFoundException);
}
}
@Test
public void testRenameFileToDestinationWithParentFile() throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/file");
createFile(src);
Path dst = getTestRootPath(fSys, "test/parentFile/newfile");
createFile(dst.getParent());
try {
rename(src, dst, false, true, false, Rename.NONE);
Assert.fail("Expected exception was not thrown");
} catch (IOException e) {
}
try {
rename(src, dst, false, true, false, Rename.OVERWRITE);
Assert.fail("Expected exception was not thrown");
} catch (IOException e) {
}
}
@Test
public void testRenameFileToExistingParent() throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/file");
createFile(src);
Path dst = getTestRootPath(fSys, "test/new/newfile");
fSys.mkdirs(dst.getParent());
rename(src, dst, true, false, true, Rename.OVERWRITE);
}
@Test
public void testRenameFileToItself() throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/file");
createFile(src);
try {
rename(src, src, false, true, false, Rename.NONE);
Assert.fail("Renamed file to itself");
} catch (IOException e) {
Assert.assertTrue(unwrapException(e) instanceof FileAlreadyExistsException);
}
// Also fails with overwrite
try {
rename(src, src, false, true, false, Rename.OVERWRITE);
Assert.fail("Renamed file to itself");
} catch (IOException e) {
// worked
}
}
@Test
public void testRenameFileAsExistingFile() throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/file");
createFile(src);
Path dst = getTestRootPath(fSys, "test/new/existingFile");
createFile(dst);
// Fails without overwrite option
try {
rename(src, dst, false, true, false, Rename.NONE);
Assert.fail("Expected exception was not thrown");
} catch (IOException e) {
Assert.assertTrue(unwrapException(e) instanceof FileAlreadyExistsException);
}
// Succeeds with overwrite option
rename(src, dst, true, false, true, Rename.OVERWRITE);
}
@Test
public void testRenameFileAsExistingDirectory() throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/file");
createFile(src);
Path dst = getTestRootPath(fSys, "test/new/existingDir");
fSys.mkdirs(dst);
// Fails without overwrite option
try {
rename(src, dst, false, false, true, Rename.NONE);
Assert.fail("Expected exception was not thrown");
} catch (IOException e) {
}
// File cannot be renamed as directory
try {
rename(src, dst, false, false, true, Rename.OVERWRITE);
Assert.fail("Expected exception was not thrown");
} catch (IOException e) {
}
}
@Test
public void testRenameDirectoryToItself() throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/dir");
fSys.mkdirs(src);
try {
rename(src, src, false, true, false, Rename.NONE);
Assert.fail("Renamed directory to itself");
} catch (IOException e) {
Assert.assertTrue(unwrapException(e) instanceof FileAlreadyExistsException);
}
// Also fails with overwrite
try {
rename(src, src, false, true, false, Rename.OVERWRITE);
Assert.fail("Renamed directory to itself");
} catch (IOException e) {
// worked
}
}
@Test
public void testRenameDirectoryToNonExistentParent() throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/dir");
fSys.mkdirs(src);
Path dst = getTestRootPath(fSys, "test/nonExistent/newdir");
try {
rename(src, dst, false, true, false, Rename.NONE);
Assert.fail("Expected exception was not thrown");
} catch (IOException e) {
IOException ioException = unwrapException(e);
if (!(ioException instanceof FileNotFoundException)) {
throw ioException;
}
}
try {
rename(src, dst, false, true, false, Rename.OVERWRITE);
Assert.fail("Expected exception was not thrown");
} catch (IOException e) {
IOException ioException = unwrapException(e);
if (!(ioException instanceof FileNotFoundException)) {
throw ioException;
}
}
}
@Test
public void testRenameDirectoryAsNonExistentDirectory() throws Exception {
doTestRenameDirectoryAsNonExistentDirectory(Rename.NONE);
tearDown();
doTestRenameDirectoryAsNonExistentDirectory(Rename.OVERWRITE);
}
private void doTestRenameDirectoryAsNonExistentDirectory(Rename... options)
throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/dir");
fSys.mkdirs(src);
createFile(getTestRootPath(fSys, "test/hadoop/dir/file1"));
createFile(getTestRootPath(fSys, "test/hadoop/dir/subdir/file2"));
Path dst = getTestRootPath(fSys, "test/new/newdir");
fSys.mkdirs(dst.getParent());
rename(src, dst, true, false, true, options);
Assert.assertFalse("Nested file1 exists",
exists(fSys, getTestRootPath(fSys, "test/hadoop/dir/file1")));
Assert.assertFalse("Nested file2 exists",
exists(fSys, getTestRootPath(fSys, "test/hadoop/dir/subdir/file2")));
Assert.assertTrue("Renamed nested file1 exists",
exists(fSys, getTestRootPath(fSys, "test/new/newdir/file1")));
Assert.assertTrue("Renamed nested exists",
exists(fSys, getTestRootPath(fSys, "test/new/newdir/subdir/file2")));
}
@Test
public void testRenameDirectoryAsEmptyDirectory() throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/dir");
fSys.mkdirs(src);
createFile(getTestRootPath(fSys, "test/hadoop/dir/file1"));
createFile(getTestRootPath(fSys, "test/hadoop/dir/subdir/file2"));
Path dst = getTestRootPath(fSys, "test/new/newdir");
fSys.mkdirs(dst);
// Fails without overwrite option
try {
rename(src, dst, false, true, false, Rename.NONE);
Assert.fail("Expected exception was not thrown");
} catch (IOException e) {
// Expected (cannot over-write non-empty destination)
Assert.assertTrue(unwrapException(e) instanceof FileAlreadyExistsException);
}
// Succeeds with the overwrite option
rename(src, dst, true, false, true, Rename.OVERWRITE);
}
@Test
public void testRenameDirectoryAsNonEmptyDirectory() throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/dir");
fSys.mkdirs(src);
createFile(getTestRootPath(fSys, "test/hadoop/dir/file1"));
createFile(getTestRootPath(fSys, "test/hadoop/dir/subdir/file2"));
Path dst = getTestRootPath(fSys, "test/new/newdir");
fSys.mkdirs(dst);
createFile(getTestRootPath(fSys, "test/new/newdir/file1"));
// Fails without overwrite option
try {
rename(src, dst, false, true, false, Rename.NONE);
Assert.fail("Expected exception was not thrown");
} catch (IOException e) {
// Expected (cannot over-write non-empty destination)
Assert.assertTrue(unwrapException(e) instanceof FileAlreadyExistsException);
}
// Fails even with the overwrite option
try {
rename(src, dst, false, true, false, Rename.OVERWRITE);
Assert.fail("Expected exception was not thrown");
} catch (IOException ex) {
// Expected (cannot over-write non-empty destination)
}
}
@Test
public void testRenameDirectoryAsFile() throws Exception {
if (!renameSupported()) return;
Path src = getTestRootPath(fSys, "test/hadoop/dir");
fSys.mkdirs(src);
Path dst = getTestRootPath(fSys, "test/new/newfile");
createFile(dst);
// Fails without overwrite option
try {
rename(src, dst, false, true, true, Rename.NONE);
Assert.fail("Expected exception was not thrown");
} catch (IOException e) {
}
// Directory cannot be renamed as existing file
try {
rename(src, dst, false, true, true, Rename.OVERWRITE);
Assert.fail("Expected exception was not thrown");
} catch (IOException ex) {
}
}
@Test
public void testInputStreamClosedTwice() throws IOException {
//HADOOP-4760 according to Closeable#close() closing already-closed
//streams should have no effect.
Path src = getTestRootPath(fSys, "test/hadoop/file");
createFile(src);
FSDataInputStream in = fSys.open(src);
in.close();
in.close();
}
@Test
public void testOutputStreamClosedTwice() throws IOException {
//HADOOP-4760 according to Closeable#close() closing already-closed
//streams should have no effect.
Path src = getTestRootPath(fSys, "test/hadoop/file");
FSDataOutputStream out = fSys.create(src);
out.writeChar('H'); //write some data
out.close();
out.close();
}
@Test
public void testGetWrappedInputStream() throws IOException {
Path src = getTestRootPath(fSys, "test/hadoop/file");
createFile(src);
FSDataInputStream in = fSys.open(src);
InputStream is = in.getWrappedStream();
in.close();
Assert.assertNotNull(is);
}
@Test
public void testCopyToLocalWithUseRawLocalFileSystemOption() throws Exception {
Configuration conf = new Configuration();
FileSystem fSys = new RawLocalFileSystem();
Path fileToFS = new Path(getTestRootDir(), "fs.txt");
Path fileToLFS = new Path(getTestRootDir(), "test.txt");
Path crcFileAtLFS = new Path(getTestRootDir(), ".test.txt.crc");
fSys.initialize(new URI("file:///"), conf);
writeFile(fSys, fileToFS);
if (fSys.exists(crcFileAtLFS))
Assert.assertTrue("CRC files not deleted", fSys
.delete(crcFileAtLFS, true));
fSys.copyToLocalFile(false, fileToFS, fileToLFS, true);
Assert.assertFalse("CRC files are created", fSys.exists(crcFileAtLFS));
}
private void writeFile(FileSystem fs, Path name) throws IOException {
FSDataOutputStream stm = fs.create(name);
try {
stm.writeBytes("42\n");
} finally {
stm.close();
}
}
protected void createFile(Path path) throws IOException {
createFile(fSys, path);
}
@SuppressWarnings("deprecation")
private void rename(Path src, Path dst, boolean renameShouldSucceed,
boolean srcExists, boolean dstExists, Rename... options)
throws IOException {
fSys.rename(src, dst, options);
if (!renameShouldSucceed)
Assert.fail("rename should have thrown exception");
Assert.assertEquals("Source exists", srcExists, exists(fSys, src));
Assert.assertEquals("Destination exists", dstExists, exists(fSys, dst));
}
private boolean containsTestRootPath(Path path, FileStatus[] filteredPaths)
throws IOException {
Path testRootPath = getTestRootPath(fSys, path.toString());
for(int i = 0; i < filteredPaths.length; i ++) {
if (testRootPath.equals(
filteredPaths[i].getPath()))
return true;
}
return false;
}
}
|
googleapis/google-cloud-java
| 38,213
|
java-networkservices/proto-google-cloud-networkservices-v1/src/main/java/com/google/cloud/networkservices/v1/CreateEndpointPolicyRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/networkservices/v1/endpoint_policy.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.networkservices.v1;
/**
*
*
* <pre>
* Request used with the CreateEndpointPolicy method.
* </pre>
*
* Protobuf type {@code google.cloud.networkservices.v1.CreateEndpointPolicyRequest}
*/
public final class CreateEndpointPolicyRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.networkservices.v1.CreateEndpointPolicyRequest)
CreateEndpointPolicyRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateEndpointPolicyRequest.newBuilder() to construct.
private CreateEndpointPolicyRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateEndpointPolicyRequest() {
parent_ = "";
endpointPolicyId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateEndpointPolicyRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.networkservices.v1.EndpointPolicyProto
.internal_static_google_cloud_networkservices_v1_CreateEndpointPolicyRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.networkservices.v1.EndpointPolicyProto
.internal_static_google_cloud_networkservices_v1_CreateEndpointPolicyRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest.class,
com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest.Builder.class);
}
private int bitField0_;
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource of the EndpointPolicy. Must be in the
* format `projects/*/locations/global`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The parent resource of the EndpointPolicy. Must be in the
* format `projects/*/locations/global`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ENDPOINT_POLICY_ID_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object endpointPolicyId_ = "";
/**
*
*
* <pre>
* Required. Short name of the EndpointPolicy resource to be created.
* E.g. "CustomECS".
* </pre>
*
* <code>string endpoint_policy_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The endpointPolicyId.
*/
@java.lang.Override
public java.lang.String getEndpointPolicyId() {
java.lang.Object ref = endpointPolicyId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
endpointPolicyId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Short name of the EndpointPolicy resource to be created.
* E.g. "CustomECS".
* </pre>
*
* <code>string endpoint_policy_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for endpointPolicyId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getEndpointPolicyIdBytes() {
java.lang.Object ref = endpointPolicyId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
endpointPolicyId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ENDPOINT_POLICY_FIELD_NUMBER = 3;
private com.google.cloud.networkservices.v1.EndpointPolicy endpointPolicy_;
/**
*
*
* <pre>
* Required. EndpointPolicy resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.EndpointPolicy endpoint_policy = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the endpointPolicy field is set.
*/
@java.lang.Override
public boolean hasEndpointPolicy() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. EndpointPolicy resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.EndpointPolicy endpoint_policy = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The endpointPolicy.
*/
@java.lang.Override
public com.google.cloud.networkservices.v1.EndpointPolicy getEndpointPolicy() {
return endpointPolicy_ == null
? com.google.cloud.networkservices.v1.EndpointPolicy.getDefaultInstance()
: endpointPolicy_;
}
/**
*
*
* <pre>
* Required. EndpointPolicy resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.EndpointPolicy endpoint_policy = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.networkservices.v1.EndpointPolicyOrBuilder getEndpointPolicyOrBuilder() {
return endpointPolicy_ == null
? com.google.cloud.networkservices.v1.EndpointPolicy.getDefaultInstance()
: endpointPolicy_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(endpointPolicyId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, endpointPolicyId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(3, getEndpointPolicy());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(endpointPolicyId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, endpointPolicyId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getEndpointPolicy());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest)) {
return super.equals(obj);
}
com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest other =
(com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getEndpointPolicyId().equals(other.getEndpointPolicyId())) return false;
if (hasEndpointPolicy() != other.hasEndpointPolicy()) return false;
if (hasEndpointPolicy()) {
if (!getEndpointPolicy().equals(other.getEndpointPolicy())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + ENDPOINT_POLICY_ID_FIELD_NUMBER;
hash = (53 * hash) + getEndpointPolicyId().hashCode();
if (hasEndpointPolicy()) {
hash = (37 * hash) + ENDPOINT_POLICY_FIELD_NUMBER;
hash = (53 * hash) + getEndpointPolicy().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request used with the CreateEndpointPolicy method.
* </pre>
*
* Protobuf type {@code google.cloud.networkservices.v1.CreateEndpointPolicyRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.networkservices.v1.CreateEndpointPolicyRequest)
com.google.cloud.networkservices.v1.CreateEndpointPolicyRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.networkservices.v1.EndpointPolicyProto
.internal_static_google_cloud_networkservices_v1_CreateEndpointPolicyRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.networkservices.v1.EndpointPolicyProto
.internal_static_google_cloud_networkservices_v1_CreateEndpointPolicyRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest.class,
com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest.Builder.class);
}
// Construct using com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getEndpointPolicyFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
endpointPolicyId_ = "";
endpointPolicy_ = null;
if (endpointPolicyBuilder_ != null) {
endpointPolicyBuilder_.dispose();
endpointPolicyBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.networkservices.v1.EndpointPolicyProto
.internal_static_google_cloud_networkservices_v1_CreateEndpointPolicyRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest
getDefaultInstanceForType() {
return com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest build() {
com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest buildPartial() {
com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest result =
new com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.endpointPolicyId_ = endpointPolicyId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.endpointPolicy_ =
endpointPolicyBuilder_ == null ? endpointPolicy_ : endpointPolicyBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest) {
return mergeFrom((com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest other) {
if (other
== com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getEndpointPolicyId().isEmpty()) {
endpointPolicyId_ = other.endpointPolicyId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasEndpointPolicy()) {
mergeEndpointPolicy(other.getEndpointPolicy());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
endpointPolicyId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getEndpointPolicyFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent resource of the EndpointPolicy. Must be in the
* format `projects/*/locations/global`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The parent resource of the EndpointPolicy. Must be in the
* format `projects/*/locations/global`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The parent resource of the EndpointPolicy. Must be in the
* format `projects/*/locations/global`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent resource of the EndpointPolicy. Must be in the
* format `projects/*/locations/global`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent resource of the EndpointPolicy. Must be in the
* format `projects/*/locations/global`.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object endpointPolicyId_ = "";
/**
*
*
* <pre>
* Required. Short name of the EndpointPolicy resource to be created.
* E.g. "CustomECS".
* </pre>
*
* <code>string endpoint_policy_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The endpointPolicyId.
*/
public java.lang.String getEndpointPolicyId() {
java.lang.Object ref = endpointPolicyId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
endpointPolicyId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Short name of the EndpointPolicy resource to be created.
* E.g. "CustomECS".
* </pre>
*
* <code>string endpoint_policy_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for endpointPolicyId.
*/
public com.google.protobuf.ByteString getEndpointPolicyIdBytes() {
java.lang.Object ref = endpointPolicyId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
endpointPolicyId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Short name of the EndpointPolicy resource to be created.
* E.g. "CustomECS".
* </pre>
*
* <code>string endpoint_policy_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The endpointPolicyId to set.
* @return This builder for chaining.
*/
public Builder setEndpointPolicyId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
endpointPolicyId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Short name of the EndpointPolicy resource to be created.
* E.g. "CustomECS".
* </pre>
*
* <code>string endpoint_policy_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearEndpointPolicyId() {
endpointPolicyId_ = getDefaultInstance().getEndpointPolicyId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Short name of the EndpointPolicy resource to be created.
* E.g. "CustomECS".
* </pre>
*
* <code>string endpoint_policy_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for endpointPolicyId to set.
* @return This builder for chaining.
*/
public Builder setEndpointPolicyIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
endpointPolicyId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.cloud.networkservices.v1.EndpointPolicy endpointPolicy_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.networkservices.v1.EndpointPolicy,
com.google.cloud.networkservices.v1.EndpointPolicy.Builder,
com.google.cloud.networkservices.v1.EndpointPolicyOrBuilder>
endpointPolicyBuilder_;
/**
*
*
* <pre>
* Required. EndpointPolicy resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.EndpointPolicy endpoint_policy = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the endpointPolicy field is set.
*/
public boolean hasEndpointPolicy() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Required. EndpointPolicy resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.EndpointPolicy endpoint_policy = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The endpointPolicy.
*/
public com.google.cloud.networkservices.v1.EndpointPolicy getEndpointPolicy() {
if (endpointPolicyBuilder_ == null) {
return endpointPolicy_ == null
? com.google.cloud.networkservices.v1.EndpointPolicy.getDefaultInstance()
: endpointPolicy_;
} else {
return endpointPolicyBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. EndpointPolicy resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.EndpointPolicy endpoint_policy = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setEndpointPolicy(com.google.cloud.networkservices.v1.EndpointPolicy value) {
if (endpointPolicyBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
endpointPolicy_ = value;
} else {
endpointPolicyBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. EndpointPolicy resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.EndpointPolicy endpoint_policy = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setEndpointPolicy(
com.google.cloud.networkservices.v1.EndpointPolicy.Builder builderForValue) {
if (endpointPolicyBuilder_ == null) {
endpointPolicy_ = builderForValue.build();
} else {
endpointPolicyBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. EndpointPolicy resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.EndpointPolicy endpoint_policy = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeEndpointPolicy(com.google.cloud.networkservices.v1.EndpointPolicy value) {
if (endpointPolicyBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& endpointPolicy_ != null
&& endpointPolicy_
!= com.google.cloud.networkservices.v1.EndpointPolicy.getDefaultInstance()) {
getEndpointPolicyBuilder().mergeFrom(value);
} else {
endpointPolicy_ = value;
}
} else {
endpointPolicyBuilder_.mergeFrom(value);
}
if (endpointPolicy_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. EndpointPolicy resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.EndpointPolicy endpoint_policy = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearEndpointPolicy() {
bitField0_ = (bitField0_ & ~0x00000004);
endpointPolicy_ = null;
if (endpointPolicyBuilder_ != null) {
endpointPolicyBuilder_.dispose();
endpointPolicyBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. EndpointPolicy resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.EndpointPolicy endpoint_policy = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.networkservices.v1.EndpointPolicy.Builder getEndpointPolicyBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getEndpointPolicyFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. EndpointPolicy resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.EndpointPolicy endpoint_policy = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.networkservices.v1.EndpointPolicyOrBuilder
getEndpointPolicyOrBuilder() {
if (endpointPolicyBuilder_ != null) {
return endpointPolicyBuilder_.getMessageOrBuilder();
} else {
return endpointPolicy_ == null
? com.google.cloud.networkservices.v1.EndpointPolicy.getDefaultInstance()
: endpointPolicy_;
}
}
/**
*
*
* <pre>
* Required. EndpointPolicy resource to be created.
* </pre>
*
* <code>
* .google.cloud.networkservices.v1.EndpointPolicy endpoint_policy = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.networkservices.v1.EndpointPolicy,
com.google.cloud.networkservices.v1.EndpointPolicy.Builder,
com.google.cloud.networkservices.v1.EndpointPolicyOrBuilder>
getEndpointPolicyFieldBuilder() {
if (endpointPolicyBuilder_ == null) {
endpointPolicyBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.networkservices.v1.EndpointPolicy,
com.google.cloud.networkservices.v1.EndpointPolicy.Builder,
com.google.cloud.networkservices.v1.EndpointPolicyOrBuilder>(
getEndpointPolicy(), getParentForChildren(), isClean());
endpointPolicy_ = null;
}
return endpointPolicyBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.networkservices.v1.CreateEndpointPolicyRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.networkservices.v1.CreateEndpointPolicyRequest)
private static final com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest();
}
public static com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateEndpointPolicyRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateEndpointPolicyRequest>() {
@java.lang.Override
public CreateEndpointPolicyRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<CreateEndpointPolicyRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateEndpointPolicyRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.networkservices.v1.CreateEndpointPolicyRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/felix-dev
| 37,168
|
ipojo/runtime/core-it/ipojo-core-configuration-test/src/test/java/org/apache/felix/ipojo/runtime/core/TestBothProperties.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.felix.ipojo.runtime.core;
import org.apache.felix.ipojo.ComponentInstance;
import org.apache.felix.ipojo.Factory;
import org.apache.felix.ipojo.runtime.core.services.CheckService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.osgi.framework.ServiceReference;
import java.util.Properties;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.*;
public class TestBothProperties extends Common {
ComponentInstance instance, instance2;
@Before
public void setUp() {
Factory fact = ipojoHelper.getFactory("CONFIG-BothConfigurableCheckService");
Properties props = new Properties();
props.put("instance.name", "under-test");
props.put("b", "1");
props.put("s", "1");
props.put("i", "1");
props.put("l", "1");
props.put("d", "1");
props.put("f", "1");
props.put("c", "a");
props.put("bool", "true");
props.put("bs", "{1,2,3}");
props.put("ss", "{1,2,3}");
props.put("is", "{1,2,3}");
props.put("ls", "{1,2,3}");
props.put("ds", "{1,2,3}");
props.put("fs", "{1,2,3}");
props.put("cs", "{a,b,c}");
props.put("bools", "{true,true,true}");
props.put("string", "foo");
props.put("strings", "{foo, bar, baz}");
try {
instance = fact.createComponentInstance(props);
} catch (Exception e) {
fail("Cannot create the under-test instance : " + e.getMessage());
}
try {
instance2 = fact.createComponentInstance(null);
} catch (Exception e) {
fail("Cannot create the under-test instance2 : " + e.getMessage());
}
}
@After
public void tearDown() {
instance.dispose();
instance2.dispose();
instance = null;
instance2 = null;
}
@Test
public void testConfigurationPrimitive() {
ServiceReference ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance.getInstanceName());
assertNotNull("Test check service availability", ref);
CheckService check = (CheckService) osgiHelper.getRawServiceObject(ref);
Properties props = check.getProps();
Byte b = (Byte) props.get("b");
Short s = (Short) props.get("s");
Integer i = (Integer) props.get("i");
Long l = (Long) props.get("l");
Double d = (Double) props.get("d");
Float f = (Float) props.get("f");
Character c = (Character) props.get("c");
Boolean bool = (Boolean) props.get("bool");
assertEquals("Check b", b, new Byte("1"));
assertEquals("Check s", s, new Short("1"));
assertEquals("Check i", i, new Integer("1"));
assertEquals("Check l", l, new Long("1"));
assertEquals("Check d", d, new Double("1"), 0);
assertEquals("Check f", f, new Float("1"), 0);
assertEquals("Check c", c, new Character('a'));
assertEquals("Check bool", bool, new Boolean("true"));
Integer upb = (Integer) props.get("upb");
Integer ups = (Integer) props.get("ups");
Integer upi = (Integer) props.get("upi");
Integer upl = (Integer) props.get("upl");
Integer upd = (Integer) props.get("upd");
Integer upf = (Integer) props.get("upf");
Integer upc = (Integer) props.get("upc");
Integer upbool = (Integer) props.get("upbool");
assertEquals("Check upb", upb, new Integer(1));
assertEquals("Check ups", ups, new Integer(1));
assertEquals("Check upi", upi, new Integer(1));
assertEquals("Check upl", upl, new Integer(1));
assertEquals("Check upd", upd, new Integer(1));
assertEquals("Check upf", upf, new Integer(1));
assertEquals("Check upc", upc, new Integer(1));
assertEquals("Check upbool", upbool, new Integer(1));
reconfigure(instance);
ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance.getInstanceName());
assertNotNull("Test check service availability", ref);
check = (CheckService) osgiHelper.getRawServiceObject(ref);
props = check.getProps();
b = (Byte) props.get("b");
s = (Short) props.get("s");
i = (Integer) props.get("i");
l = (Long) props.get("l");
d = (Double) props.get("d");
f = (Float) props.get("f");
c = (Character) props.get("c");
bool = (Boolean) props.get("bool");
assertEquals("2) Check b (" + b + ")", b, new Byte("2"));
assertEquals("2) Check s", s, new Short("2"));
assertEquals("2) Check i", i, new Integer("2"));
assertEquals("2) Check l", l, new Long("2"));
assertEquals("2) Check d", d, new Double("2"), 0);
assertEquals("2) Check f", f, new Float("2"), 0);
assertEquals("2) Check c", c, new Character('b'));
assertEquals("2) Check bool", bool, new Boolean("false"));
upb = (Integer) props.get("upb");
ups = (Integer) props.get("ups");
upi = (Integer) props.get("upi");
upl = (Integer) props.get("upl");
upd = (Integer) props.get("upd");
upf = (Integer) props.get("upf");
upc = (Integer) props.get("upc");
upbool = (Integer) props.get("upbool");
assertEquals("2) Check upb", upb, new Integer(2));
assertEquals("2) Check ups", ups, new Integer(2));
assertEquals("2) Check upi", upi, new Integer(2));
assertEquals("2) Check upl", upl, new Integer(2));
assertEquals("2) Check upd", upd, new Integer(2));
assertEquals("2) Check upf", upf, new Integer(2));
assertEquals("2) Check upc", upc, new Integer(2));
assertEquals("2) Check upbool", upbool, new Integer(2));
}
@Test
public void testConfigurationPrimitiveString() {
ServiceReference ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance.getInstanceName());
assertNotNull("Test check service availability", ref);
CheckService check = (CheckService) osgiHelper.getRawServiceObject(ref);
Properties props = check.getProps();
Byte b = (Byte) props.get("b");
Short s = (Short) props.get("s");
Integer i = (Integer) props.get("i");
Long l = (Long) props.get("l");
Double d = (Double) props.get("d");
Float f = (Float) props.get("f");
Character c = (Character) props.get("c");
Boolean bool = (Boolean) props.get("bool");
assertEquals("Check b", b, new Byte("1"));
assertEquals("Check s", s, new Short("1"));
assertEquals("Check i", i, new Integer("1"));
assertEquals("Check l", l, new Long("1"));
assertEquals("Check d", d, new Double("1"), 0);
assertEquals("Check f", f, new Float("1"), 0);
assertEquals("Check c", c, new Character('a'));
assertEquals("Check bool", bool, new Boolean("true"));
Integer upb = (Integer) props.get("upb");
Integer ups = (Integer) props.get("ups");
Integer upi = (Integer) props.get("upi");
Integer upl = (Integer) props.get("upl");
Integer upd = (Integer) props.get("upd");
Integer upf = (Integer) props.get("upf");
Integer upc = (Integer) props.get("upc");
Integer upbool = (Integer) props.get("upbool");
assertEquals("Check upb", upb, new Integer(1));
assertEquals("Check ups", ups, new Integer(1));
assertEquals("Check upi", upi, new Integer(1));
assertEquals("Check upl", upl, new Integer(1));
assertEquals("Check upd", upd, new Integer(1));
assertEquals("Check upf", upf, new Integer(1));
assertEquals("Check upc", upc, new Integer(1));
assertEquals("Check upbool", upbool, new Integer(1));
reconfigureString(instance);
ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance.getInstanceName());
assertNotNull("Test check service availability", ref);
check = (CheckService) osgiHelper.getRawServiceObject(ref);
props = check.getProps();
b = (Byte) props.get("b");
s = (Short) props.get("s");
i = (Integer) props.get("i");
l = (Long) props.get("l");
d = (Double) props.get("d");
f = (Float) props.get("f");
c = (Character) props.get("c");
bool = (Boolean) props.get("bool");
assertEquals("2) Check b (" + b + ")", b, new Byte("2"));
assertEquals("2) Check s", s, new Short("2"));
assertEquals("2) Check i", i, new Integer("2"));
assertEquals("2) Check l", l, new Long("2"));
assertEquals("2) Check d", d, new Double("2"), 0);
assertEquals("2) Check f", f, new Float("2"), 0);
assertEquals("2) Check c", c, new Character('b'));
assertEquals("2) Check bool", bool, new Boolean("false"));
upb = (Integer) props.get("upb");
ups = (Integer) props.get("ups");
upi = (Integer) props.get("upi");
upl = (Integer) props.get("upl");
upd = (Integer) props.get("upd");
upf = (Integer) props.get("upf");
upc = (Integer) props.get("upc");
upbool = (Integer) props.get("upbool");
assertEquals("2) Check upb", upb, new Integer(2));
assertEquals("2) Check ups", ups, new Integer(2));
assertEquals("2) Check upi", upi, new Integer(2));
assertEquals("2) Check upl", upl, new Integer(2));
assertEquals("2) Check upd", upd, new Integer(2));
assertEquals("2) Check upf", upf, new Integer(2));
assertEquals("2) Check upc", upc, new Integer(2));
assertEquals("2) Check upbool", upbool, new Integer(2));
}
@Test
public void testConfigurationPrimitiveArrays() {
ServiceReference ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance.getInstanceName());
assertNotNull("Test check service availability", ref);
CheckService check = (CheckService) osgiHelper.getRawServiceObject(ref);
Properties props = check.getProps();
byte[] b = (byte[]) props.get("bs");
short[] s = (short[]) props.get("ss");
int[] i = (int[]) props.get("is");
long[] l = (long[]) props.get("ls");
double[] d = (double[]) props.get("ds");
float[] f = (float[]) props.get("fs");
char[] c = (char[]) props.get("cs");
boolean[] bool = (boolean[]) props.get("bools");
assertEquals("Check b 0", b[0], 1);
assertEquals("Check b 1", b[1], 2);
assertEquals("Check b 2", b[2], 3);
assertEquals("Check s 0", s[0], 1);
assertEquals("Check s 1", s[1], 2);
assertEquals("Check s 2", s[2], 3);
assertEquals("Check i 0", i[0], 1);
assertEquals("Check i 1", i[1], 2);
assertEquals("Check i 2", i[2], 3);
assertEquals("Check l 0", l[0], 1);
assertEquals("Check l 1", l[1], 2);
assertEquals("Check l 2", l[2], 3);
assertEquals("Check d 0", d[0], 1.0, 0);
assertEquals("Check d 1", d[1], 2.0, 0);
assertEquals("Check d 2", d[2], 3.0, 0);
assertEquals("Check f 0", f[0], 1.0, 0);
assertEquals("Check f 1", f[1], 2.0, 0);
assertEquals("Check f 2", f[2], 3.0, 0);
assertEquals("Check c 0", c[0], 'a');
assertEquals("Check c 1", c[1], 'b');
assertEquals("Check c 2", c[2], 'c');
assertTrue("Check bool 0", bool[0]);
assertTrue("Check bool 1", bool[0]);
assertTrue("Check bool 2", bool[0]);
Integer upb = (Integer) props.get("upbs");
Integer ups = (Integer) props.get("upss");
Integer upi = (Integer) props.get("upis");
Integer upl = (Integer) props.get("upls");
Integer upd = (Integer) props.get("upds");
Integer upf = (Integer) props.get("upfs");
Integer upc = (Integer) props.get("upcs");
Integer upbool = (Integer) props.get("upbools");
assertEquals("Check upb", upb, new Integer(1));
assertEquals("Check ups", ups, new Integer(1));
assertEquals("Check upi", upi, new Integer(1));
assertEquals("Check upl", upl, new Integer(1));
assertEquals("Check upd", upd, new Integer(1));
assertEquals("Check upf", upf, new Integer(1));
assertEquals("Check upc", upc, new Integer(1));
assertEquals("Check upbool", upbool, new Integer(1));
reconfigure(instance);
ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance.getInstanceName());
assertNotNull("Test check service availability", ref);
check = (CheckService) osgiHelper.getRawServiceObject(ref);
props = check.getProps();
b = (byte[]) props.get("bs");
s = (short[]) props.get("ss");
i = (int[]) props.get("is");
l = (long[]) props.get("ls");
d = (double[]) props.get("ds");
f = (float[]) props.get("fs");
c = (char[]) props.get("cs");
bool = (boolean[]) props.get("bools");
assertEquals("2) Check b 0", b[0], 3);
assertEquals("2) Check b 1", b[1], 2);
assertEquals("2) Check b 2", b[2], 1);
assertEquals("2) Check s 0", s[0], 3);
assertEquals("2) Check s 1", s[1], 2);
assertEquals("2) Check s 2", s[2], 1);
assertEquals("2) Check i 0", i[0], 3);
assertEquals("2) Check i 1", i[1], 2);
assertEquals("2) Check i 2", i[2], 1);
assertEquals("2) Check l 0", l[0], 3);
assertEquals("2) Check l 1", l[1], 2);
assertEquals("2) Check l 2", l[2], 1);
assertEquals("2) Check d 0", d[0], 3.0, 0);
assertEquals("2) Check d 1", d[1], 2.0, 0);
assertEquals("2) Check d 2", d[2], 1.0, 0);
assertEquals("2) Check f 0", f[0], 3.0, 0);
assertEquals("2) Check f 1", f[1], 2.0, 0);
assertEquals("2) Check f 2", f[2], 1.0, 0);
assertEquals("2) Check c 0", c[0], 'c');
assertEquals("2) Check c 1", c[1], 'b');
assertEquals("2) Check c 2", c[2], 'a');
assertFalse("2) Check bool 0", bool[0]);
assertFalse("2) Check bool 1", bool[0]);
assertFalse("2) Check bool 2", bool[0]);
upb = (Integer) props.get("upbs");
ups = (Integer) props.get("upss");
upi = (Integer) props.get("upis");
upl = (Integer) props.get("upls");
upd = (Integer) props.get("upds");
upf = (Integer) props.get("upfs");
upc = (Integer) props.get("upcs");
upbool = (Integer) props.get("upbools");
assertEquals("2) Check upb", upb, new Integer(2));
assertEquals("2) Check ups", ups, new Integer(2));
assertEquals("2) Check upi", upi, new Integer(2));
assertEquals("2) Check upl", upl, new Integer(2));
assertEquals("2) Check upd", upd, new Integer(2));
assertEquals("2) Check upf", upf, new Integer(2));
assertEquals("2) Check upc", upc, new Integer(2));
assertEquals("2) Check upbool", upbool, new Integer(2));
}
@Test
public void testConfigurationPrimitiveArraysString() {
ServiceReference ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance.getInstanceName());
assertNotNull("Test check service availability", ref);
CheckService check = (CheckService) osgiHelper.getRawServiceObject(ref);
Properties props = check.getProps();
byte[] b = (byte[]) props.get("bs");
short[] s = (short[]) props.get("ss");
int[] i = (int[]) props.get("is");
long[] l = (long[]) props.get("ls");
double[] d = (double[]) props.get("ds");
float[] f = (float[]) props.get("fs");
char[] c = (char[]) props.get("cs");
boolean[] bool = (boolean[]) props.get("bools");
assertEquals("Check b 0", b[0], 1);
assertEquals("Check b 1", b[1], 2);
assertEquals("Check b 2", b[2], 3);
assertEquals("Check s 0", s[0], 1);
assertEquals("Check s 1", s[1], 2);
assertEquals("Check s 2", s[2], 3);
assertEquals("Check i 0", i[0], 1);
assertEquals("Check i 1", i[1], 2);
assertEquals("Check i 2", i[2], 3);
assertEquals("Check l 0", l[0], 1);
assertEquals("Check l 1", l[1], 2);
assertEquals("Check l 2", l[2], 3);
assertEquals("Check d 0", d[0], 1.0, 0);
assertEquals("Check d 1", d[1], 2.0, 0);
assertEquals("Check d 2", d[2], 3.0, 0);
assertEquals("Check f 0", f[0], 1, 0);
assertEquals("Check f 1", f[1], 2, 0);
assertEquals("Check f 2", f[2], 3, 0);
assertEquals("Check c 0", c[0], 'a');
assertEquals("Check c 1", c[1], 'b');
assertEquals("Check c 2", c[2], 'c');
assertTrue("Check bool 0", bool[0]);
assertTrue("Check bool 1", bool[0]);
assertTrue("Check bool 2", bool[0]);
Integer upb = (Integer) props.get("upbs");
Integer ups = (Integer) props.get("upss");
Integer upi = (Integer) props.get("upis");
Integer upl = (Integer) props.get("upls");
Integer upd = (Integer) props.get("upds");
Integer upf = (Integer) props.get("upfs");
Integer upc = (Integer) props.get("upcs");
Integer upbool = (Integer) props.get("upbools");
assertEquals("Check upb", upb, new Integer(1));
assertEquals("Check ups", ups, new Integer(1));
assertEquals("Check upi", upi, new Integer(1));
assertEquals("Check upl", upl, new Integer(1));
assertEquals("Check upd", upd, new Integer(1));
assertEquals("Check upf", upf, new Integer(1));
assertEquals("Check upc", upc, new Integer(1));
assertEquals("Check upbool", upbool, new Integer(1));
reconfigureString(instance);
ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance.getInstanceName());
assertNotNull("Test check service availability", ref);
check = (CheckService) osgiHelper.getRawServiceObject(ref);
props = check.getProps();
b = (byte[]) props.get("bs");
s = (short[]) props.get("ss");
i = (int[]) props.get("is");
l = (long[]) props.get("ls");
d = (double[]) props.get("ds");
f = (float[]) props.get("fs");
c = (char[]) props.get("cs");
bool = (boolean[]) props.get("bools");
assertEquals("2) Check b 0", b[0], 3);
assertEquals("2) Check b 1", b[1], 2);
assertEquals("2) Check b 2", b[2], 1);
assertEquals("2) Check s 0", s[0], 3);
assertEquals("2) Check s 1", s[1], 2);
assertEquals("2) Check s 2", s[2], 1);
assertEquals("2) Check i 0", i[0], 3);
assertEquals("2) Check i 1", i[1], 2);
assertEquals("2) Check i 2", i[2], 1);
assertEquals("2) Check l 0", l[0], 3);
assertEquals("2) Check l 1", l[1], 2);
assertEquals("2) Check l 2", l[2], 1);
assertEquals("2) Check d 0", d[0], 3.0, 0);
assertEquals("2) Check d 1", d[1], 2.0, 0);
assertEquals("2) Check d 2", d[2], 1.0, 0);
assertEquals("2) Check f 0", f[0], 3, 0);
assertEquals("2) Check f 1", f[1], 2, 0);
assertEquals("2) Check f 2", f[2], 1, 0);
assertEquals("2) Check c 0", c[0], 'c');
assertEquals("2) Check c 1", c[1], 'b');
assertEquals("2) Check c 2", c[2], 'a');
assertFalse("2) Check bool 0", bool[0]);
assertFalse("2) Check bool 1", bool[0]);
assertFalse("2) Check bool 2", bool[0]);
upb = (Integer) props.get("upbs");
ups = (Integer) props.get("upss");
upi = (Integer) props.get("upis");
upl = (Integer) props.get("upls");
upd = (Integer) props.get("upds");
upf = (Integer) props.get("upfs");
upc = (Integer) props.get("upcs");
upbool = (Integer) props.get("upbools");
assertEquals("2) Check upb", upb, new Integer(2));
assertEquals("2) Check ups", ups, new Integer(2));
assertEquals("2) Check upi", upi, new Integer(2));
assertEquals("2) Check upl", upl, new Integer(2));
assertEquals("2) Check upd", upd, new Integer(2));
assertEquals("2) Check upf", upf, new Integer(2));
assertEquals("2) Check upc", upc, new Integer(2));
assertEquals("2) Check upbool", upbool, new Integer(2));
}
@Test
public void testConfigurationObj() {
ServiceReference ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance.getInstanceName());
assertNotNull("Test check service availability", ref);
CheckService check = (CheckService) osgiHelper.getRawServiceObject(ref);
Properties props = check.getProps();
String s = (String) props.get("string");
String[] ss = (String[]) props.get("strings");
assertEquals("Check string", s, "foo");
assertEquals("Check strings 0", ss[0], "foo");
assertEquals("Check strings 1", ss[1], "bar");
assertEquals("Check strings 2", ss[2], "baz");
Integer upString = (Integer) props.get("upstring");
Integer upStrings = (Integer) props.get("upstrings");
assertEquals("Check upString", upString, new Integer(1));
assertEquals("Check upStrings", upStrings, new Integer(1));
reconfigure(instance);
ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance.getInstanceName());
assertNotNull("Test check service availability", ref);
check = (CheckService) osgiHelper.getRawServiceObject(ref);
props = check.getProps();
s = (String) props.get("string");
ss = (String[]) props.get("strings");
assertEquals("2) Check string", s, "bar");
assertEquals("2) Check strings 0", ss[0], "baz");
assertEquals("2) Check strings 1", ss[1], "bar");
assertEquals("2) Check strings 2", ss[2], "foo");
upString = (Integer) props.get("upstring");
upStrings = (Integer) props.get("upstrings");
assertEquals("2) Check upstring", upString, new Integer(2));
assertEquals("2) Check upstrings", upStrings, new Integer(2));
}
@Test
public void testConfigurationObjString() {
ServiceReference ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance.getInstanceName());
assertNotNull("Test check service availability", ref);
CheckService check = (CheckService) osgiHelper.getRawServiceObject(ref);
Properties props = check.getProps();
String s = (String) props.get("string");
String[] ss = (String[]) props.get("strings");
assertEquals("Check string", s, "foo");
assertEquals("Check strings 0", ss[0], "foo");
assertEquals("Check strings 1", ss[1], "bar");
assertEquals("Check strings 2", ss[2], "baz");
Integer upString = (Integer) props.get("upstring");
Integer upStrings = (Integer) props.get("upstrings");
assertEquals("Check upString", upString, new Integer(1));
assertEquals("Check upStrings", upStrings, new Integer(1));
reconfigureString(instance);
ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance.getInstanceName());
assertNotNull("Test check service availability", ref);
check = (CheckService) osgiHelper.getRawServiceObject(ref);
props = check.getProps();
s = (String) props.get("string");
ss = (String[]) props.get("strings");
assertEquals("2) Check string", s, "bar");
assertEquals("2) Check strings 0", ss[0], "baz");
assertEquals("2) Check strings 1", ss[1], "bar");
assertEquals("2) Check strings 2", ss[2], "foo");
upString = (Integer) props.get("upstring");
upStrings = (Integer) props.get("upstrings");
assertEquals("2) Check upstring", upString, new Integer(2));
assertEquals("2) Check upstrings", upStrings, new Integer(2));
}
private void reconfigure(ComponentInstance ci) {
Properties props2 = new Properties();
props2.put("b", new Byte("2"));
props2.put("s", new Short("2"));
props2.put("i", new Integer("2"));
props2.put("l", new Long("2"));
props2.put("d", new Double("2"));
props2.put("f", new Float("2"));
props2.put("c", new Character('b'));
props2.put("bool", new Boolean(false));
props2.put("bs", new byte[]{(byte) 3, (byte) 2, (byte) 1});
props2.put("ss", new short[]{(short) 3, (short) 2, (short) 1});
props2.put("is", new int[]{3, 2, 1});
props2.put("ls", new long[]{3, 2, 1});
props2.put("ds", new double[]{3, 2, 1});
props2.put("fs", new float[]{3, 2, 1});
props2.put("cs", new char[]{'c', 'b', 'a'});
props2.put("bools", new boolean[]{false, false, false});
props2.put("string", "bar");
props2.put("strings", new String[]{"baz", "bar", "foo"});
ci.reconfigure(props2);
}
private void reconfigureString(ComponentInstance ci) {
Properties props2 = new Properties();
props2.put("b", "2");
props2.put("s", "2");
props2.put("i", "2");
props2.put("l", "2");
props2.put("d", "2");
props2.put("f", "2");
props2.put("c", "b");
props2.put("bool", "false");
props2.put("bs", "{3, 2,1}");
props2.put("ss", "{3, 2,1}");
props2.put("is", "{3, 2,1}");
props2.put("ls", "{3, 2,1}");
props2.put("ds", "{3, 2,1}");
props2.put("fs", "{3, 2,1}");
props2.put("cs", "{c, b , a}");
props2.put("bools", "{false,false,false}");
props2.put("string", "bar");
props2.put("strings", "{baz, bar, foo}");
ci.reconfigure(props2);
}
@Test
public void testConfigurationPrimitiveNoValue() {
ServiceReference ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance2.getInstanceName());
assertNotNull("Test check service availability", ref);
CheckService check = (CheckService) osgiHelper.getRawServiceObject(ref);
Properties props = check.getProps();
Byte b = (Byte) props.get("b");
Short s = (Short) props.get("s");
Integer i = (Integer) props.get("i");
Long l = (Long) props.get("l");
Double d = (Double) props.get("d");
Float f = (Float) props.get("f");
Character c = (Character) props.get("c");
Boolean bool = (Boolean) props.get("bool");
assertEquals("Check b", b, new Byte("0"));
assertEquals("Check s", s, new Short("0"));
assertEquals("Check i", i, new Integer("0"));
assertEquals("Check l", l, new Long("0"));
assertEquals("Check d", d, new Double("0"), 0);
assertEquals("Check f", f, new Float("0"), 0);
assertEquals("Check c", c, new Character((char) 0));
assertEquals("Check bool", bool, new Boolean(false));
Integer upb = (Integer) props.get("upb");
Integer ups = (Integer) props.get("ups");
Integer upi = (Integer) props.get("upi");
Integer upl = (Integer) props.get("upl");
Integer upd = (Integer) props.get("upd");
Integer upf = (Integer) props.get("upf");
Integer upc = (Integer) props.get("upc");
Integer upbool = (Integer) props.get("upbool");
assertEquals("Check upb", upb, new Integer(0));
assertEquals("Check ups", ups, new Integer(0));
assertEquals("Check upi", upi, new Integer(0));
assertEquals("Check upl", upl, new Integer(0));
assertEquals("Check upd", upd, new Integer(0));
assertEquals("Check upf", upf, new Integer(0));
assertEquals("Check upc", upc, new Integer(0));
assertEquals("Check upbool", upbool, new Integer(0));
reconfigure(instance2);
ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance2.getInstanceName());
assertNotNull("Test check service availability", ref);
check = (CheckService) osgiHelper.getRawServiceObject(ref);
props = check.getProps();
b = (Byte) props.get("b");
s = (Short) props.get("s");
i = (Integer) props.get("i");
l = (Long) props.get("l");
d = (Double) props.get("d");
f = (Float) props.get("f");
c = (Character) props.get("c");
bool = (Boolean) props.get("bool");
assertEquals("2) Check b (" + b + ")", b, new Byte("2"));
assertEquals("2) Check s", s, new Short("2"));
assertEquals("2) Check i", i, new Integer("2"));
assertEquals("2) Check l", l, new Long("2"));
assertEquals("2) Check d", d, new Double("2"), 0);
assertEquals("2) Check f", f, new Float("2"), 0);
assertEquals("2) Check c", c, new Character('b'));
assertEquals("2) Check bool", bool, new Boolean("false"));
upb = (Integer) props.get("upb");
ups = (Integer) props.get("ups");
upi = (Integer) props.get("upi");
upl = (Integer) props.get("upl");
upd = (Integer) props.get("upd");
upf = (Integer) props.get("upf");
upc = (Integer) props.get("upc");
upbool = (Integer) props.get("upbool");
assertEquals("2) Check upb", upb, new Integer(1));
assertEquals("2) Check ups", ups, new Integer(1));
assertEquals("2) Check upi", upi, new Integer(1));
assertEquals("2) Check upl", upl, new Integer(1));
assertEquals("2) Check upd", upd, new Integer(1));
assertEquals("2) Check upf", upf, new Integer(1));
assertEquals("2) Check upc", upc, new Integer(1));
//assertEquals("2) Check upbool", upbool, new Integer(1)); // TODO Why 0 ???
}
@Test
public void testConfigurationPrimitiveArraysNoValue() {
ServiceReference ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance2.getInstanceName());
assertNotNull("Test check service availability", ref);
CheckService check = (CheckService) osgiHelper.getRawServiceObject(ref);
Properties props = check.getProps();
byte[] b = (byte[]) props.get("bs");
short[] s = (short[]) props.get("ss");
int[] i = (int[]) props.get("is");
long[] l = (long[]) props.get("ls");
double[] d = (double[]) props.get("ds");
float[] f = (float[]) props.get("fs");
char[] c = (char[]) props.get("cs");
boolean[] bool = (boolean[]) props.get("bools");
assertNull("Check b nullity", b);
assertNull("Check s nullity", s);
assertNull("Check i nullity", i);
assertNull("Check l nullity", l);
assertNull("Check d nullity", d);
assertNull("Check f nullity", f);
assertNull("Check c nullity", c);
assertNull("Check bool nullity", bool);
Integer upb = (Integer) props.get("upbs");
Integer ups = (Integer) props.get("upss");
Integer upi = (Integer) props.get("upis");
Integer upl = (Integer) props.get("upls");
Integer upd = (Integer) props.get("upds");
Integer upf = (Integer) props.get("upfs");
Integer upc = (Integer) props.get("upcs");
Integer upbool = (Integer) props.get("upbools");
assertEquals("Check upb", upb, new Integer(0));
assertEquals("Check ups", ups, new Integer(0));
assertEquals("Check upi", upi, new Integer(0));
assertEquals("Check upl", upl, new Integer(0));
assertEquals("Check upd", upd, new Integer(0));
assertEquals("Check upf", upf, new Integer(0));
assertEquals("Check upc", upc, new Integer(0));
assertEquals("Check upbool", upbool, new Integer(0));
reconfigure(instance2);
ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance2.getInstanceName());
assertNotNull("Test check service availability", ref);
check = (CheckService) osgiHelper.getRawServiceObject(ref);
props = check.getProps();
b = (byte[]) props.get("bs");
s = (short[]) props.get("ss");
i = (int[]) props.get("is");
l = (long[]) props.get("ls");
d = (double[]) props.get("ds");
f = (float[]) props.get("fs");
c = (char[]) props.get("cs");
bool = (boolean[]) props.get("bools");
assertEquals("2) Check b 0", b[0], 3);
assertEquals("2) Check b 1", b[1], 2);
assertEquals("2) Check b 2", b[2], 1);
assertEquals("2) Check s 0", s[0], 3);
assertEquals("2) Check s 1", s[1], 2);
assertEquals("2) Check s 2", s[2], 1);
assertEquals("2) Check i 0", i[0], 3);
assertEquals("2) Check i 1", i[1], 2);
assertEquals("2) Check i 2", i[2], 1);
assertEquals("2) Check l 0", l[0], 3);
assertEquals("2) Check l 1", l[1], 2);
assertEquals("2) Check l 2", l[2], 1);
assertEquals("2) Check d 0", d[0], 3.0, 0);
assertEquals("2) Check d 1", d[1], 2.0, 0);
assertEquals("2) Check d 2", d[2], 1.0, 0);
assertEquals("2) Check f 0", f[0], 3, 0);
assertEquals("2) Check f 1", f[1], 2, 0);
assertEquals("2) Check f 2", f[2], 1, 0);
assertEquals("2) Check c 0", c[0], 'c');
assertEquals("2) Check c 1", c[1], 'b');
assertEquals("2) Check c 2", c[2], 'a');
assertFalse("2) Check bool 0", bool[0]);
assertFalse("2) Check bool 1", bool[0]);
assertFalse("2) Check bool 2", bool[0]);
upb = (Integer) props.get("upbs");
ups = (Integer) props.get("upss");
upi = (Integer) props.get("upis");
upl = (Integer) props.get("upls");
upd = (Integer) props.get("upds");
upf = (Integer) props.get("upfs");
upc = (Integer) props.get("upcs");
upbool = (Integer) props.get("upbools");
assertEquals("2) Check upb", upb, new Integer(1));
assertEquals("2) Check ups", ups, new Integer(1));
assertEquals("2) Check upi", upi, new Integer(1));
assertEquals("2) Check upl", upl, new Integer(1));
assertEquals("2) Check upd", upd, new Integer(1));
assertEquals("2) Check upf", upf, new Integer(1));
assertEquals("2) Check upc", upc, new Integer(1));
assertEquals("2) Check upbool", upbool, new Integer(1));
}
@Test
public void testConfigurationObjNoValue() {
ServiceReference ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance2.getInstanceName());
assertNotNull("Test check service availability", ref);
CheckService check = (CheckService) osgiHelper.getRawServiceObject(ref);
Properties props = check.getProps();
String s = (String) props.get("string");
String[] ss = (String[]) props.get("strings");
assertEquals("Check string", s, null);
assertEquals("Check strings", ss, null);
Integer upString = (Integer) props.get("upstring");
Integer upStrings = (Integer) props.get("upstrings");
assertEquals("Check upString", upString, new Integer(0));
assertEquals("Check upStrings", upStrings, new Integer(0));
reconfigure(instance2);
ref = ipojoHelper.getServiceReferenceByName(CheckService.class.getName(), instance2.getInstanceName());
assertNotNull("Test check service availability", ref);
check = (CheckService) osgiHelper.getRawServiceObject(ref);
props = check.getProps();
s = (String) props.get("string");
ss = (String[]) props.get("strings");
assertEquals("2) Check string", s, "bar");
assertEquals("2) Check strings 0", ss[0], "baz");
assertEquals("2) Check strings 1", ss[1], "bar");
assertEquals("2) Check strings 2", ss[2], "foo");
upString = (Integer) props.get("upstring");
upStrings = (Integer) props.get("upstrings");
assertEquals("2) Check upstring", upString, new Integer(1));
assertEquals("2) Check upstrings", upStrings, new Integer(1));
}
}
|
apache/royale-compiler
| 38,244
|
compiler/src/main/java/org/apache/royale/compiler/internal/mxml/MXMLTagData.java
|
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.royale.compiler.internal.mxml;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.ListIterator;
import java.util.Map;
import org.apache.royale.compiler.common.ISourceLocation;
import org.apache.royale.compiler.common.MutablePrefixMap;
import org.apache.royale.compiler.common.PrefixMap;
import org.apache.royale.compiler.common.PrefixedXMLName;
import org.apache.royale.compiler.common.SourceLocation;
import org.apache.royale.compiler.common.XMLName;
import org.apache.royale.compiler.filespecs.IFileSpecification;
import org.apache.royale.compiler.internal.parsing.mxml.MXMLToken;
import org.apache.royale.compiler.mxml.IMXMLData;
import org.apache.royale.compiler.mxml.IMXMLNamespaceAttributeData;
import org.apache.royale.compiler.mxml.IMXMLTagAttributeData;
import org.apache.royale.compiler.mxml.IMXMLTagData;
import org.apache.royale.compiler.mxml.IMXMLTextData;
import org.apache.royale.compiler.mxml.IMXMLUnitData;
import org.apache.royale.compiler.mxml.IMXMLTextData.TextType;
import org.apache.royale.compiler.parsing.IMXMLToken;
import org.apache.royale.compiler.parsing.MXMLTokenTypes;
import org.apache.royale.compiler.problems.ICompilerProblem;
import org.apache.royale.compiler.problems.MXMLDuplicateAttributeProblem;
import org.apache.royale.compiler.problems.MXMLUnclosedTagProblem;
import org.apache.royale.compiler.problems.SyntaxProblem;
import org.apache.royale.utils.FastStack;
/**
* Encapsulation of an open tag, a close tag, or an empty tag in MXML.
*/
public class MXMLTagData extends MXMLUnitData implements IMXMLTagData
{
private static final IMXMLTagAttributeData[] NO_ATTRIBUTES = new IMXMLTagAttributeData[0];
/**
* Constructor.
*/
public MXMLTagData()
{
// Although we don't normally rely on the default ctor to make a completely valid object,
// in some cases we don't end up calling init, and we end up with a partially construced object.
// So let's init enough stuff so that the object is well behaved.
this.attributeMap = Collections.emptyMap();
this.attributes = NO_ATTRIBUTES;
}
/**
* Copy constructor.
*/
protected MXMLTagData(MXMLTagData other)
{
super(other);
this.nameStart = other.nameStart;
this.contentEnd = other.contentEnd;
this.tagName = other.tagName;
this.nameType = other.nameType;
this.commentToken = other.commentToken;
this.stateStart = other.stateStart;
this.stateName = other.stateName;
this.attributesStart = other.attributesStart;
this.emptyTag = other.emptyTag;
this.explicitCloseToken = other.explicitCloseToken;
this.attributeMap = other.attributeMap;
this.attributes = other.attributes;
this.uri = other.uri;
this.setOffsets(other.getStart(), other.getEnd());
this.setLine(other.getLine());
this.setColumn(other.getColumn());
this.setEndLine(other.getEndLine());
this.setEndColumn(other.getEndColumn());
}
protected String tagName;
/**
* The URI specified by this tag's prefix.
*/
protected String uri;
protected String stateName;
/**
* In-order list of MXML attributes
*/
protected IMXMLTagAttributeData[] attributes;
/**
* Map of attribute name to MXML attribute
*/
protected Map<String, IMXMLTagAttributeData> attributeMap;
/*
* offset where the tag name starts Note that we also use the for
* offsetContains(), as it is the first "real" character in the tag
*/
protected int nameStart;
/*
* this is the offset of the end of the "stuff inside the punctuation
*/
protected int contentEnd;
protected int nameType;
/**
* MXML Comment
*/
protected IMXMLToken commentToken;
protected int stateStart;
/**
* Start of the attribute list (after the tag name + whitespace)
*/
protected int attributesStart;
/**
* Is this an empty tag (ending with "/>")?
*/
protected boolean emptyTag;
/**
* Indicates if we have an explicit close tag
*/
protected boolean explicitCloseToken;
/**
* The problems list in case we find a problem later
*/
Collection<ICompilerProblem> problems;
/*
* unlike most MXML units, our "content" bounds are not the same as the
* {@link SourceLocation#getStart()} For tags, we don't count the outer
* punctuation as "content", although we do count spaces. Example:
* 0123456789 <foo /> start ==0 contentStart==1 contentEnd== 6 end == 8
*/
@Override
public int getContentStart()
{
return nameStart;
}
@Override
public int getContentEnd()
{
return contentEnd;
}
protected void setProblems(Collection<ICompilerProblem> problems)
{
this.problems = problems;
}
@SuppressWarnings("fallthrough")
MutablePrefixMap init(IMXMLData mxmlData, MXMLToken nameToken, ListIterator<MXMLToken> tokenIterator, MXMLDialect dialect, IFileSpecification spec, Collection<ICompilerProblem> problems)
{
this.problems = problems;
setSourcePath(mxmlData.getPath());
MutablePrefixMap map = null;
emptyTag = false;
explicitCloseToken = false;
// the start offset will by where '<' is. We strip that text off, but need to remember correct offset first
int startOffset = nameToken.getStart();
if (nameToken.getType() == MXMLTokenTypes.TOKEN_OPEN_TAG_START)
nameToken.truncate(1, 0);
else if (nameToken.getType() == MXMLTokenTypes.TOKEN_CLOSE_TAG_START)
nameToken.truncate(2, 0);
else
{
problems.add(new SyntaxProblem(nameToken));
return map;
}
// Deal with name if it is of the form name.state
int nameStart = nameToken.getStart();
MXMLStateSplitter splitState = new MXMLStateSplitter(nameToken, dialect, problems, spec);
tagName = splitState.getBaseName();
if (splitState.getStateName() != null)
{
stateName = splitState.getStateName();
stateStart = nameToken.getStart() + splitState.getStateNameOffset();
}
nameType = nameToken.getType();
int nameEnd = nameStart + tagName.length();
int contentEnd = nameEnd;
setTagOffsets(startOffset, nameEnd, nameStart, contentEnd);
setColumn(nameToken.getColumn());
setLine(nameToken.getLine());
setEndColumn(nameToken.getEndColumn());
setEndLine(nameToken.getEndLine());
attributesStart = getNameEnd();
ArrayList<IMXMLTagAttributeData> attrs = new ArrayList<IMXMLTagAttributeData>();
attributeMap = new LinkedHashMap<String, IMXMLTagAttributeData>(); //preserve order of attrs
boolean foundTagEnd = false;
boolean putTokenBack = false; // This is a pre-royale algorithm that helped recover from tag nesting errors
// I am bringing it back to life
while (tokenIterator.hasNext() && !foundTagEnd)
{
MXMLToken token = tokenIterator.next();
MXMLTagAttributeData attribute = null;
switch (token.getType())
{
case MXMLTokenTypes.TOKEN_NAME:
if (nameType == MXMLTokenTypes.TOKEN_CLOSE_TAG_START)
{
problems.add(new SyntaxProblem(token));
//burn forward until the end tag
//TODO do we want to mark each token as an error, or just the first?
while (tokenIterator.hasNext() && !foundTagEnd)
{
token = tokenIterator.next();
switch (token.getType())
{
case MXMLTokenTypes.TOKEN_TAG_END:
case MXMLTokenTypes.TOKEN_EMPTY_TAG_END:
foundTagEnd = true;
break;
}
}
break;
}
if (token.getText().startsWith("xmlns"))
{
attribute = new MXMLNamespaceAttributeData(token, tokenIterator, dialect, spec, problems);
if (map == null)
map = new MutablePrefixMap();
map.add(((IMXMLNamespaceAttributeData)attribute).getNamespacePrefix(), ((IMXMLNamespaceAttributeData)attribute).getNamespace());
}
else
{
attribute = new MXMLTagAttributeData(token, tokenIterator, dialect, spec, problems);
}
attribute.setParent(this);
// add the attribute to the attributes list even if it is duplicate
// otherwise code-hinting will not work properly
if (attributeMap.containsKey(token.getText()))
{
MXMLDuplicateAttributeProblem problem = new MXMLDuplicateAttributeProblem(attribute);
problems.add(problem);
}
attrs.add(attribute);
attributeMap.put(token.getText(), attribute);
// Now advance the offsets to include the newly parsed attributes
contentEnd = attribute.getAbsoluteEnd();
setTagOffsets(startOffset, contentEnd, nameStart, contentEnd);
break;
case MXMLTokenTypes.TOKEN_TAG_END:
foundTagEnd = true;
explicitCloseToken = !token.isImplicit();
break;
case MXMLTokenTypes.TOKEN_EMPTY_TAG_END:
emptyTag = true;
explicitCloseToken = !token.isImplicit();
foundTagEnd = true;
break;
case MXMLTokenTypes.TOKEN_OPEN_TAG_START:
case MXMLTokenTypes.TOKEN_CLOSE_TAG_START:
problems.add(new SyntaxProblem(token));
foundTagEnd = true; // Don't keep going - bail from malformed tag
putTokenBack = true;
// if we added this.fEmptyTag = true; then we could repair the damage here,
// but it's better to let the balancer repair it (in case there is a matching close lurking somewhere)
break;
default:
problems.add(new SyntaxProblem(token));
break;
}
if (foundTagEnd)
{
if (token.isImplicit() && token.getStart() == -1)
{
explicitCloseToken = false;
//let's try to end at the start of the next token if one exists
if (tokenIterator.hasNext())
{
MXMLToken next = tokenIterator.next();
if (next != null)
{
// extend the end, but not the content end
setTagOffsets(getAbsoluteStart() == -1 ? next.getStart() : getAbsoluteStart(), getAbsoluteEnd() == -1 ? next.getStart() : getAbsoluteEnd(), nameStart == -1 ? next.getStart() : nameStart, contentEnd == -1 ? next.getStart() : contentEnd);
tokenIterator.previous();
}
}
else
{
// TODO: if we hit this case do we need to call setTagOffset.
// and is getNameEnd() correct in any case?
setOffsets(startOffset, getNameEnd());
}
}
else
{
// A Tag's content extends all the way to the end token,
// so use the token to set content end
contentEnd = token.getStart();
if (!putTokenBack)
{
// if we are terminating on a "real" close tag, then the "end"
// of our tag will be the end of the TOKEN_TAG_END
setTagOffsets(startOffset, token.getEnd(), nameStart, contentEnd);
}
else
{
// ... conversely, if we are terminating on some other kind of token
// and are going to push the token back, we definietly don't
// want to adjust our bounds based on the end of THAT token.
//
// So.. use the token start to set the conent end (above) and the end
setTagOffsets(startOffset, contentEnd, nameStart, contentEnd);
tokenIterator.previous();
}
}
}
else if (getAbsoluteEnd() < token.getEnd())
{
contentEnd = token.getEnd();
setTagOffsets(startOffset, contentEnd, nameStart, contentEnd);
}
}
attributes = attrs.toArray(new MXMLTagAttributeData[0]);
return map;
}
/**
* For tags, we "contain" an offset if our content contains the offset. This
* means that we return false for the outside "<", ">", "</", "/>"
*/
@Override
public boolean containsOffset(int offset)
{
boolean ret = offset >= nameStart && offset <= contentEnd;
return ret;
}
private void setTagOffsets(int start, int end, int contentStart, int contentEnd)
{
assert (start <= contentStart) && ((contentStart <= contentEnd) || contentEnd == -1) && ((contentEnd <= end) || (end == -1));
setOffsets(start, end);
nameStart = contentStart;
if (contentEnd != -1)
this.contentEnd = contentEnd;
}
public void setCommentToken(IMXMLToken commentToken)
{
this.commentToken = commentToken;
}
public IMXMLToken getCommentToken()
{
return commentToken;
}
@Override
public void setParentUnitDataIndex(int parentIndex)
{
//when we fixup tokens, we don't have enough context to determine if we are a root tag. When we're a root tag, we cannot be
//an emty
if (emptyTag && !explicitCloseToken)
{
if (parentIndex == -1)
{
emptyTag = false;
}
}
super.setParentUnitDataIndex(parentIndex);
}
/**
* Adjust all associated offsets by the adjustment amount
*
* @param offsetAdjustment amount to add to offsets
*/
@Override
public void adjustOffsets(int offsetAdjustment)
{
super.adjustOffsets(offsetAdjustment);
nameStart += offsetAdjustment;
contentEnd += offsetAdjustment;
if (stateName != null)
{
stateStart += offsetAdjustment;
}
attributesStart += offsetAdjustment;
for (int i = 0; i < attributes.length; i++)
{
IMXMLTagAttributeData attribute = attributes[i];
((MXMLTagAttributeData)attribute).adjustOffsets(offsetAdjustment);
}
}
@Override
public boolean isTag()
{
return true;
}
@Override
public boolean isEmptyTag()
{
return emptyTag;
}
/**
* accessor for repair. This lets the balancer mark a tag as empty.
*/
public void setEmptyTag()
{
emptyTag = true;
}
/**
* True if this MXMLTagData object has an actual close token, and was not
* closed as a post-process step of MXML repair
*
* @return if we have an explicit close tag
*/
public boolean hasExplicitCloseTag()
{
return explicitCloseToken;
}
/**
* Returns true if this tag is the root tag of the containing MXML document
*
* @return true if we are the root tag
*/
public boolean isDocumentRoot()
{
if (isOpenTag())
{
if (getParentUnitDataIndex() == -1)
{
int index = getIndex();
if (index == 0)
return true;
//if we are not zero, scan backwards to see if there is a tag before us
index--;
while (index >= 0)
{
IMXMLUnitData unit = getParent().getUnit(index);
if (unit == null || unit.isTag())
return false;
index--;
}
return true;
}
}
return false;
}
/**
* Is this MXML unit an open tag? (i.e. <foo> OR <foo/>, note
* that the latter is also an empty tag)
*
* @return true if the unit is an open tag
*/
@Override
public boolean isOpenTag()
{
return nameType == MXMLTokenTypes.TOKEN_OPEN_TAG_START;
}
@Override
public boolean isOpenAndNotEmptyTag()
{
return (isOpenTag() && !isEmptyTag());
}
@Override
public boolean isCloseTag()
{
return nameType == MXMLTokenTypes.TOKEN_CLOSE_TAG_START;
}
@Override
public String getName()
{
return tagName;
}
/**
* Get the tag name as an {@link PrefixedXMLName}
*
* @return the tag name as an {@link PrefixedXMLName}
*/
public PrefixedXMLName getPrefixedXMLName()
{
return new PrefixedXMLName(getName(), getURI());
}
@Override
public XMLName getXMLName()
{
return new XMLName(getURI(), getShortName());
}
@Override
public PrefixMap getPrefixMap()
{
return getParent().getPrefixMapForData(this);
}
@Override
public PrefixMap getCompositePrefixMap()
{
MutablePrefixMap compMap = new MutablePrefixMap();
IMXMLTagData lookingAt = this;
while (lookingAt != null)
{
PrefixMap depth = getParent().getPrefixMapForData(lookingAt);
if (depth != null)
{
compMap.addAll(depth, true);
}
lookingAt = lookingAt.getParentTag();
}
return compMap;
}
@Override
public String getPrefix()
{
String name = getName();
int i = name.indexOf(':');
return i != -1 ? name.substring(0, i) : "";
}
@Override
public String getShortName()
{
String name = getName();
int i = name.indexOf(':');
return i != -1 ? name.substring(i + 1) : name;
}
@Override
public String getURI()
{
if (uri == null)
{
//walk up our chain to find the correct uri for our namespace. first one wins
String prefix = getPrefix();
IMXMLTagData lookingAt = this;
while (lookingAt != null)
{
PrefixMap depth = getParent().getPrefixMapForData(lookingAt);
if (depth != null && depth.containsPrefix(prefix))
{
uri = depth.getNamespaceForPrefix(prefix);
break;
}
lookingAt = lookingAt.getParentTag();
}
}
return uri;
}
public void invalidateURI()
{
uri = null;
int length = attributes.length;
for (int i = 0; i < length; i++)
{
((MXMLTagAttributeData)attributes[i]).invalidateURI();
}
}
@Override
public String getStateName()
{
return stateName != null ? stateName : "";
}
/**
* Find out if this tag contains the specified attribute.
*
* @param attributeName name of the attribute
* @return true if the attribute is present
*/
public boolean hasAttribute(String attributeName)
{
return attributeMap.containsKey(attributeName);
}
public boolean hasState()
{
return stateName != null;
}
public int getStateStart()
{
return stateStart;
}
public int getStateEnd()
{
return stateName != null ? stateName.length() + stateStart : 0;
}
@Override
public String getRawAttributeValue(String attributeName)
{
IMXMLTagAttributeData attributeData = attributeMap.get(attributeName);
if (attributeData != null)
return attributeData.getRawValue();
return null;
}
@Override
public IMXMLTagAttributeData getTagAttributeData(String attributeName)
{
return attributeMap.get(attributeName);
}
/**
* Get the start position of the tag name
*
* @return the start position of the tag name
*/
public int getNameStart()
{
return nameStart;
}
/**
* Get the end position of the tag name
*
* @return the end position of the tag name
*/
public int getNameEnd()
{
return nameStart + tagName.length();
}
/**
* Get the start position of the state name
*
* @return the start position of the tag name
*/
public int getStateNameStart()
{
return stateName != null ? stateStart : -1;
}
/**
* Get the end position of the state name
*
* @return the end position of the tag name
*/
public int getStateNameEnd()
{
return getStateEnd();
}
/**
* Get the start position of the attribute list (after the first whitespace
* after the tag name).
*
* @return the start position of the attribute list
*/
public int getAttributesStart()
{
return attributesStart;
}
/**
* Get the end position of the attribute list (before the ">" or "/>" or the
* start of the next tag).
*
* @return the end position of the attribute list
*/
public int getAttributesEnd()
{
return getAbsoluteEnd(); //attr end is just the end of this tag unit
}
@Override
public boolean isOffsetInAttributeList(int offset)
{
return MXMLData.contains(attributesStart, getAbsoluteEnd(), offset);
}
public boolean isInsideStateName(int offset)
{
if (stateName != null)
return MXMLData.contains(getStateStart(), getStateEnd(), offset);
return false;
}
/**
* Does the offset fall inside this tag's contents?
*
* @param offset test offset
* @return true iff the offset falls inside this tag's contents
*/
public boolean isOffsetInsideContents(int offset)
{
return MXMLData.contains(getContentStart(), getContentEnd(), // was getContentsEnd (plural)
offset);
}
/**
* Get all of the attribute names in this tag
*
* @return all of the attribute names (as a String [])
*/
public String[] getAttributeNames()
{
String[] attributeNames = new String[attributes.length];
for (int i = 0; i < attributeNames.length; i++)
{
attributeNames[i] = attributes[i].getName();
}
return attributeNames;
}
@Override
public IMXMLTagAttributeData[] getAttributeDatas()
{
return attributes;
}
/**
* Find the attribute that contains the offset
*
* @param offset test offset
* @return the attribute (or null, if no attribute contains the offset)
*/
public IMXMLTagAttributeData findAttributeContainingOffset(int offset)
{
// Find the last attribute that starts to the left of offset
IMXMLTagAttributeData lastAttribute = null;
IMXMLTagAttributeData attribute = null;
for (int i = 0; i < attributes.length; i++)
{
attribute = attributes[i];
if (attribute.getAbsoluteStart() < offset)
lastAttribute = attribute;
else
break;
}
// That last attribute is good if it's unfinished or if it contains the offset in question
if (lastAttribute != null && (lastAttribute.getAbsoluteEnd() == -1 || lastAttribute.getAbsoluteEnd() >= offset))
return lastAttribute;
return null;
}
/**
* Collect the text contents of this tag (like <mx:Script> or <mx:Style>)
*
* @return the text contents of this tag
*/
public int[] getTextContentOffsets()
{
int startOffset = -1;
int endOffset = -1;
if (!isEmptyTag() && isOpenTag())
{
IMXMLUnitData[] list = getParent().getUnits();
int index = getIndex() + 1;
for (int i = index; i < list.length; i++)
{
IMXMLUnitData next = list[i];
if (next instanceof IMXMLTextData && ((IMXMLTextData)next).getTextType() == TextType.WHITESPACE)
continue;
if (next.isText())
{
startOffset = startOffset == -1 ? next.getAbsoluteStart() : startOffset;
endOffset = next.getAbsoluteEnd();
}
else
{
if (startOffset == -1 && endOffset == -1)
{
startOffset = getAbsoluteEnd();
endOffset = next.getAbsoluteStart();
}
break;
}
}
}
return new int[] {startOffset, endOffset};
}
@Override
public String getCompilableText()
{
StringBuilder sb = new StringBuilder();
for (IMXMLUnitData unit = getFirstChildUnit(); unit != null; unit = unit.getNextSiblingUnit())
{
if (unit.isText())
sb.append(((IMXMLTextData)unit).getCompilableText());
}
return sb.toString();
}
@Override
public IMXMLTagData findMatchingEndTag()
{
return findMatchingEndTag(false);
}
/**
* Finds the close tag that matches this tag.
* <p>
* Returns null if this tag is a close or empty tag.
* <p>
* Returns null if a surrounding tag is unbalanced ONLY if includeImplicit
* is false; this is determined by backing up to the innermost parent tag
* with a different tag.
* <p>
* {@code <a> <b> <b> <-- find matching for this one will return null
* </b> </a> * }
*/
public IMXMLTagData findMatchingEndTag(boolean includeImplicit)
{
if (isCloseTag() || isEmptyTag())
return null;
// Back up to the first surrounding tag that has a different name, and ensure
// that *it* is balanced, saving our expected return value along the way.
IMXMLTagData startTag = this;
while (true)
{
IMXMLTagData parentTag = startTag.getContainingTag(startTag.getAbsoluteStart());
if (parentTag == null)
break;
startTag = parentTag;
if (!parentTag.getName().equals(this.getName()))
{
break;
}
}
// Now walk through the tags starting at startTag. Once we pop ourselves
// off the tagStack, we've found our candidate result -- but keep going
// until the stack is null, to ensure that we're balanced out to the
// surrounding tag.
IMXMLUnitData[] list = getParent().getUnits();
FastStack<IMXMLTagData> tagStack = new FastStack<IMXMLTagData>();
IMXMLTagData result = null;
for (int i = startTag.getIndex(); i < list.length; i++)
{
IMXMLUnitData curUnit = list[i];
if (curUnit.isTag())
{
IMXMLTagData curTag = (IMXMLTagData)curUnit;
if (curTag.isEmptyTag())
{
// do nothing for empty tags.
}
else if (curTag.isOpenTag())
{
tagStack.push(curTag);
}
else if (curTag.isCloseTag())
{
if (tagStack.isEmpty())
{
// document is unbalanced.
return null;
}
IMXMLTagData pop = tagStack.pop();
//check the short name in case the namespace is not spelled properly
if (!pop.getName().equals(curTag.getName()) && !pop.getShortName().equals(curTag.getShortName()))
{
// document is unbalanced.
return null;
}
if (pop == this)
{
// This is our result -- remember it.
result = curTag;
}
if (tagStack.isEmpty())
{
if (result != null && result.isImplicit() && !includeImplicit)
return null;
return result;
}
}
}
}
if (!tagStack.isEmpty())
{
IMXMLTagData pop = tagStack.pop();
problems.add(new MXMLUnclosedTagProblem(pop, pop.getName()));
}
return null;
}
@Override
public boolean isImplicit()
{
return false;
}
/**
* determines if the current tag has an end tag. Will return true if this
* tag is a close tag or an end tag. If the document is not balanced, we
* will return false. If the end tag was implicit, we will return false
*
* @return true if this tag has an end tag
*/
public boolean hasEndTag()
{
if (isCloseTag() || isEmptyTag())
return explicitCloseToken;
IMXMLTagData tagData = findMatchingEndTag();
return tagData != null && !tagData.isImplicit();
}
@Override
public IMXMLUnitData getFirstChildUnit()
{
// If this tag is <foo/> then it has no child units.
if (!isOpenAndNotEmptyTag())
return null;
IMXMLUnitData next = getNext();
// If this tag is followed immediately by its end tag,
// as in <foo></foo>, then it has no child units.
if (next == findMatchingEndTag())
return null;
// Otherwise, the first child unit is the unit after the tag.
return next;
}
@Override
public IMXMLTagData getFirstChild(boolean includeEmptyTags)
{
IMXMLTagData nextTag = null;
if (isEmptyTag())
return null;
if (isOpenTag())
{
nextTag = getNextTag();
}
else
{
// This is a close tag. Start at the corresponding open tag.
IMXMLTagData openTag = getContainingTag(getAbsoluteStart());
nextTag = openTag.getNextTag();
}
// Skip any text blocks to find the next actual tag. If it's an open tag,
// that is our first child. Otherwise it's a close tag, return null.
while (true)
{
if (nextTag == null || nextTag.isCloseTag())
return null;
if (nextTag.isOpenAndNotEmptyTag() || (nextTag.isEmptyTag() && includeEmptyTags))
return nextTag;
nextTag = nextTag.getNextTag();
}
}
@Override
public IMXMLTagData getNextSibling(boolean includeEmptyTags)
{
IMXMLTagData nextTag = null;
// Be sure we're starting at the close tag, then get the next tag.
if (isCloseTag() || isEmptyTag())
{
nextTag = getNextTag();
}
else
{
IMXMLTagData endTag = findMatchingEndTag();
if (endTag == null)
return null;
nextTag = endTag.getNextTag();
}
while (true)
{
if (nextTag == null || nextTag.isCloseTag())
return null;
if (nextTag.isOpenAndNotEmptyTag() || (nextTag.isEmptyTag() && includeEmptyTags))
return nextTag;
nextTag = nextTag.getNextTag();
}
}
/**
* Get the start tags for all children of this tag.
*
* @param includeEmptyTags <code>true</code> if empty tags should be
* included.
* @return Array of children.
*/
public IMXMLTagData[] getChildren(boolean includeEmptyTags)
{
ArrayList<IMXMLTagData> children = new ArrayList<IMXMLTagData>();
IMXMLTagData child = getFirstChild(includeEmptyTags);
while (child != null)
{
children.add(child);
child = child.getNextSibling(includeEmptyTags);
}
return children.toArray(new IMXMLTagData[0]);
}
/**
* Return the parent tag of this tag. If the document is not balanced before
* this tag, returns null.
*/
public IMXMLTagData getParentTag()
{
IMXMLUnitData data = getParentUnitData();
if (data instanceof IMXMLTagData)
return (IMXMLTagData)data;
return null;
}
@Override
public ISourceLocation getLocationOfChildUnits()
{
String sourcePath = getSourcePath();
int start = getStart();
int end = getEnd();
int line = getLine();
int column = getColumn();
int endLine = getEndLine();
int endColumn = getEndColumn();
boolean foundFirstChild = false;
for (IMXMLUnitData unit = getFirstChildUnit(); unit != null; unit = unit.getNextSiblingUnit())
{
if (!foundFirstChild)
{
sourcePath = unit.getSourcePath();
start = unit.getStart();
line = unit.getLine();
column = unit.getColumn();
endLine = unit.getEndLine();
endColumn = unit.getEndColumn();
foundFirstChild = true;
}
end = unit.getEnd();
}
return new SourceLocation(sourcePath, start, end, line, column, endLine, endColumn);
}
/**
* Verifies that this tag and its attributes have their source location
* information set.
* <p>
* This is used only in asserts.
*/
@Override
public boolean verify()
{
// Verify the source location.
super.verify();
// Verify the attributes.
for (IMXMLTagAttributeData attribute : getAttributeDatas())
{
((MXMLTagAttributeData)attribute).verify();
}
return true;
}
/**
* For debugging only. This format is nice in the Eclipse debugger.
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append('<');
if (isCloseTag())
sb.append('/');
sb.append(getName());
if (isEmptyTag())
sb.append('/');
sb.append('>');
sb.append(' ');
// Display line, column, start, end as "17:5 160-188"
sb.append(super.toString());
// add content range as "(161-187)"
sb.append(' ');
sb.append('(');
sb.append(nameStart);
sb.append('-');
sb.append(contentEnd);
sb.append(')');
return sb.toString();
}
/**
* For debugging only. This format is nice in a text file.
*/
@Override
public String toDumpString()
{
return buildDumpString(false);
}
@Override
public String buildDumpString(boolean skipSrcPath)
{
StringBuilder sb = new StringBuilder();
sb.append(super.buildDumpString(skipSrcPath));
sb.append('\t');
sb.append('|');
sb.append(getName());
sb.append('|');
return sb.toString();
}
public String stringify()
{
StringBuilder sb = new StringBuilder();
sb.append('<');
if (isCloseTag())
sb.append('/');
sb.append(getName());
// Verify the attributes.
for (IMXMLTagAttributeData attribute : getAttributeDatas())
{
sb.append(" ");
sb.append(attribute.getName());
sb.append("=\"");
sb.append(attribute.getRawValue());
sb.append("\"");
}
if (isEmptyTag())
sb.append('/');
sb.append('>');
for (IMXMLUnitData unit = getFirstChildUnit(); unit != null; unit = unit.getNextSiblingUnit())
{
if (unit.isText())
sb.append(((IMXMLTextData)unit).getCompilableText());
else if (unit instanceof MXMLTagData)
sb.append(((MXMLTagData)unit).stringify());
}
if (!isEmptyTag())
{
sb.append('<');
sb.append('/');
sb.append(getName());
sb.append('>');
}
return sb.toString();
}
}
|
apache/tomcat80
| 38,189
|
modules/tomcat-lite/java/org/apache/tomcat/lite/io/NioThread.java
|
/* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tomcat.lite.io;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.Channel;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.tomcat.lite.io.NioChannel.NioChannelCallback;
/**
* Abstract NIO/APR to avoid some of the complexity and allow more code
* sharing and experiments.
*
* SelectorThread provides non-blocking methods for read/write and generates
* callbacks using SelectorCallback. It has no buffers of its own.
*
* This is non-blocking, non-buffering and uses callbacks.
*
* @author Costin Manolache
*/
public class NioThread implements Runnable {
// ----------- IO handling -----------
protected long inactivityTimeout = 5000;
protected Thread selectorThread;
static Logger log = Logger.getLogger("NIO");
Selector selector;
// will be processed in the selector thread
List<NioChannel> readInterest = new ArrayList<NioChannel>();
List<NioChannel> writeInterest = new ArrayList<NioChannel>();
List<NioChannel> connectAcceptInterest = new ArrayList<NioChannel>();
List<NioChannel> updateCallback = new ArrayList<NioChannel>();
List<NioChannel> closeInterest = new LinkedList<NioChannel>();
List<Runnable> runnableInterest = new ArrayList<Runnable>();
// Statistics
AtomicInteger opened = new AtomicInteger();
AtomicInteger closed = new AtomicInteger();
AtomicInteger loops = new AtomicInteger();
AtomicInteger callbackCount = new AtomicInteger();
AtomicLong callbackTotalTime = new AtomicLong();
long maxCallbackTime = 0;
// actives are also stored in the Selector. This is only updated in the main
// thread
public ArrayList<NioChannel> active = new ArrayList<NioChannel>();
public static boolean debug = false;
boolean debugWakeup = false;
boolean running = true;
long lastWakeup = System.currentTimeMillis(); // last time we woke
long nextWakeup; // next scheduled wakeup
// Normally select will wait for the next time event - if it's
// too far in future, maxSleep will override it.
private long maxSleep = 600000;
long sleepTime = maxSleep;
// Never sleep less than minSleep. This defines the resulution for
// time events.
private long minSleep = 100;
boolean daemon = false;
// TODO: trace log - record all events with timestamps, replay
public NioThread(String name, boolean daemon) {
try {
selectorThread = (name == null) ? new Thread(this) :
new Thread(this, name);
selector = Selector.open();
// TODO: start it on-demand, close it when not in use
selectorThread.setDaemon(daemon);
this.daemon = daemon;
selectorThread.start();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
/**
* Opened sockets, waiting for something ( close at least )
*/
public int getOpen() {
return opened.get();
}
/**
* Closed - we're done with them.
*/
public int getClosed() {
return closed.get();
}
public int getActive() {
return active.size();
}
public int getCallbacks() {
return callbackCount.get();
}
public long getMaxCallbackTime() {
return maxCallbackTime;
}
public long getAvgCallbackTime() {
int cnt = callbackCount.get();
if (cnt == 0) {
return 0;
}
return callbackTotalTime.get() / cnt;
}
/**
* How many times we looped
*/
public int getLoops() {
return loops.get();
}
public long getLastWakeup() {
return lastWakeup;
}
public long getTimeSinceLastWakeup() {
return System.currentTimeMillis() - lastWakeup;
}
/**
* Close all resources, stop accepting, stop the thread.
* The actual stop will happen in background.
*/
public void stop() {
running = false;
if (debug) {
log.info("Selector thread stop " + this);
}
selector.wakeup();
}
public void run() {
int sloops = 0;
if (debug) {
log.info("Start NIO thread, daemon=" + daemon);
}
while (running) {
// if we want timeouts - set here.
try {
loops.incrementAndGet();
// Check if new requests were added
processPending();
// Timers
long now = System.currentTimeMillis();
if (nextWakeup < now) {
// We don't want to iterate on every I/O
updateSleepTimeAndProcessTimeouts(now);
}
int selected = selector.select(sleepTime);
lastWakeup = System.currentTimeMillis();
long slept = lastWakeup - now;
if (debugWakeup && selected == 0) {
if (sleepTime < maxSleep - 1000) { // short wakeup
log.info("Wakeup " + selected + " " + slept
+ " " + sleepTime);
}
}
if (slept < 10 && selected == 0) {
if (sloops > 50) {
sloops = 0;
log.severe("Looping !");
resetSelector();
}
sloops++;
}
// handle events for existing req first.
if (selected != 0) {
sloops = 0;
int callbackCnt = 0;
Set<SelectionKey> sel = selector.selectedKeys();
Iterator<SelectionKey> i = sel.iterator();
while (i.hasNext()) {
callbackCnt++;
long beforeCallback = System.currentTimeMillis();
SelectionKey sk = i.next();
i.remove();
boolean valid = sk.isValid();
int readyOps = (valid) ? sk.readyOps() : 0;
NioChannel ch = (NioChannel) sk.attachment();
if (debugWakeup) {
log.info("Wakeup selCnt=" + selected + " slept=" + (lastWakeup - now) +
" ready: " + readyOps + " v=" +
sk.isValid() + " ch=" + ch);
}
if (ch == null) {
log.severe("Missing channel");
sk.cancel();
continue;
}
if (ch.selKey != sk) {
// if (ch.selKey != null) { // null if closed
log.severe("Invalid state, selKey doesn't match ");
ch.selKey = sk;
}
if (ch.channel != sk.channel()) {
ch.channel = sk.channel();
log.severe("Invalid state, channel doesn't match ");
}
if (!sk.isValid()) {
if (debug) {
log.info("!isValid, closed socket " + ch);
}
ch.close();
continue;
}
try {
int ready = sk.readyOps();
// callbacks
if (sk.isValid() && sk.isAcceptable()) {
handleAccept(ch, sk);
}
if (sk.isValid() && sk.isConnectable()) {
sk.interestOps(sk.interestOps() & ~SelectionKey.OP_CONNECT);
SocketChannel sc = (SocketChannel) sk.channel();
handleConnect(ch, sc);
}
if (sk.isValid() && sk.isWritable()) {
// Needs to be explicitely re-enabled by callback
// if more data.
sk.interestOps(sk.interestOps() & ~SelectionKey.OP_WRITE);
ch.writeInterest = false;
handleDataWriteable(ch);
}
if (sk.isValid() && sk.isReadable()) {
// Leave readable interest !
handleReadable(ch);
}
long callbackTime =
System.currentTimeMillis() - beforeCallback;
if (callbackTime > 250) {
log.warning("Callback too long ! ops=" + ready +
" time=" + callbackTime + " ch=" + ch +
" " + callbackCnt);
}
if (callbackTime > maxCallbackTime) {
maxCallbackTime = callbackTime;
}
callbackCount.incrementAndGet();
this.callbackTotalTime.addAndGet(callbackTime);
} catch (Throwable t) {
log.log(Level.SEVERE, "SelectorThread: Channel error, closing", t);
ch.lastException = t;
ch.close();
}
}
// All at once
sel.clear();
}
} catch (Throwable e) {
log.log(Level.SEVERE, "SelectorThread: Error in select", e);
}
} // while(running)
log.info("SelectorThread done");
}
private void log(String msg, int selected, long slept, SelectionKey sk, int readyOps) {
log.info(msg + " " + selected
+ " " + slept
+ " ready: " + readyOps + " "
+ sk.readyOps() + " " + sk);
}
private void resetSelector() throws IOException, ClosedChannelException {
// Let's close all sockets - one is bad, but we can't do much.
Set<SelectionKey> keys = selector.keys();
//Set<SelectionKey> keys = selector.keys();
ArrayList<NioChannel> oldCh = new ArrayList<NioChannel>();
ArrayList<Integer> interests = new ArrayList<Integer>();
for (SelectionKey k : keys) {
NioChannel cd = (NioChannel) k.attachment();
interests.add(k.interestOps());
oldCh.add(cd);
k.cancel();
}
selector.close();
selector = Selector.open();
for (int i = 0; i < oldCh.size(); i++) {
NioChannel selectorData = oldCh.get(i);
if (selectorData == null) {
continue;
}
int interest = interests.get(i);
if (selectorData.channel instanceof ServerSocketChannel) {
ServerSocketChannel socketChannel =
(ServerSocketChannel) selectorData.channel;
selectorData.selKey = socketChannel.register(selector, SelectionKey.OP_ACCEPT);
} else {
SocketChannel socketChannel =
(SocketChannel) selectorData.channel;
if (interest != 0) {
selectorData.selKey = socketChannel.register(selector,
interest);
}
}
}
}
private void handleReadable(NioChannel ch) throws IOException {
ch.lastReadResult = 0;
if (ch.callback != null) {
ch.callback.handleReadable(ch);
}
if (ch.lastReadResult != 0 && ch.readInterest && !ch.inClosed) {
log.warning("LOOP: read interest" +
" after incomplete read");
ch.close();
}
}
private void handleDataWriteable(NioChannel ch) throws IOException {
ch.lastWriteResult = 0;
if (ch.callback != null) {
ch.callback.handleWriteable(ch);
}
if (ch.lastWriteResult > 0 && ch.writeInterest) {
log.warning("SelectorThread: write interest" +
" after incomplete write, LOOP");
}
}
private void handleConnect(NioChannel ch, SocketChannel sc)
throws IOException, SocketException {
try {
if (!sc.finishConnect()) {
log.warning("handleConnected - finishConnect returns false");
}
ch.sel = this;
//sc.socket().setSoLinger(true, 0);
if (debug) {
log.info("connected() " + ch + " isConnected()=" + sc.isConnected() + " " +
sc.isConnectionPending());
}
readInterest(ch, true);
} catch (Throwable t) {
close(ch, t);
}
try {
if (ch.callback != null) {
ch.callback.handleConnected(ch);
}
} catch(Throwable t1) {
log.log(Level.WARNING, "Error in connect callback", t1);
}
}
private void handleAccept(NioChannel ch, SelectionKey sk)
throws IOException, ClosedChannelException {
SelectableChannel selc = sk.channel();
ServerSocketChannel ssc=(ServerSocketChannel)selc;
SocketChannel sockC = ssc.accept();
sockC.configureBlocking(false);
NioChannel acceptedChannel = new NioChannel(this);
acceptedChannel.selKey = sockC.register(selector,
SelectionKey.OP_READ,
acceptedChannel);
acceptedChannel.channel = sockC;
synchronized (active) {
active.add(acceptedChannel);
}
// Find the callback for the new socket
if (ch.callback != null) {
// TODO: use future !
try {
ch.callback.handleConnected(acceptedChannel);
} catch (Throwable t) {
log.log(Level.SEVERE, "SelectorThread: Channel error, closing ", t);
acceptedChannel.lastException = t;
acceptedChannel.close();
}
}
//sk.interestOps(sk.interestOps() | SelectionKey.OP_ACCEPT);
if (debug) {
log.info("handleAccept " + ch);
}
}
public void shutdownOutput(NioChannel ch) throws IOException {
Channel channel = ch.channel;
if (channel instanceof SocketChannel) {
SocketChannel sc = (SocketChannel) channel;
if (sc.isOpen() && sc.isConnected()) {
if (debug) {
log.info("Half shutdown " + ch);
}
sc.socket().shutdownOutput(); // TCP end to the other side
}
}
}
/**
* Called from the IO thread
*/
private void closeIOThread(NioChannel ch, boolean remove) {
SelectionKey sk = (SelectionKey) ch.selKey;
Channel channel = ch.channel;
try {
synchronized(closeInterest) {
if (ch.closeCalled) {
if (debug) {
log.severe("Close called 2x ");
}
return;
}
ch.closeCalled = true;
int o = opened.decrementAndGet();
if (debug) {
log.info("-------------> close: " + ch + " t=" + ch.lastException);
}
if (sk != null) {
if (sk.isValid()) {
sk.interestOps(0);
}
sk.cancel();
ch.selKey = null;
}
if (channel instanceof SocketChannel) {
SocketChannel sc = (SocketChannel) channel;
if (sc.isConnected()) {
if (debug) {
log.info("Close socket, opened=" + o);
}
try {
sc.socket().shutdownInput();
} catch(IOException io1) {
}
try {
sc.socket().shutdownOutput(); // TCP end to the other side
} catch(IOException io1) {
}
sc.socket().close();
}
}
channel.close();
closed.incrementAndGet();
if (ch.callback != null) {
ch.callback.handleClosed(ch);
}
// remove from active - false only if already removed
if (remove) {
synchronized (active) {
boolean removed = active.remove(ch);
}
}
}
} catch (IOException ex2) {
log.log(Level.SEVERE, "SelectorThread: Error closing socket ", ex2);
}
}
// --------------- Socket op abstractions ------------
public int readNonBlocking(NioChannel selectorData, ByteBuffer bb)
throws IOException {
try {
int off = bb.position();
int done = 0;
done = ((SocketChannel) selectorData.channel).read(bb);
if (debug) {
log.info("-------------readNB rd=" + done + " bb.limit=" +
bb.limit() + " pos=" + bb.position() + " " + selectorData);
}
if (done > 0) {
if (debug) {
if (!bb.isDirect()) {
String s = new String(bb.array(), off,
bb.position() - off);
log.info("Data:\n" + s);
} else {
log.info("Data: " + bb.toString());
}
}
selectorData.zeroReads = 0;
} else if (done < 0) {
if (debug) {
log.info("SelectorThread: EOF while reading " + selectorData);
}
} else {
// need more...
if (selectorData.lastReadResult == 0) {
selectorData.zeroReads++;
if (selectorData.zeroReads > 6) {
log.severe("LOOP 0 reading ");
selectorData.lastException = new IOException("Polling read");
selectorData.close();
return -1;
}
}
}
selectorData.lastReadResult = done;
return done;
} catch(IOException ex) {
if (debug) {
log.info("readNB error rd=" + -1 + " bblen=" +
(bb.limit() - bb.position()) + " " + selectorData + " " + ex);
}
// common case: other side closed the connection. No need for trace
if (ex.toString().indexOf("Connection reset by peer") < 0) {
ex.printStackTrace();
}
selectorData.lastException = ex;
selectorData.close();
return -1;
}
}
/**
* May be called from any thread
*/
public int writeNonBlocking(NioChannel selectorData, ByteBuffer bb)
throws IOException {
try {
if (debug) {
log.info("writeNB pos=" + bb.position() + " len=" +
(bb.limit() - bb.position()) + " " + selectorData);
if (!bb.isDirect()) {
String s = new String(bb.array(), bb.position(),
bb.limit() - bb.position());
log.info("Data:\n" + s);
}
}
if (selectorData.writeInterest) {
// writeInterest will be false after a callback, if it is
// set it means we want to wait for the callback.
if (debug) {
log.info("Prevent writeNB when writeInterest is set");
}
return 0;
}
int done = 0;
done = ((SocketChannel) selectorData.channel).write(bb);
selectorData.lastWriteResult = done;
return done;
} catch(IOException ex) {
if (debug) {
log.info("writeNB error pos=" + bb.position() + " len=" +
(bb.limit() - bb.position()) + " " + selectorData + " " +
ex);
}
//ex.printStackTrace();
selectorData.lastException = ex;
selectorData.close();
throw ex;
// return -1;
}
}
public int getPort(NioChannel sd, boolean remote) {
SocketChannel socketChannel = (SocketChannel) sd.channel;
if (remote) {
return socketChannel.socket().getPort();
} else {
return socketChannel.socket().getLocalPort();
}
}
public InetAddress getAddress(NioChannel sd, boolean remote) {
SocketChannel socketChannel = (SocketChannel) sd.channel;
if (remote) {
return socketChannel.socket().getInetAddress();
} else {
return socketChannel.socket().getLocalAddress();
}
}
/**
*/
public void connect(String host, int port, NioChannelCallback cstate)
throws IOException {
connect(new InetSocketAddress(host, port), cstate);
}
public void connect(SocketAddress sa, NioChannelCallback cstate)
throws IOException {
connect(sa, cstate, null);
}
public void connect(SocketAddress sa, NioChannelCallback cstate,
NioChannel filter)
throws IOException {
SocketChannel socketChannel = SocketChannel.open();
socketChannel.configureBlocking(false);
NioChannel selectorData = new NioChannel(this);
selectorData.sel = this;
selectorData.callback = cstate;
selectorData.channel = socketChannel;
selectorData.channel = socketChannel; // no key
socketChannel.connect(sa);
opened.incrementAndGet();
synchronized (connectAcceptInterest) {
connectAcceptInterest.add(selectorData);
}
selector.wakeup();
}
// TODO
public void configureSocket(ByteChannel ch,
boolean noDelay) throws IOException {
SocketChannel sockC = (SocketChannel) ch;
sockC.socket().setTcpNoDelay(noDelay);
}
// TODO
public void setSocketOptions(NioChannel selectorData,
int linger,
boolean tcpNoDelay,
int socketTimeout)
throws IOException {
SocketChannel socketChannel =
(SocketChannel) selectorData.channel;
Socket socket = socketChannel.socket();
if(linger >= 0 )
socket.setSoLinger( true, linger);
if( tcpNoDelay )
socket.setTcpNoDelay(tcpNoDelay);
if( socketTimeout > 0 )
socket.setSoTimeout( socketTimeout );
}
/**
* Can be called from multiple threads or multiple times.
*/
public int close(NioChannel selectorData, Throwable exception) throws IOException {
synchronized (closeInterest) {
if (exception != null) {
selectorData.lastException = exception;
}
selectorData.readInterest = false;
if (isSelectorThread()) {
closeIOThread(selectorData, true);
return 0;
}
if (!selectorData.inClosed) {
closeInterest.add(selectorData);
}
}
selector.wakeup();
return 0;
}
public void acceptor(NioChannelCallback cstate,
int port,
InetAddress inet,
int backlog,
int serverTimeout)
throws IOException
{
ServerSocketChannel ssc=ServerSocketChannel.open();
ServerSocket serverSocket = ssc.socket();
SocketAddress sa = null;
if (inet == null) {
sa = new InetSocketAddress( port );
} else {
sa = new InetSocketAddress(inet, port);
}
if (backlog > 0) {
serverSocket.bind( sa , backlog);
} else {
serverSocket.bind(sa);
}
if( serverTimeout >= 0 ) {
serverSocket.setSoTimeout( serverTimeout );
}
ssc.configureBlocking(false);
NioChannel selectorData = new NioChannel(this);
selectorData.channel = ssc; // no key yet
selectorData.callback = cstate;
// key will be set in pending
// TODO: add SSL here
synchronized (connectAcceptInterest) {
connectAcceptInterest.add(selectorData);
}
selector.wakeup();
}
public void runInSelectorThread(Runnable cb) throws IOException {
if (isSelectorThread()) {
cb.run();
} else {
synchronized (runnableInterest) {
runnableInterest.add(cb);
}
selector.wakeup();
}
}
/**
* Example config:
*
* www stream tcp wait USER PATH_TO_tomcatInetd.sh
*
* For a different port, you need to add it to /etc/services.
*
* 'wait' is critical - the common use of inetd is 'nowait' for
* tcp services, which doesn't make sense for java ( too slow startup
* time ). It may make sense in future with something like android VM.
*
* In 'wait' mode, inetd will pass the acceptor socket to java - so
* you can listen on port 80 and run as regular user with no special
* code and magic.
* If tomcat dies, inetd will get back the acceptor and on next connection
* restart tomcat.
*
* This also works with xinetd. It might work with Apple launchd.
*
* TODO: detect inactivity for N minutes, exist - to free resources.
*/
public void inetdAcceptor(NioChannelCallback cstate) throws IOException {
SelectorProvider sp=SelectorProvider.provider();
Channel ch=sp.inheritedChannel();
if(ch!=null ) {
log.info("Inherited: " + ch.getClass().getName());
// blocking mode
ServerSocketChannel ssc=(ServerSocketChannel)ch;
ssc.configureBlocking(false);
NioChannel selectorData = new NioChannel(this);
selectorData.channel = ssc;
selectorData.callback = cstate;
synchronized (connectAcceptInterest) {
connectAcceptInterest.add(selectorData);
}
selector.wakeup();
} else {
log.severe("No inet socket ");
throw new IOException("Invalid inheritedChannel");
}
}
// -------------- Housekeeping -------------
/**
* Same as APR connector - iterate over tasks, get
* smallest timeout
* @throws IOException
*/
void updateSleepTimeAndProcessTimeouts(long now)
throws IOException {
long min = Long.MAX_VALUE;
// TODO: test with large sets, maybe sort
synchronized (active) {
Iterator<NioChannel> activeIt = active.iterator();
while(activeIt.hasNext()) {
NioChannel selectorData = activeIt.next();
if (! selectorData.channel.isOpen()) {
if (debug) {
log.info("Found closed socket, removing " +
selectorData.channel);
}
// activeIt.remove();
// selectorData.close();
}
long t = selectorData.nextTimeEvent;
if (t == 0) {
continue;
}
if (t < now) {
// Timeout
if (debug) {
log.info("Time event " + selectorData);
}
if (selectorData.timeEvent != null) {
selectorData.timeEvent.run();
}
// TODO: make sure this is updated if it was selected
continue;
}
if (t < min) {
min = t;
}
}
}
long nextSleep = min - now;
if (nextSleep > maxSleep) {
sleepTime = maxSleep;
} else if (nextSleep < minSleep) {
sleepTime = minSleep;
} else {
sleepTime = nextSleep;
}
nextWakeup = now + sleepTime;
}
/**
* Request a callback whenever data can be written.
* When the callback is invoked, the write interest is removed ( to avoid
* looping ). If the write() operation doesn't complete, you must call
* writeInterest - AND stop writing, some implementations will throw
* exception. write() will actually attempt to detect this and avoid the
* error.
*
* @param sc
*/
public void writeInterest(NioChannel selectorData) {
// TODO: suspended ?
SelectionKey sk = (SelectionKey) selectorData.selKey;
if (!sk.isValid()) {
return;
}
selectorData.writeInterest = true;
int interest = sk.interestOps();
if ((interest & SelectionKey.OP_WRITE) != 0) {
return;
}
if (Thread.currentThread() == selectorThread) {
interest =
interest | SelectionKey.OP_WRITE;
sk.interestOps(interest);
if (debug) {
log.info("Write interest " + selectorData + " i=" + interest);
}
return;
}
if (debug) {
log.info("Pending write interest " + selectorData);
}
synchronized (writeInterest) {
writeInterest.add(selectorData);
}
selector.wakeup();
}
public void readInterest(NioChannel selectorData, boolean b) throws IOException {
if (Thread.currentThread() == selectorThread) {
selectorData.readInterest = b;
selThreadReadInterest(selectorData);
return;
}
SelectionKey sk = (SelectionKey) selectorData.selKey;
if (sk == null) {
close(selectorData, null);
return;
}
int interest = sk.interestOps();
selectorData.readInterest = b;
if (b && (interest & SelectionKey.OP_READ) != 0) {
return;
}
if (!b && (interest & SelectionKey.OP_READ) == 0) {
return;
}
// Schedule the interest update.
synchronized (readInterest) {
readInterest.add(selectorData);
}
if (debug) {
log.info("Registering pending read interest");
}
selector.wakeup();
}
private void selThreadReadInterest(NioChannel selectorData) throws IOException {
SelectionKey sk = (SelectionKey) selectorData.selKey;
if (sk == null) {
if (selectorData.readInterest) {
if (debug) {
log.info("Register again for read interest");
}
SocketChannel socketChannel =
(SocketChannel) selectorData.channel;
if (socketChannel.isOpen()) {
selectorData.sel = this;
selectorData.selKey =
socketChannel.register(selector,
SelectionKey.OP_READ, selectorData);
selectorData.channel = socketChannel;
}
}
return;
}
if (!sk.isValid()) {
return;
}
int interest = sk.interestOps();
if (sk != null && sk.isValid()) {
if (selectorData.readInterest) {
// if ((interest | SelectionKey.OP_READ) != 0) {
// return;
// }
interest =
interest | SelectionKey.OP_READ;
} else {
// if ((interest | SelectionKey.OP_READ) == 0) {
// return;
// }
interest =
interest & ~SelectionKey.OP_READ;
}
if (interest == 0) {
if (!selectorData.inClosed) {
new Throwable().printStackTrace();
log.warning("No interest(rd removed) " + selectorData);
}
// TODO: should we remove it ? It needs to be re-activated
// later.
sk.cancel(); //??
selectorData.selKey = null;
} else {
sk.interestOps(interest);
}
if (debug) {
log.info(((selectorData.readInterest)
? "RESUME read " : "SUSPEND read ")
+ selectorData);
}
}
}
private void processPendingConnectAccept() throws IOException {
synchronized (connectAcceptInterest) {
Iterator<NioChannel> ci = connectAcceptInterest.iterator();
while (ci.hasNext()) {
NioChannel selectorData = ci.next();
// Find host, port - initiate connection
try {
// Accept interest ?
if (selectorData.channel instanceof ServerSocketChannel) {
ServerSocketChannel socketChannel =
(ServerSocketChannel) selectorData.channel;
selectorData.sel = this;
selectorData.selKey =
socketChannel.register(selector,
SelectionKey.OP_ACCEPT, selectorData);
selectorData.channel = socketChannel;
synchronized (active) {
active.add(selectorData);
}
if (debug) {
log.info("Pending acceptor added: " + selectorData);
}
} else {
SocketChannel socketChannel =
(SocketChannel) selectorData.channel;
selectorData.sel = this;
selectorData.selKey =
socketChannel.register(selector,
SelectionKey.OP_CONNECT, selectorData);
synchronized (active) {
active.add(selectorData);
}
if (debug) {
log.info("Pending connect added: " + selectorData);
}
}
} catch (Throwable e) {
log.log(Level.SEVERE, "error registering connect/accept",
e);
}
}
connectAcceptInterest.clear();
}
}
private void processPending() throws IOException {
if (closeInterest.size() > 0) {
synchronized (closeInterest) {
List<NioChannel> closeList = new ArrayList(closeInterest);
closeInterest.clear();
Iterator<NioChannel> ci = closeList.iterator();
while (ci.hasNext()) {
try {
NioChannel selectorData = ci.next();
closeIOThread(selectorData, true);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
processPendingConnectAccept();
processPendingReadWrite();
if (runnableInterest.size() > 0) {
synchronized (runnableInterest) {
Iterator<Runnable> ci = runnableInterest.iterator();
while (ci.hasNext()) {
Runnable cstate = ci.next();
try {
cstate.run();
} catch (Throwable t) {
t.printStackTrace();
}
if (debug) {
log.info("Run in selthread: " + cstate);
}
}
runnableInterest.clear();
}
}
//processPendingUpdateCallback();
}
private void processPendingReadWrite() throws IOException {
// Update interest
if (readInterest.size() > 0) {
synchronized (readInterest) {
Iterator<NioChannel> ci = readInterest.iterator();
while (ci.hasNext()) {
NioChannel cstate = ci.next();
selThreadReadInterest(cstate);
if (debug) {
log.info("Read interest added: " + cstate);
}
}
readInterest.clear();
}
}
if (writeInterest.size() > 0) {
synchronized (writeInterest) {
Iterator<NioChannel> ci = writeInterest.iterator();
while (ci.hasNext()) {
NioChannel cstate = ci.next();
// Fake callback - will update as side effect
handleDataWriteable(cstate);
if (debug) {
log.info("Write interest, calling dataWritable: " + cstate);
}
}
writeInterest.clear();
}
}
}
protected boolean isSelectorThread() {
return Thread.currentThread() == selectorThread;
}
public static boolean isSelectorThread(IOChannel ch) {
SocketIOChannel sc = (SocketIOChannel) ch.getFirst();
return Thread.currentThread() == sc.ch.sel.selectorThread;
}
}
|
googleapis/google-cloud-java
| 38,074
|
java-distributedcloudedge/proto-google-cloud-distributedcloudedge-v1/src/main/java/com/google/cloud/edgecontainer/v1/ListMachinesRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/edgecontainer/v1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.edgecontainer.v1;
/**
*
*
* <pre>
* Lists machines in a site.
* </pre>
*
* Protobuf type {@code google.cloud.edgecontainer.v1.ListMachinesRequest}
*/
public final class ListMachinesRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.edgecontainer.v1.ListMachinesRequest)
ListMachinesRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListMachinesRequest.newBuilder() to construct.
private ListMachinesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListMachinesRequest() {
parent_ = "";
pageToken_ = "";
filter_ = "";
orderBy_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListMachinesRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.edgecontainer.v1.ServiceProto
.internal_static_google_cloud_edgecontainer_v1_ListMachinesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.edgecontainer.v1.ServiceProto
.internal_static_google_cloud_edgecontainer_v1_ListMachinesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.edgecontainer.v1.ListMachinesRequest.class,
com.google.cloud.edgecontainer.v1.ListMachinesRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent site, which owns this collection of machines.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The parent site, which owns this collection of machines.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* The maximum number of resources to list.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A page token received from previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* A page token received from previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Only resources matching this filter will be listed.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Only resources matching this filter will be listed.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ORDER_BY_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Specifies the order in which resources will be listed.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
@java.lang.Override
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
}
}
/**
*
*
* <pre>
* Specifies the order in which resources will be listed.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (pageSize_ != 0) {
output.writeInt32(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, orderBy_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, pageToken_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, filter_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(orderBy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, orderBy_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.edgecontainer.v1.ListMachinesRequest)) {
return super.equals(obj);
}
com.google.cloud.edgecontainer.v1.ListMachinesRequest other =
(com.google.cloud.edgecontainer.v1.ListMachinesRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (!getOrderBy().equals(other.getOrderBy())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + ORDER_BY_FIELD_NUMBER;
hash = (53 * hash) + getOrderBy().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.edgecontainer.v1.ListMachinesRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Lists machines in a site.
* </pre>
*
* Protobuf type {@code google.cloud.edgecontainer.v1.ListMachinesRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.edgecontainer.v1.ListMachinesRequest)
com.google.cloud.edgecontainer.v1.ListMachinesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.edgecontainer.v1.ServiceProto
.internal_static_google_cloud_edgecontainer_v1_ListMachinesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.edgecontainer.v1.ServiceProto
.internal_static_google_cloud_edgecontainer_v1_ListMachinesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.edgecontainer.v1.ListMachinesRequest.class,
com.google.cloud.edgecontainer.v1.ListMachinesRequest.Builder.class);
}
// Construct using com.google.cloud.edgecontainer.v1.ListMachinesRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
pageSize_ = 0;
pageToken_ = "";
filter_ = "";
orderBy_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.edgecontainer.v1.ServiceProto
.internal_static_google_cloud_edgecontainer_v1_ListMachinesRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.edgecontainer.v1.ListMachinesRequest getDefaultInstanceForType() {
return com.google.cloud.edgecontainer.v1.ListMachinesRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.edgecontainer.v1.ListMachinesRequest build() {
com.google.cloud.edgecontainer.v1.ListMachinesRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.edgecontainer.v1.ListMachinesRequest buildPartial() {
com.google.cloud.edgecontainer.v1.ListMachinesRequest result =
new com.google.cloud.edgecontainer.v1.ListMachinesRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.edgecontainer.v1.ListMachinesRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageToken_ = pageToken_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.orderBy_ = orderBy_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.edgecontainer.v1.ListMachinesRequest) {
return mergeFrom((com.google.cloud.edgecontainer.v1.ListMachinesRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.edgecontainer.v1.ListMachinesRequest other) {
if (other == com.google.cloud.edgecontainer.v1.ListMachinesRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getOrderBy().isEmpty()) {
orderBy_ = other.orderBy_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
orderBy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The parent site, which owns this collection of machines.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The parent site, which owns this collection of machines.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The parent site, which owns this collection of machines.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent site, which owns this collection of machines.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The parent site, which owns this collection of machines.
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of resources to list.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The maximum number of resources to list.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The maximum number of resources to list.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000002);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* A page token received from previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A page token received from previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A page token received from previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* A page token received from previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* A page token received from previous list request.
* </pre>
*
* <code>string page_token = 3;</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Only resources matching this filter will be listed.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Only resources matching this filter will be listed.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Only resources matching this filter will be listed.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Only resources matching this filter will be listed.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Only resources matching this filter will be listed.
* </pre>
*
* <code>string filter = 4;</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object orderBy_ = "";
/**
*
*
* <pre>
* Specifies the order in which resources will be listed.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The orderBy.
*/
public java.lang.String getOrderBy() {
java.lang.Object ref = orderBy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
orderBy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Specifies the order in which resources will be listed.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return The bytes for orderBy.
*/
public com.google.protobuf.ByteString getOrderByBytes() {
java.lang.Object ref = orderBy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
orderBy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Specifies the order in which resources will be listed.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderBy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Specifies the order in which resources will be listed.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearOrderBy() {
orderBy_ = getDefaultInstance().getOrderBy();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Specifies the order in which resources will be listed.
* </pre>
*
* <code>string order_by = 5;</code>
*
* @param value The bytes for orderBy to set.
* @return This builder for chaining.
*/
public Builder setOrderByBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
orderBy_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.edgecontainer.v1.ListMachinesRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.edgecontainer.v1.ListMachinesRequest)
private static final com.google.cloud.edgecontainer.v1.ListMachinesRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.edgecontainer.v1.ListMachinesRequest();
}
public static com.google.cloud.edgecontainer.v1.ListMachinesRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListMachinesRequest> PARSER =
new com.google.protobuf.AbstractParser<ListMachinesRequest>() {
@java.lang.Override
public ListMachinesRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListMachinesRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListMachinesRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.edgecontainer.v1.ListMachinesRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,377
|
java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/TrajectoryPrecisionResults.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1beta1/evaluation_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Results for TrajectoryPrecision metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults}
*/
public final class TrajectoryPrecisionResults extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults)
TrajectoryPrecisionResultsOrBuilder {
private static final long serialVersionUID = 0L;
// Use TrajectoryPrecisionResults.newBuilder() to construct.
private TrajectoryPrecisionResults(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private TrajectoryPrecisionResults() {
trajectoryPrecisionMetricValues_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new TrajectoryPrecisionResults();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_TrajectoryPrecisionResults_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_TrajectoryPrecisionResults_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults.class,
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults.Builder.class);
}
public static final int TRAJECTORY_PRECISION_METRIC_VALUES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue>
trajectoryPrecisionMetricValues_;
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue>
getTrajectoryPrecisionMetricValuesList() {
return trajectoryPrecisionMetricValues_;
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
@java.lang.Override
public java.util.List<
? extends com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValueOrBuilder>
getTrajectoryPrecisionMetricValuesOrBuilderList() {
return trajectoryPrecisionMetricValues_;
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
@java.lang.Override
public int getTrajectoryPrecisionMetricValuesCount() {
return trajectoryPrecisionMetricValues_.size();
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue
getTrajectoryPrecisionMetricValues(int index) {
return trajectoryPrecisionMetricValues_.get(index);
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValueOrBuilder
getTrajectoryPrecisionMetricValuesOrBuilder(int index) {
return trajectoryPrecisionMetricValues_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < trajectoryPrecisionMetricValues_.size(); i++) {
output.writeMessage(1, trajectoryPrecisionMetricValues_.get(i));
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < trajectoryPrecisionMetricValues_.size(); i++) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, trajectoryPrecisionMetricValues_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults other =
(com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults) obj;
if (!getTrajectoryPrecisionMetricValuesList()
.equals(other.getTrajectoryPrecisionMetricValuesList())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getTrajectoryPrecisionMetricValuesCount() > 0) {
hash = (37 * hash) + TRAJECTORY_PRECISION_METRIC_VALUES_FIELD_NUMBER;
hash = (53 * hash) + getTrajectoryPrecisionMetricValuesList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Results for TrajectoryPrecision metric.
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults)
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResultsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_TrajectoryPrecisionResults_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_TrajectoryPrecisionResults_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults.class,
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
trajectoryPrecisionMetricValues_ = java.util.Collections.emptyList();
} else {
trajectoryPrecisionMetricValues_ = null;
trajectoryPrecisionMetricValuesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.EvaluationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_TrajectoryPrecisionResults_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults build() {
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults buildPartial() {
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults result =
new com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults result) {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
trajectoryPrecisionMetricValues_ =
java.util.Collections.unmodifiableList(trajectoryPrecisionMetricValues_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.trajectoryPrecisionMetricValues_ = trajectoryPrecisionMetricValues_;
} else {
result.trajectoryPrecisionMetricValues_ = trajectoryPrecisionMetricValuesBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults result) {
int from_bitField0_ = bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults other) {
if (other
== com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults.getDefaultInstance())
return this;
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
if (!other.trajectoryPrecisionMetricValues_.isEmpty()) {
if (trajectoryPrecisionMetricValues_.isEmpty()) {
trajectoryPrecisionMetricValues_ = other.trajectoryPrecisionMetricValues_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureTrajectoryPrecisionMetricValuesIsMutable();
trajectoryPrecisionMetricValues_.addAll(other.trajectoryPrecisionMetricValues_);
}
onChanged();
}
} else {
if (!other.trajectoryPrecisionMetricValues_.isEmpty()) {
if (trajectoryPrecisionMetricValuesBuilder_.isEmpty()) {
trajectoryPrecisionMetricValuesBuilder_.dispose();
trajectoryPrecisionMetricValuesBuilder_ = null;
trajectoryPrecisionMetricValues_ = other.trajectoryPrecisionMetricValues_;
bitField0_ = (bitField0_ & ~0x00000001);
trajectoryPrecisionMetricValuesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getTrajectoryPrecisionMetricValuesFieldBuilder()
: null;
} else {
trajectoryPrecisionMetricValuesBuilder_.addAllMessages(
other.trajectoryPrecisionMetricValues_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue m =
input.readMessage(
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue.parser(),
extensionRegistry);
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
ensureTrajectoryPrecisionMetricValuesIsMutable();
trajectoryPrecisionMetricValues_.add(m);
} else {
trajectoryPrecisionMetricValuesBuilder_.addMessage(m);
}
break;
} // case 10
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue>
trajectoryPrecisionMetricValues_ = java.util.Collections.emptyList();
private void ensureTrajectoryPrecisionMetricValuesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
trajectoryPrecisionMetricValues_ =
new java.util.ArrayList<
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue>(
trajectoryPrecisionMetricValues_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue,
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue.Builder,
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValueOrBuilder>
trajectoryPrecisionMetricValuesBuilder_;
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue>
getTrajectoryPrecisionMetricValuesList() {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
return java.util.Collections.unmodifiableList(trajectoryPrecisionMetricValues_);
} else {
return trajectoryPrecisionMetricValuesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public int getTrajectoryPrecisionMetricValuesCount() {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
return trajectoryPrecisionMetricValues_.size();
} else {
return trajectoryPrecisionMetricValuesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue
getTrajectoryPrecisionMetricValues(int index) {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
return trajectoryPrecisionMetricValues_.get(index);
} else {
return trajectoryPrecisionMetricValuesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder setTrajectoryPrecisionMetricValues(
int index, com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue value) {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTrajectoryPrecisionMetricValuesIsMutable();
trajectoryPrecisionMetricValues_.set(index, value);
onChanged();
} else {
trajectoryPrecisionMetricValuesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder setTrajectoryPrecisionMetricValues(
int index,
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue.Builder
builderForValue) {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
ensureTrajectoryPrecisionMetricValuesIsMutable();
trajectoryPrecisionMetricValues_.set(index, builderForValue.build());
onChanged();
} else {
trajectoryPrecisionMetricValuesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder addTrajectoryPrecisionMetricValues(
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue value) {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTrajectoryPrecisionMetricValuesIsMutable();
trajectoryPrecisionMetricValues_.add(value);
onChanged();
} else {
trajectoryPrecisionMetricValuesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder addTrajectoryPrecisionMetricValues(
int index, com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue value) {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTrajectoryPrecisionMetricValuesIsMutable();
trajectoryPrecisionMetricValues_.add(index, value);
onChanged();
} else {
trajectoryPrecisionMetricValuesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder addTrajectoryPrecisionMetricValues(
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue.Builder
builderForValue) {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
ensureTrajectoryPrecisionMetricValuesIsMutable();
trajectoryPrecisionMetricValues_.add(builderForValue.build());
onChanged();
} else {
trajectoryPrecisionMetricValuesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder addTrajectoryPrecisionMetricValues(
int index,
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue.Builder
builderForValue) {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
ensureTrajectoryPrecisionMetricValuesIsMutable();
trajectoryPrecisionMetricValues_.add(index, builderForValue.build());
onChanged();
} else {
trajectoryPrecisionMetricValuesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder addAllTrajectoryPrecisionMetricValues(
java.lang.Iterable<
? extends com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue>
values) {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
ensureTrajectoryPrecisionMetricValuesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(
values, trajectoryPrecisionMetricValues_);
onChanged();
} else {
trajectoryPrecisionMetricValuesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder clearTrajectoryPrecisionMetricValues() {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
trajectoryPrecisionMetricValues_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
trajectoryPrecisionMetricValuesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public Builder removeTrajectoryPrecisionMetricValues(int index) {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
ensureTrajectoryPrecisionMetricValuesIsMutable();
trajectoryPrecisionMetricValues_.remove(index);
onChanged();
} else {
trajectoryPrecisionMetricValuesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue.Builder
getTrajectoryPrecisionMetricValuesBuilder(int index) {
return getTrajectoryPrecisionMetricValuesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValueOrBuilder
getTrajectoryPrecisionMetricValuesOrBuilder(int index) {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
return trajectoryPrecisionMetricValues_.get(index);
} else {
return trajectoryPrecisionMetricValuesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public java.util.List<
? extends com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValueOrBuilder>
getTrajectoryPrecisionMetricValuesOrBuilderList() {
if (trajectoryPrecisionMetricValuesBuilder_ != null) {
return trajectoryPrecisionMetricValuesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(trajectoryPrecisionMetricValues_);
}
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue.Builder
addTrajectoryPrecisionMetricValuesBuilder() {
return getTrajectoryPrecisionMetricValuesFieldBuilder()
.addBuilder(
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue
.getDefaultInstance());
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue.Builder
addTrajectoryPrecisionMetricValuesBuilder(int index) {
return getTrajectoryPrecisionMetricValuesFieldBuilder()
.addBuilder(
index,
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue
.getDefaultInstance());
}
/**
*
*
* <pre>
* Output only. TrajectoryPrecision metric values.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue trajectory_precision_metric_values = 1 [(.google.api.field_behavior) = OUTPUT_ONLY];
* </code>
*/
public java.util.List<
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue.Builder>
getTrajectoryPrecisionMetricValuesBuilderList() {
return getTrajectoryPrecisionMetricValuesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue,
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue.Builder,
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValueOrBuilder>
getTrajectoryPrecisionMetricValuesFieldBuilder() {
if (trajectoryPrecisionMetricValuesBuilder_ == null) {
trajectoryPrecisionMetricValuesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue,
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValue.Builder,
com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionMetricValueOrBuilder>(
trajectoryPrecisionMetricValues_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
trajectoryPrecisionMetricValues_ = null;
}
return trajectoryPrecisionMetricValuesBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults)
private static final com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults();
}
public static com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<TrajectoryPrecisionResults> PARSER =
new com.google.protobuf.AbstractParser<TrajectoryPrecisionResults>() {
@java.lang.Override
public TrajectoryPrecisionResults parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<TrajectoryPrecisionResults> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<TrajectoryPrecisionResults> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.TrajectoryPrecisionResults
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
google/filament
| 38,482
|
android/filament-android/src/main/java/com/google/android/filament/MaterialInstance.java
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.filament;
import androidx.annotation.IntRange;
import androidx.annotation.NonNull;
import androidx.annotation.Size;
import com.google.android.filament.proguard.UsedByNative;
@UsedByNative("AssetLoader.cpp")
public class MaterialInstance {
private static final Material.CullingMode[] sCullingModeValues = Material.CullingMode.values();
private Material mMaterial;
private String mName;
private long mNativeObject;
private long mNativeMaterial;
public enum BooleanElement {
BOOL,
BOOL2,
BOOL3,
BOOL4
}
public enum IntElement {
INT,
INT2,
INT3,
INT4
}
public enum FloatElement {
FLOAT,
FLOAT2,
FLOAT3,
FLOAT4,
MAT3,
MAT4
}
/**
* Operations that control how the stencil buffer is updated.
*/
public enum StencilOperation {
/**
* Keeps the current value.
*/
KEEP,
/**
* Sets the value to 0.
*/
ZERO,
/**
* Sets the value to the stencil reference value.
*/
REPLACE,
/**
* Increments the current value. Clamps to the maximum representable unsigned value.
*/
INCR_CLAMP,
/**
* Increments the current value. Wraps value to zero when incrementing the maximum
* representable unsigned value.
*/
INCR_WRAP,
/**
* Decrements the current value. Clamps to 0.
*/
DECR_CLAMP,
/**
* Decrements the current value. Wraps value to the maximum representable unsigned value
* when decrementing a value of zero.
*/
DECR_WRAP,
/**
* Bitwise inverts the current value.
*/
INVERT,
}
public enum StencilFace {
FRONT,
BACK,
FRONT_AND_BACK
}
// Converts the StencilFace enum ordinal to Filament's equivalent bit field.
static final int[] sStencilFaceMapping = {0x1, 0x2, 0x3};
public MaterialInstance(Engine engine, long nativeMaterialInstance) {
mNativeObject = nativeMaterialInstance;
mNativeMaterial = nGetMaterial(mNativeObject);
}
MaterialInstance(@NonNull Material material, long nativeMaterialInstance) {
mMaterial = material;
mNativeMaterial = material.getNativeObject();
mNativeObject = nativeMaterialInstance;
}
MaterialInstance(long nativeMaterialInstance) {
mNativeObject = nativeMaterialInstance;
mNativeMaterial = nGetMaterial(mNativeObject);
}
/**
* Creates a new {@link #MaterialInstance} using another {@link #MaterialInstance} as a template for initialization.
* The new {@link #MaterialInstance} is an instance of the same {@link Material} of the template instance and
* must be destroyed just like any other {@link #MaterialInstance}.
*
* @param other A {@link #MaterialInstance} to use as a template for initializing a new instance
* @param name A name for the new {@link #MaterialInstance} or nullptr to use the template's name
* @return A new {@link #MaterialInstance}
*/
@NonNull
public static MaterialInstance duplicate(@NonNull MaterialInstance other, String name) {
long nativeInstance = nDuplicate(other.mNativeObject, name);
if (nativeInstance == 0) throw new IllegalStateException("Couldn't duplicate MaterialInstance");
return new MaterialInstance(other.getMaterial(), nativeInstance);
}
/** @return the {@link Material} associated with this instance */
@NonNull
public Material getMaterial() {
if (mMaterial == null) {
mMaterial = new Material(mNativeMaterial);
}
return mMaterial;
}
/** @return the name associated with this instance */
@NonNull
public String getName() {
if (mName == null) {
mName = nGetName(getNativeObject());
}
return mName;
}
/**
* Sets the value of a bool parameter.
*
* @param name the name of the material parameter
* @param x the value of the material parameter
*/
public void setParameter(@NonNull String name, boolean x) {
nSetParameterBool(getNativeObject(), name, x);
}
/**
* Sets the value of a float parameter.
*
* @param name the name of the material parameter
* @param x the value of the material parameter
*/
public void setParameter(@NonNull String name, float x) {
nSetParameterFloat(getNativeObject(), name, x);
}
/**
* Sets the value of an int parameter.
*
* @param name the name of the material parameter
* @param x the value of the material parameter
*/
public void setParameter(@NonNull String name, int x) {
nSetParameterInt(getNativeObject(), name, x);
}
/**
* Sets the value of a bool2 parameter.
*
* @param name the name of the material parameter
* @param x the value of the first component
* @param y the value of the second component
*/
public void setParameter(@NonNull String name, boolean x, boolean y) {
nSetParameterBool2(getNativeObject(), name, x, y);
}
/**
* Sets the value of a float2 parameter.
*
* @param name the name of the material parameter
* @param x the value of the first component
* @param y the value of the second component
*/
public void setParameter(@NonNull String name, float x, float y) {
nSetParameterFloat2(getNativeObject(), name, x, y);
}
/**
* Sets the value of an int2 parameter.
*
* @param name the name of the material parameter
* @param x the value of the first component
* @param y the value of the second component
*/
public void setParameter(@NonNull String name, int x, int y) {
nSetParameterInt2(getNativeObject(), name, x, y);
}
/**
* Sets the value of a bool3 parameter.
*
* @param name the name of the material parameter
* @param x the value of the first component
* @param y the value of the second component
* @param z the value of the third component
*/
public void setParameter(@NonNull String name, boolean x, boolean y, boolean z) {
nSetParameterBool3(getNativeObject(), name, x, y, z);
}
/**
* Sets the value of a float3 parameter.
*
* @param name the name of the material parameter
* @param x the value of the first component
* @param y the value of the second component
* @param z the value of the third component
*/
public void setParameter(@NonNull String name, float x, float y, float z) {
nSetParameterFloat3(getNativeObject(), name, x, y, z);
}
/**
* Sets the value of a int3 parameter.
*
* @param name the name of the material parameter
* @param x the value of the first component
* @param y the value of the second component
* @param z the value of the third component
*/
public void setParameter(@NonNull String name, int x, int y, int z) {
nSetParameterInt3(getNativeObject(), name, x, y, z);
}
/**
* Sets the value of a bool4 parameter.
*
* @param name the name of the material parameter
* @param x the value of the first component
* @param y the value of the second component
* @param z the value of the third component
* @param w the value of the fourth component
*/
public void setParameter(@NonNull String name, boolean x, boolean y, boolean z, boolean w) {
nSetParameterBool4(getNativeObject(), name, x, y, z, w);
}
/**
* Sets the value of a float4 parameter.
*
* @param name the name of the material parameter
* @param x the value of the first component
* @param y the value of the second component
* @param z the value of the third component
* @param w the value of the fourth component
*/
public void setParameter(@NonNull String name, float x, float y, float z, float w) {
nSetParameterFloat4(getNativeObject(), name, x, y, z, w);
}
/**
* Sets the value of a int4 parameter.
*
* @param name the name of the material parameter
* @param x the value of the first component
* @param y the value of the second component
* @param z the value of the third component
* @param w the value of the fourth component
*/
public void setParameter(@NonNull String name, int x, int y, int z, int w) {
nSetParameterInt4(getNativeObject(), name, x, y, z, w);
}
/**
* Sets a texture and sampler parameter on this material's default instance.
* <p>
* Note: Depth textures can't be sampled with a linear filter unless the comparison mode is set
* to COMPARE_TO_TEXTURE.
* </p>
*
* @param name The name of the material texture parameter
* @param texture The texture to set as parameter
* @param sampler The sampler to be used with this texture
*/
public void setParameter(@NonNull String name,
@NonNull Texture texture, @NonNull TextureSampler sampler) {
nSetParameterTexture(getNativeObject(), name, texture.getNativeObject(), sampler.mSampler);
}
/**
* Set a bool parameter array by name.
*
* @param name name of the parameter array as defined by this Material
* @param type the number of components for each individual parameter
* @param v array of values to set to the named parameter array
* @param offset the number of elements in <code>v</code> to skip
* @param count the number of elements in the parameter array to set
*
* <p>For example, to set a parameter array of 4 bool4s:
* <pre>{@code
* boolean[] a = new boolean[4 * 4];
* instance.setParameter("param", MaterialInstance.BooleanElement.BOOL4, a, 0, 4);
* }</pre>
* </p>
*/
public void setParameter(@NonNull String name,
@NonNull BooleanElement type, @NonNull boolean[] v,
@IntRange(from = 0) int offset, @IntRange(from = 1) int count) {
nSetBooleanParameterArray(getNativeObject(), name, type.ordinal(), v, offset, count);
}
/**
* Set an int parameter array by name.
*
* @param name name of the parameter array as defined by this Material
* @param type the number of components for each individual parameter
* @param v array of values to set to the named parameter array
* @param offset the number of elements in <code>v</code> to skip
* @param count the number of elements in the parameter array to set
*
* <p>For example, to set a parameter array of 4 int4s:
* <pre>{@code
* int[] a = new int[4 * 4];
* instance.setParameter("param", MaterialInstance.IntElement.INT4, a, 0, 4);
* }</pre>
* </p>
*/
public void setParameter(@NonNull String name,
@NonNull IntElement type, @NonNull int[] v,
@IntRange(from = 0) int offset, @IntRange(from = 1) int count) {
nSetIntParameterArray(getNativeObject(), name, type.ordinal(), v, offset, count);
}
/**
* Set a float parameter array by name.
*
* @param name name of the parameter array as defined by this Material
* @param type the number of components for each individual parameter
* @param v array of values to set to the named parameter array
* @param offset the number of elements in <code>v</code> to skip
* @param count the number of elements in the parameter array to set
*
* <p>For example, to set a parameter array of 4 float4s:
* <pre>{@code
* float[] a = new float[4 * 4];
* material.setDefaultParameter("param", MaterialInstance.FloatElement.FLOAT4, a, 0, 4);
* }</pre>
* </p>
*/
public void setParameter(@NonNull String name,
@NonNull FloatElement type, @NonNull float[] v,
@IntRange(from = 0) int offset, @IntRange(from = 1) int count) {
nSetFloatParameterArray(getNativeObject(), name, type.ordinal(), v, offset, count);
}
/**
* Sets the color of the given parameter on this material's default instance.
*
* @param name the name of the material color parameter
* @param type whether the color is specified in the linear or sRGB space
* @param r red component
* @param g green component
* @param b blue component
*/
public void setParameter(@NonNull String name, @NonNull Colors.RgbType type,
float r, float g, float b) {
float[] color = Colors.toLinear(type, r, g, b);
nSetParameterFloat3(getNativeObject(), name, color[0], color[1], color[2]);
}
/**
* Sets the color of the given parameter on this material's default instance.
*
* @param name the name of the material color parameter
* @param type whether the color is specified in the linear or sRGB space
* @param r red component
* @param g green component
* @param b blue component
* @param a alpha component
*/
public void setParameter(@NonNull String name, @NonNull Colors.RgbaType type,
float r, float g, float b, float a) {
float[] color = Colors.toLinear(type, r, g, b, a);
nSetParameterFloat4(getNativeObject(), name, color[0], color[1], color[2], color[3]);
}
/**
* Set-up a custom scissor rectangle; by default it is disabled.
*
* <p>
* The scissor rectangle gets clipped by the View's viewport, in other words, the scissor
* cannot affect fragments outside of the View's Viewport.
* </p>
*
* <p>
* Currently the scissor is not compatible with dynamic resolution and should always be
* disabled when dynamic resolution is used.
* </p>
*
* @param left left coordinate of the scissor box relative to the viewport
* @param bottom bottom coordinate of the scissor box relative to the viewport
* @param width width of the scissor box
* @param height height of the scissor box
*
* @see #unsetScissor
* @see View#setViewport
* @see View#setDynamicResolutionOptions
*/
public void setScissor(@IntRange(from = 0) int left, @IntRange(from = 0) int bottom,
@IntRange(from = 0) int width, @IntRange(from = 0) int height) {
nSetScissor(getNativeObject(), left, bottom, width, height);
}
/**
* Returns the scissor rectangle to its default disabled setting.
* <p>
* Currently the scissor is not compatible with dynamic resolution and should always be
* disabled when dynamic resolution is used.
* </p>
* @see View#setDynamicResolutionOptions
*/
public void unsetScissor() {
nUnsetScissor(getNativeObject());
}
/**
* Sets a polygon offset that will be applied to all renderables drawn with this material
* instance.
*
* The value of the offset is scale * dz + r * constant, where dz is the change in depth
* relative to the screen area of the triangle, and r is the smallest value that is guaranteed
* to produce a resolvable offset for a given implementation. This offset is added before the
* depth test.
*
* Warning: using a polygon offset other than zero has a significant negative performance
* impact, as most implementations have to disable early depth culling. DO NOT USE unless
* absolutely necessary.
*
* @param scale scale factor used to create a variable depth offset for each triangle
* @param constant scale factor used to create a constant depth offset for each triangle
*/
public void setPolygonOffset(float scale, float constant) {
nSetPolygonOffset(getNativeObject(), scale, constant);
}
/**
* Overrides the minimum alpha value a fragment must have to not be discarded when the blend
* mode is MASKED. Defaults to 0.4 if it has not been set in the parent Material. The specified
* value should be between 0 and 1 and will be clamped if necessary.
*
* @see
* <a href="https://google.github.io/filament/Materials.html#materialdefinitions/materialblock/blendingandtransparency:maskthreshold">
* Blending and transparency: maskThreshold</a>
*/
public void setMaskThreshold(float threshold) {
nSetMaskThreshold(getNativeObject(), threshold);
}
/**
* Gets the minimum alpha value a fragment must have to not be discarded when the blend
* mode is MASKED
*/
public float getMaskThreshold() {
return nGetMaskThreshold(getNativeObject());
}
/**
* Sets the screen space variance of the filter kernel used when applying specular
* anti-aliasing. The default value is set to 0.15. The specified value should be between
* 0 and 1 and will be clamped if necessary.
*
* @see
* <a href="https://google.github.io/filament/Materials.html#materialdefinitions/materialblock/anti-aliasing:specularantialiasingvariance">
* Anti-aliasing: specularAntiAliasingVariance</a>
*/
public void setSpecularAntiAliasingVariance(float variance) {
nSetSpecularAntiAliasingVariance(getNativeObject(), variance);
}
/**
* Gets the screen space variance of the filter kernel used when applying specular
* anti-aliasing.
*/
public float getSpecularAntiAliasingVariance() {
return nGetSpecularAntiAliasingVariance(getNativeObject());
}
/**
* Sets the clamping threshold used to suppress estimation errors when applying specular
* anti-aliasing. The default value is set to 0.2. The specified value should be between 0
* and 1 and will be clamped if necessary.
*
* @see
* <a href="https://google.github.io/filament/Materials.html#materialdefinitions/materialblock/anti-aliasing:specularantialiasingthreshold">
* Anti-aliasing: specularAntiAliasingThreshold</a>
*/
public void setSpecularAntiAliasingThreshold(float threshold) {
nSetSpecularAntiAliasingThreshold(getNativeObject(), threshold);
}
/**
* Gets the clamping threshold used to suppress estimation errors when applying specular
* anti-aliasing.
*/
public float getSpecularAntiAliasingThreshold() {
return nGetSpecularAntiAliasingThreshold(getNativeObject());
}
/**
* Enables or disables double-sided lighting if the parent Material has double-sided capability,
* otherwise prints a warning. If double-sided lighting is enabled, backface culling is
* automatically disabled.
*
* @see
* <a href="https://google.github.io/filament/Materials.html#materialdefinitions/materialblock/rasterization:doublesided">
* Rasterization: doubleSided</a>
*/
public void setDoubleSided(boolean doubleSided) {
nSetDoubleSided(getNativeObject(), doubleSided);
}
/**
* Returns whether double-sided lighting is enabled when the parent Material has double-sided
* capability.
*/
public boolean isDoubleSided() {
return nIsDoubleSided(getNativeObject());
}
/**
* Overrides the default triangle culling state that was set on the material.
*
* @see
* <a href="https://google.github.io/filament/Materials.html#materialdefinitions/materialblock/rasterization:culling">
* Rasterization: culling</a>
*/
public void setCullingMode(@NonNull Material.CullingMode mode) {
nSetCullingMode(getNativeObject(), mode.ordinal());
}
/**
* Overrides the default triangle culling state that was set on the material separately for the
* color and shadow passes
*
* @see
* <a href="https://google.github.io/filament/Materials.html#materialdefinitions/materialblock/rasterization:culling">
* Rasterization: culling</a>
*/
public void setCullingMode(@NonNull Material.CullingMode colorPassCullingMode,
@NonNull Material.CullingMode shadowPassCullingMode) {
nSetCullingModeSeparate(getNativeObject(),
colorPassCullingMode.ordinal(), shadowPassCullingMode.ordinal());
}
/**
* Returns the face culling mode.
*/
@NonNull
public Material.CullingMode getCullingMode() {
return sCullingModeValues[nGetCullingMode(getNativeObject())];
}
/**
* Returns the face culling mode for the shadow passes.
*/
@NonNull
public Material.CullingMode getShadowCullingMode() {
return sCullingModeValues[nGetShadowCullingMode(getNativeObject())];
}
/**
* Overrides the default color-buffer write state that was set on the material.
*
* @see
* <a href="https://google.github.io/filament/Materials.html#materialdefinitions/materialblock/rasterization:colorWrite">
* Rasterization: colorWrite</a>
*/
public void setColorWrite(boolean enable) {
nSetColorWrite(getNativeObject(), enable);
}
/**
* Returns whether color write is enabled.
*/
public boolean isColorWriteEnabled() {
return nIsColorWriteEnabled(getNativeObject());
}
/**
* Overrides the default depth-buffer write state that was set on the material.
*
* @see
* <a href="https://google.github.io/filament/Materials.html#materialdefinitions/materialblock/rasterization:depthWrite">
* Rasterization: depthWrite</a>
*/
public void setDepthWrite(boolean enable) {
nSetDepthWrite(getNativeObject(), enable);
}
/**
* Returns whether depth write is enabled.
*/
public boolean isDepthWriteEnabled() {
return nIsDepthWriteEnabled(getNativeObject());
}
/**
* Enables or Disable stencil writes
*/
public void setStencilWrite(boolean enable) {
nSetStencilWrite(getNativeObject(), enable);
}
/**
* Returns whether stencil write is enabled.
*/
public boolean isStencilWriteEnabled() {
return nIsStencilWriteEnabled(getNativeObject());
}
/**
* Overrides the default depth testing state that was set on the material.
*
* @see
* <a href="https://google.github.io/filament/Materials.html#materialdefinitions/materialblock/rasterization:depthCulling">
* Rasterization: depthCulling</a>
*/
public void setDepthCulling(boolean enable) {
nSetDepthCulling(getNativeObject(), enable);
}
/**
* Sets the depth comparison function (default is {@link TextureSampler.CompareFunction#GE}).
*
* @param func the depth comparison function
*/
public void setDepthFunc(TextureSampler.CompareFunction func) {
nSetDepthFunc(getNativeObject(), func.ordinal());
}
/**
* Returns whether depth culling is enabled.
*/
public boolean isDepthCullingEnabled() {
return nIsDepthCullingEnabled(getNativeObject());
}
/**
* Returns the depth comparison function.
*/
public TextureSampler.CompareFunction getDepthFunc() {
return TextureSampler.EnumCache.sCompareFunctionValues[nGetDepthFunc(getNativeObject())];
}
/**
* Sets the stencil comparison function (default is {@link TextureSampler.CompareFunction#ALWAYS}).
*
* <p>
* It's possible to set separate stencil comparison functions; one for front-facing polygons,
* and one for back-facing polygons. The face parameter determines the comparison function(s)
* updated by this call.
* </p>
*
* @param func the stencil comparison function
* @param face the faces to update the comparison function for
*/
public void setStencilCompareFunction(TextureSampler.CompareFunction func, StencilFace face) {
nSetStencilCompareFunction(getNativeObject(), func.ordinal(),
sStencilFaceMapping[face.ordinal()]);
}
/**
* Sets the stencil comparison function for both front and back-facing polygons.
* @see #setStencilCompareFunction(TextureSampler.CompareFunction, StencilFace)
*/
public void setStencilCompareFunction(TextureSampler.CompareFunction func) {
setStencilCompareFunction(func, StencilFace.FRONT_AND_BACK);
}
/**
* Sets the stencil fail operation (default is {@link StencilOperation#KEEP}).
*
* <p>
* The stencil fail operation is performed to update values in the stencil buffer when the
* stencil test fails.
* </p>
*
* <p>
* It's possible to set separate stencil fail operations; one for front-facing polygons, and one
* for back-facing polygons. The face parameter determines the stencil fail operation(s) updated
* by this call.
* </p>
*
* @param op the stencil fail operation
* @param face the faces to update the stencil fail operation for
*/
public void setStencilOpStencilFail(StencilOperation op, StencilFace face) {
nSetStencilOpStencilFail(getNativeObject(), op.ordinal(),
sStencilFaceMapping[face.ordinal()]);
}
/**
* Sets the stencil fail operation for both front and back-facing polygons.
* @see #setStencilOpStencilFail(StencilOperation, StencilFace)
*/
public void setStencilOpStencilFail(StencilOperation op) {
setStencilOpStencilFail(op, StencilFace.FRONT_AND_BACK);
}
/**
* Sets the depth fail operation (default is {@link StencilOperation#KEEP}).
*
* <p>
* The depth fail operation is performed to update values in the stencil buffer when the depth
* test fails.
* </p>
*
* <p>
* It's possible to set separate depth fail operations; one for front-facing polygons, and one
* for back-facing polygons. The face parameter determines the depth fail operation(s) updated
* by this call.
* </p>
*
* @param op the depth fail operation
* @param face the faces to update the depth fail operation for
*/
public void setStencilOpDepthFail(StencilOperation op, StencilFace face) {
nSetStencilOpDepthFail(getNativeObject(), op.ordinal(),
sStencilFaceMapping[face.ordinal()]);
}
/**
* Sets the depth fail operation for both front and back-facing polygons.
* @see #setStencilOpDepthFail(StencilOperation, StencilFace)
*/
public void setStencilOpDepthFail(StencilOperation op) {
setStencilOpDepthFail(op, StencilFace.FRONT_AND_BACK);
}
/**
* Sets the depth-stencil pass operation (default is {@link StencilOperation#KEEP}).
*
* <p>
* The depth-stencil pass operation is performed to update values in the stencil buffer when
* both the stencil test and depth test pass.
* </p>
*
* <p>
* It's possible to set separate depth-stencil pass operations; one for front-facing polygons,
* and one for back-facing polygons. The face parameter determines the depth-stencil pass
* operation(s) updated by this call.
* </p>
*
* @param op the depth-stencil pass operation
* @param face the faces to update the depth-stencil operation for
*/
public void setStencilOpDepthStencilPass(StencilOperation op, StencilFace face) {
nSetStencilOpDepthStencilPass(getNativeObject(), op.ordinal(),
sStencilFaceMapping[face.ordinal()]);
}
/**
* Sets the depth-stencil pass operation for both front and back-facing polygons.
* @see #setStencilOpDepthStencilPass(StencilOperation, StencilFace)
*/
public void setStencilOpDepthStencilPass(StencilOperation op) {
setStencilOpDepthStencilPass(op, StencilFace.FRONT_AND_BACK);
}
/**
* Sets the stencil reference value (default is 0).
*
* <p>
* The stencil reference value is the left-hand side for stencil comparison tests. It's also
* used as the replacement stencil value when {@link StencilOperation} is
* {@link StencilOperation#REPLACE}.
* </p>
*
* <p>
* It's possible to set separate stencil reference values; one for front-facing polygons, and
* one for back-facing polygons. The face parameter determines the reference value(s) updated by
* this call.
* </p>
*
* @param value the stencil reference value (only the least significant 8 bits are used)
* @param face the faces to update the reference value for
*/
public void setStencilReferenceValue(@IntRange(from = 0, to = 255) int value, StencilFace face) {
nSetStencilReferenceValue(getNativeObject(), value, sStencilFaceMapping[face.ordinal()]);
}
/**
* Sets the stencil reference value for both front and back-facing polygons.
* @see #setStencilReferenceValue(int, StencilFace)
*/
public void setStencilReferenceValue(@IntRange(from = 0, to = 255) int value) {
setStencilReferenceValue(value, StencilFace.FRONT_AND_BACK);
}
/**
* Sets the stencil read mask (default is 0xFF).
*
* <p>
* The stencil read mask masks the bits of the values participating in the stencil comparison
* test- both the value read from the stencil buffer and the reference value.
* </p>
*
* <p>
* It's possible to set separate stencil read masks; one for front-facing polygons, and one for
* back-facing polygons. The face parameter determines the stencil read mask(s) updated by this
* call.
* </p>
*
* @param readMask the read mask (only the least significant 8 bits are used)
* @param face the faces to update the read mask for
*/
public void setStencilReadMask(@IntRange(from = 0, to = 255) int readMask, StencilFace face) {
nSetStencilReadMask(getNativeObject(), readMask, sStencilFaceMapping[face.ordinal()]);
}
/**
* Sets the stencil read mask for both front and back-facing polygons.
* @see #setStencilReadMask(int, StencilFace)
*/
public void setStencilReadMask(@IntRange(from = 0, to = 255) int readMask) {
setStencilReadMask(readMask, StencilFace.FRONT_AND_BACK);
}
/**
* Sets the stencil write mask (default is 0xFF).
*
* <p>
* The stencil write mask masks the bits in the stencil buffer updated by stencil operations.
* </p>
*
* <p>
* It's possible to set separate stencil write masks; one for front-facing polygons, and one for
* back-facing polygons. The face parameter determines the stencil write mask(s) updated by this
* call.
* </p>
*
* @param writeMask the write mask (only the least significant 8 bits are used)
* @param face the faces to update the read mask for
*/
public void setStencilWriteMask(@IntRange(from = 0, to = 255) int writeMask, StencilFace face) {
nSetStencilWriteMask(getNativeObject(), writeMask, sStencilFaceMapping[face.ordinal()]);
}
/**
* Sets the stencil write mask for both front and back-facing polygons.
* @see #setStencilWriteMask(int, StencilFace)
*/
public void setStencilWriteMask(int writeMask) {
setStencilWriteMask(writeMask, StencilFace.FRONT_AND_BACK);
}
public long getNativeObject() {
if (mNativeObject == 0) {
throw new IllegalStateException("Calling method on destroyed MaterialInstance");
}
return mNativeObject;
}
void clearNativeObject() {
mNativeObject = 0;
}
private static native void nSetParameterBool(long nativeMaterialInstance,
@NonNull String name, boolean x);
private static native void nSetParameterFloat(long nativeMaterialInstance,
@NonNull String name, float x);
private static native void nSetParameterInt(long nativeMaterialInstance,
@NonNull String name, int x);
private static native void nSetParameterBool2(long nativeMaterialInstance,
@NonNull String name, boolean x, boolean y);
private static native void nSetParameterFloat2(long nativeMaterialInstance,
@NonNull String name, float x, float y);
private static native void nSetParameterInt2(long nativeMaterialInstance,
@NonNull String name, int x, int y);
private static native void nSetParameterBool3(long nativeMaterialInstance,
@NonNull String name, boolean x, boolean y, boolean z);
private static native void nSetParameterFloat3(long nativeMaterialInstance,
@NonNull String name, float x, float y, float z);
private static native void nSetParameterInt3(long nativeMaterialInstance,
@NonNull String name, int x, int y, int z);
private static native void nSetParameterBool4(long nativeMaterialInstance,
@NonNull String name, boolean x, boolean y, boolean z, boolean w);
private static native void nSetParameterFloat4(long nativeMaterialInstance,
@NonNull String name, float x, float y, float z, float w);
private static native void nSetParameterInt4(long nativeMaterialInstance,
@NonNull String name, int x, int y, int z, int w);
private static native void nSetBooleanParameterArray(long nativeMaterialInstance,
@NonNull String name, int element, @NonNull @Size(min = 1) boolean[] v,
@IntRange(from = 0) int offset, @IntRange(from = 1) int count);
private static native void nSetIntParameterArray(long nativeMaterialInstance,
@NonNull String name, int element, @NonNull @Size(min = 1) int[] v,
@IntRange(from = 0) int offset, @IntRange(from = 1) int count);
private static native void nSetFloatParameterArray(long nativeMaterialInstance,
@NonNull String name, int element, @NonNull @Size(min = 1) float[] v,
@IntRange(from = 0) int offset, @IntRange(from = 1) int count);
private static native void nSetParameterTexture(long nativeMaterialInstance,
@NonNull String name, long nativeTexture, long sampler);
private static native void nSetScissor(long nativeMaterialInstance,
@IntRange(from = 0) int left, @IntRange(from = 0) int bottom,
@IntRange(from = 0) int width, @IntRange(from = 0) int height);
private static native void nUnsetScissor(long nativeMaterialInstance);
private static native void nSetPolygonOffset(long nativeMaterialInstance,
float scale, float constant);
private static native void nSetMaskThreshold(long nativeMaterialInstance, float threshold);
private static native void nSetSpecularAntiAliasingVariance(long nativeMaterialInstance,
float variance);
private static native void nSetSpecularAntiAliasingThreshold(long nativeMaterialInstance,
float threshold);
private static native void nSetDoubleSided(long nativeMaterialInstance, boolean doubleSided);
private static native void nSetCullingMode(long nativeMaterialInstance, long mode);
private static native void nSetCullingModeSeparate(long nativeMaterialInstance,
long colorPassCullingMode, long shadowPassCullingMode);
private static native void nSetColorWrite(long nativeMaterialInstance, boolean enable);
private static native void nSetDepthWrite(long nativeMaterialInstance, boolean enable);
private static native void nSetStencilWrite(long nativeMaterialInstance, boolean enable);
private static native void nSetDepthCulling(long nativeMaterialInstance, boolean enable);
private static native void nSetDepthFunc(long nativeMaterialInstance, long function);
private static native void nSetStencilCompareFunction(long nativeMaterialInstance,
long function, long face);
private static native void nSetStencilOpStencilFail(long nativeMaterialInstance, long op,
long face);
private static native void nSetStencilOpDepthFail(long nativeMaterialInstance, long op,
long face);
private static native void nSetStencilOpDepthStencilPass(long nativeMaterialInstance, long op,
long face);
private static native void nSetStencilReferenceValue(long nativeMaterialInstance, int value,
long face);
private static native void nSetStencilReadMask(long nativeMaterialInstance, int readMask,
long face);
private static native void nSetStencilWriteMask(long nativeMaterialInstance, int writeMask,
long face);
private static native String nGetName(long nativeMaterialInstance);
private static native long nGetMaterial(long nativeMaterialInstance);
private static native long nDuplicate(long otherNativeMaterialInstance, String name);
private static native float nGetMaskThreshold(long nativeMaterialInstance);
private static native float nGetSpecularAntiAliasingVariance(long nativeMaterialInstance);
private static native float nGetSpecularAntiAliasingThreshold(long nativeMaterialInstance);
private static native boolean nIsDoubleSided(long nativeMaterialInstance);
private static native int nGetCullingMode(long nativeMaterialInstance);
private static native int nGetShadowCullingMode(long nativeMaterialInstance);
private static native boolean nIsColorWriteEnabled(long nativeMaterialInstance);
private static native boolean nIsDepthWriteEnabled(long nativeMaterialInstance);
private static native boolean nIsStencilWriteEnabled(long nativeMaterialInstance);
private static native boolean nIsDepthCullingEnabled(long nativeMaterialInstance);
private static native int nGetDepthFunc(long nativeMaterialInstance);
}
|
googleapis/google-cloud-java
| 38,195
|
java-notebooks/proto-google-cloud-notebooks-v1/src/main/java/com/google/cloud/notebooks/v1/ReportInstanceInfoRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/notebooks/v1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.notebooks.v1;
/**
*
*
* <pre>
* Request for notebook instances to report information to Notebooks API.
* </pre>
*
* Protobuf type {@code google.cloud.notebooks.v1.ReportInstanceInfoRequest}
*/
public final class ReportInstanceInfoRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.notebooks.v1.ReportInstanceInfoRequest)
ReportInstanceInfoRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ReportInstanceInfoRequest.newBuilder() to construct.
private ReportInstanceInfoRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ReportInstanceInfoRequest() {
name_ = "";
vmId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ReportInstanceInfoRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_ReportInstanceInfoRequest_descriptor;
}
@SuppressWarnings({"rawtypes"})
@java.lang.Override
protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection(
int number) {
switch (number) {
case 3:
return internalGetMetadata();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_ReportInstanceInfoRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.notebooks.v1.ReportInstanceInfoRequest.class,
com.google.cloud.notebooks.v1.ReportInstanceInfoRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. Format:
* `projects/{project_id}/locations/{location}/instances/{instance_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. Format:
* `projects/{project_id}/locations/{location}/instances/{instance_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VM_ID_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object vmId_ = "";
/**
*
*
* <pre>
* Required. The VM hardware token for authenticating the VM.
* https://cloud.google.com/compute/docs/instances/verifying-instance-identity
* </pre>
*
* <code>string vm_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The vmId.
*/
@java.lang.Override
public java.lang.String getVmId() {
java.lang.Object ref = vmId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
vmId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The VM hardware token for authenticating the VM.
* https://cloud.google.com/compute/docs/instances/verifying-instance-identity
* </pre>
*
* <code>string vm_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for vmId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getVmIdBytes() {
java.lang.Object ref = vmId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
vmId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int METADATA_FIELD_NUMBER = 3;
private static final class MetadataDefaultEntryHolder {
static final com.google.protobuf.MapEntry<java.lang.String, java.lang.String> defaultEntry =
com.google.protobuf.MapEntry.<java.lang.String, java.lang.String>newDefaultInstance(
com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_ReportInstanceInfoRequest_MetadataEntry_descriptor,
com.google.protobuf.WireFormat.FieldType.STRING,
"",
com.google.protobuf.WireFormat.FieldType.STRING,
"");
}
@SuppressWarnings("serial")
private com.google.protobuf.MapField<java.lang.String, java.lang.String> metadata_;
private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetMetadata() {
if (metadata_ == null) {
return com.google.protobuf.MapField.emptyMapField(MetadataDefaultEntryHolder.defaultEntry);
}
return metadata_;
}
public int getMetadataCount() {
return internalGetMetadata().getMap().size();
}
/**
*
*
* <pre>
* The metadata reported to Notebooks API. This will be merged to the instance
* metadata store
* </pre>
*
* <code>map<string, string> metadata = 3;</code>
*/
@java.lang.Override
public boolean containsMetadata(java.lang.String key) {
if (key == null) {
throw new NullPointerException("map key");
}
return internalGetMetadata().getMap().containsKey(key);
}
/** Use {@link #getMetadataMap()} instead. */
@java.lang.Override
@java.lang.Deprecated
public java.util.Map<java.lang.String, java.lang.String> getMetadata() {
return getMetadataMap();
}
/**
*
*
* <pre>
* The metadata reported to Notebooks API. This will be merged to the instance
* metadata store
* </pre>
*
* <code>map<string, string> metadata = 3;</code>
*/
@java.lang.Override
public java.util.Map<java.lang.String, java.lang.String> getMetadataMap() {
return internalGetMetadata().getMap();
}
/**
*
*
* <pre>
* The metadata reported to Notebooks API. This will be merged to the instance
* metadata store
* </pre>
*
* <code>map<string, string> metadata = 3;</code>
*/
@java.lang.Override
public /* nullable */ java.lang.String getMetadataOrDefault(
java.lang.String key,
/* nullable */
java.lang.String defaultValue) {
if (key == null) {
throw new NullPointerException("map key");
}
java.util.Map<java.lang.String, java.lang.String> map = internalGetMetadata().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
*
*
* <pre>
* The metadata reported to Notebooks API. This will be merged to the instance
* metadata store
* </pre>
*
* <code>map<string, string> metadata = 3;</code>
*/
@java.lang.Override
public java.lang.String getMetadataOrThrow(java.lang.String key) {
if (key == null) {
throw new NullPointerException("map key");
}
java.util.Map<java.lang.String, java.lang.String> map = internalGetMetadata().getMap();
if (!map.containsKey(key)) {
throw new java.lang.IllegalArgumentException();
}
return map.get(key);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(vmId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, vmId_);
}
com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(
output, internalGetMetadata(), MetadataDefaultEntryHolder.defaultEntry, 3);
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(vmId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, vmId_);
}
for (java.util.Map.Entry<java.lang.String, java.lang.String> entry :
internalGetMetadata().getMap().entrySet()) {
com.google.protobuf.MapEntry<java.lang.String, java.lang.String> metadata__ =
MetadataDefaultEntryHolder.defaultEntry
.newBuilderForType()
.setKey(entry.getKey())
.setValue(entry.getValue())
.build();
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, metadata__);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.notebooks.v1.ReportInstanceInfoRequest)) {
return super.equals(obj);
}
com.google.cloud.notebooks.v1.ReportInstanceInfoRequest other =
(com.google.cloud.notebooks.v1.ReportInstanceInfoRequest) obj;
if (!getName().equals(other.getName())) return false;
if (!getVmId().equals(other.getVmId())) return false;
if (!internalGetMetadata().equals(other.internalGetMetadata())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (37 * hash) + VM_ID_FIELD_NUMBER;
hash = (53 * hash) + getVmId().hashCode();
if (!internalGetMetadata().getMap().isEmpty()) {
hash = (37 * hash) + METADATA_FIELD_NUMBER;
hash = (53 * hash) + internalGetMetadata().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.notebooks.v1.ReportInstanceInfoRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for notebook instances to report information to Notebooks API.
* </pre>
*
* Protobuf type {@code google.cloud.notebooks.v1.ReportInstanceInfoRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.notebooks.v1.ReportInstanceInfoRequest)
com.google.cloud.notebooks.v1.ReportInstanceInfoRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_ReportInstanceInfoRequest_descriptor;
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapFieldReflectionAccessor internalGetMapFieldReflection(
int number) {
switch (number) {
case 3:
return internalGetMetadata();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapFieldReflectionAccessor internalGetMutableMapFieldReflection(
int number) {
switch (number) {
case 3:
return internalGetMutableMetadata();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_ReportInstanceInfoRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.notebooks.v1.ReportInstanceInfoRequest.class,
com.google.cloud.notebooks.v1.ReportInstanceInfoRequest.Builder.class);
}
// Construct using com.google.cloud.notebooks.v1.ReportInstanceInfoRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
name_ = "";
vmId_ = "";
internalGetMutableMetadata().clear();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_ReportInstanceInfoRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.notebooks.v1.ReportInstanceInfoRequest getDefaultInstanceForType() {
return com.google.cloud.notebooks.v1.ReportInstanceInfoRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.notebooks.v1.ReportInstanceInfoRequest build() {
com.google.cloud.notebooks.v1.ReportInstanceInfoRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.notebooks.v1.ReportInstanceInfoRequest buildPartial() {
com.google.cloud.notebooks.v1.ReportInstanceInfoRequest result =
new com.google.cloud.notebooks.v1.ReportInstanceInfoRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.notebooks.v1.ReportInstanceInfoRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.name_ = name_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.vmId_ = vmId_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.metadata_ = internalGetMetadata();
result.metadata_.makeImmutable();
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.notebooks.v1.ReportInstanceInfoRequest) {
return mergeFrom((com.google.cloud.notebooks.v1.ReportInstanceInfoRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.notebooks.v1.ReportInstanceInfoRequest other) {
if (other == com.google.cloud.notebooks.v1.ReportInstanceInfoRequest.getDefaultInstance())
return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getVmId().isEmpty()) {
vmId_ = other.vmId_;
bitField0_ |= 0x00000002;
onChanged();
}
internalGetMutableMetadata().mergeFrom(other.internalGetMetadata());
bitField0_ |= 0x00000004;
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
name_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
vmId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
com.google.protobuf.MapEntry<java.lang.String, java.lang.String> metadata__ =
input.readMessage(
MetadataDefaultEntryHolder.defaultEntry.getParserForType(),
extensionRegistry);
internalGetMutableMetadata()
.getMutableMap()
.put(metadata__.getKey(), metadata__.getValue());
bitField0_ |= 0x00000004;
break;
} // case 26
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. Format:
* `projects/{project_id}/locations/{location}/instances/{instance_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. Format:
* `projects/{project_id}/locations/{location}/instances/{instance_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. Format:
* `projects/{project_id}/locations/{location}/instances/{instance_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Format:
* `projects/{project_id}/locations/{location}/instances/{instance_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Format:
* `projects/{project_id}/locations/{location}/instances/{instance_id}`
* </pre>
*
* <code>string name = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object vmId_ = "";
/**
*
*
* <pre>
* Required. The VM hardware token for authenticating the VM.
* https://cloud.google.com/compute/docs/instances/verifying-instance-identity
* </pre>
*
* <code>string vm_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The vmId.
*/
public java.lang.String getVmId() {
java.lang.Object ref = vmId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
vmId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The VM hardware token for authenticating the VM.
* https://cloud.google.com/compute/docs/instances/verifying-instance-identity
* </pre>
*
* <code>string vm_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for vmId.
*/
public com.google.protobuf.ByteString getVmIdBytes() {
java.lang.Object ref = vmId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
vmId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The VM hardware token for authenticating the VM.
* https://cloud.google.com/compute/docs/instances/verifying-instance-identity
* </pre>
*
* <code>string vm_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The vmId to set.
* @return This builder for chaining.
*/
public Builder setVmId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
vmId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The VM hardware token for authenticating the VM.
* https://cloud.google.com/compute/docs/instances/verifying-instance-identity
* </pre>
*
* <code>string vm_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearVmId() {
vmId_ = getDefaultInstance().getVmId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The VM hardware token for authenticating the VM.
* https://cloud.google.com/compute/docs/instances/verifying-instance-identity
* </pre>
*
* <code>string vm_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for vmId to set.
* @return This builder for chaining.
*/
public Builder setVmIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
vmId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.protobuf.MapField<java.lang.String, java.lang.String> metadata_;
private com.google.protobuf.MapField<java.lang.String, java.lang.String> internalGetMetadata() {
if (metadata_ == null) {
return com.google.protobuf.MapField.emptyMapField(MetadataDefaultEntryHolder.defaultEntry);
}
return metadata_;
}
private com.google.protobuf.MapField<java.lang.String, java.lang.String>
internalGetMutableMetadata() {
if (metadata_ == null) {
metadata_ =
com.google.protobuf.MapField.newMapField(MetadataDefaultEntryHolder.defaultEntry);
}
if (!metadata_.isMutable()) {
metadata_ = metadata_.copy();
}
bitField0_ |= 0x00000004;
onChanged();
return metadata_;
}
public int getMetadataCount() {
return internalGetMetadata().getMap().size();
}
/**
*
*
* <pre>
* The metadata reported to Notebooks API. This will be merged to the instance
* metadata store
* </pre>
*
* <code>map<string, string> metadata = 3;</code>
*/
@java.lang.Override
public boolean containsMetadata(java.lang.String key) {
if (key == null) {
throw new NullPointerException("map key");
}
return internalGetMetadata().getMap().containsKey(key);
}
/** Use {@link #getMetadataMap()} instead. */
@java.lang.Override
@java.lang.Deprecated
public java.util.Map<java.lang.String, java.lang.String> getMetadata() {
return getMetadataMap();
}
/**
*
*
* <pre>
* The metadata reported to Notebooks API. This will be merged to the instance
* metadata store
* </pre>
*
* <code>map<string, string> metadata = 3;</code>
*/
@java.lang.Override
public java.util.Map<java.lang.String, java.lang.String> getMetadataMap() {
return internalGetMetadata().getMap();
}
/**
*
*
* <pre>
* The metadata reported to Notebooks API. This will be merged to the instance
* metadata store
* </pre>
*
* <code>map<string, string> metadata = 3;</code>
*/
@java.lang.Override
public /* nullable */ java.lang.String getMetadataOrDefault(
java.lang.String key,
/* nullable */
java.lang.String defaultValue) {
if (key == null) {
throw new NullPointerException("map key");
}
java.util.Map<java.lang.String, java.lang.String> map = internalGetMetadata().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
*
*
* <pre>
* The metadata reported to Notebooks API. This will be merged to the instance
* metadata store
* </pre>
*
* <code>map<string, string> metadata = 3;</code>
*/
@java.lang.Override
public java.lang.String getMetadataOrThrow(java.lang.String key) {
if (key == null) {
throw new NullPointerException("map key");
}
java.util.Map<java.lang.String, java.lang.String> map = internalGetMetadata().getMap();
if (!map.containsKey(key)) {
throw new java.lang.IllegalArgumentException();
}
return map.get(key);
}
public Builder clearMetadata() {
bitField0_ = (bitField0_ & ~0x00000004);
internalGetMutableMetadata().getMutableMap().clear();
return this;
}
/**
*
*
* <pre>
* The metadata reported to Notebooks API. This will be merged to the instance
* metadata store
* </pre>
*
* <code>map<string, string> metadata = 3;</code>
*/
public Builder removeMetadata(java.lang.String key) {
if (key == null) {
throw new NullPointerException("map key");
}
internalGetMutableMetadata().getMutableMap().remove(key);
return this;
}
/** Use alternate mutation accessors instead. */
@java.lang.Deprecated
public java.util.Map<java.lang.String, java.lang.String> getMutableMetadata() {
bitField0_ |= 0x00000004;
return internalGetMutableMetadata().getMutableMap();
}
/**
*
*
* <pre>
* The metadata reported to Notebooks API. This will be merged to the instance
* metadata store
* </pre>
*
* <code>map<string, string> metadata = 3;</code>
*/
public Builder putMetadata(java.lang.String key, java.lang.String value) {
if (key == null) {
throw new NullPointerException("map key");
}
if (value == null) {
throw new NullPointerException("map value");
}
internalGetMutableMetadata().getMutableMap().put(key, value);
bitField0_ |= 0x00000004;
return this;
}
/**
*
*
* <pre>
* The metadata reported to Notebooks API. This will be merged to the instance
* metadata store
* </pre>
*
* <code>map<string, string> metadata = 3;</code>
*/
public Builder putAllMetadata(java.util.Map<java.lang.String, java.lang.String> values) {
internalGetMutableMetadata().getMutableMap().putAll(values);
bitField0_ |= 0x00000004;
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.notebooks.v1.ReportInstanceInfoRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.notebooks.v1.ReportInstanceInfoRequest)
private static final com.google.cloud.notebooks.v1.ReportInstanceInfoRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.notebooks.v1.ReportInstanceInfoRequest();
}
public static com.google.cloud.notebooks.v1.ReportInstanceInfoRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ReportInstanceInfoRequest> PARSER =
new com.google.protobuf.AbstractParser<ReportInstanceInfoRequest>() {
@java.lang.Override
public ReportInstanceInfoRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ReportInstanceInfoRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ReportInstanceInfoRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.notebooks.v1.ReportInstanceInfoRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/hive
| 38,222
|
itests/hive-unit/src/test/java/org/apache/hive/jdbc/TestActivePassiveHA.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hive.jdbc;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import org.apache.curator.test.TestingServer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.registry.impl.ZkRegistryBase;
import org.apache.hive.http.security.PamAuthenticator;
import org.apache.hive.jdbc.miniHS2.MiniHS2;
import org.apache.hive.service.server.HS2ActivePassiveHARegistry;
import org.apache.hive.service.server.HS2ActivePassiveHARegistryClient;
import org.apache.hive.service.server.HiveServer2Instance;
import org.apache.hive.service.server.TestHS2HttpServerPam;
import org.apache.hive.service.servlet.HS2Peers;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.util.B64Code;
import org.eclipse.jetty.util.StringUtil;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
public class TestActivePassiveHA {
private MiniHS2 miniHS2_1 = null;
private MiniHS2 miniHS2_2 = null;
private static TestingServer zkServer;
private Connection hs2Conn = null;
private static String ADMIN_USER = "user1"; // user from TestPamAuthenticator
private static String ADMIN_PASSWORD = "1";
private static String serviceDiscoveryMode = "zooKeeperHA";
private static String zkHANamespace = "hs2ActivePassiveHATest";
private HiveConf hiveConf1;
private HiveConf hiveConf2;
private static Path kvDataFilePath;
@BeforeClass
public static void beforeTest() throws Exception {
MiniHS2.cleanupLocalDir();
zkServer = new TestingServer();
Class.forName(MiniHS2.getJdbcDriverName());
}
@AfterClass
public static void afterTest() throws Exception {
if (zkServer != null) {
zkServer.close();
zkServer = null;
}
MiniHS2.cleanupLocalDir();
}
@Before
public void setUp() throws Exception {
hiveConf1 = new HiveConf();
hiveConf1.setBoolVar(ConfVars.HIVE_SUPPORT_CONCURRENCY, false);
// Set up zookeeper dynamic service discovery configs
setHAConfigs(hiveConf1);
miniHS2_1 = new MiniHS2.Builder().withConf(hiveConf1).cleanupLocalDirOnStartup(false).build();
hiveConf2 = new HiveConf();
hiveConf2.setBoolVar(ConfVars.HIVE_SUPPORT_CONCURRENCY, false);
// Set up zookeeper dynamic service discovery configs
setHAConfigs(hiveConf2);
miniHS2_2 = new MiniHS2.Builder().withConf(hiveConf2).cleanupLocalDirOnStartup(false).build();
final String dataFileDir = hiveConf1.get("test.data.files").replace('\\', '/').replace("c:", "");
kvDataFilePath = new Path(dataFileDir, "kv1.txt");
}
@After
public void tearDown() throws Exception {
if (hs2Conn != null) {
hs2Conn.close();
}
if ((miniHS2_1 != null) && miniHS2_1.isStarted()) {
miniHS2_1.stop();
}
if ((miniHS2_2 != null) && miniHS2_2.isStarted()) {
miniHS2_2.stop();
}
}
private static void setHAConfigs(Configuration conf) {
conf.setBoolean(ConfVars.HIVE_SERVER2_SUPPORT_DYNAMIC_SERVICE_DISCOVERY.varname, true);
conf.set(ConfVars.HIVE_ZOOKEEPER_QUORUM.varname, zkServer.getConnectString());
conf.setBoolean(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_ENABLE.varname, true);
conf.set(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_REGISTRY_NAMESPACE.varname, zkHANamespace);
conf.setTimeDuration(ConfVars.HIVE_ZOOKEEPER_CONNECTION_TIMEOUT.varname, 2, TimeUnit.SECONDS);
conf.setTimeDuration(ConfVars.HIVE_ZOOKEEPER_CONNECTION_BASESLEEPTIME.varname, 100, TimeUnit.MILLISECONDS);
conf.setInt(ConfVars.HIVE_ZOOKEEPER_CONNECTION_MAX_RETRIES.varname, 1);
}
@Test(timeout = 60000)
public void testHealthCheck() throws Exception {
String instanceId1 = UUID.randomUUID().toString();
miniHS2_1.start(getConfOverlay(instanceId1));
String leaderURL = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
String healthCheckURL = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
String leaderURLHealthCheckPort = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/leader";
String healthCheckURLWebUIPort = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/ha-healthcheck/health-ha";
assertEquals(true, miniHS2_1.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_1.isLeader());
assertEquals("true", sendGet(leaderURL));
assertEquals("true", sendGet(healthCheckURL));
assertEquals("Not Found", sendGet(leaderURLHealthCheckPort));
assertEquals("Not Found", sendGet(healthCheckURLWebUIPort));
}
@Test(timeout = 60000)
public void testHealthCheckAuth() throws Exception {
hiveConf1.setBoolVar(ConfVars.HIVE_SERVER2_WEBUI_ENABLE_CORS, true);
setPamConfs(hiveConf1);
PamAuthenticator pamAuthenticator = new TestHS2HttpServerPam.TestPamAuthenticator(hiveConf1);
String instanceId1 = UUID.randomUUID().toString();
miniHS2_1.setPamAuthenticator(pamAuthenticator);
miniHS2_1.start(getSecureConfOverlay(instanceId1));
String leaderURL = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
String healthCheckURL = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
String leaderURLHealthCheckPort = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/leader";
String healthCheckURLWebUIPort = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/ha-healthcheck/health-ha";
assertEquals(true, miniHS2_1.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_1.isLeader());
assertEquals("true", sendGet(leaderURL, true, true));
assertEquals("true", sendGet(healthCheckURL, true, true));
try {
sendGet(leaderURLHealthCheckPort, true, true);
} catch (AssertionError e) {
assertTrue(e.getMessage().contains("Not Found"));
} catch (Exception e) {
fail("Expected AssertionError");
}
assertEquals("Not Found", sendGet(healthCheckURLWebUIPort, true, true));
assertEquals("Method Not Allowed", sendDelete(healthCheckURL, true, true));
assertEquals("Method Not Allowed", sendDelete(healthCheckURLWebUIPort, true, true));
try {
sendDelete(leaderURLHealthCheckPort, true, true);
} catch (AssertionError e) {
assertTrue(e.getMessage().contains("Not Found"));
} catch (Exception e) {
fail("Expected AssertionError");
}
String resp = sendDelete(leaderURL, true, true);
assertTrue(resp.contains("Failover successful!"));
}
@Test(timeout = 60000)
public void testActivePassiveHA() throws Exception {
String instanceId1 = UUID.randomUUID().toString();
miniHS2_1.start(getConfOverlay(instanceId1));
String instanceId2 = UUID.randomUUID().toString();
miniHS2_2.start(getConfOverlay(instanceId2));
assertEquals(true, miniHS2_1.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_1.isLeader());
String url = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
assertEquals("true", sendGet(url));
String healthCheckURL = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
assertEquals("true", sendGet(healthCheckURL));
assertEquals(false, miniHS2_2.isLeader());
url = "http://localhost:" +
hiveConf2.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
assertEquals("false", sendGet(url));
healthCheckURL = "http://localhost:" +
hiveConf2.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
assertEquals("false", sendGet(healthCheckURL));
url = "http://localhost:" + hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/peers";
String resp = sendGet(url);
ObjectMapper objectMapper = new ObjectMapper();
HS2Peers.HS2Instances hs2Peers = objectMapper.readValue(resp, HS2Peers.HS2Instances.class);
int port1 = Integer.parseInt(hiveConf1.get(ConfVars.HIVE_SERVER2_THRIFT_PORT.varname));
assertEquals(2, hs2Peers.getHiveServer2Instances().size());
for (HiveServer2Instance hsi : hs2Peers.getHiveServer2Instances()) {
if (hsi.getRpcPort() == port1 && hsi.getWorkerIdentity().equals(instanceId1)) {
assertEquals(true, hsi.isLeader());
} else {
assertEquals(false, hsi.isLeader());
}
}
Configuration conf = new Configuration();
setHAConfigs(conf);
HS2ActivePassiveHARegistry client = HS2ActivePassiveHARegistryClient.getClient(conf);
List<HiveServer2Instance> hs2Instances = new ArrayList<>(client.getAll());
assertEquals(2, hs2Instances.size());
List<HiveServer2Instance> leaders = new ArrayList<>();
List<HiveServer2Instance> standby = new ArrayList<>();
for (HiveServer2Instance instance : hs2Instances) {
if (instance.isLeader()) {
leaders.add(instance);
} else {
standby.add(instance);
}
}
assertEquals(1, leaders.size());
assertEquals(1, standby.size());
miniHS2_1.stop();
assertEquals(true, miniHS2_2.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_2.isLeader());
url = "http://localhost:" +
hiveConf2.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
assertEquals("true", sendGet(url));
healthCheckURL = "http://localhost:" +
hiveConf2.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
assertEquals("true", sendGet(healthCheckURL));
while (client.getAll().size() != 1) {
Thread.sleep(100);
}
client = HS2ActivePassiveHARegistryClient.getClient(conf);
hs2Instances = new ArrayList<>(client.getAll());
assertEquals(1, hs2Instances.size());
leaders = new ArrayList<>();
standby = new ArrayList<>();
for (HiveServer2Instance instance : hs2Instances) {
if (instance.isLeader()) {
leaders.add(instance);
} else {
standby.add(instance);
}
}
assertEquals(1, leaders.size());
assertEquals(0, standby.size());
url = "http://localhost:" + hiveConf2.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/peers";
resp = sendGet(url);
objectMapper = new ObjectMapper();
hs2Peers = objectMapper.readValue(resp, HS2Peers.HS2Instances.class);
int port2 = Integer.parseInt(hiveConf2.get(ConfVars.HIVE_SERVER2_THRIFT_PORT.varname));
assertEquals(1, hs2Peers.getHiveServer2Instances().size());
for (HiveServer2Instance hsi : hs2Peers.getHiveServer2Instances()) {
if (hsi.getRpcPort() == port2 && hsi.getWorkerIdentity().equals(instanceId2)) {
assertEquals(true, hsi.isLeader());
} else {
assertEquals(false, hsi.isLeader());
}
}
// start 1st server again
instanceId1 = UUID.randomUUID().toString();
miniHS2_1.start(getConfOverlay(instanceId1));
assertEquals(false, miniHS2_1.isLeader());
url = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
assertEquals("false", sendGet(url));
healthCheckURL = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
assertEquals("false", sendGet(healthCheckURL));
while (client.getAll().size() != 2) {
Thread.sleep(100);
}
client = HS2ActivePassiveHARegistryClient.getClient(conf);
hs2Instances = new ArrayList<>(client.getAll());
assertEquals(2, hs2Instances.size());
leaders = new ArrayList<>();
standby = new ArrayList<>();
for (HiveServer2Instance instance : hs2Instances) {
if (instance.isLeader()) {
leaders.add(instance);
} else {
standby.add(instance);
}
}
assertEquals(1, leaders.size());
assertEquals(1, standby.size());
url = "http://localhost:" + hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/peers";
resp = sendGet(url);
objectMapper = new ObjectMapper();
hs2Peers = objectMapper.readValue(resp, HS2Peers.HS2Instances.class);
port2 = Integer.parseInt(hiveConf2.get(ConfVars.HIVE_SERVER2_THRIFT_PORT.varname));
assertEquals(2, hs2Peers.getHiveServer2Instances().size());
for (HiveServer2Instance hsi : hs2Peers.getHiveServer2Instances()) {
if (hsi.getRpcPort() == port2 && hsi.getWorkerIdentity().equals(instanceId2)) {
assertEquals(true, hsi.isLeader());
} else {
assertEquals(false, hsi.isLeader());
}
}
}
@Test(timeout = 60000)
public void testConnectionActivePassiveHAServiceDiscovery() throws Exception {
String instanceId1 = UUID.randomUUID().toString();
miniHS2_1.start(getConfOverlay(instanceId1));
String instanceId2 = UUID.randomUUID().toString();
Map<String, String> confOverlay = getConfOverlay(instanceId2);
confOverlay.put(ConfVars.HIVE_SERVER2_TRANSPORT_MODE.varname, "http");
confOverlay.put(ConfVars.HIVE_SERVER2_THRIFT_HTTP_PATH.varname, "clidriverTest");
miniHS2_2.start(confOverlay);
assertEquals(true, miniHS2_1.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_1.isLeader());
String url = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
assertEquals("true", sendGet(url));
String healthCheckURL = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
assertEquals("true", sendGet(healthCheckURL));
assertEquals(false, miniHS2_2.isLeader());
url = "http://localhost:" +
hiveConf2.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
assertEquals("false", sendGet(url));
healthCheckURL = "http://localhost:" +
hiveConf2.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
assertEquals("false", sendGet(healthCheckURL));
// miniHS2_1 will be leader
String zkConnectString = zkServer.getConnectString();
String zkJdbcUrl = miniHS2_1.getJdbcURL();
// getAllUrls will parse zkJdbcUrl and will plugin the active HS2's host:port
String parsedUrl = HiveConnection.getAllUrls(zkJdbcUrl).get(0).getJdbcUriString();
String hs2_1_directUrl = "jdbc:hive2://" + miniHS2_1.getHost() + ":" + miniHS2_1.getBinaryPort() +
"/default;serviceDiscoveryMode=" + serviceDiscoveryMode + ";zooKeeperNamespace=" + zkHANamespace + ";";
assertTrue(zkJdbcUrl.contains(zkConnectString));
assertEquals(hs2_1_directUrl, parsedUrl);
openConnectionAndRunQuery(zkJdbcUrl);
// miniHS2_2 will become leader
miniHS2_1.stop();
assertEquals(true, miniHS2_2.getIsLeaderTestFuture().get());
parsedUrl = HiveConnection.getAllUrls(zkJdbcUrl).get(0).getJdbcUriString();
String hs2_2_directUrl = "jdbc:hive2://" + miniHS2_2.getHost() + ":" + miniHS2_2.getHttpPort() +
"/default;serviceDiscoveryMode=" + serviceDiscoveryMode + ";zooKeeperNamespace=" + zkHANamespace + ";";
assertTrue(zkJdbcUrl.contains(zkConnectString));
assertEquals(hs2_2_directUrl, parsedUrl);
openConnectionAndRunQuery(zkJdbcUrl);
// miniHS2_2 will continue to be leader
instanceId1 = UUID.randomUUID().toString();
miniHS2_1.start(getConfOverlay(instanceId1));
parsedUrl = HiveConnection.getAllUrls(zkJdbcUrl).get(0).getJdbcUriString();
assertTrue(zkJdbcUrl.contains(zkConnectString));
assertEquals(hs2_2_directUrl, parsedUrl);
openConnectionAndRunQuery(zkJdbcUrl);
// miniHS2_1 will become leader
miniHS2_2.stop();
assertEquals(true, miniHS2_1.getIsLeaderTestFuture().get());
parsedUrl = HiveConnection.getAllUrls(zkJdbcUrl).get(0).getJdbcUriString();
hs2_1_directUrl = "jdbc:hive2://" + miniHS2_1.getHost() + ":" + miniHS2_1.getBinaryPort() +
"/default;serviceDiscoveryMode=" + serviceDiscoveryMode + ";zooKeeperNamespace=" + zkHANamespace + ";";
assertTrue(zkJdbcUrl.contains(zkConnectString));
assertEquals(hs2_1_directUrl, parsedUrl);
openConnectionAndRunQuery(zkJdbcUrl);
}
@Test(timeout = 60000)
public void testManualFailover() throws Exception {
hiveConf1.setBoolVar(ConfVars.HIVE_SERVER2_WEBUI_ENABLE_CORS, true);
hiveConf2.setBoolVar(ConfVars.HIVE_SERVER2_WEBUI_ENABLE_CORS, true);
setPamConfs(hiveConf1);
setPamConfs(hiveConf2);
PamAuthenticator pamAuthenticator1 = new TestHS2HttpServerPam.TestPamAuthenticator(hiveConf1);
PamAuthenticator pamAuthenticator2 = new TestHS2HttpServerPam.TestPamAuthenticator(hiveConf2);
try {
String instanceId1 = UUID.randomUUID().toString();
miniHS2_1.setPamAuthenticator(pamAuthenticator1);
miniHS2_1.start(getSecureConfOverlay(instanceId1));
String instanceId2 = UUID.randomUUID().toString();
Map<String, String> confOverlay = getSecureConfOverlay(instanceId2);
confOverlay.put(ConfVars.HIVE_SERVER2_TRANSPORT_MODE.varname, "http");
confOverlay.put(ConfVars.HIVE_SERVER2_THRIFT_HTTP_PATH.varname, "clidriverTest");
miniHS2_2.setPamAuthenticator(pamAuthenticator2);
miniHS2_2.start(confOverlay);
String url1 = "http://localhost:" + hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
String url2 = "http://localhost:" + hiveConf2.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
String healthCheckURL1 = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
String healthCheckURL2 = "http://localhost:" +
hiveConf2.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
// when we start miniHS2_1 will be leader (sequential start)
assertEquals(true, miniHS2_1.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_1.isLeader());
assertEquals("true", sendGet(url1, true, true));
assertEquals("true", sendGet(healthCheckURL1, true, true));
// trigger failover on miniHS2_1
String resp = sendDelete(url1, true, true);
assertTrue(resp.contains("Failover successful!"));
// make sure miniHS2_1 is not leader
assertEquals(true, miniHS2_1.getNotLeaderTestFuture().get());
assertEquals(false, miniHS2_1.isLeader());
assertEquals("false", sendGet(url1, true, true));
assertEquals("false", sendGet(healthCheckURL1, true, true));
// make sure miniHS2_2 is the new leader
assertEquals(true, miniHS2_2.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_2.isLeader());
assertEquals("true", sendGet(url2, true, true));
assertEquals("true", sendGet(healthCheckURL2, true, true));
// send failover request again to miniHS2_1 and get a failure
resp = sendDelete(url1, true, true);
assertTrue(resp.contains("Cannot failover an instance that is not a leader"));
assertEquals(true, miniHS2_1.getNotLeaderTestFuture().get());
assertEquals(false, miniHS2_1.isLeader());
// send failover request to miniHS2_2 and make sure miniHS2_1 takes over (returning back to leader, test listeners)
resp = sendDelete(url2, true, true);
assertTrue(resp.contains("Failover successful!"));
assertEquals(true, miniHS2_1.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_1.isLeader());
assertEquals("true", sendGet(url1, true, true));
assertEquals("true", sendGet(healthCheckURL1, true, true));
assertEquals(true, miniHS2_2.getNotLeaderTestFuture().get());
assertEquals("false", sendGet(url2, true, true));
assertEquals("false", sendGet(healthCheckURL2, true, true));
assertEquals(false, miniHS2_2.isLeader());
} finally {
resetFailoverConfs();
}
}
@Test(timeout = 60000)
public void testManualFailoverUnauthorized() throws Exception {
setPamConfs(hiveConf1);
PamAuthenticator pamAuthenticator1 = new TestHS2HttpServerPam.TestPamAuthenticator(hiveConf1);
try {
String instanceId1 = UUID.randomUUID().toString();
miniHS2_1.setPamAuthenticator(pamAuthenticator1);
miniHS2_1.start(getSecureConfOverlay(instanceId1));
// dummy HS2 instance just to trigger failover
String instanceId2 = UUID.randomUUID().toString();
Map<String, String> confOverlay = getSecureConfOverlay(instanceId2);
confOverlay.put(ConfVars.HIVE_SERVER2_TRANSPORT_MODE.varname, "http");
confOverlay.put(ConfVars.HIVE_SERVER2_THRIFT_HTTP_PATH.varname, "clidriverTest");
miniHS2_2.start(confOverlay);
String url1 = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
String healthCheckURL1 = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
// when we start miniHS2_1 will be leader (sequential start)
assertEquals(true, miniHS2_1.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_1.isLeader());
assertEquals("true", sendGet(url1, true));
assertEquals("true", sendGet(healthCheckURL1, true));
// trigger failover on miniHS2_1 without authorization header
assertTrue(sendDelete(url1, false).contains("Unauthorized"));
assertTrue(sendDelete(url1, true).contains("Failover successful!"));
assertEquals(true, miniHS2_1.getNotLeaderTestFuture().get());
assertEquals(false, miniHS2_1.isLeader());
assertEquals(true, miniHS2_2.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_2.isLeader());
} finally {
// revert configs to not affect other tests
unsetPamConfs(hiveConf1);
}
}
@Test(timeout = 60000)
public void testNoConnectionOnPassive() throws Exception {
hiveConf1.setBoolVar(ConfVars.HIVE_SERVER2_WEBUI_ENABLE_CORS, true);
hiveConf2.setBoolVar(ConfVars.HIVE_SERVER2_WEBUI_ENABLE_CORS, true);
setPamConfs(hiveConf1);
setPamConfs(hiveConf2);
try {
PamAuthenticator pamAuthenticator1 = new TestHS2HttpServerPam.TestPamAuthenticator(hiveConf1);
PamAuthenticator pamAuthenticator2 = new TestHS2HttpServerPam.TestPamAuthenticator(hiveConf2);
String instanceId1 = UUID.randomUUID().toString();
miniHS2_1.setPamAuthenticator(pamAuthenticator1);
miniHS2_1.start(getSecureConfOverlay(instanceId1));
String instanceId2 = UUID.randomUUID().toString();
Map<String, String> confOverlay = getSecureConfOverlay(instanceId2);
miniHS2_2.setPamAuthenticator(pamAuthenticator2);
miniHS2_2.start(confOverlay);
String url1 = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
String healthCheckURL1 = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
assertEquals(true, miniHS2_1.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_1.isLeader());
// Don't get urls from ZK, it will actually be a service discovery URL that we don't want.
String hs1Url = "jdbc:hive2://" + miniHS2_1.getHost() + ":" + miniHS2_1.getBinaryPort();
Connection hs2Conn = getConnection(hs1Url, System.getProperty("user.name")); // Should work.
hs2Conn.close();
String resp = sendDelete(url1, true);
assertTrue(resp, resp.contains("Failover successful!"));
// wait for failover to close sessions
while (miniHS2_1.getOpenSessionsCount() != 0) {
Thread.sleep(100);
}
resp = sendDelete(healthCheckURL1, true);
assertTrue(resp, resp.contains("Method Not Allowed"));
assertEquals(true, miniHS2_2.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_2.isLeader());
try {
hs2Conn = getConnection(hs1Url, System.getProperty("user.name"));
fail("Should throw");
} catch (Exception e) {
if (!e.getMessage().contains("Cannot open sessions on an inactive HS2")) {
throw e;
}
}
} finally {
resetFailoverConfs();
}
}
private void resetFailoverConfs() {
// revert configs to not affect other tests
unsetPamConfs(hiveConf1);
unsetPamConfs(hiveConf2);
hiveConf1.unset(ConfVars.HIVE_SERVER2_WEBUI_ENABLE_CORS.varname);
hiveConf2.unset(ConfVars.HIVE_SERVER2_WEBUI_ENABLE_CORS.varname);
}
@Test(timeout = 60000)
public void testClientConnectionsOnFailover() throws Exception {
setPamConfs(hiveConf1);
setPamConfs(hiveConf2);
PamAuthenticator pamAuthenticator1 = new TestHS2HttpServerPam.TestPamAuthenticator(hiveConf1);
PamAuthenticator pamAuthenticator2 = new TestHS2HttpServerPam.TestPamAuthenticator(hiveConf2);
try {
String instanceId1 = UUID.randomUUID().toString();
miniHS2_1.setPamAuthenticator(pamAuthenticator1);
miniHS2_1.start(getSecureConfOverlay(instanceId1));
String instanceId2 = UUID.randomUUID().toString();
Map<String, String> confOverlay = getSecureConfOverlay(instanceId2);
confOverlay.put(ConfVars.HIVE_SERVER2_TRANSPORT_MODE.varname, "http");
confOverlay.put(ConfVars.HIVE_SERVER2_THRIFT_HTTP_PATH.varname, "clidriverTest");
miniHS2_2.setPamAuthenticator(pamAuthenticator2);
miniHS2_2.start(confOverlay);
String url1 = "http://localhost:" + hiveConf1.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
String url2 = "http://localhost:" + hiveConf2.get(ConfVars.HIVE_SERVER2_WEBUI_PORT.varname) + "/leader";
String healthCheckUrl1 = "http://localhost:" +
hiveConf1.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
String healthCheckUrl2 = "http://localhost:" +
hiveConf2.get(ConfVars.HIVE_SERVER2_ACTIVE_PASSIVE_HA_HEALTHCHECK_PORT.varname) + "/ha-healthcheck/health-ha";
String zkJdbcUrl = miniHS2_1.getJdbcURL();
String zkConnectString = zkServer.getConnectString();
assertTrue(zkJdbcUrl.contains(zkConnectString));
// when we start miniHS2_1 will be leader (sequential start)
assertEquals(true, miniHS2_1.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_1.isLeader());
assertEquals("true", sendGet(url1, true));
assertEquals("true", sendGet(healthCheckUrl1, true));
// before failover, check if we are getting connection from miniHS2_1
String hs2_1_directUrl = "jdbc:hive2://" + miniHS2_1.getHost() + ":" + miniHS2_1.getBinaryPort() +
"/default;serviceDiscoveryMode=" + serviceDiscoveryMode + ";zooKeeperNamespace=" + zkHANamespace + ";";
String parsedUrl = HiveConnection.getAllUrls(zkJdbcUrl).get(0).getJdbcUriString();
assertEquals(hs2_1_directUrl, parsedUrl);
hs2Conn = getConnection(zkJdbcUrl, System.getProperty("user.name"));
while (miniHS2_1.getOpenSessionsCount() != 1) {
Thread.sleep(100);
}
// trigger failover on miniHS2_1 and make sure the connections are closed
String resp = sendDelete(url1, true);
assertTrue(resp.contains("Failover successful!"));
// wait for failover to close sessions
while (miniHS2_1.getOpenSessionsCount() != 0) {
Thread.sleep(100);
}
resp = sendDelete(healthCheckUrl1, true);
assertTrue(resp.contains("Method Not Allowed"));
// make sure miniHS2_1 is not leader
assertEquals(true, miniHS2_1.getNotLeaderTestFuture().get());
assertEquals(false, miniHS2_1.isLeader());
assertEquals("false", sendGet(url1, true));
assertEquals("false", sendGet(healthCheckUrl1, true));
// make sure miniHS2_2 is the new leader
assertEquals(true, miniHS2_2.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_2.isLeader());
assertEquals("true", sendGet(url2, true));
assertEquals("true", sendGet(healthCheckUrl2, true));
// when we make a new connection we should get it from miniHS2_2 this time
String hs2_2_directUrl = "jdbc:hive2://" + miniHS2_2.getHost() + ":" + miniHS2_2.getHttpPort() +
"/default;serviceDiscoveryMode=" + serviceDiscoveryMode + ";zooKeeperNamespace=" + zkHANamespace + ";";
parsedUrl = HiveConnection.getAllUrls(zkJdbcUrl).get(0).getJdbcUriString();
assertEquals(hs2_2_directUrl, parsedUrl);
hs2Conn = getConnection(zkJdbcUrl, System.getProperty("user.name"));
while (miniHS2_2.getOpenSessionsCount() != 1) {
Thread.sleep(100);
}
// send failover request again to miniHS2_1 and get a failure
resp = sendDelete(url1, true);
assertTrue(resp.contains("Cannot failover an instance that is not a leader"));
assertEquals(true, miniHS2_1.getNotLeaderTestFuture().get());
assertEquals(false, miniHS2_1.isLeader());
// send failover request to miniHS2_2 and make sure miniHS2_1 takes over (returning back to leader, test listeners)
resp = sendDelete(url2, true);
assertTrue(resp.contains("Failover successful!"));
assertEquals(true, miniHS2_1.getIsLeaderTestFuture().get());
assertEquals(true, miniHS2_1.isLeader());
assertEquals("true", sendGet(url1, true));
assertEquals("true", sendGet(healthCheckUrl1, true));
assertEquals(true, miniHS2_2.getNotLeaderTestFuture().get());
assertEquals("false", sendGet(url2, true));
assertEquals("false", sendGet(healthCheckUrl2, true));
assertEquals(false, miniHS2_2.isLeader());
// make sure miniHS2_2 closes all its connections
while (miniHS2_2.getOpenSessionsCount() != 0) {
Thread.sleep(100);
}
// new connections goes to miniHS2_1 now
hs2Conn = getConnection(zkJdbcUrl, System.getProperty("user.name"));
while (miniHS2_1.getOpenSessionsCount() != 1) {
Thread.sleep(100);
}
} finally {
// revert configs to not affect other tests
unsetPamConfs(hiveConf1);
unsetPamConfs(hiveConf2);
}
}
private Connection getConnection(String jdbcURL, String user) throws SQLException {
return DriverManager.getConnection(jdbcURL, user, "bar");
}
private void openConnectionAndRunQuery(String jdbcUrl) throws Exception {
hs2Conn = getConnection(jdbcUrl, System.getProperty("user.name"));
String tableName = "testTab1";
Statement stmt = hs2Conn.createStatement();
// create table
stmt.execute("DROP TABLE IF EXISTS " + tableName);
stmt.execute("CREATE TABLE " + tableName
+ " (under_col INT COMMENT 'the under column', value STRING) COMMENT ' test table'");
// load data
stmt.execute("load data local inpath '" + kvDataFilePath.toString() + "' into table "
+ tableName);
ResultSet res = stmt.executeQuery("SELECT * FROM " + tableName);
assertTrue(res.next());
assertEquals("val_238", res.getString(2));
res.close();
stmt.close();
}
private String sendGet(String url) throws Exception {
return sendGet(url, false);
}
private String sendGet(String url, boolean enableAuth) throws Exception {
return sendAuthMethod(new HttpGet(url), enableAuth, false);
}
private String sendGet(String url, boolean enableAuth, boolean enableCORS) throws Exception {
return sendAuthMethod(new HttpGet(url), enableAuth, enableCORS);
}
private String sendDelete(String url, boolean enableAuth) throws Exception {
return sendAuthMethod(new HttpDelete(url), enableAuth, false);
}
private String sendDelete(String url, boolean enableAuth, boolean enableCORS) throws Exception {
return sendAuthMethod(new HttpDelete(url), enableAuth, enableCORS);
}
private String sendAuthMethod(HttpRequestBase method, boolean enableAuth, boolean enableCORS) throws Exception {
CloseableHttpResponse httpResponse = null;
String response = null;
int statusCode = -1;
try (
CloseableHttpClient client = HttpClients.createDefault();
) {
// CORS check
if (enableCORS) {
String origin = "http://example.com";
HttpOptions optionsMethod = new HttpOptions(method.getURI().toString());
optionsMethod.addHeader("Origin", origin);
if (enableAuth) {
setupAuthHeaders(optionsMethod);
}
httpResponse = client.execute(optionsMethod);
if (httpResponse != null) {
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine != null) {
response = httpResponse.getStatusLine().getReasonPhrase();
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
Header originHeader = httpResponse.getFirstHeader("Access-Control-Allow-Origin");
assertNotNull(originHeader);
assertEquals(origin, originHeader.getValue());
} else {
fail("CORS returned: " + statusCode + " Error: " + response);
}
} else {
fail("Status line is null");
}
} else {
fail("No http Response");
}
}
if (enableAuth) {
setupAuthHeaders(method);
}
httpResponse = client.execute(method);
if (httpResponse != null) {
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine != null) {
response = httpResponse.getStatusLine().getReasonPhrase();
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
return EntityUtils.toString(httpResponse.getEntity());
}
}
}
return response;
} finally {
httpResponse.close();
}
}
private void setupAuthHeaders(final HttpRequestBase method) {
String authB64Code =
B64Code.encode(ADMIN_USER + ":" + ADMIN_PASSWORD, StringUtil.__ISO_8859_1);
method.setHeader(HttpHeader.AUTHORIZATION.asString(), "Basic " + authB64Code);
}
private Map<String, String> getConfOverlay(final String instanceId) {
Map<String, String> confOverlay = new HashMap<>();
confOverlay.put("hive.server2.zookeeper.publish.configs", "true");
confOverlay.put(ZkRegistryBase.UNIQUE_IDENTIFIER, instanceId);
return confOverlay;
}
private Map<String, String> getSecureConfOverlay(final String instanceId) {
Map<String, String> confOverlay = new HashMap<>();
confOverlay.put("hive.server2.zookeeper.publish.configs", "true");
confOverlay.put(ZkRegistryBase.UNIQUE_IDENTIFIER, instanceId);
confOverlay.put("hadoop.security.instrumentation.requires.admin", "true");
confOverlay.put("hadoop.security.authorization", "true");
confOverlay.put(ConfVars.USERS_IN_ADMIN_ROLE.varname, ADMIN_USER);
return confOverlay;
}
private void setPamConfs(final HiveConf hiveConf) {
hiveConf.setVar(HiveConf.ConfVars.HIVE_SERVER2_PAM_SERVICES, "sshd");
hiveConf.setBoolVar(ConfVars.HIVE_SERVER2_WEBUI_USE_PAM, true);
hiveConf.setBoolVar(ConfVars.HIVE_IN_TEST, true);
}
private void unsetPamConfs(final HiveConf hiveConf) {
hiveConf.setVar(HiveConf.ConfVars.HIVE_SERVER2_PAM_SERVICES, "");
hiveConf.setBoolVar(ConfVars.HIVE_SERVER2_WEBUI_USE_PAM, false);
hiveConf.setBoolVar(ConfVars.HIVE_IN_TEST, false);
}
// This is test for llap command AuthZ added in HIVE-19033 which require ZK access for it to pass
@Test(timeout = 60000)
public void testNoAuthZLlapClusterInfo() throws Exception {
String instanceId1 = UUID.randomUUID().toString();
miniHS2_1.start(getConfOverlay(instanceId1));
Connection hs2Conn = getConnection(miniHS2_1.getJdbcURL(), "user1");
boolean caughtException = false;
Statement stmt = hs2Conn.createStatement();
try {
stmt.execute("set hive.llap.daemon.service.hosts=@localhost");
stmt.execute("llap cluster -info");
} catch (SQLException e) {
caughtException = true;
} finally {
stmt.close();
hs2Conn.close();
}
assertEquals(false, caughtException);
}
}
|
googleapis/google-cloud-java
| 38,314
|
java-retail/proto-google-cloud-retail-v2alpha/src/main/java/com/google/cloud/retail/v2alpha/UpdateAttributesConfigRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/retail/v2alpha/catalog_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.retail.v2alpha;
/**
*
*
* <pre>
* Request for
* [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.retail.v2alpha.UpdateAttributesConfigRequest}
*/
public final class UpdateAttributesConfigRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.retail.v2alpha.UpdateAttributesConfigRequest)
UpdateAttributesConfigRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateAttributesConfigRequest.newBuilder() to construct.
private UpdateAttributesConfigRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateAttributesConfigRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateAttributesConfigRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.retail.v2alpha.CatalogServiceProto
.internal_static_google_cloud_retail_v2alpha_UpdateAttributesConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.retail.v2alpha.CatalogServiceProto
.internal_static_google_cloud_retail_v2alpha_UpdateAttributesConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest.class,
com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest.Builder.class);
}
private int bitField0_;
public static final int ATTRIBUTES_CONFIG_FIELD_NUMBER = 1;
private com.google.cloud.retail.v2alpha.AttributesConfig attributesConfig_;
/**
*
*
* <pre>
* Required. The
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2alpha.AttributesConfig attributes_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the attributesConfig field is set.
*/
@java.lang.Override
public boolean hasAttributesConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2alpha.AttributesConfig attributes_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The attributesConfig.
*/
@java.lang.Override
public com.google.cloud.retail.v2alpha.AttributesConfig getAttributesConfig() {
return attributesConfig_ == null
? com.google.cloud.retail.v2alpha.AttributesConfig.getDefaultInstance()
: attributesConfig_;
}
/**
*
*
* <pre>
* Required. The
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2alpha.AttributesConfig attributes_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.retail.v2alpha.AttributesConfigOrBuilder getAttributesConfigOrBuilder() {
return attributesConfig_ == null
? com.google.cloud.retail.v2alpha.AttributesConfig.getDefaultInstance()
: attributesConfig_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Indicates which fields in the provided
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* The following is the only supported field:
*
* * [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* The following is the only supported field:
*
* * [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* The following is the only supported field:
*
* * [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(1, getAttributesConfig());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(2, getUpdateMask());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getAttributesConfig());
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getUpdateMask());
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest)) {
return super.equals(obj);
}
com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest other =
(com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest) obj;
if (hasAttributesConfig() != other.hasAttributesConfig()) return false;
if (hasAttributesConfig()) {
if (!getAttributesConfig().equals(other.getAttributesConfig())) return false;
}
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask().equals(other.getUpdateMask())) return false;
}
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasAttributesConfig()) {
hash = (37 * hash) + ATTRIBUTES_CONFIG_FIELD_NUMBER;
hash = (53 * hash) + getAttributesConfig().hashCode();
}
if (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for
* [CatalogService.UpdateAttributesConfig][google.cloud.retail.v2alpha.CatalogService.UpdateAttributesConfig]
* method.
* </pre>
*
* Protobuf type {@code google.cloud.retail.v2alpha.UpdateAttributesConfigRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.retail.v2alpha.UpdateAttributesConfigRequest)
com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.retail.v2alpha.CatalogServiceProto
.internal_static_google_cloud_retail_v2alpha_UpdateAttributesConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.retail.v2alpha.CatalogServiceProto
.internal_static_google_cloud_retail_v2alpha_UpdateAttributesConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest.class,
com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest.Builder.class);
}
// Construct using com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getAttributesConfigFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
attributesConfig_ = null;
if (attributesConfigBuilder_ != null) {
attributesConfigBuilder_.dispose();
attributesConfigBuilder_ = null;
}
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.retail.v2alpha.CatalogServiceProto
.internal_static_google_cloud_retail_v2alpha_UpdateAttributesConfigRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest
getDefaultInstanceForType() {
return com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest build() {
com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest buildPartial() {
com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest result =
new com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.attributesConfig_ =
attributesConfigBuilder_ == null ? attributesConfig_ : attributesConfigBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null ? updateMask_ : updateMaskBuilder_.build();
to_bitField0_ |= 0x00000002;
}
result.bitField0_ |= to_bitField0_;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest) {
return mergeFrom((com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest other) {
if (other
== com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest.getDefaultInstance())
return this;
if (other.hasAttributesConfig()) {
mergeAttributesConfig(other.getAttributesConfig());
}
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
input.readMessage(
getAttributesConfigFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getUpdateMaskFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private com.google.cloud.retail.v2alpha.AttributesConfig attributesConfig_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.retail.v2alpha.AttributesConfig,
com.google.cloud.retail.v2alpha.AttributesConfig.Builder,
com.google.cloud.retail.v2alpha.AttributesConfigOrBuilder>
attributesConfigBuilder_;
/**
*
*
* <pre>
* Required. The
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2alpha.AttributesConfig attributes_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the attributesConfig field is set.
*/
public boolean hasAttributesConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2alpha.AttributesConfig attributes_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The attributesConfig.
*/
public com.google.cloud.retail.v2alpha.AttributesConfig getAttributesConfig() {
if (attributesConfigBuilder_ == null) {
return attributesConfig_ == null
? com.google.cloud.retail.v2alpha.AttributesConfig.getDefaultInstance()
: attributesConfig_;
} else {
return attributesConfigBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2alpha.AttributesConfig attributes_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setAttributesConfig(com.google.cloud.retail.v2alpha.AttributesConfig value) {
if (attributesConfigBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
attributesConfig_ = value;
} else {
attributesConfigBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2alpha.AttributesConfig attributes_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setAttributesConfig(
com.google.cloud.retail.v2alpha.AttributesConfig.Builder builderForValue) {
if (attributesConfigBuilder_ == null) {
attributesConfig_ = builderForValue.build();
} else {
attributesConfigBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2alpha.AttributesConfig attributes_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeAttributesConfig(com.google.cloud.retail.v2alpha.AttributesConfig value) {
if (attributesConfigBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& attributesConfig_ != null
&& attributesConfig_
!= com.google.cloud.retail.v2alpha.AttributesConfig.getDefaultInstance()) {
getAttributesConfigBuilder().mergeFrom(value);
} else {
attributesConfig_ = value;
}
} else {
attributesConfigBuilder_.mergeFrom(value);
}
if (attributesConfig_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2alpha.AttributesConfig attributes_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearAttributesConfig() {
bitField0_ = (bitField0_ & ~0x00000001);
attributesConfig_ = null;
if (attributesConfigBuilder_ != null) {
attributesConfigBuilder_.dispose();
attributesConfigBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2alpha.AttributesConfig attributes_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.retail.v2alpha.AttributesConfig.Builder getAttributesConfigBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getAttributesConfigFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2alpha.AttributesConfig attributes_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.retail.v2alpha.AttributesConfigOrBuilder
getAttributesConfigOrBuilder() {
if (attributesConfigBuilder_ != null) {
return attributesConfigBuilder_.getMessageOrBuilder();
} else {
return attributesConfig_ == null
? com.google.cloud.retail.v2alpha.AttributesConfig.getDefaultInstance()
: attributesConfig_;
}
}
/**
*
*
* <pre>
* Required. The
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2alpha.AttributesConfig attributes_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.retail.v2alpha.AttributesConfig,
com.google.cloud.retail.v2alpha.AttributesConfig.Builder,
com.google.cloud.retail.v2alpha.AttributesConfigOrBuilder>
getAttributesConfigFieldBuilder() {
if (attributesConfigBuilder_ == null) {
attributesConfigBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.retail.v2alpha.AttributesConfig,
com.google.cloud.retail.v2alpha.AttributesConfig.Builder,
com.google.cloud.retail.v2alpha.AttributesConfigOrBuilder>(
getAttributesConfig(), getParentForChildren(), isClean());
attributesConfig_ = null;
}
return attributesConfigBuilder_;
}
private com.google.protobuf.FieldMask updateMask_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
updateMaskBuilder_;
/**
*
*
* <pre>
* Indicates which fields in the provided
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* The following is the only supported field:
*
* * [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* The following is the only supported field:
*
* * [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*
* @return The updateMask.
*/
public com.google.protobuf.FieldMask getUpdateMask() {
if (updateMaskBuilder_ == null) {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
} else {
return updateMaskBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* The following is the only supported field:
*
* * [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
updateMask_ = value;
} else {
updateMaskBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* The following is the only supported field:
*
* * [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder setUpdateMask(com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* The following is the only supported field:
*
* * [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& updateMask_ != null
&& updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* The following is the only supported field:
*
* * [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* The following is the only supported field:
*
* * [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* The following is the only supported field:
*
* * [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Indicates which fields in the provided
* [AttributesConfig][google.cloud.retail.v2alpha.AttributesConfig] to update.
* The following is the only supported field:
*
* * [AttributesConfig.catalog_attributes][google.cloud.retail.v2alpha.AttributesConfig.catalog_attributes]
*
* If not set, all supported fields are updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>
getUpdateMaskFieldBuilder() {
if (updateMaskBuilder_ == null) {
updateMaskBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.FieldMask,
com.google.protobuf.FieldMask.Builder,
com.google.protobuf.FieldMaskOrBuilder>(
getUpdateMask(), getParentForChildren(), isClean());
updateMask_ = null;
}
return updateMaskBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.retail.v2alpha.UpdateAttributesConfigRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.retail.v2alpha.UpdateAttributesConfigRequest)
private static final com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest();
}
public static com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateAttributesConfigRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateAttributesConfigRequest>() {
@java.lang.Override
public UpdateAttributesConfigRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<UpdateAttributesConfigRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateAttributesConfigRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.retail.v2alpha.UpdateAttributesConfigRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/juneau
| 34,738
|
juneau-utest/src/test/java/org/apache/juneau/config/ConfigMap_Test.java
|
// ***************************************************************************************************************************
// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file *
// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file *
// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
// * with the License. You may obtain a copy of the License at *
// * *
// * http://www.apache.org/licenses/LICENSE-2.0 *
// * *
// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an *
// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the *
// * specific language governing permissions and limitations under the License. *
// ***************************************************************************************************************************
package org.apache.juneau.config;
import static org.apache.juneau.TestUtils.*;
import static org.junit.jupiter.api.Assertions.*;
import java.util.*;
import org.apache.juneau.*;
import org.apache.juneau.common.utils.*;
import org.apache.juneau.config.store.*;
import org.junit.jupiter.api.*;
class ConfigMap_Test extends TestBase {
static final String ENCODED = "*";
static final String BASE64 = "^";
//-----------------------------------------------------------------------------------------------------------------
// Should be able to read non-existent files without errors.
//-----------------------------------------------------------------------------------------------------------------
@Test void a01_nonExistentConfig() throws Exception {
var s = MemoryStore.create().build();
var cm = s.getMap("A.cfg");
assertEquals("", cm.toString());
}
//-----------------------------------------------------------------------------------------------------------------
// Should be able to read blank files without errors.
//-----------------------------------------------------------------------------------------------------------------
@Test void a02_blankConfig() throws Exception {
var s = initStore("A.cfg", "");
var cm = s.getMap("A.cfg");
assertEquals("", cm.toString());
s.update("A.cfg", " \n \n ");
s.getMap("A.cfg");
}
//-----------------------------------------------------------------------------------------------------------------
// Simple one-line file.
//-----------------------------------------------------------------------------------------------------------------
@Test void a03_simpleOneLine() throws Exception {
var s = initStore("A.cfg",
"foo=bar"
);
var cm = s.getMap("A.cfg");
assertEquals("foo=bar|", pipedLines(cm));
assertEquals("", Utils.join(cm.getPreLines(""), '|'));
assertEquals("", Utils.join(cm.getEntry("", "foo").getPreLines(), '|'));
assertEquals("bar", cm.getEntry("", "foo").getValue());
// Round trip.
s.update("A.cfg", cm.toString());
cm = s.getMap("A.cfg");
assertEquals("foo=bar|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// Simple one-line file with leading comments.
//-----------------------------------------------------------------------------------------------------------------
@Test void a04_simpleOneLineWithComments() throws Exception {
var s = initStore("A.cfg",
"#comment",
"foo=bar"
);
var cm = s.getMap("A.cfg");
assertEquals("#comment|foo=bar|", pipedLines(cm));
assertEquals("", Utils.join(cm.getPreLines(""), '|'));
assertEquals("#comment", Utils.join(cm.getEntry("", "foo").getPreLines(), '|'));
assertEquals("bar", cm.getEntry("", "foo").getValue());
// Round trip.
s.update("A.cfg", cm.toString());
cm = s.getMap("A.cfg");
assertEquals("#comment|foo=bar|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// Simple section.
//-----------------------------------------------------------------------------------------------------------------
@Test void a05_simpleSection() throws Exception {
var s = initStore("A.cfg",
"[MySection]",
"foo=bar"
);
var cm = s.getMap("A.cfg");
assertEquals("[MySection]|foo=bar|", pipedLines(cm));
assertEquals("", Utils.join(cm.getPreLines(""), '|'));
assertEquals("", Utils.join(cm.getPreLines("MySection"), '|'));
assertEquals("", Utils.join(cm.getEntry("MySection", "foo").getPreLines(), '|'));
assertEquals("bar", cm.getEntry("MySection", "foo").getValue());
// Round trip.
s.update("A.cfg", cm.toString());
cm = s.getMap("A.cfg");
assertEquals("[MySection]|foo=bar|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// Non-existent values should not throw exceptions.
//-----------------------------------------------------------------------------------------------------------------
@Test void a06_nonExistentValues() throws Exception {
var s = initStore("A.cfg",
"[MySection]",
"foo=bar"
);
var cm = s.getMap("A.cfg");
assertEquals("[MySection]|foo=bar|", pipedLines(cm));
assertEquals("", Utils.join(cm.getPreLines(""), '|'));
assertNull(cm.getPreLines("XXX"));
assertNull(cm.getEntry("XXX", "yyy"));
assertNull(cm.getEntry("MySection", "yyy"));
}
//-----------------------------------------------------------------------------------------------------------------
// testSimpleSectionWithComments
//-----------------------------------------------------------------------------------------------------------------
@Test void a07_simpleSectionWithComments() throws Exception {
var s = initStore("A.cfg",
"#S1",
"[S1]",
"#k1",
"k1=v1",
"#S2",
"[S2]",
"#k2",
"k2=v2"
);
var cm = s.getMap("A.cfg");
assertEquals("#S1|[S1]|#k1|k1=v1|#S2|[S2]|#k2|k2=v2|", pipedLines(cm));
assertEquals("", Utils.join(cm.getPreLines(""), '|'));
assertEquals("#S1", Utils.join(cm.getPreLines("S1"), '|'));
assertEquals("#k1", Utils.join(cm.getEntry("S1", "k1").getPreLines(), '|'));
assertEquals("#S2", Utils.join(cm.getPreLines("S2"), '|'));
assertEquals("#k2", Utils.join(cm.getEntry("S2", "k2").getPreLines(), '|'));
assertEquals("v1", cm.getEntry("S1", "k1").getValue());
assertEquals("v2", cm.getEntry("S2", "k2").getValue());
// Round trip.
s.update("A.cfg", cm.toString());
cm = s.getMap("A.cfg");
assertEquals("#S1|[S1]|#k1|k1=v1|#S2|[S2]|#k2|k2=v2|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// testSimpleAndDefaultSectionsWithComments
//-----------------------------------------------------------------------------------------------------------------
@Test void a08_simpleAndDefaultSectionsWithComments() throws Exception {
var s = initStore("A.cfg",
"#D",
"",
"#k",
"k=v",
"#S1",
"[S1]",
"#k1",
"k1=v1"
);
var cm = s.getMap("A.cfg");
assertEquals("#D||#k|k=v|#S1|[S1]|#k1|k1=v1|", pipedLines(cm));
assertEquals("#D", Utils.join(cm.getPreLines(""), '|'));
assertEquals("#k", Utils.join(cm.getEntry("", "k").getPreLines(), '|'));
assertEquals("#S1", Utils.join(cm.getPreLines("S1"), '|'));
assertEquals("#k1", Utils.join(cm.getEntry("S1", "k1").getPreLines(), '|'));
assertEquals("v", cm.getEntry("", "k").getValue());
assertEquals("v1", cm.getEntry("S1", "k1").getValue());
// Round trip.
s.update("A.cfg", cm.toString());
cm = s.getMap("A.cfg");
assertEquals("#D||#k|k=v|#S1|[S1]|#k1|k1=v1|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// testSimpleAndDefaultSectionsWithCommentsAndExtraSpaces
//-----------------------------------------------------------------------------------------------------------------
@Test void a09_simpleAndDefaultSectionsWithCommentsAndExtraSpaces() throws Exception {
var s = initStore("A.cfg",
"#Da",
"#Db",
"",
"#ka",
"",
"#kb",
"",
"k=v",
"",
"#S1a",
"",
"#S1b",
"",
"[S1]",
"",
"#k1a",
"",
"#k1b",
"",
"k1=v1"
);
var cm = s.getMap("A.cfg");
assertEquals("#Da|#Db||#ka||#kb||k=v||#S1a||#S1b||[S1]||#k1a||#k1b||k1=v1|", pipedLines(cm));
assertEquals("#Da|#Db", Utils.join(cm.getPreLines(""), '|'));
assertEquals("#ka||#kb|", Utils.join(cm.getEntry("", "k").getPreLines(), '|'));
assertEquals("|#S1a||#S1b|", Utils.join(cm.getPreLines("S1"), '|'));
assertEquals("|#k1a||#k1b|", Utils.join(cm.getEntry("S1", "k1").getPreLines(), '|'));
assertEquals("v", cm.getEntry("", "k").getValue());
assertEquals("v1", cm.getEntry("S1", "k1").getValue());
// Round trip.
s.update("A.cfg", cm.toString());
cm = s.getMap("A.cfg");
assertEquals("#Da|#Db||#ka||#kb||k=v||#S1a||#S1b||[S1]||#k1a||#k1b||k1=v1|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// Error conditions.
//-----------------------------------------------------------------------------------------------------------------
@Test void a10_malformedSectionHeaders() {
var test = a(
"[]", "[ ]",
"[/]", "[[]", "[]]", "[\\]",
"[foo/bar]", "[foo[bar]", "[foo]bar]", "[foo\\bar]",
"[]", "[ ]", "[\t]"
);
for (var t : test) {
var s = initStore("A.cfg", t);
assertThrowsWithMessage(Exception.class, "Invalid section name", ()->s.getMap("A.cfg"));
}
}
@Test void a01_duplicateSectionNames() {
var s = initStore("A.cfg", "[S1]", "[S1]");
assertThrowsWithMessage(ConfigException.class, "Duplicate section found in configuration: [S1]", ()->s.getMap("A.cfg"));
}
@Test void a02_duplicateEntryNames() {
var s = initStore("A.cfg", "[S1]", "foo=v1", "foo=v2");
assertThrowsWithMessage(ConfigException.class, "Duplicate entry found in section [S1] of configuration: foo", ()->s.getMap("A.cfg"));
}
//-----------------------------------------------------------------------------------------------------------------
// Lines can be split up.
//-----------------------------------------------------------------------------------------------------------------
@Test void a03_multipleLines() throws Exception {
var s = initStore("A.cfg",
"k1 = v1a,",
"\tv1b,",
"\tv1c",
"k2 = v2a,",
"\tv2b,",
"\tv2c"
);
var cm = s.getMap("A.cfg");
assertEquals("", Utils.join(cm.getEntry("", "k1").getPreLines(), '|'));
assertEquals("", Utils.join(cm.getEntry("", "k2").getPreLines(), '|'));
assertEquals("k1 = v1a,|\tv1b,|\tv1c|k2 = v2a,|\tv2b,|\tv2c|", pipedLines(cm));
assertEquals("v1a,\nv1b,\nv1c", cm.getEntry("", "k1").getValue());
assertEquals("v2a,\nv2b,\nv2c", cm.getEntry("", "k2").getValue());
// Round trip.
s.update("A.cfg", cm.toString());
cm = s.getMap("A.cfg");
assertEquals("k1 = v1a,|\tv1b,|\tv1c|k2 = v2a,|\tv2b,|\tv2c|", pipedLines(cm));
}
@Test void a04_multipleLinesWithSpacesAndComments() throws Exception {
var s = initStore("A.cfg",
"",
"#k1",
"",
"k1 = v1a,",
"\tv1b,",
"\tv1c",
"",
"#k2",
"",
"k2 = v2a,",
"\tv2b,",
"\tv2c"
);
var cm = s.getMap("A.cfg");
assertEquals("|#k1|", Utils.join(cm.getEntry("", "k1").getPreLines(), '|'));
assertEquals("|#k2|", Utils.join(cm.getEntry("", "k2").getPreLines(), '|'));
assertEquals("|#k1||k1 = v1a,| v1b,| v1c||#k2||k2 = v2a,| v2b,| v2c|", pipedLines(cm));
assertEquals("v1a,\nv1b,\nv1c", cm.getEntry("", "k1").getValue());
assertEquals("v2a,\nv2b,\nv2c", cm.getEntry("", "k2").getValue());
// Round trip.
s.update("A.cfg", cm.toString());
cm = s.getMap("A.cfg");
assertEquals("|#k1||k1 = v1a,| v1b,| v1c||#k2||k2 = v2a,| v2b,| v2c|", pipedLines(cm));
}
@Test void a05_multipleLinesInSection() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1a,",
"\tv1b,",
"\tv1c",
"k2 = v2a,",
"\tv2b,",
"\tv2c"
);
var cm = s.getMap("A.cfg");
assertEquals("", Utils.join(cm.getEntry("S1", "k1").getPreLines(), '|'));
assertEquals("", Utils.join(cm.getEntry("S1", "k2").getPreLines(), '|'));
assertEquals("[S1]|k1 = v1a,|\tv1b,|\tv1c|k2 = v2a,|\tv2b,|\tv2c|", pipedLines(cm));
assertEquals("v1a,\nv1b,\nv1c", cm.getEntry("S1", "k1").getValue());
assertEquals("v2a,\nv2b,\nv2c", cm.getEntry("S1", "k2").getValue());
// Round trip.
s.update("A.cfg", cm.toString());
cm = s.getMap("A.cfg");
assertEquals("[S1]|k1 = v1a,|\tv1b,|\tv1c|k2 = v2a,|\tv2b,|\tv2c|", pipedLines(cm));
}
@Test void a06_multipleLinesInSectionWithSpacesAndPrelines() throws Exception {
var s = initStore("A.cfg",
"",
"#S1",
"",
"[S1]",
"",
"#k1",
"",
"k1 = v1a,",
"\tv1b,",
"\tv1c",
"",
"#k2",
"",
"k2 = v2a,",
"\tv2b,",
"\tv2c"
);
var cm = s.getMap("A.cfg");
assertEquals("|#S1|", Utils.join(cm.getPreLines("S1"), '|'));
assertEquals("|#k1|", Utils.join(cm.getEntry("S1", "k1").getPreLines(), '|'));
assertEquals("|#k2|", Utils.join(cm.getEntry("S1", "k2").getPreLines(), '|'));
assertEquals("|#S1||[S1]||#k1||k1 = v1a,| v1b,| v1c||#k2||k2 = v2a,| v2b,| v2c|", pipedLines(cm));
assertEquals("v1a,\nv1b,\nv1c", cm.getEntry("S1", "k1").getValue());
assertEquals("v2a,\nv2b,\nv2c", cm.getEntry("S1", "k2").getValue());
// Round trip.
s.update("A.cfg", cm.toString());
cm = s.getMap("A.cfg");
assertEquals("|#S1||[S1]||#k1||k1 = v1a,| v1b,| v1c||#k2||k2 = v2a,| v2b,| v2c|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// Entry lines can have trailing comments.
//-----------------------------------------------------------------------------------------------------------------
@Test void a07_entriesWithComments() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = foo # comment"
);
var cm = s.getMap("A.cfg");
assertEquals("[S1]|k1 = foo # comment|", pipedLines(cm));
assertEquals("foo", cm.getEntry("S1", "k1").getValue());
assertEquals("comment", cm.getEntry("S1", "k1").getComment());
cm.setEntry("S1", "k1", null, null, "newcomment", null);
assertEquals("[S1]|k1 = foo # newcomment|", pipedLines(cm));
assertEquals("foo", cm.getEntry("S1", "k1").getValue());
assertEquals("newcomment", cm.getEntry("S1", "k1").getComment());
cm.setEntry("S1", "k1", null, null, "", null);
assertEquals("[S1]|k1 = foo|", pipedLines(cm));
assertEquals("foo", cm.getEntry("S1", "k1").getValue());
assertEquals("", cm.getEntry("S1", "k1").getComment());
cm.setEntry("S1", "k1", null, null, null, null);
assertEquals("[S1]|k1 = foo|", pipedLines(cm));
assertEquals("foo", cm.getEntry("S1", "k1").getValue());
assertEquals("", cm.getEntry("S1", "k1").getComment());
}
@Test void a08_entriesWithOddComments() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = foo#",
"k2 = foo # "
);
var cm = s.getMap("A.cfg");
assertEquals("[S1]|k1 = foo#|k2 = foo # |", pipedLines(cm));
assertEquals("", cm.getEntry("S1", "k1").getComment());
assertEquals("", cm.getEntry("S1", "k2").getComment());
}
@Test void a09_entriesWithEscapedComments() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = foo\\#bar",
"k2 = foo \\# bar",
"k3 = foo \\# bar # real-comment"
);
var cm = s.getMap("A.cfg");
assertEquals("[S1]|k1 = foo\\#bar|k2 = foo \\# bar|k3 = foo \\# bar # real-comment|", pipedLines(cm));
assertEquals(null, cm.getEntry("S1", "k1").getComment());
assertEquals(null, cm.getEntry("S1", "k2").getComment());
assertEquals("real-comment", cm.getEntry("S1", "k3").getComment());
}
//-----------------------------------------------------------------------------------------------------------------
// Test setting entries.
//-----------------------------------------------------------------------------------------------------------------
@Test void a10_settingEntries() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1a",
"k2 = v2a"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k1", "v1b", null, null, null);
cm.setEntry("S1", "k2", null, null, null, null);
cm.setEntry("S1", "k3", "v3b", null, null, null);
assertEquals("[S1]|k1 = v1b|k2 = v2a|k3 = v3b|", pipedLines(cm));
cm.commit();
assertEquals("[S1]|k1 = v1b|k2 = v2a|k3 = v3b|", pipedLines(cm));
// Round trip.
cm = s.getMap("A.cfg");
assertEquals("[S1]|k1 = v1b|k2 = v2a|k3 = v3b|", pipedLines(cm));
}
@Test void a11_settingEntriesWithPreLines() throws Exception {
var s = initStore("A.cfg",
"",
"#S1",
"",
"[S1]",
"",
"#k1",
"",
"k1 = v1a",
"",
"#k2",
"",
"k2 = v2a"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k1", "v1b", null, null, null);
cm.setEntry("S1", "k2", null, null, null, null);
cm.setEntry("S1", "k3", "v3b", null, null, null);
cm.setEntry("S1", "k4", "v4b", null, null, Arrays.asList("","#k4",""));
assertEquals("|#S1||[S1]||#k1||k1 = v1b||#k2||k2 = v2a|k3 = v3b||#k4||k4 = v4b|", pipedLines(cm));
cm.commit();
assertEquals("|#S1||[S1]||#k1||k1 = v1b||#k2||k2 = v2a|k3 = v3b||#k4||k4 = v4b|", pipedLines(s.read("A.cfg")));
// Round trip.
cm = s.getMap("A.cfg");
assertEquals("|#S1||[S1]||#k1||k1 = v1b||#k2||k2 = v2a|k3 = v3b||#k4||k4 = v4b|", pipedLines(cm));
}
@Test void a12_settingEntriesWithNewlines() throws Exception {
var s = initStore("A.cfg");
var cm = s.getMap("A.cfg");
cm.setEntry("", "k", "v1\nv2\nv3", null, null, null);
cm.setEntry("S1", "k1", "v1\nv2\nv3", null, null, null);
assertEquals("k = v1| v2| v3|[S1]|k1 = v1| v2| v3|", pipedLines(cm));
assertEquals("v1\nv2\nv3", cm.getEntry("", "k").getValue());
assertEquals("v1\nv2\nv3", cm.getEntry("S1", "k1").getValue());
cm.commit();
assertEquals("k = v1| v2| v3|[S1]|k1 = v1| v2| v3|", pipedLines(cm));
// Round trip.
cm = s.getMap("A.cfg");
assertEquals("k = v1| v2| v3|[S1]|k1 = v1| v2| v3|", pipedLines(cm));
}
@Test void a13_settingEntriesWithNewlinesAndSpaces() throws Exception {
var s = initStore("A.cfg");
var cm = s.getMap("A.cfg");
cm.setEntry("", "k", "v1 \n v2 \n v3", null, null, null);
cm.setEntry("S1", "k1", "v1\t\n\tv2\t\n\tv3", null, null, null);
assertEquals("k = v1 | v2 | v3|[S1]|k1 = v1 | v2 | v3|", pipedLines(cm));
assertEquals("v1 \n v2 \n v3", cm.getEntry("", "k").getValue());
assertEquals("v1\t\n\tv2\t\n\tv3", cm.getEntry("S1", "k1").getValue());
cm.commit();
assertEquals("k = v1 | v2 | v3|[S1]|k1 = v1 | v2 | v3|", pipedLines(cm));
// Round trip.
cm = s.getMap("A.cfg");
assertEquals("k = v1 | v2 | v3|[S1]|k1 = v1 | v2 | v3|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// setSection()
//-----------------------------------------------------------------------------------------------------------------
@Test void a14_setSectionOnExistingSection() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setSection("S1", Arrays.asList("#S1"));
assertEquals("#S1|[S1]|k1 = v1|", pipedLines(cm));
cm.setSection("S1", Collections.<String>emptyList());
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
cm.setSection("S1", null);
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
}
@Test void a15_setSectionOnDefaultSection() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setSection("", Arrays.asList("#D"));
assertEquals("#D||[S1]|k1 = v1|", pipedLines(cm));
cm.setSection("", Collections.<String>emptyList());
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
cm.setSection("", null);
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
}
@Test void a16_setSectionOnNewSection() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setSection("S2", Arrays.asList("#S2"));
assertEquals("[S1]|k1 = v1|#S2|[S2]|", pipedLines(cm));
cm.setSection("S3", Collections.<String>emptyList());
assertEquals("[S1]|k1 = v1|#S2|[S2]|[S3]|", pipedLines(cm));
cm.setSection("S4", null);
assertEquals("[S1]|k1 = v1|#S2|[S2]|[S3]|[S4]|", pipedLines(cm));
}
@Test void a17_setSectionBadNames() throws Exception {
var s = initStore("A.cfg");
var cm = s.getMap("A.cfg");
var test = a(
"/", "[", "]",
"foo/bar", "foo[bar", "foo]bar",
" ",
null
);
for (var t : test) {
assertThrowsWithMessage(Exception.class, "Invalid section name", ()->cm.setSection(t, null));
}
}
@Test void a18_setSectionOkNames() throws Exception {
var s = initStore("A.cfg");
var cm = s.getMap("A.cfg");
// These are all okay characters to use in section names.
String validChars = "~`!@#$%^&*()_-+={}|:;\"\'<,>.?";
for (var c : validChars.toCharArray()) {
var test = ""+c;
cm.setSection(test, Arrays.asList("test"));
cm.commit();
assertEquals("test", cm.getPreLines(test).get(0));
test = "foo"+c+"bar";
cm.setSection(test, Arrays.asList("test"));
cm.commit();
assertEquals("test", cm.getPreLines(test).get(0));
}
}
//-----------------------------------------------------------------------------------------------------------------
// removeSection()
//-----------------------------------------------------------------------------------------------------------------
@Test void a19_removeSectionOnExistingSection() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1",
"[S2]",
"k2 = v2"
);
var cm = s.getMap("A.cfg");
cm.removeSection("S1");
assertEquals("[S2]|k2 = v2|", pipedLines(cm));
}
@Test void a20_removeSectionOnNonExistingSection() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1",
"[S2]",
"k2 = v2"
);
var cm = s.getMap("A.cfg");
cm.removeSection("S3");
assertEquals("[S1]|k1 = v1|[S2]|k2 = v2|", pipedLines(cm));
assertThrowsWithMessage(IllegalArgumentException.class, "Invalid section name: 'null'", ()->cm.removeSection(null));
}
@Test void a21_removeDefaultSection() throws Exception {
var s = initStore("A.cfg",
"k = v",
"[S1]",
"k1 = v1",
"[S2]",
"k2 = v2"
);
var cm = s.getMap("A.cfg");
cm.removeSection("");
assertEquals("[S1]|k1 = v1|[S2]|k2 = v2|", pipedLines(cm));
}
@Test void a22_removeDefaultSectionWithComments() throws Exception {
var s = initStore("A.cfg",
"#D",
"",
"#k",
"k = v",
"[S1]",
"k1 = v1",
"[S2]",
"k2 = v2"
);
var cm = s.getMap("A.cfg");
cm.removeSection("");
assertEquals("[S1]|k1 = v1|[S2]|k2 = v2|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// setPreLines()
//-----------------------------------------------------------------------------------------------------------------
@Test void a23_setPrelinesOnExistingEntry() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k1", null, null, null, Arrays.asList("#k1"));
assertEquals("[S1]|#k1|k1 = v1|", pipedLines(cm));
cm.setEntry("S1", "k1", null, null, null, Collections.<String>emptyList());
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
cm.setEntry("S1", "k1", null, null, null, null);
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
}
@Test void a24_setPrelinesOnExistingEntryWithAtrributes() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"#k1a",
"k1 = v1 # comment"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k1", null, null, null, Arrays.asList("#k1b"));
assertEquals("[S1]|#k1b|k1 = v1 # comment|", pipedLines(cm));
}
@Test void a25_setPrelinesOnNonExistingEntry() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k2", null, null, null, Arrays.asList("#k2"));
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
cm.setEntry("S1", "k2", null, null, null, Collections.<String>emptyList());
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
cm.setEntry("S1", "k2", null, null, null, null);
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
cm.setEntry("S2", "k2", null, null, null, Arrays.asList("#k2"));
assertEquals("[S1]|k1 = v1|[S2]|", pipedLines(cm));
cm.setEntry("S2", "k2", null, null, null, Collections.<String>emptyList());
assertEquals("[S1]|k1 = v1|[S2]|", pipedLines(cm));
cm.setEntry("S2", "k2", null, null, null, null);
assertEquals("[S1]|k1 = v1|[S2]|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// setValue()
//-----------------------------------------------------------------------------------------------------------------
@Test void a26_setValueOnExistingEntry() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k1", "v2", null, null, null);
assertEquals("[S1]|k1 = v2|", pipedLines(cm));
}
@Test void a27_setValueOnExistingEntryWithAttributes() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"#k1",
"k1 = v1 # comment"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k1", "v2", null, null, null);
assertEquals("[S1]|#k1|k1 = v2 # comment|", pipedLines(cm));
}
@Test void a28_setValueToNullOnExistingEntry() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k1", null, null, null, null);
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
}
@Test void a29_setValueOnNonExistingEntry() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k2", "v2", null, null, null);
assertEquals("[S1]|k1 = v1|k2 = v2|", pipedLines(cm));
cm.setEntry("S1", "k2", null, null, null, null);
assertEquals("[S1]|k1 = v1|k2 = v2|", pipedLines(cm));
cm.setEntry("S1", "k2", null, null, null, null);
assertEquals("[S1]|k1 = v1|k2 = v2|", pipedLines(cm));
}
@Test void a30_setValueOnNonExistingEntryOnNonExistentSection() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S2", "k2", "v2", null, null, null);
assertEquals("[S1]|k1 = v1|[S2]|k2 = v2|", pipedLines(cm));
}
@Test void a31_setValueInvalidSectionNames() throws Exception {
var s = initStore("A.cfg");
var cm = s.getMap("A.cfg");
var test = a(
"/", "[", "]",
"foo/bar", "foo[bar", "foo]bar",
" ",
null
);
for (var t : test) {
assertThrowsWithMessage(Exception.class, "Invalid section name:", ()->cm.setEntry(t, "k1", "foo", null, null, null));
}
}
@Test void a32_setValueInvalidKeyNames() throws Exception {
var s = initStore("A.cfg");
var cm = s.getMap("A.cfg");
var test = a(
"", " ", "\t",
"foo=bar", "=",
"foo/bar", "/",
"foo[bar", "]",
"foo]bar", "]",
"foo\\bar", "\\",
"foo#bar", "#",
null
);
for (var t : test) {
assertThrowsWithMessage(Exception.class, "Invalid key name", ()->cm.setEntry("S1", t, "foo", null, null, null));
}
}
@Test void a33_setValueWithCommentChars() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
// If value has # in it, it should get escaped.
cm.setEntry("S1", "k1", "v1 # foo", null, null, null);
assertEquals("[S1]|k1 = v1 \\u0023 foo|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// setComment()
//-----------------------------------------------------------------------------------------------------------------
@Test void a34_setCommentOnExistingEntry() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k1", null, null, "c1", null);
assertEquals("[S1]|k1 = v1 # c1|", pipedLines(cm));
cm.setEntry("S1", "k1", null, null, "", null);
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
cm.commit();
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
cm.setEntry("S1", "k1", null, null, null, null);
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
}
@Test void a35_setCommentOnExistingEntryWithAttributes() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"#k1a",
"k1 = v1 # c1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k1", null, null, "c2", null);
assertEquals("[S1]|#k1a|k1 = v1 # c2|", pipedLines(cm));
}
@Test void a36_setCommentOnNonExistingEntry() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k2", null, null, "foo", null);
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
cm.setEntry("S1", "k2", null, null, null, null);
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
cm.setEntry("S2", "k2", null, null, "foo", null);
assertEquals("[S1]|k1 = v1|[S2]|", pipedLines(cm));
cm.setEntry("S2", "k2", null, null, null, null);
assertEquals("[S1]|k1 = v1|[S2]|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// setValue()
//-----------------------------------------------------------------------------------------------------------------
@Test void a37_setEntryOnExistingEntry() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k1", "v2", null, null, null);
assertEquals("[S1]|k1 = v2|", pipedLines(cm));
cm.setEntry("S1", "k1", "v3", ENCODED, "c3", Arrays.asList("#k1a"));
assertEquals("[S1]|#k1a|k1<*> = v3 # c3|", pipedLines(cm));
cm.setEntry("S1", "k1", "v4", BASE64, "c4", Arrays.asList("#k1b"));
assertEquals("[S1]|#k1b|k1<^> = v4 # c4|", pipedLines(cm));
}
@Test void a38_setEntryOnExistingEntryWithAttributes() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"#k1",
"k1 = v1 # comment"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k1", "v2", null, null, null);
assertEquals("[S1]|#k1|k1 = v2 # comment|", pipedLines(cm));
cm.setEntry("S1", "k1", "v3", ENCODED, "c3", Arrays.asList("#k1a"));
assertEquals("[S1]|#k1a|k1<*> = v3 # c3|", pipedLines(cm));
cm.setEntry("S1", "k1", "v4", BASE64, "c4", Arrays.asList("#k1b"));
assertEquals("[S1]|#k1b|k1<^> = v4 # c4|", pipedLines(cm));
}
@Test void a39_setEntryToNullOnExistingEntry() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k1", null, null, null, null);
assertEquals("[S1]|k1 = v1|", pipedLines(cm));
}
@Test void a40_setEntryOnNonExistingEntry() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S1", "k2", "v2", null, null, null);
assertEquals("[S1]|k1 = v1|k2 = v2|", pipedLines(cm));
cm.setEntry("S1", "k2", null, null, null, null);
assertEquals("[S1]|k1 = v1|k2 = v2|", pipedLines(cm));
cm.setEntry("S1", "k2", "", null, null, null);
assertEquals("[S1]|k1 = v1|k2 = |", pipedLines(cm));
}
@Test void a41_setEntryOnNonExistingEntryOnNonExistentSection() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
cm.setEntry("S2", "k2", "v2", null, null, null);
assertEquals("[S1]|k1 = v1|[S2]|k2 = v2|", pipedLines(cm));
}
@Test void a42_setEntryInvalidSectionNames() throws Exception {
var s = initStore("A.cfg");
var cm = s.getMap("A.cfg");
var test = a(
"/", "[", "]",
"foo/bar", "foo[bar", "foo]bar",
" ",
null
);
for (var t : test) {
assertThrowsWithMessage(Exception.class, "Invalid section name", ()->cm.setEntry(t, "k1", "foo", null, null, null));
}
}
@Test void a43_setEntryInvalidKeyNames() throws Exception {
var s = initStore("A.cfg");
var cm = s.getMap("A.cfg");
var test = a(
"", " ", "\t",
"foo=bar", "=",
"foo/bar", "/",
"foo[bar", "]",
"foo]bar", "]",
"foo\\bar", "\\",
"foo#bar", "#",
null
);
for (var t : test) {
assertThrowsWithMessage(Exception.class, "Invalid key name", ()->cm.setEntry("S1", t, "foo", null, null, null));
}
}
@Test void a44_setEntryWithCommentChars() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1 = v1"
);
var cm = s.getMap("A.cfg");
// If value has # in it, it should get escaped.
cm.setEntry("S1", "k1", "v1 # foo", null, null, null);
assertEquals("[S1]|k1 = v1 \\u0023 foo|", pipedLines(cm));
}
//-----------------------------------------------------------------------------------------------------------------
// Modifiers
//-----------------------------------------------------------------------------------------------------------------
@Test void a45_modifiers() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1<^> = v1",
"k2<*> = v2",
"k3<*^> = v3"
);
var cm = s.getMap("A.cfg");
assertEquals("[S1]|k1<^> = v1|k2<*> = v2|k3<*^> = v3|", pipedLines(cm));
assertEquals("^", cm.getEntry("S1", "k1").getModifiers());
assertEquals("*", cm.getEntry("S1", "k2").getModifiers());
assertEquals("*^", cm.getEntry("S1", "k3").getModifiers());
cm.setEntry("S1", "k1", "v1", "#$%&*+^@~", null, null);
assertEquals("[S1]|k1<#$%&*+^@~> = v1|k2<*> = v2|k3<*^> = v3|", pipedLines(cm));
}
@Test void a46_invalidModifier() throws Exception {
var s = initStore("A.cfg",
"[S1]",
"k1^ = v1",
"k2* = v2",
"k3*^ = v3"
);
var cm = s.getMap("A.cfg");
// This is okay.
assertDoesNotThrow(()->cm.setEntry("S1", "k1", "v1", "", null, null));
}
private static ConfigStore initStore(String name, String...contents) {
return MemoryStore.create().build().update(name, contents);
}
}
|
googleapis/google-cloud-java
| 38,167
|
java-monitoring/proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/ListSnoozesRequest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/snooze_service.proto
// Protobuf Java Version: 3.25.8
package com.google.monitoring.v3;
/**
*
*
* <pre>
* The message definition for listing `Snooze`s associated with the given
* `parent`, satisfying the optional `filter`.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.ListSnoozesRequest}
*/
public final class ListSnoozesRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.monitoring.v3.ListSnoozesRequest)
ListSnoozesRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListSnoozesRequest.newBuilder() to construct.
private ListSnoozesRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListSnoozesRequest() {
parent_ = "";
filter_ = "";
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListSnoozesRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.SnoozeServiceProto
.internal_static_google_monitoring_v3_ListSnoozesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.SnoozeServiceProto
.internal_static_google_monitoring_v3_ListSnoozesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.ListSnoozesRequest.class,
com.google.monitoring.v3.ListSnoozesRequest.Builder.class);
}
public static final int PARENT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The
* [project](https://cloud.google.com/monitoring/api/v3#project_name) whose
* `Snooze`s should be listed. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
@java.lang.Override
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The
* [project](https://cloud.google.com/monitoring/api/v3#project_name) whose
* `Snooze`s should be listed. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
@java.lang.Override
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int FILTER_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Optional. Optional filter to restrict results to the given criteria. The
* following fields are supported.
*
* * `interval.start_time`
* * `interval.end_time`
*
* For example:
*
* interval.start_time > "2022-03-11T00:00:00-08:00" AND
* interval.end_time < "2022-03-12T00:00:00-08:00"
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
@java.lang.Override
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. Optional filter to restrict results to the given criteria. The
* following fields are supported.
*
* * `interval.start_time`
* * `interval.end_time`
*
* For example:
*
* interval.start_time > "2022-03-11T00:00:00-08:00" AND
* interval.end_time < "2022-03-12T00:00:00-08:00"
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
@java.lang.Override
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAGE_SIZE_FIELD_NUMBER = 4;
private int pageSize_ = 0;
/**
*
*
* <pre>
* Optional. The maximum number of results to return for a single query. The
* server may further constrain the maximum number of results returned in a
* single page. The value should be in the range [1, 1000]. If the value given
* is outside this range, the server will decide the number of results to be
* returned.
* </pre>
*
* <code>int32 page_size = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
public static final int PAGE_TOKEN_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. The `next_page_token` from a previous call to
* `ListSnoozesRequest` to get the next page of results.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
@java.lang.Override
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
}
}
/**
*
*
* <pre>
* Optional. The `next_page_token` from a previous call to
* `ListSnoozesRequest` to get the next page of results.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
@java.lang.Override
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, filter_);
}
if (pageSize_ != 0) {
output.writeInt32(4, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, pageToken_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(parent_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, parent_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(filter_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, filter_);
}
if (pageSize_ != 0) {
size += com.google.protobuf.CodedOutputStream.computeInt32Size(4, pageSize_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(pageToken_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, pageToken_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.monitoring.v3.ListSnoozesRequest)) {
return super.equals(obj);
}
com.google.monitoring.v3.ListSnoozesRequest other =
(com.google.monitoring.v3.ListSnoozesRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getFilter().equals(other.getFilter())) return false;
if (getPageSize() != other.getPageSize()) return false;
if (!getPageToken().equals(other.getPageToken())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + PARENT_FIELD_NUMBER;
hash = (53 * hash) + getParent().hashCode();
hash = (37 * hash) + FILTER_FIELD_NUMBER;
hash = (53 * hash) + getFilter().hashCode();
hash = (37 * hash) + PAGE_SIZE_FIELD_NUMBER;
hash = (53 * hash) + getPageSize();
hash = (37 * hash) + PAGE_TOKEN_FIELD_NUMBER;
hash = (53 * hash) + getPageToken().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.monitoring.v3.ListSnoozesRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.ListSnoozesRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.ListSnoozesRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.ListSnoozesRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.ListSnoozesRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.ListSnoozesRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.ListSnoozesRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.ListSnoozesRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.ListSnoozesRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.ListSnoozesRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.ListSnoozesRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.ListSnoozesRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.monitoring.v3.ListSnoozesRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* The message definition for listing `Snooze`s associated with the given
* `parent`, satisfying the optional `filter`.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.ListSnoozesRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.monitoring.v3.ListSnoozesRequest)
com.google.monitoring.v3.ListSnoozesRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.SnoozeServiceProto
.internal_static_google_monitoring_v3_ListSnoozesRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.SnoozeServiceProto
.internal_static_google_monitoring_v3_ListSnoozesRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.ListSnoozesRequest.class,
com.google.monitoring.v3.ListSnoozesRequest.Builder.class);
}
// Construct using com.google.monitoring.v3.ListSnoozesRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
filter_ = "";
pageSize_ = 0;
pageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.monitoring.v3.SnoozeServiceProto
.internal_static_google_monitoring_v3_ListSnoozesRequest_descriptor;
}
@java.lang.Override
public com.google.monitoring.v3.ListSnoozesRequest getDefaultInstanceForType() {
return com.google.monitoring.v3.ListSnoozesRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.monitoring.v3.ListSnoozesRequest build() {
com.google.monitoring.v3.ListSnoozesRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.monitoring.v3.ListSnoozesRequest buildPartial() {
com.google.monitoring.v3.ListSnoozesRequest result =
new com.google.monitoring.v3.ListSnoozesRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.monitoring.v3.ListSnoozesRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.filter_ = filter_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.pageSize_ = pageSize_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.pageToken_ = pageToken_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.monitoring.v3.ListSnoozesRequest) {
return mergeFrom((com.google.monitoring.v3.ListSnoozesRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.monitoring.v3.ListSnoozesRequest other) {
if (other == com.google.monitoring.v3.ListSnoozesRequest.getDefaultInstance()) return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getFilter().isEmpty()) {
filter_ = other.filter_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.getPageSize() != 0) {
setPageSize(other.getPageSize());
}
if (!other.getPageToken().isEmpty()) {
pageToken_ = other.pageToken_;
bitField0_ |= 0x00000008;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
parent_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 32:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000004;
break;
} // case 32
case 42:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private java.lang.Object parent_ = "";
/**
*
*
* <pre>
* Required. The
* [project](https://cloud.google.com/monitoring/api/v3#project_name) whose
* `Snooze`s should be listed. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The parent.
*/
public java.lang.String getParent() {
java.lang.Object ref = parent_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
parent_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The
* [project](https://cloud.google.com/monitoring/api/v3#project_name) whose
* `Snooze`s should be listed. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for parent.
*/
public com.google.protobuf.ByteString getParentBytes() {
java.lang.Object ref = parent_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
parent_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The
* [project](https://cloud.google.com/monitoring/api/v3#project_name) whose
* `Snooze`s should be listed. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The parent to set.
* @return This builder for chaining.
*/
public Builder setParent(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The
* [project](https://cloud.google.com/monitoring/api/v3#project_name) whose
* `Snooze`s should be listed. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearParent() {
parent_ = getDefaultInstance().getParent();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The
* [project](https://cloud.google.com/monitoring/api/v3#project_name) whose
* `Snooze`s should be listed. The format is:
*
* projects/[PROJECT_ID_OR_NUMBER]
* </pre>
*
* <code>
* string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for parent to set.
* @return This builder for chaining.
*/
public Builder setParentBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
parent_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object filter_ = "";
/**
*
*
* <pre>
* Optional. Optional filter to restrict results to the given criteria. The
* following fields are supported.
*
* * `interval.start_time`
* * `interval.end_time`
*
* For example:
*
* interval.start_time > "2022-03-11T00:00:00-08:00" AND
* interval.end_time < "2022-03-12T00:00:00-08:00"
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The filter.
*/
public java.lang.String getFilter() {
java.lang.Object ref = filter_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
filter_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. Optional filter to restrict results to the given criteria. The
* following fields are supported.
*
* * `interval.start_time`
* * `interval.end_time`
*
* For example:
*
* interval.start_time > "2022-03-11T00:00:00-08:00" AND
* interval.end_time < "2022-03-12T00:00:00-08:00"
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for filter.
*/
public com.google.protobuf.ByteString getFilterBytes() {
java.lang.Object ref = filter_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
filter_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. Optional filter to restrict results to the given criteria. The
* following fields are supported.
*
* * `interval.start_time`
* * `interval.end_time`
*
* For example:
*
* interval.start_time > "2022-03-11T00:00:00-08:00" AND
* interval.end_time < "2022-03-12T00:00:00-08:00"
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The filter to set.
* @return This builder for chaining.
*/
public Builder setFilter(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
filter_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Optional filter to restrict results to the given criteria. The
* following fields are supported.
*
* * `interval.start_time`
* * `interval.end_time`
*
* For example:
*
* interval.start_time > "2022-03-11T00:00:00-08:00" AND
* interval.end_time < "2022-03-12T00:00:00-08:00"
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Optional filter to restrict results to the given criteria. The
* following fields are supported.
*
* * `interval.start_time`
* * `interval.end_time`
*
* For example:
*
* interval.start_time > "2022-03-11T00:00:00-08:00" AND
* interval.end_time < "2022-03-12T00:00:00-08:00"
* </pre>
*
* <code>string filter = 2 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for filter to set.
* @return This builder for chaining.
*/
public Builder setFilterBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
filter_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* Optional. The maximum number of results to return for a single query. The
* server may further constrain the maximum number of results returned in a
* single page. The value should be in the range [1, 1000]. If the value given
* is outside this range, the server will decide the number of results to be
* returned.
* </pre>
*
* <code>int32 page_size = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* Optional. The maximum number of results to return for a single query. The
* server may further constrain the maximum number of results returned in a
* single page. The value should be in the range [1, 1000]. If the value given
* is outside this range, the server will decide the number of results to be
* returned.
* </pre>
*
* <code>int32 page_size = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageSize to set.
* @return This builder for chaining.
*/
public Builder setPageSize(int value) {
pageSize_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The maximum number of results to return for a single query. The
* server may further constrain the maximum number of results returned in a
* single page. The value should be in the range [1, 1000]. If the value given
* is outside this range, the server will decide the number of results to be
* returned.
* </pre>
*
* <code>int32 page_size = 4 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000004);
pageSize_ = 0;
onChanged();
return this;
}
private java.lang.Object pageToken_ = "";
/**
*
*
* <pre>
* Optional. The `next_page_token` from a previous call to
* `ListSnoozesRequest` to get the next page of results.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The pageToken.
*/
public java.lang.String getPageToken() {
java.lang.Object ref = pageToken_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
pageToken_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Optional. The `next_page_token` from a previous call to
* `ListSnoozesRequest` to get the next page of results.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return The bytes for pageToken.
*/
public com.google.protobuf.ByteString getPageTokenBytes() {
java.lang.Object ref = pageToken_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
pageToken_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Optional. The `next_page_token` from a previous call to
* `ListSnoozesRequest` to get the next page of results.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageToken(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
pageToken_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The `next_page_token` from a previous call to
* `ListSnoozesRequest` to get the next page of results.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @return This builder for chaining.
*/
public Builder clearPageToken() {
pageToken_ = getDefaultInstance().getPageToken();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. The `next_page_token` from a previous call to
* `ListSnoozesRequest` to get the next page of results.
* </pre>
*
* <code>string page_token = 5 [(.google.api.field_behavior) = OPTIONAL];</code>
*
* @param value The bytes for pageToken to set.
* @return This builder for chaining.
*/
public Builder setPageTokenBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
pageToken_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.monitoring.v3.ListSnoozesRequest)
}
// @@protoc_insertion_point(class_scope:google.monitoring.v3.ListSnoozesRequest)
private static final com.google.monitoring.v3.ListSnoozesRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.monitoring.v3.ListSnoozesRequest();
}
public static com.google.monitoring.v3.ListSnoozesRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListSnoozesRequest> PARSER =
new com.google.protobuf.AbstractParser<ListSnoozesRequest>() {
@java.lang.Override
public ListSnoozesRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<ListSnoozesRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListSnoozesRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.monitoring.v3.ListSnoozesRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java
| 38,281
|
java-billing/google-cloud-billing/src/test/java/com/google/cloud/billing/v1/CloudBillingClientTest.java
|
/*
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.billing.v1;
import static com.google.cloud.billing.v1.CloudBillingClient.ListBillingAccountsPagedResponse;
import static com.google.cloud.billing.v1.CloudBillingClient.ListProjectBillingInfoPagedResponse;
import com.google.api.gax.core.NoCredentialsProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.testing.LocalChannelProvider;
import com.google.api.gax.grpc.testing.MockGrpcService;
import com.google.api.gax.grpc.testing.MockServiceHelper;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.api.resourcenames.ResourceName;
import com.google.common.collect.Lists;
import com.google.iam.v1.AuditConfig;
import com.google.iam.v1.Binding;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.iam.v1.TestIamPermissionsRequest;
import com.google.iam.v1.TestIamPermissionsResponse;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.ByteString;
import io.grpc.StatusRuntimeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import javax.annotation.Generated;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
@Generated("by gapic-generator-java")
public class CloudBillingClientTest {
private static MockCloudBilling mockCloudBilling;
private static MockServiceHelper mockServiceHelper;
private LocalChannelProvider channelProvider;
private CloudBillingClient client;
@BeforeClass
public static void startStaticServer() {
mockCloudBilling = new MockCloudBilling();
mockServiceHelper =
new MockServiceHelper(
UUID.randomUUID().toString(), Arrays.<MockGrpcService>asList(mockCloudBilling));
mockServiceHelper.start();
}
@AfterClass
public static void stopServer() {
mockServiceHelper.stop();
}
@Before
public void setUp() throws IOException {
mockServiceHelper.reset();
channelProvider = mockServiceHelper.createChannelProvider();
CloudBillingSettings settings =
CloudBillingSettings.newBuilder()
.setTransportChannelProvider(channelProvider)
.setCredentialsProvider(NoCredentialsProvider.create())
.build();
client = CloudBillingClient.create(settings);
}
@After
public void tearDown() throws Exception {
client.close();
}
@Test
public void getBillingAccountTest() throws Exception {
BillingAccount expectedResponse =
BillingAccount.newBuilder()
.setName(BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]").toString())
.setOpen(true)
.setDisplayName("displayName1714148973")
.setMasterBillingAccount("masterBillingAccount1488941620")
.setParent("parent-995424086")
.setCurrencyCode("currencyCode1004773790")
.build();
mockCloudBilling.addResponse(expectedResponse);
BillingAccountName name = BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]");
BillingAccount actualResponse = client.getBillingAccount(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetBillingAccountRequest actualRequest = ((GetBillingAccountRequest) actualRequests.get(0));
Assert.assertEquals(name.toString(), actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getBillingAccountExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
BillingAccountName name = BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]");
client.getBillingAccount(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getBillingAccountTest2() throws Exception {
BillingAccount expectedResponse =
BillingAccount.newBuilder()
.setName(BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]").toString())
.setOpen(true)
.setDisplayName("displayName1714148973")
.setMasterBillingAccount("masterBillingAccount1488941620")
.setParent("parent-995424086")
.setCurrencyCode("currencyCode1004773790")
.build();
mockCloudBilling.addResponse(expectedResponse);
String name = "name3373707";
BillingAccount actualResponse = client.getBillingAccount(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetBillingAccountRequest actualRequest = ((GetBillingAccountRequest) actualRequests.get(0));
Assert.assertEquals(name, actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getBillingAccountExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
String name = "name3373707";
client.getBillingAccount(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listBillingAccountsTest() throws Exception {
BillingAccount responsesElement = BillingAccount.newBuilder().build();
ListBillingAccountsResponse expectedResponse =
ListBillingAccountsResponse.newBuilder()
.setNextPageToken("")
.addAllBillingAccounts(Arrays.asList(responsesElement))
.build();
mockCloudBilling.addResponse(expectedResponse);
ListBillingAccountsPagedResponse pagedListResponse = client.listBillingAccounts();
List<BillingAccount> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getBillingAccountsList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListBillingAccountsRequest actualRequest = ((ListBillingAccountsRequest) actualRequests.get(0));
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listBillingAccountsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
ListBillingAccountsRequest request =
ListBillingAccountsRequest.newBuilder()
.setPageSize(883849137)
.setPageToken("pageToken873572522")
.setFilter("filter-1274492040")
.setParent("parent-995424086")
.build();
client.listBillingAccounts(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listBillingAccountsTest2() throws Exception {
BillingAccount responsesElement = BillingAccount.newBuilder().build();
ListBillingAccountsResponse expectedResponse =
ListBillingAccountsResponse.newBuilder()
.setNextPageToken("")
.addAllBillingAccounts(Arrays.asList(responsesElement))
.build();
mockCloudBilling.addResponse(expectedResponse);
String parent = "parent-995424086";
ListBillingAccountsPagedResponse pagedListResponse = client.listBillingAccounts(parent);
List<BillingAccount> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getBillingAccountsList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListBillingAccountsRequest actualRequest = ((ListBillingAccountsRequest) actualRequests.get(0));
Assert.assertEquals(parent, actualRequest.getParent());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listBillingAccountsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
String parent = "parent-995424086";
client.listBillingAccounts(parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updateBillingAccountTest() throws Exception {
BillingAccount expectedResponse =
BillingAccount.newBuilder()
.setName(BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]").toString())
.setOpen(true)
.setDisplayName("displayName1714148973")
.setMasterBillingAccount("masterBillingAccount1488941620")
.setParent("parent-995424086")
.setCurrencyCode("currencyCode1004773790")
.build();
mockCloudBilling.addResponse(expectedResponse);
BillingAccountName name = BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]");
BillingAccount account = BillingAccount.newBuilder().build();
BillingAccount actualResponse = client.updateBillingAccount(name, account);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
UpdateBillingAccountRequest actualRequest =
((UpdateBillingAccountRequest) actualRequests.get(0));
Assert.assertEquals(name.toString(), actualRequest.getName());
Assert.assertEquals(account, actualRequest.getAccount());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void updateBillingAccountExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
BillingAccountName name = BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]");
BillingAccount account = BillingAccount.newBuilder().build();
client.updateBillingAccount(name, account);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updateBillingAccountTest2() throws Exception {
BillingAccount expectedResponse =
BillingAccount.newBuilder()
.setName(BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]").toString())
.setOpen(true)
.setDisplayName("displayName1714148973")
.setMasterBillingAccount("masterBillingAccount1488941620")
.setParent("parent-995424086")
.setCurrencyCode("currencyCode1004773790")
.build();
mockCloudBilling.addResponse(expectedResponse);
String name = "name3373707";
BillingAccount account = BillingAccount.newBuilder().build();
BillingAccount actualResponse = client.updateBillingAccount(name, account);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
UpdateBillingAccountRequest actualRequest =
((UpdateBillingAccountRequest) actualRequests.get(0));
Assert.assertEquals(name, actualRequest.getName());
Assert.assertEquals(account, actualRequest.getAccount());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void updateBillingAccountExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
String name = "name3373707";
BillingAccount account = BillingAccount.newBuilder().build();
client.updateBillingAccount(name, account);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void createBillingAccountTest() throws Exception {
BillingAccount expectedResponse =
BillingAccount.newBuilder()
.setName(BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]").toString())
.setOpen(true)
.setDisplayName("displayName1714148973")
.setMasterBillingAccount("masterBillingAccount1488941620")
.setParent("parent-995424086")
.setCurrencyCode("currencyCode1004773790")
.build();
mockCloudBilling.addResponse(expectedResponse);
BillingAccount billingAccount = BillingAccount.newBuilder().build();
BillingAccount actualResponse = client.createBillingAccount(billingAccount);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
CreateBillingAccountRequest actualRequest =
((CreateBillingAccountRequest) actualRequests.get(0));
Assert.assertEquals(billingAccount, actualRequest.getBillingAccount());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void createBillingAccountExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
BillingAccount billingAccount = BillingAccount.newBuilder().build();
client.createBillingAccount(billingAccount);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void createBillingAccountTest2() throws Exception {
BillingAccount expectedResponse =
BillingAccount.newBuilder()
.setName(BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]").toString())
.setOpen(true)
.setDisplayName("displayName1714148973")
.setMasterBillingAccount("masterBillingAccount1488941620")
.setParent("parent-995424086")
.setCurrencyCode("currencyCode1004773790")
.build();
mockCloudBilling.addResponse(expectedResponse);
BillingAccount billingAccount = BillingAccount.newBuilder().build();
String parent = "parent-995424086";
BillingAccount actualResponse = client.createBillingAccount(billingAccount, parent);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
CreateBillingAccountRequest actualRequest =
((CreateBillingAccountRequest) actualRequests.get(0));
Assert.assertEquals(billingAccount, actualRequest.getBillingAccount());
Assert.assertEquals(parent, actualRequest.getParent());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void createBillingAccountExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
BillingAccount billingAccount = BillingAccount.newBuilder().build();
String parent = "parent-995424086";
client.createBillingAccount(billingAccount, parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listProjectBillingInfoTest() throws Exception {
ProjectBillingInfo responsesElement = ProjectBillingInfo.newBuilder().build();
ListProjectBillingInfoResponse expectedResponse =
ListProjectBillingInfoResponse.newBuilder()
.setNextPageToken("")
.addAllProjectBillingInfo(Arrays.asList(responsesElement))
.build();
mockCloudBilling.addResponse(expectedResponse);
BillingAccountName name = BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]");
ListProjectBillingInfoPagedResponse pagedListResponse = client.listProjectBillingInfo(name);
List<ProjectBillingInfo> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getProjectBillingInfoList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListProjectBillingInfoRequest actualRequest =
((ListProjectBillingInfoRequest) actualRequests.get(0));
Assert.assertEquals(name.toString(), actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listProjectBillingInfoExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
BillingAccountName name = BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]");
client.listProjectBillingInfo(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listProjectBillingInfoTest2() throws Exception {
ProjectBillingInfo responsesElement = ProjectBillingInfo.newBuilder().build();
ListProjectBillingInfoResponse expectedResponse =
ListProjectBillingInfoResponse.newBuilder()
.setNextPageToken("")
.addAllProjectBillingInfo(Arrays.asList(responsesElement))
.build();
mockCloudBilling.addResponse(expectedResponse);
String name = "name3373707";
ListProjectBillingInfoPagedResponse pagedListResponse = client.listProjectBillingInfo(name);
List<ProjectBillingInfo> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getProjectBillingInfoList().get(0), resources.get(0));
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
ListProjectBillingInfoRequest actualRequest =
((ListProjectBillingInfoRequest) actualRequests.get(0));
Assert.assertEquals(name, actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void listProjectBillingInfoExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
String name = "name3373707";
client.listProjectBillingInfo(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getProjectBillingInfoTest() throws Exception {
ProjectBillingInfo expectedResponse =
ProjectBillingInfo.newBuilder()
.setName("name3373707")
.setProjectId("projectId-894832108")
.setBillingAccountName("billingAccountName929322205")
.setBillingEnabled(true)
.build();
mockCloudBilling.addResponse(expectedResponse);
ProjectName name = ProjectName.of("[PROJECT]");
ProjectBillingInfo actualResponse = client.getProjectBillingInfo(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetProjectBillingInfoRequest actualRequest =
((GetProjectBillingInfoRequest) actualRequests.get(0));
Assert.assertEquals(name.toString(), actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getProjectBillingInfoExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
ProjectName name = ProjectName.of("[PROJECT]");
client.getProjectBillingInfo(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getProjectBillingInfoTest2() throws Exception {
ProjectBillingInfo expectedResponse =
ProjectBillingInfo.newBuilder()
.setName("name3373707")
.setProjectId("projectId-894832108")
.setBillingAccountName("billingAccountName929322205")
.setBillingEnabled(true)
.build();
mockCloudBilling.addResponse(expectedResponse);
String name = "name3373707";
ProjectBillingInfo actualResponse = client.getProjectBillingInfo(name);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetProjectBillingInfoRequest actualRequest =
((GetProjectBillingInfoRequest) actualRequests.get(0));
Assert.assertEquals(name, actualRequest.getName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getProjectBillingInfoExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
String name = "name3373707";
client.getProjectBillingInfo(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updateProjectBillingInfoTest() throws Exception {
ProjectBillingInfo expectedResponse =
ProjectBillingInfo.newBuilder()
.setName("name3373707")
.setProjectId("projectId-894832108")
.setBillingAccountName("billingAccountName929322205")
.setBillingEnabled(true)
.build();
mockCloudBilling.addResponse(expectedResponse);
String name = "name3373707";
ProjectBillingInfo projectBillingInfo = ProjectBillingInfo.newBuilder().build();
ProjectBillingInfo actualResponse = client.updateProjectBillingInfo(name, projectBillingInfo);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
UpdateProjectBillingInfoRequest actualRequest =
((UpdateProjectBillingInfoRequest) actualRequests.get(0));
Assert.assertEquals(name, actualRequest.getName());
Assert.assertEquals(projectBillingInfo, actualRequest.getProjectBillingInfo());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void updateProjectBillingInfoExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
String name = "name3373707";
ProjectBillingInfo projectBillingInfo = ProjectBillingInfo.newBuilder().build();
client.updateProjectBillingInfo(name, projectBillingInfo);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getIamPolicyTest() throws Exception {
Policy expectedResponse =
Policy.newBuilder()
.setVersion(351608024)
.addAllBindings(new ArrayList<Binding>())
.addAllAuditConfigs(new ArrayList<AuditConfig>())
.setEtag(ByteString.EMPTY)
.build();
mockCloudBilling.addResponse(expectedResponse);
ResourceName resource = BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]");
Policy actualResponse = client.getIamPolicy(resource);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetIamPolicyRequest actualRequest = ((GetIamPolicyRequest) actualRequests.get(0));
Assert.assertEquals(resource.toString(), actualRequest.getResource());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getIamPolicyExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
ResourceName resource = BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]");
client.getIamPolicy(resource);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getIamPolicyTest2() throws Exception {
Policy expectedResponse =
Policy.newBuilder()
.setVersion(351608024)
.addAllBindings(new ArrayList<Binding>())
.addAllAuditConfigs(new ArrayList<AuditConfig>())
.setEtag(ByteString.EMPTY)
.build();
mockCloudBilling.addResponse(expectedResponse);
String resource = "resource-341064690";
Policy actualResponse = client.getIamPolicy(resource);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetIamPolicyRequest actualRequest = ((GetIamPolicyRequest) actualRequests.get(0));
Assert.assertEquals(resource, actualRequest.getResource());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void getIamPolicyExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
String resource = "resource-341064690";
client.getIamPolicy(resource);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void setIamPolicyTest() throws Exception {
Policy expectedResponse =
Policy.newBuilder()
.setVersion(351608024)
.addAllBindings(new ArrayList<Binding>())
.addAllAuditConfigs(new ArrayList<AuditConfig>())
.setEtag(ByteString.EMPTY)
.build();
mockCloudBilling.addResponse(expectedResponse);
ResourceName resource = BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]");
Policy policy = Policy.newBuilder().build();
Policy actualResponse = client.setIamPolicy(resource, policy);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
SetIamPolicyRequest actualRequest = ((SetIamPolicyRequest) actualRequests.get(0));
Assert.assertEquals(resource.toString(), actualRequest.getResource());
Assert.assertEquals(policy, actualRequest.getPolicy());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void setIamPolicyExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
ResourceName resource = BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]");
Policy policy = Policy.newBuilder().build();
client.setIamPolicy(resource, policy);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void setIamPolicyTest2() throws Exception {
Policy expectedResponse =
Policy.newBuilder()
.setVersion(351608024)
.addAllBindings(new ArrayList<Binding>())
.addAllAuditConfigs(new ArrayList<AuditConfig>())
.setEtag(ByteString.EMPTY)
.build();
mockCloudBilling.addResponse(expectedResponse);
String resource = "resource-341064690";
Policy policy = Policy.newBuilder().build();
Policy actualResponse = client.setIamPolicy(resource, policy);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
SetIamPolicyRequest actualRequest = ((SetIamPolicyRequest) actualRequests.get(0));
Assert.assertEquals(resource, actualRequest.getResource());
Assert.assertEquals(policy, actualRequest.getPolicy());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void setIamPolicyExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
String resource = "resource-341064690";
Policy policy = Policy.newBuilder().build();
client.setIamPolicy(resource, policy);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void testIamPermissionsTest() throws Exception {
TestIamPermissionsResponse expectedResponse =
TestIamPermissionsResponse.newBuilder().addAllPermissions(new ArrayList<String>()).build();
mockCloudBilling.addResponse(expectedResponse);
ResourceName resource = BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]");
List<String> permissions = new ArrayList<>();
TestIamPermissionsResponse actualResponse = client.testIamPermissions(resource, permissions);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
TestIamPermissionsRequest actualRequest = ((TestIamPermissionsRequest) actualRequests.get(0));
Assert.assertEquals(resource.toString(), actualRequest.getResource());
Assert.assertEquals(permissions, actualRequest.getPermissionsList());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void testIamPermissionsExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
ResourceName resource = BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]");
List<String> permissions = new ArrayList<>();
client.testIamPermissions(resource, permissions);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void testIamPermissionsTest2() throws Exception {
TestIamPermissionsResponse expectedResponse =
TestIamPermissionsResponse.newBuilder().addAllPermissions(new ArrayList<String>()).build();
mockCloudBilling.addResponse(expectedResponse);
String resource = "resource-341064690";
List<String> permissions = new ArrayList<>();
TestIamPermissionsResponse actualResponse = client.testIamPermissions(resource, permissions);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
TestIamPermissionsRequest actualRequest = ((TestIamPermissionsRequest) actualRequests.get(0));
Assert.assertEquals(resource, actualRequest.getResource());
Assert.assertEquals(permissions, actualRequest.getPermissionsList());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void testIamPermissionsExceptionTest2() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
String resource = "resource-341064690";
List<String> permissions = new ArrayList<>();
client.testIamPermissions(resource, permissions);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void moveBillingAccountTest() throws Exception {
BillingAccount expectedResponse =
BillingAccount.newBuilder()
.setName(BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]").toString())
.setOpen(true)
.setDisplayName("displayName1714148973")
.setMasterBillingAccount("masterBillingAccount1488941620")
.setParent("parent-995424086")
.setCurrencyCode("currencyCode1004773790")
.build();
mockCloudBilling.addResponse(expectedResponse);
MoveBillingAccountRequest request =
MoveBillingAccountRequest.newBuilder()
.setName(BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]").toString())
.setDestinationParent(OrganizationName.of("[ORGANIZATION]").toString())
.build();
BillingAccount actualResponse = client.moveBillingAccount(request);
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockCloudBilling.getRequests();
Assert.assertEquals(1, actualRequests.size());
MoveBillingAccountRequest actualRequest = ((MoveBillingAccountRequest) actualRequests.get(0));
Assert.assertEquals(request.getName(), actualRequest.getName());
Assert.assertEquals(request.getDestinationParent(), actualRequest.getDestinationParent());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
@Test
public void moveBillingAccountExceptionTest() throws Exception {
StatusRuntimeException exception = new StatusRuntimeException(io.grpc.Status.INVALID_ARGUMENT);
mockCloudBilling.addException(exception);
try {
MoveBillingAccountRequest request =
MoveBillingAccountRequest.newBuilder()
.setName(BillingAccountName.ofBillingAccountName("[BILLING_ACCOUNT]").toString())
.setDestinationParent(OrganizationName.of("[ORGANIZATION]").toString())
.build();
client.moveBillingAccount(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.