repo_id stringclasses 875
values | size int64 974 38.9k | file_path stringlengths 10 308 | content stringlengths 974 38.9k |
|---|---|---|---|
apache/ozone | 35,886 | hadoop-hdds/server-scm/src/test/java/org/apache/hadoop/hdds/scm/block/TestDeletedBlockLog.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.hdds.scm.block;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import org.apache.commons.lang3.RandomUtils;
import org.apache.hadoop.hdds.HddsConfigKeys;
import org.apache.hadoop.hdds.client.RatisReplicationConfig;
import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.hdds.conf.StorageUnit;
import org.apache.hadoop.hdds.protocol.DatanodeDetails;
import org.apache.hadoop.hdds.protocol.DatanodeID;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
import org.apache.hadoop.hdds.protocol.proto.HddsProtos.ReplicationFactor;
import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos;
import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.ContainerBlocksDeletionACKProto.DeleteBlockTransactionResult;
import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.ContainerReplicaProto;
import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.DeletedBlocksTransaction;
import org.apache.hadoop.hdds.protocol.proto.StorageContainerDatanodeProtocolProtos.SCMCommandProto.Type;
import org.apache.hadoop.hdds.scm.HddsTestUtils;
import org.apache.hadoop.hdds.scm.ScmConfigKeys;
import org.apache.hadoop.hdds.scm.container.ContainerID;
import org.apache.hadoop.hdds.scm.container.ContainerInfo;
import org.apache.hadoop.hdds.scm.container.ContainerManager;
import org.apache.hadoop.hdds.scm.container.ContainerReplica;
import org.apache.hadoop.hdds.scm.container.replication.ContainerHealthResult;
import org.apache.hadoop.hdds.scm.container.replication.ReplicationManager;
import org.apache.hadoop.hdds.scm.ha.SCMHADBTransactionBuffer;
import org.apache.hadoop.hdds.scm.ha.SCMHADBTransactionBufferStub;
import org.apache.hadoop.hdds.scm.ha.SCMHAManagerStub;
import org.apache.hadoop.hdds.scm.pipeline.Pipeline;
import org.apache.hadoop.hdds.scm.pipeline.PipelineID;
import org.apache.hadoop.hdds.scm.server.SCMConfigurator;
import org.apache.hadoop.hdds.scm.server.StorageContainerManager;
import org.apache.hadoop.hdds.utils.db.Table;
import org.apache.hadoop.ozone.protocol.commands.CommandStatus;
import org.apache.hadoop.ozone.protocol.commands.DeleteBlocksCommand;
import org.apache.hadoop.ozone.protocol.commands.SCMCommand;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/**
* Tests for DeletedBlockLog.
*/
public class TestDeletedBlockLog {
private DeletedBlockLogImpl deletedBlockLog;
private static final int BLOCKS_PER_TXN = 5;
private OzoneConfiguration conf;
@TempDir
private File testDir;
private ContainerManager containerManager;
private Table<ContainerID, ContainerInfo> containerTable;
private StorageContainerManager scm;
private List<DatanodeDetails> dnList;
private SCMHADBTransactionBuffer scmHADBTransactionBuffer;
private final Map<ContainerID, ContainerInfo> containers = new HashMap<>();
private final Map<ContainerID, Set<ContainerReplica>> replicas = new HashMap<>();
private ScmBlockDeletingServiceMetrics metrics;
private static final int THREE = ReplicationFactor.THREE_VALUE;
private static final int ONE = ReplicationFactor.ONE_VALUE;
private ReplicationManager replicationManager;
@BeforeEach
public void setup() throws Exception {
conf = new OzoneConfiguration();
conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, testDir.getAbsolutePath());
replicationManager = mock(ReplicationManager.class);
SCMConfigurator configurator = new SCMConfigurator();
configurator.setSCMHAManager(SCMHAManagerStub.getInstance(true));
configurator.setReplicationManager(replicationManager);
scm = HddsTestUtils.getScm(conf, configurator);
containerManager = mock(ContainerManager.class);
containerTable = scm.getScmMetadataStore().getContainerTable();
scmHADBTransactionBuffer =
new SCMHADBTransactionBufferStub(scm.getScmMetadataStore().getStore());
metrics = mock(ScmBlockDeletingServiceMetrics.class);
deletedBlockLog = new DeletedBlockLogImpl(conf,
scm,
containerManager,
scmHADBTransactionBuffer,
metrics);
dnList = new ArrayList<>(3);
setupContainerManager();
}
private void setupContainerManager() throws IOException {
dnList.add(
DatanodeDetails.newBuilder().setUuid(UUID.randomUUID())
.build());
dnList.add(
DatanodeDetails.newBuilder().setUuid(UUID.randomUUID())
.build());
dnList.add(
DatanodeDetails.newBuilder().setUuid(UUID.randomUUID())
.build());
when(containerManager.getContainerReplicas(any()))
.thenAnswer(invocationOnMock -> {
ContainerID cid = (ContainerID) invocationOnMock.getArguments()[0];
return replicas.get(cid);
});
when(containerManager.getContainer(any()))
.thenAnswer(invocationOnMock -> {
ContainerID cid = (ContainerID) invocationOnMock.getArguments()[0];
return containerTable.get(cid);
});
when(containerManager.getContainers())
.thenReturn(new ArrayList<>(containers.values()));
doAnswer(invocationOnMock -> {
Map<ContainerID, Long> map =
(Map<ContainerID, Long>) invocationOnMock.getArguments()[0];
for (Map.Entry<ContainerID, Long> e : map.entrySet()) {
ContainerInfo info = containers.get(e.getKey());
try {
assertThat(e.getValue()).isGreaterThan(info.getDeleteTransactionId());
} catch (AssertionError err) {
throw new Exception("New TxnId " + e.getValue() + " < " + info
.getDeleteTransactionId());
}
info.updateDeleteTransactionId(e.getValue());
scmHADBTransactionBuffer.addToBuffer(containerTable, e.getKey(), info);
}
return null;
}).when(containerManager).updateDeleteTransactionId(any());
}
private void updateContainerMetadata(long cid,
HddsProtos.LifeCycleState state) throws IOException {
final ContainerInfo container =
new ContainerInfo.Builder()
.setContainerID(cid)
.setReplicationConfig(RatisReplicationConfig.getInstance(
ReplicationFactor.THREE))
.setState(state)
.setOwner("TestDeletedBlockLog")
.setPipelineID(PipelineID.randomId())
.build();
final Set<ContainerReplica> replicaSet = dnList.stream()
.map(datanodeDetails -> ContainerReplica.newBuilder()
.setContainerID(container.containerID())
.setContainerState(ContainerReplicaProto.State.OPEN)
.setDatanodeDetails(datanodeDetails)
.build())
.collect(Collectors.toSet());
final ContainerID containerID = container.containerID();
containers.put(containerID, container);
containerTable.put(containerID, container);
replicas.put(containerID, replicaSet);
}
@AfterEach
public void tearDown() throws Exception {
deletedBlockLog.close();
scm.stop();
scm.join();
}
private Map<Long, List<Long>> generateData(int dataSize) throws IOException {
return generateData(dataSize, HddsProtos.LifeCycleState.CLOSED);
}
private Map<Long, List<Long>> generateData(int dataSize,
HddsProtos.LifeCycleState state) throws IOException {
Map<Long, List<Long>> blockMap = new HashMap<>();
int continerIDBase = RandomUtils.secure().randomInt(0, 100);
int localIDBase = RandomUtils.secure().randomInt(0, 1000);
for (int i = 0; i < dataSize; i++) {
long containerID = continerIDBase + i;
updateContainerMetadata(containerID, state);
List<Long> blocks = new ArrayList<>();
for (int j = 0; j < BLOCKS_PER_TXN; j++) {
long localID = localIDBase + j;
blocks.add(localID);
}
blockMap.put(containerID, blocks);
}
return blockMap;
}
private void addTransactions(Map<Long, List<Long>> containerBlocksMap,
boolean shouldFlush) throws IOException {
deletedBlockLog.addTransactions(containerBlocksMap);
if (shouldFlush) {
scmHADBTransactionBuffer.flush();
}
}
private void commitTransactions(
List<DeleteBlockTransactionResult> transactionResults,
DatanodeDetails... dns) throws IOException {
for (DatanodeDetails dnDetails : dns) {
deletedBlockLog.getSCMDeletedBlockTransactionStatusManager()
.commitTransactions(transactionResults, dnDetails.getID());
}
scmHADBTransactionBuffer.flush();
}
private void commitTransactions(
List<DeleteBlockTransactionResult> transactionResults)
throws IOException {
commitTransactions(transactionResults,
dnList.toArray(new DatanodeDetails[0]));
}
private void commitTransactions(
Collection<DeletedBlocksTransaction> deletedBlocksTransactions,
DatanodeDetails... dns) throws IOException {
commitTransactions(deletedBlocksTransactions.stream()
.map(this::createDeleteBlockTransactionResult)
.collect(Collectors.toList()), dns);
}
private void commitTransactions(
Collection<DeletedBlocksTransaction> deletedBlocksTransactions)
throws IOException {
commitTransactions(deletedBlocksTransactions.stream()
.map(this::createDeleteBlockTransactionResult)
.collect(Collectors.toList()));
}
private DeleteBlockTransactionResult createDeleteBlockTransactionResult(
DeletedBlocksTransaction transaction) {
return DeleteBlockTransactionResult.newBuilder()
.setContainerID(transaction.getContainerID()).setSuccess(true)
.setTxID(transaction.getTxID()).build();
}
private List<DeletedBlocksTransaction> getAllTransactions() throws Exception {
return getTransactions(Integer.MAX_VALUE);
}
private List<DeletedBlocksTransaction> getTransactions(
int maximumAllowedBlocksNum) throws IOException {
DatanodeDeletedBlockTransactions transactions =
deletedBlockLog.getTransactions(maximumAllowedBlocksNum, new HashSet<>(dnList));
List<DeletedBlocksTransaction> txns = new LinkedList<>();
for (DatanodeDetails dn : dnList) {
txns.addAll(Optional.ofNullable(
transactions.getDatanodeTransactionMap().get(dn.getID()))
.orElseGet(LinkedList::new));
}
// Simulated transactions are sent
for (Map.Entry<DatanodeID, List<DeletedBlocksTransaction>> entry :
transactions.getDatanodeTransactionMap().entrySet()) {
DeleteBlocksCommand command = new DeleteBlocksCommand(entry.getValue());
recordScmCommandToStatusManager(entry.getKey(), command);
sendSCMDeleteBlocksCommand(entry.getKey(), command);
}
return txns;
}
@Test
public void testContainerManagerTransactionId() throws Exception {
// Initially all containers should have deleteTransactionId as 0
for (ContainerInfo containerInfo : containerManager.getContainers()) {
assertEquals(0, containerInfo.getDeleteTransactionId());
}
// Create 30 TXs
addTransactions(generateData(30), false);
// Since transactions are not yet flushed deleteTransactionId should be
// 0 for all containers
assertEquals(0, getAllTransactions().size());
for (ContainerInfo containerInfo : containerManager.getContainers()) {
assertEquals(0, containerInfo.getDeleteTransactionId());
}
scmHADBTransactionBuffer.flush();
// After flush there should be 30 transactions in deleteTable
// All containers should have positive deleteTransactionId
mockContainerHealthResult(true);
assertEquals(30 * THREE, getAllTransactions().size());
for (ContainerInfo containerInfo : containerManager.getContainers()) {
assertThat(containerInfo.getDeleteTransactionId()).isGreaterThan(0);
}
}
private void mockContainerHealthResult(Boolean healthy) {
ContainerInfo containerInfo = mock(ContainerInfo.class);
ContainerHealthResult healthResult =
new ContainerHealthResult.HealthyResult(containerInfo);
if (!healthy) {
healthResult = new ContainerHealthResult.UnHealthyResult(containerInfo);
}
doReturn(healthResult).when(replicationManager)
.getContainerReplicationHealth(any(), any());
}
@Test
public void testAddTransactionsIsBatched() throws Exception {
conf.setStorageSize(ScmConfigKeys.OZONE_SCM_HA_RAFT_LOG_APPENDER_QUEUE_BYTE_LIMIT, 1, StorageUnit.KB);
DeletedBlockLogStateManager mockStateManager = mock(DeletedBlockLogStateManager.class);
DeletedBlockLogImpl log = new DeletedBlockLogImpl(conf, scm, containerManager, scmHADBTransactionBuffer, metrics);
log.setDeletedBlockLogStateManager(mockStateManager);
Map<Long, List<Long>> containerBlocksMap = generateData(100);
log.addTransactions(containerBlocksMap);
verify(mockStateManager, atLeast(2)).addTransactionsToDB(any());
}
@Test
public void testSCMDelIteratorProgress() throws Exception {
// Create 8 TXs in the log.
int noOfTransactions = 8;
addTransactions(generateData(noOfTransactions), true);
mockContainerHealthResult(true);
List<DeletedBlocksTransaction> blocks;
int i = 1;
while (i < noOfTransactions) {
// In each iteration read two transactions, API returns all the transactions in order.
// 1st iteration: {1, 2}
// 2nd iteration: {3, 4}
// 3rd iteration: {5, 6}
// 4th iteration: {7, 8}
blocks = getTransactions(2 * BLOCKS_PER_TXN * THREE);
assertEquals(blocks.get(0).getTxID(), i++);
assertEquals(blocks.get(1).getTxID(), i++);
}
// Since all the transactions are in-flight, the getTransaction should return empty list.
blocks = getTransactions(2 * BLOCKS_PER_TXN * THREE);
assertTrue(blocks.isEmpty());
}
@Test
public void testCommitTransactions() throws Exception {
deletedBlockLog.setScmCommandTimeoutMs(Long.MAX_VALUE);
addTransactions(generateData(50), true);
mockContainerHealthResult(true);
List<DeletedBlocksTransaction> blocks =
getTransactions(20 * BLOCKS_PER_TXN * THREE);
// Add an invalid txn.
blocks.add(
DeletedBlocksTransaction.newBuilder().setContainerID(1).setTxID(70)
.setCount(0).addLocalID(0).build());
commitTransactions(blocks);
blocks = getTransactions(50 * BLOCKS_PER_TXN * THREE);
assertEquals(30 * THREE, blocks.size());
commitTransactions(blocks, dnList.get(1), dnList.get(2),
DatanodeDetails.newBuilder().setUuid(UUID.randomUUID())
.build());
blocks = getTransactions(50 * BLOCKS_PER_TXN * THREE);
// SCM will not repeat a transaction until it has timed out.
assertEquals(0, blocks.size());
// Lets the SCM delete the transaction and wait for the DN reply
// to timeout, thus allowing the transaction to resend the
deletedBlockLog.setScmCommandTimeoutMs(-1L);
blocks = getTransactions(50 * BLOCKS_PER_TXN * THREE);
// only uncommitted dn have transactions
assertEquals(30, blocks.size());
commitTransactions(blocks, dnList.get(0));
blocks = getTransactions(50 * BLOCKS_PER_TXN * THREE);
assertEquals(0, blocks.size());
}
private void recordScmCommandToStatusManager(
DatanodeID dnId, DeleteBlocksCommand command) {
Set<Long> dnTxSet = command.blocksTobeDeleted()
.stream().map(DeletedBlocksTransaction::getTxID)
.collect(Collectors.toSet());
deletedBlockLog.recordTransactionCreated(dnId, command.getId(), dnTxSet);
}
private void sendSCMDeleteBlocksCommand(DatanodeID dnId, SCMCommand<?> scmCommand) {
deletedBlockLog.onSent(DatanodeDetails.newBuilder().setID(dnId).build(), scmCommand);
}
private void assertNoDuplicateTransactions(
DatanodeDeletedBlockTransactions transactions1,
DatanodeDeletedBlockTransactions transactions2) {
Map<DatanodeID, List<DeletedBlocksTransaction>> map1 =
transactions1.getDatanodeTransactionMap();
Map<DatanodeID, List<DeletedBlocksTransaction>> map2 =
transactions2.getDatanodeTransactionMap();
for (Map.Entry<DatanodeID, List<DeletedBlocksTransaction>> entry :
map1.entrySet()) {
DatanodeID dnId = entry.getKey();
Set<DeletedBlocksTransaction> txSet1 = new HashSet<>(entry.getValue());
Set<DeletedBlocksTransaction> txSet2 = new HashSet<>(map2.get(dnId));
txSet1.retainAll(txSet2);
assertEquals(0, txSet1.size(),
String.format("Duplicate Transactions found first transactions %s " +
"second transactions %s for Dn %s", txSet1, txSet2, dnId));
}
}
private void assertContainsAllTransactions(
DatanodeDeletedBlockTransactions transactions1,
DatanodeDeletedBlockTransactions transactions2) {
Map<DatanodeID, List<DeletedBlocksTransaction>> map1 =
transactions1.getDatanodeTransactionMap();
Map<DatanodeID, List<DeletedBlocksTransaction>> map2 =
transactions2.getDatanodeTransactionMap();
for (Map.Entry<DatanodeID, List<DeletedBlocksTransaction>> entry :
map1.entrySet()) {
DatanodeID dnId = entry.getKey();
Set<DeletedBlocksTransaction> txSet1 = new HashSet<>(entry.getValue());
Set<DeletedBlocksTransaction> txSet2 = new HashSet<>(map2.get(dnId));
assertThat(txSet1).containsAll(txSet2);
}
}
private void commitSCMCommandStatus(Long scmCmdId, DatanodeID dnID,
StorageContainerDatanodeProtocolProtos.CommandStatus.Status status) {
List<StorageContainerDatanodeProtocolProtos
.CommandStatus> deleteBlockStatus = new ArrayList<>();
deleteBlockStatus.add(CommandStatus.CommandStatusBuilder.newBuilder()
.setCmdId(scmCmdId)
.setType(Type.deleteBlocksCommand)
.setStatus(status)
.build()
.getProtoBufMessage());
deletedBlockLog.getSCMDeletedBlockTransactionStatusManager()
.commitSCMCommandStatus(deleteBlockStatus, dnID);
}
private void createDeleteBlocksCommandAndAction(
DatanodeDeletedBlockTransactions transactions,
BiConsumer<DatanodeID, DeleteBlocksCommand> afterCreate) {
for (Map.Entry<DatanodeID, List<DeletedBlocksTransaction>> entry :
transactions.getDatanodeTransactionMap().entrySet()) {
DatanodeID dnId = entry.getKey();
List<DeletedBlocksTransaction> dnTXs = entry.getValue();
DeleteBlocksCommand command = new DeleteBlocksCommand(dnTXs);
afterCreate.accept(dnId, command);
}
}
@Test
public void testNoDuplicateTransactionsForInProcessingSCMCommand()
throws Exception {
// The SCM will not resend these transactions in blow case:
// - If the command has not been sent;
// - The DN does not report the status of the command via heartbeat
// After the command is sent;
// - If the DN reports the command status as PENDING;
addTransactions(generateData(10), true);
int blockLimit = 2 * BLOCKS_PER_TXN * THREE;
mockContainerHealthResult(true);
// If the command has not been sent
DatanodeDeletedBlockTransactions transactions1 =
deletedBlockLog.getTransactions(blockLimit, new HashSet<>(dnList));
createDeleteBlocksCommandAndAction(transactions1,
this::recordScmCommandToStatusManager);
// - The DN does not report the status of the command via heartbeat
// After the command is sent
DatanodeDeletedBlockTransactions transactions2 =
deletedBlockLog.getTransactions(blockLimit, new HashSet<>(dnList));
assertNoDuplicateTransactions(transactions1, transactions2);
createDeleteBlocksCommandAndAction(transactions2, (dnId, command) -> {
recordScmCommandToStatusManager(dnId, command);
sendSCMDeleteBlocksCommand(dnId, command);
});
// - If the DN reports the command status as PENDING
DatanodeDeletedBlockTransactions transactions3 =
deletedBlockLog.getTransactions(blockLimit, new HashSet<>(dnList));
assertNoDuplicateTransactions(transactions1, transactions3);
createDeleteBlocksCommandAndAction(transactions3, (dnId, command) -> {
recordScmCommandToStatusManager(dnId, command);
sendSCMDeleteBlocksCommand(dnId, command);
commitSCMCommandStatus(command.getId(), dnId,
StorageContainerDatanodeProtocolProtos.CommandStatus.Status.PENDING);
});
assertNoDuplicateTransactions(transactions3, transactions1);
assertNoDuplicateTransactions(transactions3, transactions2);
DatanodeDeletedBlockTransactions transactions4 =
deletedBlockLog.getTransactions(blockLimit, new HashSet<>(dnList));
assertNoDuplicateTransactions(transactions4, transactions1);
assertNoDuplicateTransactions(transactions4, transactions2);
assertNoDuplicateTransactions(transactions4, transactions3);
}
@Test
public void testFailedAndTimeoutSCMCommandCanBeResend() throws Exception {
// The SCM will be resent these transactions in blow case:
// - Executed failed commands;
// - DN does not refresh the PENDING state for more than a period of time;
deletedBlockLog.setScmCommandTimeoutMs(Long.MAX_VALUE);
addTransactions(generateData(10), true);
int blockLimit = 2 * BLOCKS_PER_TXN * THREE;
mockContainerHealthResult(true);
// - DN does not refresh the PENDING state for more than a period of time;
DatanodeDeletedBlockTransactions transactions =
deletedBlockLog.getTransactions(blockLimit, new HashSet<>(dnList));
createDeleteBlocksCommandAndAction(transactions, (dnId, command) -> {
recordScmCommandToStatusManager(dnId, command);
sendSCMDeleteBlocksCommand(dnId, command);
commitSCMCommandStatus(command.getId(), dnId,
StorageContainerDatanodeProtocolProtos.CommandStatus.Status.PENDING);
});
// - Executed failed commands;
DatanodeDeletedBlockTransactions transactions2 =
deletedBlockLog.getTransactions(blockLimit, new HashSet<>(dnList));
createDeleteBlocksCommandAndAction(transactions2, (dnId, command) -> {
recordScmCommandToStatusManager(dnId, command);
sendSCMDeleteBlocksCommand(dnId, command);
commitSCMCommandStatus(command.getId(), dnId,
StorageContainerDatanodeProtocolProtos.CommandStatus.Status.FAILED);
});
deletedBlockLog.setScmCommandTimeoutMs(-1L);
DatanodeDeletedBlockTransactions transactions3 =
deletedBlockLog.getTransactions(Integer.MAX_VALUE,
new HashSet<>(dnList));
assertNoDuplicateTransactions(transactions, transactions2);
assertContainsAllTransactions(transactions3, transactions);
assertContainsAllTransactions(transactions3, transactions2);
}
@Test
public void testDNOnlyOneNodeHealthy() throws Exception {
Map<Long, List<Long>> deletedBlocks = generateData(50);
addTransactions(deletedBlocks, true);
mockContainerHealthResult(false);
DatanodeDeletedBlockTransactions transactions
= deletedBlockLog.getTransactions(
30 * BLOCKS_PER_TXN * THREE,
dnList.subList(0, 1).stream().collect(Collectors.toSet()));
assertEquals(0, transactions.getDatanodeTransactionMap().size());
}
@Test
public void testInadequateReplicaCommit() throws Exception {
Map<Long, List<Long>> deletedBlocks = generateData(50);
addTransactions(deletedBlocks, true);
long containerID;
// let the first 30 container only consisting of only two unhealthy replicas
int count = 0;
for (Map.Entry<Long, List<Long>> entry : deletedBlocks.entrySet()) {
containerID = entry.getKey();
mockInadequateReplicaUnhealthyContainerInfo(containerID, count);
count += 1;
}
// getTransactions will get existing container replicas then add transaction
// to DN.
// For the first 30 txn, deletedBlockLog only has the txn from dn1 and dn2
// For the rest txn, txn will be got from all dns.
// Committed txn will be: 1-40. 1-40. 31-40
commitTransactions(getTransactions(30 * BLOCKS_PER_TXN * THREE));
// The rest txn shall be: 41-50. 41-50. 41-50
List<DeletedBlocksTransaction> blocks = getAllTransactions();
// First 30 txns aren't considered for deletion as they don't have required
// container replica's so getAllTransactions() won't be able to fetch them
// and rest 20 txns are already committed and removed so in total
// getAllTransactions() will fetch 0 txns.
assertEquals(0, blocks.size());
}
@Test
public void testRandomOperateTransactions() throws Exception {
mockContainerHealthResult(true);
int added = 0, committed = 0;
List<DeletedBlocksTransaction> blocks = new ArrayList<>();
List<Long> txIDs;
// Randomly add/get/commit/increase transactions.
for (int i = 0; i < 100; i++) {
int state = RandomUtils.secure().randomInt(0, 4);
if (state == 0) {
addTransactions(generateData(10), true);
added += 10;
} else if (state == 1) {
blocks = getTransactions(20 * BLOCKS_PER_TXN * THREE);
txIDs = new ArrayList<>();
for (DeletedBlocksTransaction block : blocks) {
txIDs.add(block.getTxID());
}
} else if (state == 2) {
commitTransactions(blocks);
committed += blocks.size() / THREE;
blocks = new ArrayList<>();
} else {
// verify the number of added and committed.
try (Table.KeyValueIterator<Long, DeletedBlocksTransaction> iter =
scm.getScmMetadataStore().getDeletedBlocksTXTable().iterator()) {
AtomicInteger count = new AtomicInteger();
iter.forEachRemaining((keyValue) -> count.incrementAndGet());
assertEquals(added, count.get() + committed);
}
}
}
blocks = getAllTransactions();
commitTransactions(blocks);
}
@Test
public void testPersistence() throws Exception {
addTransactions(generateData(50), true);
mockContainerHealthResult(true);
// close db and reopen it again to make sure
// transactions are stored persistently.
deletedBlockLog.close();
deletedBlockLog = new DeletedBlockLogImpl(conf,
scm,
containerManager,
scmHADBTransactionBuffer,
metrics);
List<DeletedBlocksTransaction> blocks =
getTransactions(10 * BLOCKS_PER_TXN * THREE);
assertEquals(10 * THREE, blocks.size());
commitTransactions(blocks);
blocks = getTransactions(40 * BLOCKS_PER_TXN * THREE);
assertEquals(40 * THREE, blocks.size());
commitTransactions(blocks);
// close db and reopen it again to make sure
// currentTxnID = 50
deletedBlockLog.close();
new DeletedBlockLogImpl(conf,
scm,
containerManager,
scmHADBTransactionBuffer,
metrics);
blocks = getTransactions(40 * BLOCKS_PER_TXN * THREE);
assertEquals(0, blocks.size());
//assertEquals((long)deletedBlockLog.getCurrentTXID(), 50L);
}
@Test
public void testDeletedBlockTransactions() throws IOException {
deletedBlockLog.setScmCommandTimeoutMs(Long.MAX_VALUE);
mockContainerHealthResult(true);
int txNum = 10;
List<DeletedBlocksTransaction> blocks;
DatanodeDetails dnId1 = dnList.get(0), dnId2 = dnList.get(1);
int count = 0;
long containerID;
// Creates {TXNum} TX in the log.
Map<Long, List<Long>> deletedBlocks = generateData(txNum);
addTransactions(deletedBlocks, true);
for (Map.Entry<Long, List<Long>> entry :deletedBlocks.entrySet()) {
count++;
containerID = entry.getKey();
// let the container replication factor to be ONE
if (count % 2 == 0) {
mockStandAloneContainerInfo(containerID, dnId1);
} else {
mockStandAloneContainerInfo(containerID, dnId2);
}
}
// fetch and delete 1 less txn Id
commitTransactions(getTransactions((txNum - 1) * BLOCKS_PER_TXN * ONE));
blocks = getTransactions(txNum * BLOCKS_PER_TXN * ONE);
// There should be one txn remaining
assertEquals(1, blocks.size());
// add two transactions for same container
containerID = blocks.get(0).getContainerID();
Map<Long, List<Long>> deletedBlocksMap = new HashMap<>();
long localId = RandomUtils.secure().randomLong();
deletedBlocksMap.put(containerID, new LinkedList<>(
Collections.singletonList(localId)));
addTransactions(deletedBlocksMap, true);
blocks = getTransactions(txNum * BLOCKS_PER_TXN * ONE);
// Only newly added Blocks will be sent, as previously sent transactions
// that have not yet timed out will not be sent.
assertEquals(1, blocks.size());
assertEquals(1, blocks.get(0).getLocalIDCount());
assertEquals(blocks.get(0).getLocalID(0), localId);
// Lets the SCM delete the transaction and wait for the DN reply
// to timeout, thus allowing the transaction to resend the
deletedBlockLog.setScmCommandTimeoutMs(-1L);
// get should return two transactions for the same container
blocks = getTransactions(txNum * BLOCKS_PER_TXN * ONE);
assertEquals(2, blocks.size());
}
@ParameterizedTest
@ValueSource(ints = {30, 45})
public void testGetTransactionsWithMaxBlocksPerDatanode(int maxAllowedBlockNum) throws IOException {
int deleteBlocksFactorPerDatanode = 1;
deletedBlockLog.setDeleteBlocksFactorPerDatanode(deleteBlocksFactorPerDatanode);
mockContainerHealthResult(true);
int txNum = 10;
DatanodeDetails dnId1 = dnList.get(0), dnId2 = dnList.get(1);
// Creates {TXNum} TX in the log.
Map<Long, List<Long>> deletedBlocks = generateData(txNum);
addTransactions(deletedBlocks, true);
List<Long> containerIds = new ArrayList<>(deletedBlocks.keySet());
for (int i = 0; i < containerIds.size(); i++) {
DatanodeDetails assignedDn = (i % 2 == 0) ? dnId1 : dnId2;
mockStandAloneContainerInfo(containerIds.get(i), assignedDn);
}
int blocksPerDataNode = maxAllowedBlockNum / (dnList.size() / deleteBlocksFactorPerDatanode);
DatanodeDeletedBlockTransactions transactions =
deletedBlockLog.getTransactions(maxAllowedBlockNum, new HashSet<>(dnList));
Map<DatanodeID, Integer> datanodeBlockCountMap = transactions.getDatanodeTransactionMap()
.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue()
.stream()
.mapToInt(tx -> tx.getLocalIDList().size())
.sum()
));
// Transactions should have blocksPerDataNode for both DNs
assertEquals(datanodeBlockCountMap.get(dnId1.getID()), blocksPerDataNode);
assertEquals(datanodeBlockCountMap.get(dnId2.getID()), blocksPerDataNode);
}
@Test
public void testDeletedBlockTransactionsOfDeletedContainer() throws IOException {
int txNum = 10;
List<DeletedBlocksTransaction> blocks;
// Creates {TXNum} TX in the log.
Map<Long, List<Long>> deletedBlocks = generateData(txNum,
HddsProtos.LifeCycleState.DELETED);
addTransactions(deletedBlocks, true);
blocks = getTransactions(txNum * BLOCKS_PER_TXN);
// There should be no txn remaining
assertEquals(0, blocks.size());
}
private void mockStandAloneContainerInfo(long containerID, DatanodeDetails dd)
throws IOException {
List<DatanodeDetails> dns = Collections.singletonList(dd);
Pipeline pipeline = Pipeline.newBuilder()
.setReplicationConfig(
StandaloneReplicationConfig.getInstance(ReplicationFactor.ONE))
.setState(Pipeline.PipelineState.OPEN)
.setId(PipelineID.randomId())
.setNodes(dns)
.build();
ContainerInfo.Builder builder = new ContainerInfo.Builder();
builder.setContainerID(containerID)
.setPipelineID(pipeline.getId())
.setReplicationConfig(pipeline.getReplicationConfig());
ContainerInfo containerInfo = builder.build();
doReturn(containerInfo).when(containerManager)
.getContainer(ContainerID.valueOf(containerID));
final Set<ContainerReplica> replicaSet = dns.stream()
.map(datanodeDetails -> ContainerReplica.newBuilder()
.setContainerID(containerInfo.containerID())
.setContainerState(ContainerReplicaProto.State.OPEN)
.setDatanodeDetails(datanodeDetails)
.build())
.collect(Collectors.toSet());
when(containerManager.getContainerReplicas(
ContainerID.valueOf(containerID)))
.thenReturn(replicaSet);
}
private void mockInadequateReplicaUnhealthyContainerInfo(long containerID,
int count) throws IOException {
List<DatanodeDetails> dns = dnList.subList(0, 2);
Pipeline pipeline = Pipeline.newBuilder()
.setReplicationConfig(
RatisReplicationConfig.getInstance(ReplicationFactor.THREE))
.setState(Pipeline.PipelineState.OPEN)
.setId(PipelineID.randomId())
.setNodes(dnList)
.build();
ContainerInfo.Builder builder = new ContainerInfo.Builder();
builder.setContainerID(containerID)
.setPipelineID(pipeline.getId())
.setReplicationConfig(pipeline.getReplicationConfig());
ContainerInfo containerInfo = builder.build();
doReturn(containerInfo).when(containerManager)
.getContainer(ContainerID.valueOf(containerID));
final Set<ContainerReplica> replicaSet = dns.stream()
.map(datanodeDetails -> ContainerReplica.newBuilder()
.setContainerID(containerInfo.containerID())
.setContainerState(ContainerReplicaProto.State.CLOSED)
.setDatanodeDetails(datanodeDetails)
.build())
.collect(Collectors.toSet());
ContainerHealthResult healthResult;
if (count < 30) {
healthResult = new ContainerHealthResult.UnHealthyResult(containerInfo);
} else {
healthResult = new ContainerHealthResult.HealthyResult(containerInfo);
}
doReturn(healthResult).when(replicationManager)
.getContainerReplicationHealth(containerInfo, replicaSet);
when(containerManager.getContainerReplicas(
ContainerID.valueOf(containerID)))
.thenReturn(replicaSet);
}
}
|
googleapis/google-cloud-java | 35,541 | java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/ListTrialsResponse.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/v1/vizier_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1;
/**
*
*
* <pre>
* Response message for
* [VizierService.ListTrials][google.cloud.aiplatform.v1.VizierService.ListTrials].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.ListTrialsResponse}
*/
public final class ListTrialsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.ListTrialsResponse)
ListTrialsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListTrialsResponse.newBuilder() to construct.
private ListTrialsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListTrialsResponse() {
trials_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListTrialsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1_ListTrialsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1_ListTrialsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.ListTrialsResponse.class,
com.google.cloud.aiplatform.v1.ListTrialsResponse.Builder.class);
}
public static final int TRIALS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1.Trial> trials_;
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1.Trial> getTrialsList() {
return trials_;
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.aiplatform.v1.TrialOrBuilder>
getTrialsOrBuilderList() {
return trials_;
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
@java.lang.Override
public int getTrialsCount() {
return trials_.size();
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.Trial getTrials(int index) {
return trials_.get(index);
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1.TrialOrBuilder getTrialsOrBuilder(int index) {
return trials_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Pass this token as the `page_token` field of the request for a
* subsequent call.
* 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>
* Pass this token as the `page_token` field of the request for a
* subsequent call.
* 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 < trials_.size(); i++) {
output.writeMessage(1, trials_.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 < trials_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, trials_.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.v1.ListTrialsResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1.ListTrialsResponse other =
(com.google.cloud.aiplatform.v1.ListTrialsResponse) obj;
if (!getTrialsList().equals(other.getTrialsList())) 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 (getTrialsCount() > 0) {
hash = (37 * hash) + TRIALS_FIELD_NUMBER;
hash = (53 * hash) + getTrialsList().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.v1.ListTrialsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ListTrialsResponse 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.v1.ListTrialsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ListTrialsResponse 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.v1.ListTrialsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1.ListTrialsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.aiplatform.v1.ListTrialsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ListTrialsResponse 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.v1.ListTrialsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ListTrialsResponse 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.v1.ListTrialsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1.ListTrialsResponse 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.v1.ListTrialsResponse 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
* [VizierService.ListTrials][google.cloud.aiplatform.v1.VizierService.ListTrials].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1.ListTrialsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.ListTrialsResponse)
com.google.cloud.aiplatform.v1.ListTrialsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1_ListTrialsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1_ListTrialsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1.ListTrialsResponse.class,
com.google.cloud.aiplatform.v1.ListTrialsResponse.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1.ListTrialsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (trialsBuilder_ == null) {
trials_ = java.util.Collections.emptyList();
} else {
trials_ = null;
trialsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1.VizierServiceProto
.internal_static_google_cloud_aiplatform_v1_ListTrialsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ListTrialsResponse getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1.ListTrialsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ListTrialsResponse build() {
com.google.cloud.aiplatform.v1.ListTrialsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ListTrialsResponse buildPartial() {
com.google.cloud.aiplatform.v1.ListTrialsResponse result =
new com.google.cloud.aiplatform.v1.ListTrialsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1.ListTrialsResponse result) {
if (trialsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
trials_ = java.util.Collections.unmodifiableList(trials_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.trials_ = trials_;
} else {
result.trials_ = trialsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.aiplatform.v1.ListTrialsResponse 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.v1.ListTrialsResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1.ListTrialsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1.ListTrialsResponse other) {
if (other == com.google.cloud.aiplatform.v1.ListTrialsResponse.getDefaultInstance())
return this;
if (trialsBuilder_ == null) {
if (!other.trials_.isEmpty()) {
if (trials_.isEmpty()) {
trials_ = other.trials_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureTrialsIsMutable();
trials_.addAll(other.trials_);
}
onChanged();
}
} else {
if (!other.trials_.isEmpty()) {
if (trialsBuilder_.isEmpty()) {
trialsBuilder_.dispose();
trialsBuilder_ = null;
trials_ = other.trials_;
bitField0_ = (bitField0_ & ~0x00000001);
trialsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getTrialsFieldBuilder()
: null;
} else {
trialsBuilder_.addAllMessages(other.trials_);
}
}
}
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.v1.Trial m =
input.readMessage(
com.google.cloud.aiplatform.v1.Trial.parser(), extensionRegistry);
if (trialsBuilder_ == null) {
ensureTrialsIsMutable();
trials_.add(m);
} else {
trialsBuilder_.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.v1.Trial> trials_ =
java.util.Collections.emptyList();
private void ensureTrialsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
trials_ = new java.util.ArrayList<com.google.cloud.aiplatform.v1.Trial>(trials_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1.Trial,
com.google.cloud.aiplatform.v1.Trial.Builder,
com.google.cloud.aiplatform.v1.TrialOrBuilder>
trialsBuilder_;
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1.Trial> getTrialsList() {
if (trialsBuilder_ == null) {
return java.util.Collections.unmodifiableList(trials_);
} else {
return trialsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public int getTrialsCount() {
if (trialsBuilder_ == null) {
return trials_.size();
} else {
return trialsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public com.google.cloud.aiplatform.v1.Trial getTrials(int index) {
if (trialsBuilder_ == null) {
return trials_.get(index);
} else {
return trialsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public Builder setTrials(int index, com.google.cloud.aiplatform.v1.Trial value) {
if (trialsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTrialsIsMutable();
trials_.set(index, value);
onChanged();
} else {
trialsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public Builder setTrials(
int index, com.google.cloud.aiplatform.v1.Trial.Builder builderForValue) {
if (trialsBuilder_ == null) {
ensureTrialsIsMutable();
trials_.set(index, builderForValue.build());
onChanged();
} else {
trialsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public Builder addTrials(com.google.cloud.aiplatform.v1.Trial value) {
if (trialsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTrialsIsMutable();
trials_.add(value);
onChanged();
} else {
trialsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public Builder addTrials(int index, com.google.cloud.aiplatform.v1.Trial value) {
if (trialsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureTrialsIsMutable();
trials_.add(index, value);
onChanged();
} else {
trialsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public Builder addTrials(com.google.cloud.aiplatform.v1.Trial.Builder builderForValue) {
if (trialsBuilder_ == null) {
ensureTrialsIsMutable();
trials_.add(builderForValue.build());
onChanged();
} else {
trialsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public Builder addTrials(
int index, com.google.cloud.aiplatform.v1.Trial.Builder builderForValue) {
if (trialsBuilder_ == null) {
ensureTrialsIsMutable();
trials_.add(index, builderForValue.build());
onChanged();
} else {
trialsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public Builder addAllTrials(
java.lang.Iterable<? extends com.google.cloud.aiplatform.v1.Trial> values) {
if (trialsBuilder_ == null) {
ensureTrialsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, trials_);
onChanged();
} else {
trialsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public Builder clearTrials() {
if (trialsBuilder_ == null) {
trials_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
trialsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public Builder removeTrials(int index) {
if (trialsBuilder_ == null) {
ensureTrialsIsMutable();
trials_.remove(index);
onChanged();
} else {
trialsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public com.google.cloud.aiplatform.v1.Trial.Builder getTrialsBuilder(int index) {
return getTrialsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public com.google.cloud.aiplatform.v1.TrialOrBuilder getTrialsOrBuilder(int index) {
if (trialsBuilder_ == null) {
return trials_.get(index);
} else {
return trialsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public java.util.List<? extends com.google.cloud.aiplatform.v1.TrialOrBuilder>
getTrialsOrBuilderList() {
if (trialsBuilder_ != null) {
return trialsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(trials_);
}
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public com.google.cloud.aiplatform.v1.Trial.Builder addTrialsBuilder() {
return getTrialsFieldBuilder()
.addBuilder(com.google.cloud.aiplatform.v1.Trial.getDefaultInstance());
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public com.google.cloud.aiplatform.v1.Trial.Builder addTrialsBuilder(int index) {
return getTrialsFieldBuilder()
.addBuilder(index, com.google.cloud.aiplatform.v1.Trial.getDefaultInstance());
}
/**
*
*
* <pre>
* The Trials associated with the Study.
* </pre>
*
* <code>repeated .google.cloud.aiplatform.v1.Trial trials = 1;</code>
*/
public java.util.List<com.google.cloud.aiplatform.v1.Trial.Builder> getTrialsBuilderList() {
return getTrialsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1.Trial,
com.google.cloud.aiplatform.v1.Trial.Builder,
com.google.cloud.aiplatform.v1.TrialOrBuilder>
getTrialsFieldBuilder() {
if (trialsBuilder_ == null) {
trialsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1.Trial,
com.google.cloud.aiplatform.v1.Trial.Builder,
com.google.cloud.aiplatform.v1.TrialOrBuilder>(
trials_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
trials_ = null;
}
return trialsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Pass this token as the `page_token` field of the request for a
* subsequent call.
* 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>
* Pass this token as the `page_token` field of the request for a
* subsequent call.
* 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>
* Pass this token as the `page_token` field of the request for a
* subsequent call.
* 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>
* Pass this token as the `page_token` field of the request for a
* subsequent call.
* 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>
* Pass this token as the `page_token` field of the request for a
* subsequent call.
* 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.aiplatform.v1.ListTrialsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.ListTrialsResponse)
private static final com.google.cloud.aiplatform.v1.ListTrialsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.ListTrialsResponse();
}
public static com.google.cloud.aiplatform.v1.ListTrialsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListTrialsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListTrialsResponse>() {
@java.lang.Override
public ListTrialsResponse 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<ListTrialsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListTrialsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1.ListTrialsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
openjdk/nashorn | 36,081 | src/org.openjdk.nashorn/share/classes/org/openjdk/nashorn/internal/runtime/doubleconv/FastDtoa.java | /*
* Copyright (c) 2015, 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.
*/
// This file is available under and governed by the GNU General Public
// License version 2 only, as published by the Free Software Foundation.
// However, the following notice accompanied the original version of this
// file:
//
// Copyright 2010 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.openjdk.nashorn.internal.runtime.doubleconv;
// Fast Dtoa implementation supporting shortest and precision modes. Does not
// work for all numbers so BugnumDtoa is used as fallback.
class FastDtoa {
// FastDtoa will produce at most kFastDtoaMaximalLength digits. This does not
// include the terminating '\0' character.
static final int kFastDtoaMaximalLength = 17;
// The minimal and maximal target exponent define the range of w's binary
// exponent, where 'w' is the result of multiplying the input by a cached power
// of ten.
//
// A different range might be chosen on a different platform, to optimize digit
// generation, but a smaller range requires more powers of ten to be cached.
static final int kMinimalTargetExponent = -60;
static final int kMaximalTargetExponent = -32;
// Adjusts the last digit of the generated number, and screens out generated
// solutions that may be inaccurate. A solution may be inaccurate if it is
// outside the safe interval, or if we cannot prove that it is closer to the
// input than a neighboring representation of the same length.
//
// Input: * buffer containing the digits of too_high / 10^kappa
// * distance_too_high_w == (too_high - w).f() * unit
// * unsafe_interval == (too_high - too_low).f() * unit
// * rest = (too_high - buffer * 10^kappa).f() * unit
// * ten_kappa = 10^kappa * unit
// * unit = the common multiplier
// Output: returns true if the buffer is guaranteed to contain the closest
// representable number to the input.
// Modifies the generated digits in the buffer to approach (round towards) w.
static boolean roundWeed(final DtoaBuffer buffer,
final long distance_too_high_w,
final long unsafe_interval,
long rest,
final long ten_kappa,
final long unit) {
final long small_distance = distance_too_high_w - unit;
final long big_distance = distance_too_high_w + unit;
// Let w_low = too_high - big_distance, and
// w_high = too_high - small_distance.
// Note: w_low < w < w_high
//
// The real w (* unit) must lie somewhere inside the interval
// ]w_low; w_high[ (often written as "(w_low; w_high)")
// Basically the buffer currently contains a number in the unsafe interval
// ]too_low; too_high[ with too_low < w < too_high
//
// too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ^v 1 unit ^ ^ ^ ^
// boundary_high --------------------- . . . .
// ^v 1 unit . . . .
// - - - - - - - - - - - - - - - - - - - + - - + - - - - - - . .
// . . ^ . .
// . big_distance . . .
// . . . . rest
// small_distance . . . .
// v . . . .
// w_high - - - - - - - - - - - - - - - - - - . . . .
// ^v 1 unit . . . .
// w ---------------------------------------- . . . .
// ^v 1 unit v . . .
// w_low - - - - - - - - - - - - - - - - - - - - - . . .
// . . v
// buffer --------------------------------------------------+-------+--------
// . .
// safe_interval .
// v .
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .
// ^v 1 unit .
// boundary_low ------------------------- unsafe_interval
// ^v 1 unit v
// too_low - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//
//
// Note that the value of buffer could lie anywhere inside the range too_low
// to too_high.
//
// boundary_low, boundary_high and w are approximations of the real boundaries
// and v (the input number). They are guaranteed to be precise up to one unit.
// In fact the error is guaranteed to be strictly less than one unit.
//
// Anything that lies outside the unsafe interval is guaranteed not to round
// to v when read again.
// Anything that lies inside the safe interval is guaranteed to round to v
// when read again.
// If the number inside the buffer lies inside the unsafe interval but not
// inside the safe interval then we simply do not know and bail out (returning
// false).
//
// Similarly we have to take into account the imprecision of 'w' when finding
// the closest representation of 'w'. If we have two potential
// representations, and one is closer to both w_low and w_high, then we know
// it is closer to the actual value v.
//
// By generating the digits of too_high we got the largest (closest to
// too_high) buffer that is still in the unsafe interval. In the case where
// w_high < buffer < too_high we try to decrement the buffer.
// This way the buffer approaches (rounds towards) w.
// There are 3 conditions that stop the decrementation process:
// 1) the buffer is already below w_high
// 2) decrementing the buffer would make it leave the unsafe interval
// 3) decrementing the buffer would yield a number below w_high and farther
// away than the current number. In other words:
// (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
// Instead of using the buffer directly we use its distance to too_high.
// Conceptually rest ~= too_high - buffer
// We need to do the following tests in this order to avoid over- and
// underflows.
assert (Long.compareUnsigned(rest, unsafe_interval) <= 0);
while (Long.compareUnsigned(rest, small_distance) < 0 && // Negated condition 1
Long.compareUnsigned(unsafe_interval - rest, ten_kappa) >= 0 && // Negated condition 2
(Long.compareUnsigned(rest + ten_kappa, small_distance) < 0 || // buffer{-1} > w_high
Long.compareUnsigned(small_distance - rest, rest + ten_kappa - small_distance) >= 0)) {
buffer.chars[buffer.length - 1]--;
rest += ten_kappa;
}
// We have approached w+ as much as possible. We now test if approaching w-
// would require changing the buffer. If yes, then we have two possible
// representations close to w, but we cannot decide which one is closer.
if (Long.compareUnsigned(rest, big_distance) < 0 &&
Long.compareUnsigned(unsafe_interval - rest, ten_kappa) >= 0 &&
(Long.compareUnsigned(rest + ten_kappa, big_distance) < 0 ||
Long.compareUnsigned(big_distance - rest, rest + ten_kappa - big_distance) > 0)) {
return false;
}
// Weeding test.
// The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
// Since too_low = too_high - unsafe_interval this is equivalent to
// [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
// Conceptually we have: rest ~= too_high - buffer
return Long.compareUnsigned(2 * unit, rest) <= 0 && Long.compareUnsigned(rest, unsafe_interval - 4 * unit) <= 0;
}
// Rounds the buffer upwards if the result is closer to v by possibly adding
// 1 to the buffer. If the precision of the calculation is not sufficient to
// round correctly, return false.
// The rounding might shift the whole buffer in which case the kappa is
// adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
//
// If 2*rest > ten_kappa then the buffer needs to be round up.
// rest can have an error of +/- 1 unit. This function accounts for the
// imprecision and returns false, if the rounding direction cannot be
// unambiguously determined.
//
// Precondition: rest < ten_kappa.
// Changed return type to int to let caller know they should increase kappa (return value 2)
static int roundWeedCounted(final char[] buffer,
final int length,
final long rest,
final long ten_kappa,
final long unit) {
assert(Long.compareUnsigned(rest, ten_kappa) < 0);
// The following tests are done in a specific order to avoid overflows. They
// will work correctly with any uint64 values of rest < ten_kappa and unit.
//
// If the unit is too big, then we don't know which way to round. For example
// a unit of 50 means that the real number lies within rest +/- 50. If
// 10^kappa == 40 then there is no way to tell which way to round.
if (Long.compareUnsigned(unit, ten_kappa) >= 0) return 0;
// Even if unit is just half the size of 10^kappa we are already completely
// lost. (And after the previous test we know that the expression will not
// over/underflow.)
if (Long.compareUnsigned(ten_kappa - unit, unit) <= 0) return 0;
// If 2 * (rest + unit) <= 10^kappa we can safely round down.
if (Long.compareUnsigned(ten_kappa - rest, rest) > 0 && Long.compareUnsigned(ten_kappa - 2 * rest, 2 * unit) >= 0) {
return 1;
}
// If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
if (Long.compareUnsigned(rest, unit) > 0 && Long.compareUnsigned(ten_kappa - (rest - unit), (rest - unit)) <= 0) {
// Increment the last digit recursively until we find a non '9' digit.
buffer[length - 1]++;
for (int i = length - 1; i > 0; --i) {
if (buffer[i] != '0' + 10) break;
buffer[i] = '0';
buffer[i - 1]++;
}
// If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
// exception of the first digit all digits are now '0'. Simply switch the
// first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
// the power (the kappa) is increased.
if (buffer[0] == '0' + 10) {
buffer[0] = '1';
// Return value of 2 tells caller to increase (*kappa) += 1
return 2;
}
return 1;
}
return 0;
}
// Returns the biggest power of ten that is less than or equal to the given
// number. We furthermore receive the maximum number of bits 'number' has.
//
// Returns power == 10^(exponent_plus_one-1) such that
// power <= number < power * 10.
// If number_bits == 0 then 0^(0-1) is returned.
// The number of bits must be <= 32.
// Precondition: number < (1 << (number_bits + 1)).
// Inspired by the method for finding an integer log base 10 from here:
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
static final int kSmallPowersOfTen[] =
{0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
1000000000};
// Returns the biggest power of ten that is less than or equal than the given
// number. We furthermore receive the maximum number of bits 'number' has.
// If number_bits == 0 then 0^-1 is returned
// The number of bits must be <= 32.
// Precondition: (1 << number_bits) <= number < (1 << (number_bits + 1)).
static long biggestPowerTen(final int number,
final int number_bits) {
final int power, exponent_plus_one;
assert ((number & 0xFFFFFFFFL) < (1l << (number_bits + 1)));
// 1233/4096 is approximately 1/lg(10).
int exponent_plus_one_guess = ((number_bits + 1) * 1233 >>> 12);
// We increment to skip over the first entry in the kPowersOf10 table.
// Note: kPowersOf10[i] == 10^(i-1).
exponent_plus_one_guess++;
// We don't have any guarantees that 2^number_bits <= number.
if (number < kSmallPowersOfTen[exponent_plus_one_guess]) {
exponent_plus_one_guess--;
}
power = kSmallPowersOfTen[exponent_plus_one_guess];
exponent_plus_one = exponent_plus_one_guess;
return ((long) power << 32) | (long) exponent_plus_one;
}
// Generates the digits of input number w.
// w is a floating-point number (DiyFp), consisting of a significand and an
// exponent. Its exponent is bounded by kMinimalTargetExponent and
// kMaximalTargetExponent.
// Hence -60 <= w.e() <= -32.
//
// Returns false if it fails, in which case the generated digits in the buffer
// should not be used.
// Preconditions:
// * low, w and high are correct up to 1 ulp (unit in the last place). That
// is, their error must be less than a unit of their last digits.
// * low.e() == w.e() == high.e()
// * low < w < high, and taking into account their error: low~ <= high~
// * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
// Postconditions: returns false if procedure fails.
// otherwise:
// * buffer is not null-terminated, but len contains the number of digits.
// * buffer contains the shortest possible decimal digit-sequence
// such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
// correct values of low and high (without their error).
// * if more than one decimal representation gives the minimal number of
// decimal digits then the one closest to W (where W is the correct value
// of w) is chosen.
// Remark: this procedure takes into account the imprecision of its input
// numbers. If the precision is not enough to guarantee all the postconditions
// then false is returned. This usually happens rarely (~0.5%).
//
// Say, for the sake of example, that
// w.e() == -48, and w.f() == 0x1234567890abcdef
// w's value can be computed by w.f() * 2^w.e()
// We can obtain w's integral digits by simply shifting w.f() by -w.e().
// -> w's integral part is 0x1234
// w's fractional part is therefore 0x567890abcdef.
// Printing w's integral part is easy (simply print 0x1234 in decimal).
// In order to print its fraction we repeatedly multiply the fraction by 10 and
// get each digit. Example the first digit after the point would be computed by
// (0x567890abcdef * 10) >> 48. -> 3
// The whole thing becomes slightly more complicated because we want to stop
// once we have enough digits. That is, once the digits inside the buffer
// represent 'w' we can stop. Everything inside the interval low - high
// represents w. However we have to pay attention to low, high and w's
// imprecision.
static boolean digitGen(final DiyFp low,
final DiyFp w,
final DiyFp high,
final DtoaBuffer buffer,
final int mk) {
assert(low.e() == w.e() && w.e() == high.e());
assert Long.compareUnsigned(low.f() + 1, high.f() - 1) <= 0;
assert(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
// low, w and high are imprecise, but by less than one ulp (unit in the last
// place).
// If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
// the new numbers are outside of the interval we want the final
// representation to lie in.
// Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
// numbers that are certain to lie in the interval. We will use this fact
// later on.
// We will now start by generating the digits within the uncertain
// interval. Later we will weed out representations that lie outside the safe
// interval and thus _might_ lie outside the correct interval.
long unit = 1;
final DiyFp too_low = new DiyFp(low.f() - unit, low.e());
final DiyFp too_high = new DiyFp(high.f() + unit, high.e());
// too_low and too_high are guaranteed to lie outside the interval we want the
// generated number in.
final DiyFp unsafe_interval = DiyFp.minus(too_high, too_low);
// We now cut the input number into two parts: the integral digits and the
// fractionals. We will not write any decimal separator though, but adapt
// kappa instead.
// Reminder: we are currently computing the digits (stored inside the buffer)
// such that: too_low < buffer * 10^kappa < too_high
// We use too_high for the digit_generation and stop as soon as possible.
// If we stop early we effectively round down.
final DiyFp one = new DiyFp(1l << -w.e(), w.e());
// Division by one is a shift.
int integrals = (int)(too_high.f() >>> -one.e());
// Modulo by one is an and.
long fractionals = too_high.f() & (one.f() - 1);
int divisor;
final int divisor_exponent_plus_one;
final long result = biggestPowerTen(integrals, DiyFp.kSignificandSize - (-one.e()));
divisor = (int) (result >>> 32);
divisor_exponent_plus_one = (int) result;
int kappa = divisor_exponent_plus_one;
// Loop invariant: buffer = too_high / 10^kappa (integer division)
// The invariant holds for the first iteration: kappa has been initialized
// with the divisor exponent + 1. And the divisor is the biggest power of ten
// that is smaller than integrals.
while (kappa > 0) {
final int digit = integrals / divisor;
assert (digit <= 9);
buffer.append((char) ('0' + digit));
integrals %= divisor;
kappa--;
// Note that kappa now equals the exponent of the divisor and that the
// invariant thus holds again.
final long rest =
((long) integrals << -one.e()) + fractionals;
// Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e())
// Reminder: unsafe_interval.e() == one.e()
if (Long.compareUnsigned(rest, unsafe_interval.f()) < 0) {
// Rounding down (by not emitting the remaining digits) yields a number
// that lies within the unsafe interval.
buffer.decimalPoint = buffer.length - mk + kappa;
return roundWeed(buffer, DiyFp.minus(too_high, w).f(),
unsafe_interval.f(), rest,
(long) divisor << -one.e(), unit);
}
divisor /= 10;
}
// The integrals have been generated. We are at the point of the decimal
// separator. In the following loop we simply multiply the remaining digits by
// 10 and divide by one. We just need to pay attention to multiply associated
// data (like the interval or 'unit'), too.
// Note that the multiplication by 10 does not overflow, because w.e >= -60
// and thus one.e >= -60.
assert (one.e() >= -60);
assert (fractionals < one.f());
assert (Long.compareUnsigned(Long.divideUnsigned(0xFFFFFFFFFFFFFFFFL, 10), one.f()) >= 0);
for (;;) {
fractionals *= 10;
unit *= 10;
unsafe_interval.setF(unsafe_interval.f() * 10);
// Integer division by one.
final int digit = (int) (fractionals >>> -one.e());
assert (digit <= 9);
buffer.append((char) ('0' + digit));
fractionals &= one.f() - 1; // Modulo by one.
kappa--;
if (Long.compareUnsigned(fractionals, unsafe_interval.f()) < 0) {
buffer.decimalPoint = buffer.length - mk + kappa;
return roundWeed(buffer, DiyFp.minus(too_high, w).f() * unit,
unsafe_interval.f(), fractionals, one.f(), unit);
}
}
}
// Generates (at most) requested_digits digits of input number w.
// w is a floating-point number (DiyFp), consisting of a significand and an
// exponent. Its exponent is bounded by kMinimalTargetExponent and
// kMaximalTargetExponent.
// Hence -60 <= w.e() <= -32.
//
// Returns false if it fails, in which case the generated digits in the buffer
// should not be used.
// Preconditions:
// * w is correct up to 1 ulp (unit in the last place). That
// is, its error must be strictly less than a unit of its last digit.
// * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
//
// Postconditions: returns false if procedure fails.
// otherwise:
// * buffer is not null-terminated, but length contains the number of
// digits.
// * the representation in buffer is the most precise representation of
// requested_digits digits.
// * buffer contains at most requested_digits digits of w. If there are less
// than requested_digits digits then some trailing '0's have been removed.
// * kappa is such that
// w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
//
// Remark: This procedure takes into account the imprecision of its input
// numbers. If the precision is not enough to guarantee all the postconditions
// then false is returned. This usually happens rarely, but the failure-rate
// increases with higher requested_digits.
static boolean digitGenCounted(final DiyFp w,
int requested_digits,
final DtoaBuffer buffer,
final int mk) {
assert (kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
assert (kMinimalTargetExponent >= -60);
assert (kMaximalTargetExponent <= -32);
// w is assumed to have an error less than 1 unit. Whenever w is scaled we
// also scale its error.
long w_error = 1;
// We cut the input number into two parts: the integral digits and the
// fractional digits. We don't emit any decimal separator, but adapt kappa
// instead. Example: instead of writing "1.2" we put "12" into the buffer and
// increase kappa by 1.
final DiyFp one = new DiyFp(1l << -w.e(), w.e());
// Division by one is a shift.
int integrals = (int) (w.f() >>> -one.e());
// Modulo by one is an and.
long fractionals = w.f() & (one.f() - 1);
int divisor;
final int divisor_exponent_plus_one;
final long biggestPower = biggestPowerTen(integrals, DiyFp.kSignificandSize - (-one.e()));
divisor = (int) (biggestPower >>> 32);
divisor_exponent_plus_one = (int) biggestPower;
int kappa = divisor_exponent_plus_one;
// Loop invariant: buffer = w / 10^kappa (integer division)
// The invariant holds for the first iteration: kappa has been initialized
// with the divisor exponent + 1. And the divisor is the biggest power of ten
// that is smaller than 'integrals'.
while (kappa > 0) {
final int digit = integrals / divisor;
assert (digit <= 9);
buffer.append((char) ('0' + digit));
requested_digits--;
integrals %= divisor;
kappa--;
// Note that kappa now equals the exponent of the divisor and that the
// invariant thus holds again.
if (requested_digits == 0) break;
divisor /= 10;
}
if (requested_digits == 0) {
final long rest =
((long) (integrals) << -one.e()) + fractionals;
final int result = roundWeedCounted(buffer.chars, buffer.length, rest,
(long) divisor << -one.e(), w_error);
buffer.decimalPoint = buffer.length - mk + kappa + (result == 2 ? 1 : 0);
return result > 0;
}
// The integrals have been generated. We are at the decimalPoint of the decimal
// separator. In the following loop we simply multiply the remaining digits by
// 10 and divide by one. We just need to pay attention to multiply associated
// data (the 'unit'), too.
// Note that the multiplication by 10 does not overflow, because w.e >= -60
// and thus one.e >= -60.
assert (one.e() >= -60);
assert (fractionals < one.f());
assert (Long.compareUnsigned(Long.divideUnsigned(0xFFFFFFFFFFFFFFFFL, 10), one.f()) >= 0);
while (requested_digits > 0 && fractionals > w_error) {
fractionals *= 10;
w_error *= 10;
// Integer division by one.
final int digit = (int) (fractionals >>> -one.e());
assert (digit <= 9);
buffer.append((char) ('0' + digit));
requested_digits--;
fractionals &= one.f() - 1; // Modulo by one.
kappa--;
}
if (requested_digits != 0) return false;
final int result = roundWeedCounted(buffer.chars, buffer.length, fractionals, one.f(), w_error);
buffer.decimalPoint = buffer.length - mk + kappa + (result == 2 ? 1 : 0);
return result > 0;
}
// Provides a decimal representation of v.
// Returns true if it succeeds, otherwise the result cannot be trusted.
// There will be *length digits inside the buffer (not null-terminated).
// If the function returns true then
// v == (double) (buffer * 10^decimal_exponent).
// The digits in the buffer are the shortest representation possible: no
// 0.09999999999999999 instead of 0.1. The shorter representation will even be
// chosen even if the longer one would be closer to v.
// The last digit will be closest to the actual v. That is, even if several
// digits might correctly yield 'v' when read again, the closest will be
// computed.
static boolean grisu3(final double v, final DtoaBuffer buffer) {
final long d64 = IeeeDouble.doubleToLong(v);
final DiyFp w = IeeeDouble.asNormalizedDiyFp(d64);
// boundary_minus and boundary_plus are the boundaries between v and its
// closest floating-point neighbors. Any number strictly between
// boundary_minus and boundary_plus will round to v when convert to a double.
// Grisu3 will never output representations that lie exactly on a boundary.
final DiyFp boundary_minus = new DiyFp(), boundary_plus = new DiyFp();
IeeeDouble.normalizedBoundaries(d64, boundary_minus, boundary_plus);
assert(boundary_plus.e() == w.e());
final DiyFp ten_mk = new DiyFp(); // Cached power of ten: 10^-k
final int mk; // -k
final int ten_mk_minimal_binary_exponent =
kMinimalTargetExponent - (w.e() + DiyFp.kSignificandSize);
final int ten_mk_maximal_binary_exponent =
kMaximalTargetExponent - (w.e() + DiyFp.kSignificandSize);
mk = CachedPowers.getCachedPowerForBinaryExponentRange(
ten_mk_minimal_binary_exponent,
ten_mk_maximal_binary_exponent,
ten_mk);
assert(kMinimalTargetExponent <= w.e() + ten_mk.e() +
DiyFp.kSignificandSize &&
kMaximalTargetExponent >= w.e() + ten_mk.e() +
DiyFp.kSignificandSize);
// Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
// 64 bit significand and ten_mk is thus only precise up to 64 bits.
// The DiyFp::Times procedure rounds its result, and ten_mk is approximated
// too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
// off by a small amount.
// In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
// In other words: let f = scaled_w.f() and e = scaled_w.e(), then
// (f-1) * 2^e < w*10^k < (f+1) * 2^e
final DiyFp scaled_w = DiyFp.times(w, ten_mk);
assert(scaled_w.e() ==
boundary_plus.e() + ten_mk.e() + DiyFp.kSignificandSize);
// In theory it would be possible to avoid some recomputations by computing
// the difference between w and boundary_minus/plus (a power of 2) and to
// compute scaled_boundary_minus/plus by subtracting/adding from
// scaled_w. However the code becomes much less readable and the speed
// enhancements are not terriffic.
final DiyFp scaled_boundary_minus = DiyFp.times(boundary_minus, ten_mk);
final DiyFp scaled_boundary_plus = DiyFp.times(boundary_plus, ten_mk);
// DigitGen will generate the digits of scaled_w. Therefore we have
// v == (double) (scaled_w * 10^-mk).
// Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
// integer than it will be updated. For instance if scaled_w == 1.23 then
// the buffer will be filled with "123" und the decimal_exponent will be
// decreased by 2.
final boolean result = digitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
buffer, mk);
return result;
}
// The "counted" version of grisu3 (see above) only generates requested_digits
// number of digits. This version does not generate the shortest representation,
// and with enough requested digits 0.1 will at some point print as 0.9999999...
// Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
// therefore the rounding strategy for halfway cases is irrelevant.
static boolean grisu3Counted(final double v,
final int requested_digits,
final DtoaBuffer buffer) {
final long d64 = IeeeDouble.doubleToLong(v);
final DiyFp w = IeeeDouble.asNormalizedDiyFp(d64);
final DiyFp ten_mk = new DiyFp(); // Cached power of ten: 10^-k
final int mk; // -k
final int ten_mk_minimal_binary_exponent =
kMinimalTargetExponent - (w.e() + DiyFp.kSignificandSize);
final int ten_mk_maximal_binary_exponent =
kMaximalTargetExponent - (w.e() + DiyFp.kSignificandSize);
mk = CachedPowers.getCachedPowerForBinaryExponentRange(
ten_mk_minimal_binary_exponent,
ten_mk_maximal_binary_exponent,
ten_mk);
assert ((kMinimalTargetExponent <= w.e() + ten_mk.e() +
DiyFp.kSignificandSize) &&
(kMaximalTargetExponent >= w.e() + ten_mk.e() +
DiyFp.kSignificandSize));
// Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
// 64 bit significand and ten_mk is thus only precise up to 64 bits.
// The DiyFp::Times procedure rounds its result, and ten_mk is approximated
// too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
// off by a small amount.
// In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
// In other words: let f = scaled_w.f() and e = scaled_w.e(), then
// (f-1) * 2^e < w*10^k < (f+1) * 2^e
final DiyFp scaled_w = DiyFp.times(w, ten_mk);
// We now have (double) (scaled_w * 10^-mk).
// DigitGen will generate the first requested_digits digits of scaled_w and
// return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
// will not always be exactly the same since DigitGenCounted only produces a
// limited number of digits.)
final boolean result = digitGenCounted(scaled_w, requested_digits,
buffer, mk);
return result;
}
} |
google/blockly-android | 35,623 | blocklylib-core/src/main/java/com/google/blockly/model/BlocklyEvent.java | /*
* Copyright 2017 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.blockly.model;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import com.google.blockly.android.control.BlocklyController;
import com.google.blockly.utils.BlocklyXmlHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Base class for all Blockly events.
*/
public abstract class BlocklyEvent {
public static final String WORKSPACE_ID_TOOLBOX = "TOOLBOX";
public static final String WORKSPACE_ID_TRASH = "TRASH";
// JSON serialization attributes. See also TYPENAME_ and ELEMENT_ constants for ids.
private static final String JSON_BLOCK_ID = "blockId";
private static final String JSON_ELEMENT = "element";
private static final String JSON_GROUP_ID = "groupId";
private static final String JSON_IDS = "ids";
private static final String JSON_NAME = "name";
private static final String JSON_NEW_VALUE = "newValue";
private static final String JSON_OLD_VALUE = "oldValue"; // Rarely used.
private static final String JSON_TYPE = "type";
private static final String JSON_WORKSPACE_ID = "workspaceId"; // Rarely used.
private static final String JSON_XML = "xml";
/**
* Helper method for logging event groups.
* @param loggingTag The tag for this log message.
* @param prefix A string to prefix the event group.
* @param eventGroup The events received in one update.
*/
public static void log(String loggingTag, String prefix, List<BlocklyEvent> eventGroup) {
StringBuilder sb = new StringBuilder(prefix);
for (BlocklyEvent event : eventGroup) {
sb.append("\n\t").append(event);
}
Log.d(loggingTag, sb.toString());
}
@IntDef(flag = true,
value = {TYPE_CHANGE, TYPE_CREATE, TYPE_DELETE, TYPE_MOVE, TYPE_UI})
@Retention(RetentionPolicy.SOURCE)
public @interface EventType {}
public static final int TYPE_CREATE = 1 << 0;
public static final int TYPE_DELETE = 1 << 1;
public static final int TYPE_CHANGE = 1 << 2;
public static final int TYPE_MOVE = 1 << 3;
public static final int TYPE_UI = 1 << 4;
// When adding an event type, update TYPE_ID_COUNT, TYPE_ALL, TYPE_ID_TO_NAME, and
// TYPE_NAME_TO_ID.
private static final int TYPE_ID_COUNT = 5;
public static final @EventType int TYPE_ALL =
TYPE_CHANGE | TYPE_CREATE | TYPE_DELETE | TYPE_MOVE | TYPE_UI;
public static final String TYPENAME_CHANGE = "change";
public static final String TYPENAME_CREATE = "create";
public static final String TYPENAME_DELETE = "delete";
public static final String TYPENAME_MOVE = "move";
public static final String TYPENAME_UI = "ui";
@StringDef({ELEMENT_COLLAPSED, ELEMENT_COMMENT, ELEMENT_DISABLED, ELEMENT_FIELD, ELEMENT_INLINE,
ELEMENT_MUTATE})
@Retention(RetentionPolicy.SOURCE)
public @interface ChangeElement {}
public static final String ELEMENT_COLLAPSED = "collapsed";
public static final String ELEMENT_COMMENT = "comment";
public static final String ELEMENT_DISABLED = "disabled";
public static final String ELEMENT_FIELD = "field";
public static final String ELEMENT_INLINE = "inline";
public static final String ELEMENT_MUTATE = "mutate";
@StringDef({ELEMENT_CATEGORY, ELEMENT_CLICK, ELEMENT_COMMENT_OPEN, ELEMENT_MUTATOR_OPEN,
ELEMENT_SELECTED, ELEMENT_TRASH, ELEMENT_WARNING_OPEN})
@Retention(RetentionPolicy.SOURCE)
public @interface UIElement {}
public static final String ELEMENT_CATEGORY = "category";
public static final String ELEMENT_CLICK = "click";
public static final String ELEMENT_COMMENT_OPEN = "commentOpen";
public static final String ELEMENT_MUTATOR_OPEN = "mutatorOpen";
public static final String ELEMENT_SELECTED = "selected";
public static final String ELEMENT_TRASH = "trashOpen";
public static final String ELEMENT_WARNING_OPEN = "warningOpen";
private static final SparseArray<String> TYPE_ID_TO_NAME = new SparseArray<>(TYPE_ID_COUNT);
private static final Map<String, Integer> TYPE_NAME_TO_ID = new ArrayMap<>(TYPE_ID_COUNT);
static {
TYPE_ID_TO_NAME.put(TYPE_CHANGE, TYPENAME_CHANGE);
TYPE_ID_TO_NAME.put(TYPE_CREATE, TYPENAME_CREATE);
TYPE_ID_TO_NAME.put(TYPE_DELETE, TYPENAME_DELETE);
TYPE_ID_TO_NAME.put(TYPE_MOVE, TYPENAME_MOVE);
TYPE_ID_TO_NAME.put(TYPE_UI, TYPENAME_UI);
TYPE_NAME_TO_ID.put(TYPENAME_CHANGE, TYPE_CHANGE);
TYPE_NAME_TO_ID.put(TYPENAME_CREATE, TYPE_CREATE);
TYPE_NAME_TO_ID.put(TYPENAME_DELETE, TYPE_DELETE);
TYPE_NAME_TO_ID.put(TYPENAME_MOVE, TYPE_MOVE);
TYPE_NAME_TO_ID.put(TYPENAME_UI, TYPE_UI);
}
public static BlocklyEvent fromJson(String json) throws JSONException {
return fromJson(new JSONObject(json));
}
public static BlocklyEvent fromJson(JSONObject json) throws JSONException {
String typename = json.getString(JSON_TYPE);
switch(typename) {
case TYPENAME_CHANGE:
return new ChangeEvent(json);
case TYPENAME_CREATE:
return new CreateEvent(json);
case TYPENAME_DELETE:
return new DeleteEvent(json);
case TYPENAME_MOVE:
return new MoveEvent(json);
case TYPENAME_UI:
return new UIEvent(json);
default:
throw new JSONException("Unknown event type: " + typename);
}
}
@EventType
protected final int mTypeId;
protected final String mBlockId;
protected final String mWorkspaceId;
protected String mGroupId;
/**
* Base constructor for all BlocklyEvents.
*
* @param typeId The {@link EventType}.
* @param workspaceId The id of the Blockly workspace, or similar block container, if any.
* @param groupId The id string of the event group. Usually null for local events (assigned
* later); non-null for remote events.
* @param blockId The id string of the block affected. Null for a few event types (e.g., toolbox
* category).
*/
protected BlocklyEvent(@EventType int typeId, @Nullable String workspaceId,
@Nullable String groupId, @Nullable String blockId) {
validateEventType(typeId);
mTypeId = typeId;
mBlockId = blockId;
mWorkspaceId = workspaceId;
mGroupId = groupId;
}
/**
* Constructs BlocklyEvent with base attributes assigned from {@code json}.
*
* @param typeId The type of the event. Assumed to match {@link #JSON_TYPE} in {@code json}.
* @param json The JSON object with event attribute values.
* @throws JSONException
*/
protected BlocklyEvent(@EventType int typeId, JSONObject json) throws JSONException {
validateEventType(typeId);
mTypeId = typeId;
mWorkspaceId = json.optString(JSON_WORKSPACE_ID);
mGroupId = json.optString(JSON_GROUP_ID);
mBlockId = json.optString(JSON_BLOCK_ID);
}
/**
* @return The type identifier for this event.
*/
@EventType
public int getTypeId() {
return mTypeId;
}
/**
* @return The JSON type identifier string for this event.
*/
@NonNull
public String getTypeName() {
return TYPE_ID_TO_NAME.get(mTypeId);
}
/**
* This is the id of the "workspace", or similar container. This may refer to a
* {@link Workspace#getId()} workspace's id}, a toolbox
* ({@link BlocklyEvent#WORKSPACE_ID_TOOLBOX}), or the trash
* ({@link BlocklyEvent#WORKSPACE_ID_TRASH}).
*
* @return The identifier for the root container where this event occured.
*/
@NonNull
public String getWorkspaceId() {
return mWorkspaceId;
}
/**
* @return The identifier for the group of related events.
*/
@Nullable
public String getGroupId() {
return mGroupId;
}
/**
* @return The id of the primary or root affected block.
*/
@Nullable
public String getBlockId() {
return mBlockId;
}
public String toJsonString() throws JSONException {
JSONStringer out = new JSONStringer();
out.object();
out.key(JSON_TYPE);
out.value(getTypeName());
if (!TextUtils.isEmpty(mBlockId)) {
out.key(JSON_BLOCK_ID);
out.value(mBlockId);
}
if (!TextUtils.isEmpty(mGroupId)) {
out.key(JSON_GROUP_ID);
out.value(mGroupId);
}
writeJsonAttributes(out);
// Workspace id is not included to reduce size over network.
out.endObject();
return out.toString();
}
protected void setGroupId(String groupId) {
this.mGroupId = groupId;
}
protected abstract void writeJsonAttributes(JSONStringer out) throws JSONException;
/**
* Event fired when a property of a block changes.
*/
public static final class ChangeEvent extends BlocklyEvent {
/**
* Creates a ChangeEvent reflecting a change in the block's comment text.
*
* @param block The block where the state changed.
* @param oldValue The prior comment text.
* @param newValue The updated comment text.
* @return The new ChangeEvent.
*/
public static ChangeEvent newCommentTextEvent(
@NonNull Block block, @Nullable String oldValue, @Nullable String newValue) {
return new ChangeEvent(ELEMENT_COMMENT, block, null, oldValue, newValue);
}
/**
* Creates a ChangeEvent reflecting a change in a field's value.
*
* @param block The block where the state changed.
* @param field The field with the changed value.
* @param oldValue The prior value.
* @param newValue The updated value.
* @return The new ChangeEvent.
*/
public static ChangeEvent newFieldValueEvent(
@NonNull Block block, @NonNull Field field, @NonNull String oldValue,
@NonNull String newValue) {
return new ChangeEvent(ELEMENT_FIELD, block, field, oldValue, newValue);
}
/**
* Creates a ChangeEvent reflecting a change in the block's inlined inputs state.
*
* @param block The block where the state changed.
* @return The new ChangeEvent.
*/
public static ChangeEvent newInlineStateEvent(@NonNull Block block) {
boolean inline = block.getInputsInline();
return new ChangeEvent(ELEMENT_INLINE, block, null,
/* oldValue */ !inline ? "true" : "false",
/* newValue */ inline ? "true" : "false");
}
/**
* Creates a ChangeEvent reflecting a change in the block's mutation state.
*
* @param block The block where the state changed.
* @param oldValue The serialized version of the prior mutation state.
* @param newValue The serialized version of the updated mutation state.
* @return The new ChangeEvent.
*/
public static ChangeEvent newMutateEvent(
@NonNull Block block, @Nullable String oldValue, @Nullable String newValue) {
return new ChangeEvent(ELEMENT_MUTATE, block, null, oldValue, newValue);
}
@NonNull @ChangeElement
private final String mElementChanged;
@Nullable
private final String mFieldName;
@NonNull
private final String mOldValue;
@NonNull
private final String mNewValue;
/**
* Constructs a ChangeEvent, signifying {@code block}'s value changed.
*
* @param block The block containing the change.
* @param field The field containing the change, if the change is a field value. Otherwise
* null.
* @param oldValue The original value.
* @param newValue The new value.
*/
public ChangeEvent(@ChangeElement String element, @NonNull Block block,
@Nullable Field field, @Nullable String oldValue,
@Nullable String newValue) {
super(TYPE_CHANGE, block.getEventWorkspaceId(), null, block.getId());
mElementChanged = validateChangeElement(element);
if (mElementChanged == ELEMENT_FIELD) {
mFieldName = field.getName();
} else {
mFieldName = null; // otherwise ignore the field name
}
mOldValue = oldValue;
mNewValue = newValue;
}
/**
* Constructs a ChangeEvent from the JSON serialized representation.
*
* @param json The serialized ChangeEvent.
* @throws JSONException
*/
public ChangeEvent(@NonNull JSONObject json) throws JSONException {
super(TYPE_CHANGE, json);
if (TextUtils.isEmpty(mBlockId)) {
throw new JSONException(JSON_BLOCK_ID + " must be assigned.");
}
String element = json.getString(JSON_ELEMENT);
try {
mElementChanged = validateChangeElement(element);
} catch (IllegalArgumentException e) {
throw new JSONException("Invalid change element: " + element);
}
mFieldName = (mElementChanged == ELEMENT_FIELD) ? json.getString(JSON_NAME) : null;
mOldValue = json.optString(JSON_OLD_VALUE); // Not usually serialized.
mNewValue = json.getString(JSON_NEW_VALUE);
}
@NonNull @ChangeElement
public String getElement() {
return mElementChanged;
}
public String getFieldName() {
return mFieldName;
}
public String getOldValue() {
return mOldValue;
}
public String getNewValue() {
return mNewValue;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ChangeEvent{")
.append(mElementChanged);
if (mFieldName != null) {
sb.append(", field \"").append(mFieldName).append("\"");
}
sb.append(", old=\"").append(mOldValue)
.append("\", new=\"").append(mNewValue).append("\"}");
return sb.toString();
}
protected void writeJsonAttributes(JSONStringer out) throws JSONException {
out.key("element");
out.value(mElementChanged);
if (mFieldName != null) {
out.key("name");
out.value(mFieldName);
}
out.key("newValue");
out.value(mNewValue);
}
}
/**
* Event fired when a block is added to the workspace, possibly containing other child blocks
* and next blocks.
*/
public static final class CreateEvent extends BlocklyEvent {
private final String mXml;
private final List<String> mIds;
/**
* Constructs a {@code CreateEvent} for the given block.
*
* @param block The newly created block.
*/
public CreateEvent(@NonNull Block block) {
super(TYPE_CREATE, block.getEventWorkspaceId(), null, block.getId());
try {
mXml = BlocklyXmlHelper.writeBlockToXml(block, IOOptions.WRITE_ALL_DATA);
} catch (BlocklySerializerException e) {
throw new IllegalArgumentException("Invalid block for event serialization");
}
List<String> ids = new ArrayList<>();
block.addAllBlockIds(ids);
mIds = Collections.unmodifiableList(ids);
}
/**
* Constructs a CreateEvent from the JSON serialized representation.
*
* @param json The serialized CreateEvent.
* @throws JSONException
*/
public CreateEvent(JSONObject json) throws JSONException {
super(TYPE_CREATE, json);
if (mBlockId == null) {
throw new JSONException(JSON_BLOCK_ID + " must be assigned.");
}
mXml = json.getString(JSON_XML);
JSONArray jsonIds = json.getJSONArray("ids");
int count = jsonIds.length();
List<String> ids = new ArrayList<>(count);
for (int i = 0; i < count; ++i) {
ids.add(jsonIds.getString(i));
}
mIds = Collections.unmodifiableList(ids);
}
/**
* @return The XML serialization of all blocks created by this event.
*/
public String getXml() {
return mXml;
}
/**
* @return The list of all block ids for all blocks created by this event.
*/
public List<String> getIds() {
return mIds;
}
@Override
protected void writeJsonAttributes(JSONStringer out) throws JSONException {
out.key("xml");
out.value(mXml);
out.key("ids");
out.array();
for (String id : mIds) {
out.value(id);
}
out.endArray();
}
}
/**
* Event fired when a block is removed from the workspace.
*/
public static final class DeleteEvent extends BlocklyEvent {
private final String mOldXml;
private final List<String> mIds;
/**
* Constructs a {@code DeleteEvent}, signifying the removal of a block from the workspace.
*
* @param workspaceId The id of the workspace or similar block container (toolbox, trash)
* from which the block was deleted.
* @param block The root deleted block (or to-be-deleted block), with all children attached.
*/
public DeleteEvent(@NonNull String workspaceId, @NonNull Block block) {
super(TYPE_DELETE, workspaceId, null, block.getId());
try {
mOldXml = BlocklyXmlHelper.writeBlockToXml(block, IOOptions.WRITE_ALL_DATA);
} catch (BlocklySerializerException e) {
throw new IllegalArgumentException("Invalid block for event serialization");
}
List<String> ids = new ArrayList<>();
block.addAllBlockIds(ids);
mIds = Collections.unmodifiableList(ids);
}
/**
* Constructs a DeleteEvent from the JSON serialized representation.
*
* @param json The serialized DeleteEvent.
* @throws JSONException
*/
public DeleteEvent(@NonNull JSONObject json) throws JSONException {
super(TYPE_DELETE, json);
if (TextUtils.isEmpty(mBlockId)) {
throw new JSONException(TYPENAME_DELETE + " requires " + JSON_BLOCK_ID);
}
mOldXml = json.optString(JSON_OLD_VALUE); // Not usually used.
JSONArray ids = json.getJSONArray(JSON_IDS);
int count = ids.length();
List<String> temp = new ArrayList<>(count);
for (int i = 0; i < count; ++i) {
temp.add(ids.getString(i));
}
mIds = Collections.unmodifiableList(temp);
}
/**
* @return The XML serialization of all blocks deleted by this event.
*/
public String getXml() {
return mOldXml;
}
/**
* @return The list of all block ids for all blocks deleted by this event.
*/
public List<String> getIds() {
return mIds;
}
@Override
protected void writeJsonAttributes(JSONStringer out) throws JSONException {
out.key("ids");
out.array();
for (String id : mIds) {
out.value(id);
}
out.endArray();
}
}
/**
* Event fired when a block is moved on the workspace, or its parent connection is changed.
* <p/>
* This event must be created before the block is moved to capture the original position.
* After the move has been completed in the workspace, capture the updated position or parent
* using {@link #recordNew(Block)}. All of this is managed by {@link BlocklyController}, before
* {@link BlocklyController.EventsCallback}s receive the event.
*/
public static final class MoveEvent extends BlocklyEvent {
private static final String JSON_NEW_COORDINATE = "newCoordinate";
private static final String JSON_NEW_INPUT_NAME = "newInputName";
private static final String JSON_NEW_PARENT_ID = "newParentId";
@Nullable
private String mOldParentId;
@Nullable
private String mOldInputName;
private boolean mHasOldPosition;
private float mOldPositionX;
private float mOldPositionY;
// New values are recorded
@Nullable
private String mNewParentId;
@Nullable
private String mNewInputName;
private boolean mHasNewPosition;
private float mNewPositionX;
private float mNewPositionY;
/**
* Constructs a {@link MoveEvent} signifying the movement of a block on the workspace.
*
* @param block The root block of the move, while it is still in its original position.
*/
public MoveEvent(@NonNull Block block) {
super(TYPE_MOVE, block.getEventWorkspaceId(), null, block.getId());
Connection parentConnection = block.getParentConnection();
if (parentConnection == null) {
WorkspacePoint position = block.getPosition();
if (position == null) {
throw new IllegalStateException("Block must have parent or position.");
}
mHasOldPosition = true;
mOldPositionX = position.x;
mOldPositionY = position.y;
mOldParentId = null;
mOldInputName = null;
} else {
Input parentInput = parentConnection.getInput();
mOldParentId = parentConnection.getBlock().getId();
mOldInputName = parentInput == null ? null : parentInput.getName();
mHasOldPosition = false;
mOldPositionX = mOldPositionY = -1;
}
}
/**
* Constructs a MoveEvent from the JSON serialized representation.
*
* @param json The serialized MoveEvent.
* @throws JSONException
*/
public MoveEvent(JSONObject json) throws JSONException {
super(TYPE_MOVE, json);
if (TextUtils.isEmpty(mBlockId)) {
throw new JSONException(TYPENAME_MOVE + " requires " + JSON_BLOCK_ID);
}
// Old values are not stored in JSON
mOldParentId = null;
mOldInputName = null;
mOldPositionX = mOldPositionY = 0;
String newCoordinateStr = json.optString(JSON_NEW_COORDINATE);
if (newCoordinateStr != null) {
// JSON coordinates are always integers, separated by a comma.
int comma = newCoordinateStr.indexOf(',');
if (comma == -1) {
throw new JSONException(
"Invalid " + JSON_NEW_COORDINATE + ": " + newCoordinateStr);
}
try {
mNewPositionX = Integer.parseInt(newCoordinateStr.substring(0, comma));
mNewPositionY = Integer.parseInt(newCoordinateStr.substring(comma + 1));
} catch (NumberFormatException e) {
throw new JSONException(
"Invalid " + JSON_NEW_COORDINATE + ": " + newCoordinateStr);
}
} else {
}
}
public void recordNew(Block block) {
if (!block.getId().equals(mBlockId)) {
throw new IllegalArgumentException("Block id does not match original.");
}
Connection parentConnection = block.getParentConnection();
if (parentConnection == null) {
WorkspacePoint position = block.getPosition();
if (position == null) {
throw new IllegalStateException("Block must have parent or position.");
}
mHasNewPosition = true;
mNewPositionX = position.x;
mNewPositionY = position.y;
mNewParentId = null;
mNewInputName = null;
} else {
mNewParentId = parentConnection.getBlock().getId();
if (parentConnection.getType() == Connection.CONNECTION_TYPE_NEXT) {
mNewInputName = null;
} else {
mNewInputName = parentConnection.getInput().getName();
}
mHasNewPosition = false;
mNewPositionX = mNewPositionY = -1;
}
}
public String getOldParentId() {
return mOldParentId;
}
public String getOldInputName() {
return mOldInputName;
}
public boolean hasOldPosition() {
return mHasOldPosition;
}
public boolean getOldWorkspacePosition(WorkspacePoint output) {
if (mHasOldPosition) {
output.set(mOldPositionX, mOldPositionY);
}
return mHasOldPosition;
}
public String getNewParentId() {
return mNewParentId;
}
public String getNewInputName() {
return mNewInputName;
}
public boolean hasNewPosition() {
return mHasNewPosition;
}
public boolean getNewWorkspacePosition(WorkspacePoint output) {
if (mHasNewPosition) {
output.set(mNewPositionX, mNewPositionY);
}
return mHasNewPosition;
}
@Override
protected void writeJsonAttributes(JSONStringer out) throws JSONException {
if (mNewParentId != null) {
out.key(JSON_NEW_PARENT_ID);
out.value(mNewParentId);
}
if (mNewInputName != null) {
out.key(JSON_NEW_INPUT_NAME);
out.value(mNewInputName);
}
if (mHasNewPosition) {
out.key(JSON_NEW_COORDINATE);
StringBuilder sb = new StringBuilder();
sb.append(mNewPositionX).append(',').append(mNewPositionY);
out.value(sb.toString());
}
}
}
/**
* Event class for user interface related actions, including selecting blocks, opening/closing
* the toolbox or trash, and changing toolbox categories.
*/
public static final class UIEvent extends BlocklyEvent {
private final @BlocklyEvent.UIElement String mUiElement;
private final String mOldValue;
private final String mNewValue;
public UIEvent newBlockClickedEvent(@NonNull Block block) {
return new UIEvent(ELEMENT_CLICK, block, null, null);
}
public UIEvent newBlockCommentEvent(@NonNull Block block,
boolean openedBefore, boolean openedAfter) {
return new UIEvent(ELEMENT_COMMENT_OPEN, block,
openedBefore ? "true" : "false", openedAfter ? "true" : "false");
}
public UIEvent newBlockMutatorEvent(@NonNull Block block,
boolean openedBefore, boolean openedAfter) {
return new UIEvent(ELEMENT_MUTATOR_OPEN, block,
openedBefore ? "true" : "false", openedAfter ? "true" : "false");
}
public UIEvent newBlockSelectedEvent(@NonNull Block block,
boolean selectedBefore, boolean selectedAfter) {
return new UIEvent(ELEMENT_SELECTED, block,
selectedBefore ? "true" : "false", selectedAfter ? "true" : "false");
}
public UIEvent newBlockWarningEvent(@NonNull Block block,
boolean openedBefore, boolean openedAfter) {
return new UIEvent(ELEMENT_WARNING_OPEN, block,
openedBefore ? "true" : "false", openedAfter ? "true" : "false");
}
public UIEvent newToolboxCategoryEvent(@Nullable String oldValue,
@Nullable String newValue) {
return new UIEvent(ELEMENT_CATEGORY, null, oldValue, newValue);
}
/**
* Constructs a block related UI event, such as clicked, selected, comment opened, mutator
* opened, or warning opened.
*
* @param element The UI element that changed.
* @param block The related block. Null for toolbox category events.
* @param oldValue The value before the event. Booleans are mapped to "true" and "false".
* @param newValue The value after the event. Booleans are mapped to "true" and "false".
*/
public UIEvent(@BlocklyEvent.UIElement String element, @Nullable Block block,
String oldValue, String newValue) {
super(TYPE_UI,
block == null ? null : block.getEventWorkspaceId(),
/* group id */ null,
block == null ? null : block.getId());
this.mUiElement = validateUiElement(element);
this.mOldValue = oldValue;
this.mNewValue = newValue;
}
/**
* Constructs a UIEvent from the JSON serialized representation.
*
* @param json The serialized UIEvent.
* @throws JSONException
*/
public UIEvent(JSONObject json) throws JSONException {
super(TYPE_UI, json);
String element = json.getString(JSON_ELEMENT);
try {
mUiElement = validateUiElement(element);
} catch (IllegalArgumentException e) {
throw new JSONException("Invalid UI element: " + element);
}
if (mUiElement != ELEMENT_CATEGORY && TextUtils.isEmpty(mBlockId)) {
throw new JSONException("UI element " + mUiElement + " requires " + JSON_BLOCK_ID);
}
this.mOldValue = json.optString(JSON_OLD_VALUE); // Rarely used.
this.mNewValue = json.optString(JSON_NEW_VALUE);
if (mUiElement != ELEMENT_CATEGORY && mUiElement != ELEMENT_CLICK
&& TextUtils.isEmpty(mNewValue)) {
throw new JSONException("UI element " + mUiElement + " requires " + JSON_NEW_VALUE);
}
}
public String getElement() {
return mUiElement;
}
public String getOldValue() {
return mOldValue;
}
public String getNewValue() {
return mNewValue;
}
@Override
protected void writeJsonAttributes(JSONStringer out) throws JSONException {
out.key("element");
out.value(mUiElement);
if (mNewValue != null) {
out.key("newValue");
out.value(mNewValue);
}
// Old value is not included to reduce size over network.
}
}
/**
* Ensures {@code typeId} is a singular valid event id.
* @param typeId The typeId to test.
*/
private static void validateEventType(int typeId) {
if (typeId <= 0 || typeId > TYPE_ALL // Outside bounds.
|| ((typeId & (typeId - 1)) != 0)) /* Not a power of two */ {
throw new IllegalArgumentException("Invalid typeId: " + typeId);
}
}
/**
* @param eventTypeName A JSON "type" event name.
* @return returns The {@link EventType} for {@code eventTypeName}, or 0 if not valid.
* @throws IllegalArgumentException when
*/
private static int getIdForEventName(final String eventTypeName) {
Integer typeId = TYPE_NAME_TO_ID.get(eventTypeName);
if (typeId == null) {
return 0;
}
return typeId;
}
/**
* @param changeElement An element name string, as used by {@link ChangeEvent}s.
* @return The canonical (identity comparable) version of {@code changeElement}.
* @throws IllegalArgumentException If {@code changeElement} is not a {@link ChangeElement}.
*/
private static String validateChangeElement(final String changeElement) {
switch (changeElement) {
case ELEMENT_COLLAPSED:
return ELEMENT_COLLAPSED;
case ELEMENT_COMMENT:
return ELEMENT_COMMENT;
case ELEMENT_DISABLED:
return ELEMENT_DISABLED;
case ELEMENT_FIELD:
return ELEMENT_FIELD;
case ELEMENT_INLINE:
return ELEMENT_INLINE;
case ELEMENT_MUTATE:
return ELEMENT_MUTATE;
default:
throw new IllegalArgumentException("Unrecognized change element: " + changeElement);
}
}
/**
* @param uiElement An element name string, as used by {@link UIEvent}s.
* @return The canonical (identity comparable) version of the {@code uiElement}.
* @throws IllegalArgumentException If {@code changeElement} is not a {@link UIElement}.
*/
private static String validateUiElement(final String uiElement) {
switch (uiElement) {
case ELEMENT_CATEGORY:
return ELEMENT_CATEGORY;
case ELEMENT_CLICK:
return ELEMENT_CLICK;
case ELEMENT_COMMENT_OPEN:
return ELEMENT_COMMENT_OPEN;
case ELEMENT_MUTATOR_OPEN:
return ELEMENT_MUTATOR_OPEN;
case ELEMENT_SELECTED:
return ELEMENT_SELECTED;
case ELEMENT_WARNING_OPEN:
return ELEMENT_WARNING_OPEN;
default:
throw new IllegalArgumentException("Unrecognized UI element: " + uiElement);
}
}
}
|
apache/directory-studio | 35,800 | plugins/openldap.config.editor/src/main/java/org/apache/directory/studio/openldap/config/editor/pages/OverviewPage.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.openldap.config.editor.pages;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.api.util.Strings;
import org.apache.directory.studio.common.ui.widgets.BaseWidgetUtils;
import org.apache.directory.studio.common.ui.widgets.TableWidget;
import org.apache.directory.studio.common.ui.widgets.WidgetModifyListener;
import org.apache.directory.studio.openldap.common.ui.model.LogLevelEnum;
import org.apache.directory.studio.openldap.common.ui.dialogs.LogLevelDialog;
import org.apache.directory.studio.openldap.config.OpenLdapConfigurationPluginUtils;
import org.apache.directory.studio.openldap.config.editor.OpenLdapServerConfigurationEditor;
import org.apache.directory.studio.openldap.config.editor.overlays.ModuleWrapper;
import org.apache.directory.studio.openldap.config.editor.overlays.ModuleWrapperLabelProvider;
import org.apache.directory.studio.openldap.config.editor.overlays.ModuleWrapperViewerSorter;
import org.apache.directory.studio.openldap.config.editor.pages.OverlaysPage;
import org.apache.directory.studio.openldap.config.editor.wrappers.DatabaseWrapper;
import org.apache.directory.studio.openldap.config.editor.wrappers.DatabaseWrapperLabelProvider;
import org.apache.directory.studio.openldap.config.editor.wrappers.DatabaseWrapperViewerComparator;
import org.apache.directory.studio.openldap.config.editor.wrappers.ServerIdDecorator;
import org.apache.directory.studio.openldap.config.editor.wrappers.ServerIdWrapper;
import org.apache.directory.studio.openldap.config.model.OlcGlobal;
import org.apache.directory.studio.openldap.config.model.OlcModuleList;
import org.apache.directory.studio.openldap.config.model.database.OlcDatabaseConfig;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Hyperlink;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
/**
* This class represents the General Page of the Server Configuration Editor. It exposes some
* of the configured elements, and allow the user to configure some basic parameters :
* <ul>
* <li>olcServerID</li>
* <li>olcConfigDir</li>
* <li>olcConfigFile</li>
* <li>olcPidFile</li>
* <li>olcLogFile</li>
* <li>olcLogLevel</li>
* </ul>
*
* The olcConfigFile is not handled, it's deprecated.
* <pre>
* .-----------------------------------------------------------------------------------.
* | Overview |
* +-----------------------------------------------------------------------------------+
* | .-------------------------------------------------------------------------------. |
* | |V Global parameters | |
* | +-------------------------------------------------------------------------------+ |
* | | Server ID : | |
* | | +-----------------------------------------------------------------+ | |
* | | | | (Add) | |
* | | | | (Edit) | |
* | | | | (Delete) | |
* | | +-----------------------------------------------------------------+ | |
* | | | |
* | | Configuration Dir : [ ] Pid File : [ ] | |
* | | Log File : [ ] Log Level : [ ] (edit)| |
* | +-------------------------------------------------------------------------------+ |
* | |
* | .---------------------------------------. .------------------------------------. |
* | |V Databases | |V Overlays | |
* | +---------------------------------------+ +------------------------------------+ |
* | | +----------------------------------+ | | +--------------------------------+ | |
* | | | abc | | | | module 1 | | |
* | | | xyz | | | | module 2 | | |
* | | +----------------------------------+ | | +--------------------------------+ | |
* | | <Advanced databases configuration> | | <Overlays configuration> | |
* | +---------------------------------------+ +------------------------------------+ |
* | |
* | .-------------------------------------------------------------------------------. |
* | |V Configuration detail | |
* | +-------------------------------------------------------------------------------+ |
* | | <Security configuration> <Tunning configuration> | |
* | | <Schemas configuration> <Options configuration> | |
* | +-------------------------------------------------------------------------------+ |
* +-----------------------------------------------------------------------------------+
* </pre>
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
public class OverviewPage extends OpenLDAPServerConfigurationEditorPage
{
/** The Page ID*/
public static final String ID = OverviewPage.class.getName(); //$NON-NLS-1$
/** The Page Title */
private static final String TITLE = Messages.getString( "OpenLDAPOverviewPage.Title" ); //$NON-NLS-1$
// UI Controls
/** The serverID wrapper */
private List<ServerIdWrapper> serverIdWrappers = new ArrayList<>();
/** The Widget used to manage ServerID */
private TableWidget<ServerIdWrapper> serverIdTableWidget;
/** olcConfigDir */
private Text configDirText;
/** olcPidFile */
private Text pidFileText;
/** olcLogFile */
private Text logFileText;
/** olcLogLevel */
private Text logLevelText;
private Button logLevelEditButton;
/** The table listing all the existing databases */
private TableViewer databaseViewer;
/** The database wrappers */
private List<DatabaseWrapper> databaseWrappers = new ArrayList<>();
/** This link opens the Databases configuration tab */
private Hyperlink databasesPageLink;
/** The table listing all the existing modules */
private TableViewer moduleViewer;
/** The module wrappers */
private List<ModuleWrapper> moduleWrappers = new ArrayList<>();
/** This link opens the Overlays configuration tab */
private Hyperlink overlaysPageLink;
/** This link opens the Security configuration tab */
private Hyperlink securityPageLink;
/** This link opens the Tuning configuration tab */
private Hyperlink tuningPageLink;
/** This link opens the Schema configuration tab */
private Hyperlink schemaPageLink;
/** This link opens the Options configuration tab */
private Hyperlink optionsPageLink;
/**
* The olcLogFile listener
*/
private ModifyListener logFileTextListener = event ->
getConfiguration().getGlobal().setOlcLogFile( logFileText.getText() );
/**
* The olcConfigDir listener
*/
private ModifyListener configDirTextListener = event ->
getConfiguration().getGlobal().setOlcConfigDir( configDirText.getText() );
/**
* The olcPidFile listener
*/
private ModifyListener pidFileTextListener = event ->
getConfiguration().getGlobal().setOlcPidFile( pidFileText.getText() );
/**
* The olcLogLevl listener
*/
private SelectionListener logLevelEditButtonSelectionListener = new SelectionAdapter()
{
@Override
public void widgetSelected( SelectionEvent e )
{
// Creating and opening a LogLevel dialog
String logLevelStr = logLevelText.getText();
int logLevelValue = LogLevelEnum.NONE.getValue();
if ( !Strings.isEmpty( logLevelStr ) )
{
logLevelValue = LogLevelEnum.parseLogLevel( logLevelStr );
}
LogLevelDialog dialog = new LogLevelDialog( logLevelEditButton.getShell(), logLevelValue );
if ( LogLevelDialog.OK == dialog.open() )
{
logLevelStr = LogLevelEnum.getLogLevelText( dialog.getLogLevelValue() );
logLevelText.setText( logLevelStr );
List<String> logLevelList = new ArrayList<>();
logLevelList.add( logLevelStr );
getConfiguration().getGlobal().setOlcLogLevel( logLevelList );
}
}
};
/**
* Creates a new instance of GeneralPage.
*
* @param editor the associated editor
*/
public OverviewPage( OpenLdapServerConfigurationEditor editor )
{
super( editor, ID, TITLE );
}
/**
* Databases configuration hyper link adapter
*/
private HyperlinkAdapter databasesPageLinkListener = new HyperlinkAdapter()
{
@Override
public void linkActivated( HyperlinkEvent e )
{
getServerConfigurationEditor().showPage( DatabasesPage.class );
}
};
/**
* Overlays configuration hyper link adapter
*/
private HyperlinkAdapter overlaysPageLinkListener = new HyperlinkAdapter()
{
@Override
public void linkActivated( HyperlinkEvent e )
{
getServerConfigurationEditor().showPage( OverlaysPage.class );
}
};
/**
* Security configuration hyper link adapter
*/
private HyperlinkAdapter securityPageLinkListener = new HyperlinkAdapter()
{
@Override
public void linkActivated( HyperlinkEvent e )
{
getServerConfigurationEditor().showPage( SecurityPage.class );
}
};
/**
* Tuning configuration hyper link adapter
*/
private HyperlinkAdapter tuningPageLinkListener = new HyperlinkAdapter()
{
@Override
public void linkActivated( HyperlinkEvent e )
{
getServerConfigurationEditor().showPage( TuningPage.class );
}
};
/**
* Schema configuration hyper link adapter
*/
private HyperlinkAdapter schemaPageLinkListener = new HyperlinkAdapter()
{
@Override
public void linkActivated( HyperlinkEvent e )
{
//getServerConfigurationEditor().showPage( SchemaPage.class );
}
};
/**
* Options configuration hyper link adapter
*/
private HyperlinkAdapter optionsPageLinkListener = new HyperlinkAdapter()
{
@Override
public void linkActivated( HyperlinkEvent e )
{
getServerConfigurationEditor().showPage( OptionsPage.class );
}
};
// The listener for the ServerIdTableWidget
private WidgetModifyListener serverIdTableWidgetListener = event ->
{
// Process the parameter modification
TableWidget<ServerIdWrapper> serverIdWrapperTable = (TableWidget<ServerIdWrapper>)event.getSource();
List<String> serverIds = new ArrayList<>();
for ( Object serverIdWrapper : serverIdWrapperTable.getElements() )
{
String str = serverIdWrapper.toString();
serverIds.add( str );
}
getConfiguration().getGlobal().setOlcServerID( serverIds );
};
/**
* Creates the global Overview OpenLDAP config Tab. It contains 3 rows, with
* one or two sections in each :
*
* <pre>
* +---------------------------------------------------------------------+
* | |
* | Global parameters |
* | |
* +-----------------------------------+---------------------------------+
* | | |
* | Databases | Overlays |
* | | |
* +-----------------------------------+---------------------------------+
* | |
* | Configuration links |
* | |
* +---------------------------------------------------------------------+
* </pre>
* {@inheritDoc}
*/
protected void createFormContent( Composite parent, FormToolkit toolkit )
{
TableWrapLayout twl = new TableWrapLayout();
twl.numColumns = 2;
parent.setLayout( twl );
// The upper part
Composite upperComposite = toolkit.createComposite( parent );
upperComposite.setLayout( new GridLayout() );
TableWrapData leftCompositeTableWrapData = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP, 1, 2 );
leftCompositeTableWrapData.grabHorizontal = true;
upperComposite.setLayoutData( leftCompositeTableWrapData );
// The middle left part
Composite middleLeftComposite = toolkit.createComposite( parent );
middleLeftComposite.setLayout( new GridLayout() );
TableWrapData middleLeftCompositeTableWrapData = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP, 1, 1 );
middleLeftCompositeTableWrapData.grabHorizontal = true;
middleLeftComposite.setLayoutData( middleLeftCompositeTableWrapData );
// The middle right part
Composite middleRightComposite = toolkit.createComposite( parent );
middleRightComposite.setLayout( new GridLayout() );
TableWrapData middleRightCompositeTableWrapData = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP, 1, 1 );
middleRightCompositeTableWrapData.grabHorizontal = true;
middleRightComposite.setLayoutData( middleRightCompositeTableWrapData );
// The lower part
Composite lowerComposite = toolkit.createComposite( parent );
lowerComposite.setLayout( new GridLayout() );
TableWrapData lowerCompositeTableWrapData = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP, 1, 2 );
lowerCompositeTableWrapData.grabHorizontal = true;
lowerComposite.setLayoutData( lowerCompositeTableWrapData );
// Now, create the sections
createGlobalSection( toolkit, upperComposite );
createDatabasesSection( toolkit, middleLeftComposite );
createOverlaysSection( toolkit, middleRightComposite );
createConfigDetailsLinksSection( toolkit, lowerComposite );
}
/**
* Creates the global section. This section is a grid with 4 columns,
* where we configure the global options. We support the configuration
* of those parameters :
* <ul>
* <li>olcServerID</li>
* <li>olcConfigDir</li>
* <li>olcPidFile</li>
* <li>olcLogFile</li>
* <li>olcLogLevel</li>
* </ul>
*
* <pre>
* .-------------------------------------------------------------------------------.
* |V Global parameters |
* +-------------------------------------------------------------------------------+
* | Server ID : |
* | +-----------------------------------------------------------------+ |
* | | | (Add) |
* | | | (Edit) |
* | | | (Delete) |
* | +-----------------------------------------------------------------+ |
* | |
* | Configuration Dir : [ ] Pid File : [ ] |
* | Log File : [ ] Log Level : [ ] (edit)|
* +-------------------------------------------------------------------------------+
* </pre>
*
*
* @param toolkit the toolkit
* @param parent the parent composite
*/
private void createGlobalSection( FormToolkit toolkit, Composite parent )
{
// Creation of the section
Section section = createSection( toolkit, parent, Messages.getString( "OpenLDAPOverviewPage.GlobalSection" ) );
// The content
Composite globalSectionComposite = toolkit.createComposite( section );
toolkit.paintBordersFor( globalSectionComposite );
GridLayout gridLayout = new GridLayout( 5, false );
gridLayout.marginHeight = gridLayout.marginWidth = 0;
globalSectionComposite.setLayout( gridLayout );
section.setClient( globalSectionComposite );
// The ServerID parameter.
Label serverIdLabel = toolkit.createLabel( globalSectionComposite, Messages.getString( "OpenLDAPOverviewPage.ServerID" ) ); //$NON-NLS-1$
serverIdLabel.setLayoutData( new GridData( SWT.FILL, SWT.FILL, false, false, 5, 1 ) );
// The ServerID widget
serverIdTableWidget = new TableWidget<>( new ServerIdDecorator( section.getShell() ) );
serverIdTableWidget.createWidgetWithEdit( globalSectionComposite, toolkit );
serverIdTableWidget.getControl().setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 5, 1 ) );
serverIdTableWidget.addWidgetModifyListener( serverIdTableWidgetListener );
// One blank line
for ( int i = 0; i < gridLayout.numColumns; i++ )
{
toolkit.createLabel( globalSectionComposite, TABULATION );
}
// The ConfigDir parameter
toolkit.createLabel( globalSectionComposite, Messages.getString( "OpenLDAPOverviewPage.ConfigDir" ) ); //$NON-NLS-1$
configDirText = createConfigDirText( toolkit, globalSectionComposite );
// The PidFile parameter
toolkit.createLabel( globalSectionComposite, Messages.getString( "OpenLDAPOverviewPage.PidFile" ) ); //$NON-NLS-1$
pidFileText = createPidFileText( toolkit, globalSectionComposite );
// The LogFile parameter
toolkit.createLabel( globalSectionComposite, Messages.getString( "OpenLDAPOverviewPage.LogFile" ) ); //$NON-NLS-1$
logFileText = createLogFileText( toolkit, globalSectionComposite );
// The LogLevel parameter
toolkit.createLabel( globalSectionComposite, Messages.getString( "OpenLDAPOverviewPage.LogLevel" ) );
logLevelText = BaseWidgetUtils.createText( globalSectionComposite, "", 1 );
logLevelText.setEditable( false );
logLevelEditButton = BaseWidgetUtils.createButton( globalSectionComposite,
Messages.getString( "OpenLDAPSecurityPage.EditLogLevels" ), 1 );
logLevelEditButton.addSelectionListener( logLevelEditButtonSelectionListener );
}
/**
* Creates the Databases section. It only expose the existing databases,
* they can't be changed.
*
* <pre>
* .------------------------------------.
* |V Databases |
* +------------------------------------+
* | +-------------------------------+ |
* | | abc | |
* | | xyz | |
* | +-------------------------------+ |
* | <Advanced databases configuration> |
* +------------------------------------+
* </pre>
*
* @param toolkit the toolkit
* @param parent the parent composite
*/
private void createDatabasesSection( FormToolkit toolkit, Composite parent )
{
// Creation of the section
Section section = createSection( toolkit, parent, Messages.getString( "OpenLDAPOverviewPage.DatabasesSection" ) );
// The content
Composite composite = toolkit.createComposite( section );
toolkit.paintBordersFor( composite );
GridLayout gridLayout = new GridLayout( 1, false );
gridLayout.marginHeight = gridLayout.marginWidth = 0;
composite.setLayout( gridLayout );
section.setClient( composite );
// The inner composite
Composite databaseComposite = toolkit.createComposite( section );
databaseComposite.setLayout( new GridLayout( 1, false ) );
toolkit.paintBordersFor( databaseComposite );
section.setClient( databaseComposite );
section.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
// Creating the Table and Table Viewer
Table table = toolkit.createTable( databaseComposite, SWT.NONE );
GridData gd = new GridData( SWT.FILL, SWT.FILL, true, true, 1, 5 );
gd.heightHint = 100;
gd.widthHint = 100;
table.setLayoutData( gd );
databaseViewer = new TableViewer( table );
databaseViewer.setContentProvider( new ArrayContentProvider() );
databaseViewer.setLabelProvider( new DatabaseWrapperLabelProvider() );
databaseViewer.setComparator( new DatabaseWrapperViewerComparator() );
// Databases Page Link
databasesPageLink = toolkit.createHyperlink( databaseComposite,
Messages.getString( "OpenLDAPOverviewPage.DatabasesPageLink" ), SWT.NONE ); //$NON-NLS-1$
databasesPageLink.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 1, 1 ) );
databasesPageLink.addHyperlinkListener( databasesPageLinkListener );
}
/**
* Creates the Overlays section. It only expose the existing overlays,
* they can't be changed.
*
* <pre>
* .------------------------------------.
* |V Overlays |
* +------------------------------------+
* | +-------------------------------+ |
* | | abc | |
* | | xyz | |
* | +-------------------------------+ |
* | <Advanced Overlays configuration> |
* +------------------------------------+
* </pre>
*
* @param toolkit the toolkit
* @param parent the parent composite
*/
private void createOverlaysSection( FormToolkit toolkit, Composite parent )
{
// Creation of the section
Section section = createSection( toolkit, parent, Messages.getString( "OpenLDAPOverviewPage.OverlaysSection" ) );
// The content
Composite composite = toolkit.createComposite( section );
toolkit.paintBordersFor( composite );
GridLayout gridLayout = new GridLayout( 1, false );
gridLayout.marginHeight = gridLayout.marginWidth = 0;
composite.setLayout( gridLayout );
section.setClient( composite );
// The inner composite
Composite overlayComposite = toolkit.createComposite( section );
overlayComposite.setLayout( new GridLayout( 1, false ) );
toolkit.paintBordersFor( overlayComposite );
section.setClient( overlayComposite );
section.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
// Creating the Table and Table Viewer
Table table = toolkit.createTable( overlayComposite, SWT.NONE );
GridData gd = new GridData( SWT.FILL, SWT.FILL, true, true, 1, 5 );
gd.heightHint = 100;
gd.widthHint = 100;
table.setLayoutData( gd );
moduleViewer = new TableViewer( table );
moduleViewer.setContentProvider( new ArrayContentProvider() );
moduleViewer.setLabelProvider( new ModuleWrapperLabelProvider() );
moduleViewer.setComparator( new ModuleWrapperViewerSorter() );
// Overlays Page Link
overlaysPageLink = toolkit.createHyperlink( overlayComposite,
Messages.getString( "OpenLDAPOverviewPage.OverlaysPageLink" ), SWT.NONE ); //$NON-NLS-1$
overlaysPageLink.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 1, 1 ) );
overlaysPageLink.addHyperlinkListener( overlaysPageLinkListener );
}
/**
* Creates the configuration details section. It just links to some other pages
*
* <pre>
* .----------------------------------------------------.
* |V Configuration detail |
* +----------------------------------------------------+
* | <Security configuration> <Tunning configuration> |
* | <Schemas configuration> <Options configuration> |
* +----------------------------------------------------+
* </pre>
*
* @param toolkit the toolkit
* @param parent the parent composite
*/
private void createConfigDetailsLinksSection( FormToolkit toolkit, Composite parent )
{
// Creation of the section
Section section = createSection( toolkit, parent, Messages.getString( "OpenLDAPOverviewPage.ConfigDetailsSection" ) );
// The content
Composite composite = toolkit.createComposite( section );
toolkit.paintBordersFor( composite );
GridLayout gridLayout = new GridLayout( 2, false );
gridLayout.marginHeight = gridLayout.marginWidth = 0;
composite.setLayout( gridLayout );
section.setClient( composite );
// Security Page Link
securityPageLink = toolkit.createHyperlink( composite,
Messages.getString( "OpenLDAPOverviewPage.SecurityPageLink" ), SWT.NONE ); //$NON-NLS-1$
securityPageLink.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 1, 1 ) );
securityPageLink.addHyperlinkListener( securityPageLinkListener );
// Tuning Page Link
tuningPageLink = toolkit.createHyperlink( composite,
Messages.getString( "OpenLDAPOverviewPage.TuningPageLink" ), SWT.NONE ); //$NON-NLS-1$
tuningPageLink.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 1, 1 ) );
tuningPageLink.addHyperlinkListener( tuningPageLinkListener );
// Schema Page Link
schemaPageLink = toolkit.createHyperlink( composite,
Messages.getString( "OpenLDAPOverviewPage.SchemaPageLink" ), SWT.NONE ); //$NON-NLS-1$
schemaPageLink.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 1, 1 ) );
schemaPageLink.addHyperlinkListener( schemaPageLinkListener );
// Options Page Link
optionsPageLink = toolkit.createHyperlink( composite,
Messages.getString( "OpenLDAPOverviewPage.OptionsPageLink" ), SWT.NONE ); //$NON-NLS-1$
optionsPageLink.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 1, 1 ) );
optionsPageLink.addHyperlinkListener( optionsPageLinkListener );
}
/**
* Creates a Text that can be used to enter an ConfigDir.
*
* @param toolkit the toolkit
* @param parent the parent
* @return a Text that can be used to enter a config Dir
*/
private Text createConfigDirText( FormToolkit toolkit, Composite parent )
{
final Text configDirText = toolkit.createText( parent, "" ); //$NON-NLS-1$
GridData gd = new GridData( SWT.NONE, SWT.NONE, false, false );
gd.widthHint = 300;
configDirText.setLayoutData( gd );
// No more than 512 digits
configDirText.setTextLimit( 512 );
// The associated listener
addModifyListener( configDirText, configDirTextListener );
return configDirText;
}
/**
* Creates a Text that can be used to enter a PID file.
*
* @param toolkit the toolkit
* @param parent the parent
* @return a Text that can be used to enter a PID file
*/
private Text createPidFileText( FormToolkit toolkit, Composite parent )
{
final Text pidFileText = toolkit.createText( parent, "" ); //$NON-NLS-1$
GridData gd = new GridData( SWT.FILL, SWT.NONE, false, true, 2, 1 );
gd.widthHint = 300;
pidFileText.setLayoutData( gd );
// No more than 512 digits
pidFileText.setTextLimit( 512 );
// The associated listener
addModifyListener( pidFileText, pidFileTextListener );
return pidFileText;
}
/**
* Creates a Text that can be used to enter a Log file.
*
* @param toolkit the toolkit
* @param parent the parent
* @return a Text that can be used to enter a Log file
*/
private Text createLogFileText( FormToolkit toolkit, Composite parent )
{
final Text logFileText = toolkit.createText( parent, "" ); //$NON-NLS-1$
GridData gd = new GridData( SWT.NONE, SWT.NONE, false, false );
gd.widthHint = 300;
logFileText.setLayoutData( gd );
// No more than 512 digits
logFileText.setTextLimit( 512 );
// The associated listener
addModifyListener( logFileText, logFileTextListener );
return logFileText;
}
/**
* Get the various LogLevel values, and concatenate them in a String
*/
private String getLogLevel()
{
List<String> logLevelList = getConfiguration().getGlobal().getOlcLogLevel();
if ( logLevelList == null )
{
return "none";
}
boolean isFirst = true;
StringBuilder sb = new StringBuilder();
for ( String logLevel : logLevelList )
{
if ( isFirst )
{
isFirst = false;
}
else
{
sb.append( " " );
}
sb.append( logLevel );
}
return sb.toString();
}
/**
* {@inheritDoc}
*/
public void refreshUI()
{
if ( isInitialized() )
{
removeListeners();
// Getting the global configuration object
OlcGlobal global = getConfiguration().getGlobal();
if ( global != null )
{
// Update the ServerIDText
// Update the DatabaseTableViewer
serverIdWrappers.clear();
for ( String serverIdWrapper : global.getOlcServerID() )
{
serverIdWrappers.add( new ServerIdWrapper( serverIdWrapper ) );
}
serverIdTableWidget.setElements( serverIdWrappers );
// Update the ConfigDirText
BaseWidgetUtils.setValue( global.getOlcConfigDir(), configDirText );
// Update the LogFIleText
BaseWidgetUtils.setValue( global.getOlcLogFile(), logFileText );
// Update the DatabaseTableViewer
databaseWrappers.clear();
for ( OlcDatabaseConfig database : getConfiguration().getDatabases() )
{
databaseWrappers.add( new DatabaseWrapper( database ) );
}
databaseViewer.setInput( databaseWrappers );
// Update the OverlaysTableViewer
moduleWrappers.clear();
for ( OlcModuleList moduleList : getConfiguration().getModules() )
{
List<String> modules = moduleList.getOlcModuleLoad();
int index = OpenLdapConfigurationPluginUtils.getOrderingPostfix( moduleList.getCn().get( 0 ) );
if ( modules != null )
{
for ( String module : modules )
{
int order = OpenLdapConfigurationPluginUtils.getOrderingPrefix( module );
String strippedModule = OpenLdapConfigurationPluginUtils.stripOrderingPrefix( module );
String strippedModuleListName = OpenLdapConfigurationPluginUtils.stripOrderingPostfix( moduleList.getCn().get( 0 ) );
moduleWrappers.add( new ModuleWrapper( strippedModuleListName, index, strippedModule, moduleList.
getOlcModulePath(), order ) );
}
}
}
moduleViewer.setInput( moduleWrappers );
// Update the LogLevelWidget
String logLevels = getLogLevel();
logLevelText.setText( logLevels );
addListeners();
}
}
}
/**
* Removes the listeners
*/
private void removeListeners()
{
// The serverID Text
removeDirtyListener( serverIdTableWidget );
// The configDir Text
removeDirtyListener( configDirText );
// The pidFile Text
removeDirtyListener( pidFileText );
// The logFile Text
removeDirtyListener( logFileText );
// The LogLevel Widget
removeDirtyListener( logLevelText );
}
/**
* Adds listeners to UI Controls.
*/
private void addListeners()
{
// The serverID Text
addDirtyListener( serverIdTableWidget );
// The configDir Text
addDirtyListener( configDirText );
// The pidFile Text
addDirtyListener( pidFileText );
// The logFile Text
addDirtyListener( logFileText );
// The LogLevel Widget
addDirtyListener( logLevelText );
}
}
|
apache/fineract | 35,853 | fineract-provider/src/main/java/org/apache/fineract/portfolio/account/service/StandingInstructionReadPlatformServiceImpl.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.account.service;
import static org.apache.fineract.portfolio.account.service.AccountTransferEnumerations.accountType;
import static org.apache.fineract.portfolio.account.service.AccountTransferEnumerations.recurrenceType;
import static org.apache.fineract.portfolio.account.service.AccountTransferEnumerations.standingInstructionPriority;
import static org.apache.fineract.portfolio.account.service.AccountTransferEnumerations.standingInstructionStatus;
import static org.apache.fineract.portfolio.account.service.AccountTransferEnumerations.standingInstructionType;
import static org.apache.fineract.portfolio.account.service.AccountTransferEnumerations.transferType;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.MonthDay;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.apache.fineract.infrastructure.core.data.EnumOptionData;
import org.apache.fineract.infrastructure.core.domain.JdbcSupport;
import org.apache.fineract.infrastructure.core.service.DateUtils;
import org.apache.fineract.infrastructure.core.service.Page;
import org.apache.fineract.infrastructure.core.service.PaginationHelper;
import org.apache.fineract.infrastructure.core.service.SearchParameters;
import org.apache.fineract.infrastructure.core.service.database.DatabaseSpecificSQLGenerator;
import org.apache.fineract.infrastructure.security.utils.ColumnValidator;
import org.apache.fineract.organisation.office.data.OfficeData;
import org.apache.fineract.organisation.office.service.OfficeReadPlatformService;
import org.apache.fineract.portfolio.account.PortfolioAccountType;
import org.apache.fineract.portfolio.account.data.PortfolioAccountDTO;
import org.apache.fineract.portfolio.account.data.PortfolioAccountData;
import org.apache.fineract.portfolio.account.data.StandingInstructionDTO;
import org.apache.fineract.portfolio.account.data.StandingInstructionData;
import org.apache.fineract.portfolio.account.data.StandingInstructionDuesData;
import org.apache.fineract.portfolio.account.domain.AccountTransferRecurrenceType;
import org.apache.fineract.portfolio.account.domain.AccountTransferType;
import org.apache.fineract.portfolio.account.domain.StandingInstructionPriority;
import org.apache.fineract.portfolio.account.domain.StandingInstructionStatus;
import org.apache.fineract.portfolio.account.domain.StandingInstructionType;
import org.apache.fineract.portfolio.account.exception.AccountTransferNotFoundException;
import org.apache.fineract.portfolio.client.data.ClientData;
import org.apache.fineract.portfolio.client.service.ClientReadPlatformService;
import org.apache.fineract.portfolio.common.service.CommonEnumerations;
import org.apache.fineract.portfolio.common.service.DropdownReadPlatformService;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.util.CollectionUtils;
public class StandingInstructionReadPlatformServiceImpl implements StandingInstructionReadPlatformService {
private final JdbcTemplate jdbcTemplate;
private final ColumnValidator columnValidator;
private final ClientReadPlatformService clientReadPlatformService;
private final OfficeReadPlatformService officeReadPlatformService;
private final PortfolioAccountReadPlatformService portfolioAccountReadPlatformService;
private final DropdownReadPlatformService dropdownReadPlatformService;
private final DatabaseSpecificSQLGenerator sqlGenerator;
// mapper
private final StandingInstructionMapper standingInstructionMapper;
// pagination
private final PaginationHelper paginationHelper;
public StandingInstructionReadPlatformServiceImpl(final JdbcTemplate jdbcTemplate,
final ClientReadPlatformService clientReadPlatformService, final OfficeReadPlatformService officeReadPlatformService,
final PortfolioAccountReadPlatformService portfolioAccountReadPlatformService,
final DropdownReadPlatformService dropdownReadPlatformService, final ColumnValidator columnValidator,
DatabaseSpecificSQLGenerator sqlGenerator, PaginationHelper paginationHelper) {
this.jdbcTemplate = jdbcTemplate;
this.clientReadPlatformService = clientReadPlatformService;
this.officeReadPlatformService = officeReadPlatformService;
this.portfolioAccountReadPlatformService = portfolioAccountReadPlatformService;
this.dropdownReadPlatformService = dropdownReadPlatformService;
this.sqlGenerator = sqlGenerator;
this.standingInstructionMapper = new StandingInstructionMapper();
this.columnValidator = columnValidator;
this.paginationHelper = paginationHelper;
}
@Override
public StandingInstructionData retrieveTemplate(final Long fromOfficeId, final Long fromClientId, final Long fromAccountId,
final Integer fromAccountType, final Long toOfficeId, final Long toClientId, final Long toAccountId,
final Integer toAccountType, Integer transferType) {
AccountTransferType accountTransferType = AccountTransferType.INVALID;
if (transferType != null) {
accountTransferType = AccountTransferType.fromInt(transferType);
}
final EnumOptionData loanAccountType = accountType(PortfolioAccountType.LOAN);
final EnumOptionData savingsAccountType = accountType(PortfolioAccountType.SAVINGS);
final Integer mostRelevantFromAccountType = fromAccountType;
Collection<EnumOptionData> fromAccountTypeOptions = null;
Collection<EnumOptionData> toAccountTypeOptions = null;
if (accountTransferType.isAccountTransfer()) {
fromAccountTypeOptions = Arrays.asList(savingsAccountType);
toAccountTypeOptions = Arrays.asList(savingsAccountType);
} else if (accountTransferType.isLoanRepayment()) {
fromAccountTypeOptions = Arrays.asList(savingsAccountType);
toAccountTypeOptions = Arrays.asList(loanAccountType);
} else {
fromAccountTypeOptions = Arrays.asList(savingsAccountType, loanAccountType);
toAccountTypeOptions = Arrays.asList(loanAccountType, savingsAccountType);
}
final Integer mostRelevantToAccountType = toAccountType;
final EnumOptionData fromAccountTypeData = accountType(mostRelevantFromAccountType);
final EnumOptionData toAccountTypeData = accountType(mostRelevantToAccountType);
// from settings
OfficeData fromOffice = null;
ClientData fromClient = null;
PortfolioAccountData fromAccount = null;
OfficeData toOffice = null;
ClientData toClient = null;
PortfolioAccountData toAccount = null;
// template
Collection<PortfolioAccountData> fromAccountOptions = null;
Collection<PortfolioAccountData> toAccountOptions = null;
Long mostRelevantFromOfficeId = fromOfficeId;
Long mostRelevantFromClientId = fromClientId;
Long mostRelevantToOfficeId = toOfficeId;
Long mostRelevantToClientId = toClientId;
if (fromAccountId != null) {
Integer accountType;
if (mostRelevantFromAccountType == 1) {
accountType = PortfolioAccountType.LOAN.getValue();
} else {
accountType = PortfolioAccountType.SAVINGS.getValue();
}
fromAccount = this.portfolioAccountReadPlatformService.retrieveOne(fromAccountId, accountType);
// override provided fromClient with client of account
mostRelevantFromClientId = fromAccount.getClientId();
}
if (mostRelevantFromClientId != null) {
fromClient = this.clientReadPlatformService.retrieveOne(mostRelevantFromClientId);
mostRelevantFromOfficeId = fromClient.getOfficeId();
long[] loanStatus = null;
if (mostRelevantFromAccountType == 1) {
loanStatus = new long[] { 300, 700 };
}
PortfolioAccountDTO portfolioAccountDTO = new PortfolioAccountDTO(mostRelevantFromAccountType, mostRelevantFromClientId,
loanStatus);
fromAccountOptions = this.portfolioAccountReadPlatformService.retrieveAllForLookup(portfolioAccountDTO);
}
Collection<OfficeData> fromOfficeOptions = this.officeReadPlatformService.retrieveAllOfficesForDropdown();
Collection<ClientData> fromClientOptions = null;
if (mostRelevantFromOfficeId != null) {
fromOffice = this.officeReadPlatformService.retrieveOffice(mostRelevantFromOfficeId);
fromClientOptions = this.clientReadPlatformService.retrieveAllForLookupByOfficeId(mostRelevantFromOfficeId);
}
// defaults
final LocalDate transferDate = DateUtils.getBusinessLocalDate();
Collection<OfficeData> toOfficeOptions = fromOfficeOptions;
Collection<ClientData> toClientOptions = null;
if (toAccountId != null && fromAccount != null) {
toAccount = this.portfolioAccountReadPlatformService.retrieveOne(toAccountId, mostRelevantToAccountType,
fromAccount.getCurrencyCodeFromCurrency());
mostRelevantToClientId = toAccount.getClientId();
}
if (mostRelevantToClientId != null) {
toClient = this.clientReadPlatformService.retrieveOne(mostRelevantToClientId);
mostRelevantToOfficeId = toClient.getOfficeId();
toClientOptions = this.clientReadPlatformService.retrieveAllForLookupByOfficeId(mostRelevantToOfficeId);
toAccountOptions = retrieveToAccounts(fromAccount, mostRelevantToAccountType, mostRelevantToClientId);
}
if (mostRelevantToOfficeId != null) {
toOffice = this.officeReadPlatformService.retrieveOffice(mostRelevantToOfficeId);
toOfficeOptions = this.officeReadPlatformService.retrieveAllOfficesForDropdown();
toClientOptions = this.clientReadPlatformService.retrieveAllForLookupByOfficeId(mostRelevantToOfficeId);
if (toClientOptions != null && toClientOptions.size() == 1) {
toClient = new ArrayList<>(toClientOptions).get(0);
toAccountOptions = retrieveToAccounts(fromAccount, mostRelevantToAccountType, mostRelevantToClientId);
}
}
final Collection<EnumOptionData> transferTypeOptions = Arrays.asList(transferType(AccountTransferType.ACCOUNT_TRANSFER),
transferType(
AccountTransferType.LOAN_REPAYMENT)/*
* , transferType( AccountTransferType . CHARGE_PAYMENT )
*/);
final Collection<EnumOptionData> statusOptions = Arrays.asList(standingInstructionStatus(StandingInstructionStatus.ACTIVE),
standingInstructionStatus(StandingInstructionStatus.DISABLED));
final Collection<EnumOptionData> instructionTypeOptions = Arrays.asList(standingInstructionType(StandingInstructionType.FIXED),
standingInstructionType(StandingInstructionType.DUES));
final Collection<EnumOptionData> priorityOptions = Arrays.asList(standingInstructionPriority(StandingInstructionPriority.URGENT),
standingInstructionPriority(StandingInstructionPriority.HIGH),
standingInstructionPriority(StandingInstructionPriority.MEDIUM),
standingInstructionPriority(StandingInstructionPriority.LOW));
final Collection<EnumOptionData> recurrenceTypeOptions = Arrays.asList(recurrenceType(AccountTransferRecurrenceType.PERIODIC),
recurrenceType(AccountTransferRecurrenceType.AS_PER_DUES));
final Collection<EnumOptionData> recurrenceFrequencyOptions = this.dropdownReadPlatformService.retrievePeriodFrequencyTypeOptions();
return StandingInstructionData.template(fromOffice, fromClient, fromAccountTypeData, fromAccount, transferDate, toOffice, toClient,
toAccountTypeData, toAccount, fromOfficeOptions, fromClientOptions, fromAccountTypeOptions, fromAccountOptions,
toOfficeOptions, toClientOptions, toAccountTypeOptions, toAccountOptions, transferTypeOptions, statusOptions,
instructionTypeOptions, priorityOptions, recurrenceTypeOptions, recurrenceFrequencyOptions);
}
private Collection<PortfolioAccountData> retrieveToAccounts(final PortfolioAccountData excludeThisAccountFromOptions,
final Integer toAccountType, final Long toClientId) {
final String currencyCode = excludeThisAccountFromOptions != null ? excludeThisAccountFromOptions.getCurrencyCodeFromCurrency()
: null;
PortfolioAccountDTO portfolioAccountDTO = new PortfolioAccountDTO(toAccountType, toClientId, currencyCode, null, null);
Collection<PortfolioAccountData> accountOptions = this.portfolioAccountReadPlatformService
.retrieveAllForLookup(portfolioAccountDTO);
if (!CollectionUtils.isEmpty(accountOptions)) {
accountOptions.remove(excludeThisAccountFromOptions);
} else {
accountOptions = null;
}
return accountOptions;
}
@Override
public Page<StandingInstructionData> retrieveAll(final StandingInstructionDTO standingInstructionDTO) {
final StringBuilder sqlBuilder = new StringBuilder(200);
sqlBuilder.append("select " + sqlGenerator.calcFoundRows() + " ");
sqlBuilder.append(this.standingInstructionMapper.schema());
if (standingInstructionDTO.transferType() != null || standingInstructionDTO.clientId() != null
|| standingInstructionDTO.clientName() != null) {
sqlBuilder.append(" where ");
}
boolean addAndCaluse = false;
List<Object> paramObj = new ArrayList<>();
if (standingInstructionDTO.transferType() != null) {
if (addAndCaluse) {
sqlBuilder.append(" and ");
}
sqlBuilder.append(" atd.transfer_type=? ");
paramObj.add(standingInstructionDTO.transferType());
addAndCaluse = true;
}
if (standingInstructionDTO.clientId() != null) {
if (addAndCaluse) {
sqlBuilder.append(" and ");
}
sqlBuilder.append(" fromclient.id=? ");
paramObj.add(standingInstructionDTO.clientId());
addAndCaluse = true;
} else if (standingInstructionDTO.clientName() != null) {
if (addAndCaluse) {
sqlBuilder.append(" and ");
}
sqlBuilder.append(" fromclient.display_name=? ");
paramObj.add(standingInstructionDTO.clientName());
addAndCaluse = true;
}
if (standingInstructionDTO.fromAccountType() != null && standingInstructionDTO.fromAccount() != null) {
PortfolioAccountType accountType = PortfolioAccountType.fromInt(standingInstructionDTO.fromAccountType());
if (addAndCaluse) {
sqlBuilder.append(" and ");
}
if (accountType.isSavingsAccount()) {
sqlBuilder.append(" fromsavacc.id=? ");
paramObj.add(standingInstructionDTO.fromAccount());
} else if (accountType.isLoanAccount()) {
sqlBuilder.append(" fromloanacc.id=? ");
paramObj.add(standingInstructionDTO.fromAccount());
}
addAndCaluse = true;
}
final SearchParameters searchParameters = standingInstructionDTO.searchParameters();
if (searchParameters.hasOrderBy()) {
sqlBuilder.append(" order by ").append(searchParameters.getOrderBy());
this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getOrderBy());
if (searchParameters.hasSortOrder()) {
sqlBuilder.append(' ').append(searchParameters.getSortOrder());
this.columnValidator.validateSqlInjection(sqlBuilder.toString(), searchParameters.getSortOrder());
}
}
if (searchParameters.hasLimit()) {
sqlBuilder.append(" ");
if (searchParameters.hasOffset()) {
sqlBuilder.append(sqlGenerator.limit(searchParameters.getLimit(), searchParameters.getOffset()));
} else {
sqlBuilder.append(sqlGenerator.limit(searchParameters.getLimit()));
}
}
final Object[] finalObjectArray = paramObj.toArray();
return this.paginationHelper.fetchPage(this.jdbcTemplate, sqlBuilder.toString(), finalObjectArray, this.standingInstructionMapper);
}
@Override
public Collection<StandingInstructionData> retrieveAll(final Integer status) {
final StringBuilder sqlBuilder = new StringBuilder(200);
String businessDate = sqlGenerator.currentBusinessDate();
sqlBuilder.append("select ");
sqlBuilder.append(this.standingInstructionMapper.schema());
sqlBuilder
.append(" where atsi.status=? and " + businessDate + " >= atsi.valid_from and (atsi.valid_till IS NULL or " + businessDate
+ " < atsi.valid_till) ")
.append(" and (atsi.last_run_date <> " + businessDate + " or atsi.last_run_date IS NULL)")
.append(" ORDER BY atsi.priority DESC");
return this.jdbcTemplate.query(sqlBuilder.toString(), this.standingInstructionMapper, status);
}
@Override
public StandingInstructionData retrieveOne(final Long instructionId) {
try {
final String sql = "select " + this.standingInstructionMapper.schema() + " where atsi.id = ?";
return this.jdbcTemplate.queryForObject(sql, this.standingInstructionMapper, new Object[] { instructionId }); // NOSONAR
} catch (final EmptyResultDataAccessException e) {
throw new AccountTransferNotFoundException(instructionId, e);
}
}
@Override
public StandingInstructionDuesData retriveLoanDuesData(final Long loanId) {
final StandingInstructionLoanDuesMapper rm = new StandingInstructionLoanDuesMapper();
final String sql = "select " + rm.schema() + " where ml.id= ? and ls.duedate <= " + sqlGenerator.currentBusinessDate()
+ " and ls.completed_derived <> 1";
return this.jdbcTemplate.queryForObject(sql, rm, new Object[] { loanId }); // NOSONAR
}
private static final class StandingInstructionMapper implements RowMapper<StandingInstructionData> {
private final String schemaSql;
StandingInstructionMapper() {
final StringBuilder sqlBuilder = new StringBuilder(400);
sqlBuilder.append("atsi.id as id,atsi.name as name, atsi.priority as priority,");
sqlBuilder.append("atsi.status as status, atsi.instruction_type as instructionType,");
sqlBuilder.append("atsi.amount as amount,");
sqlBuilder.append("atsi.valid_from as validFrom, atsi.valid_till as validTill,");
sqlBuilder.append("atsi.recurrence_type as recurrenceType, atsi.recurrence_frequency as recurrenceFrequency,");
sqlBuilder.append("atsi.recurrence_interval as recurrenceInterval, atsi.recurrence_on_day as recurrenceOnDay,");
sqlBuilder.append("atsi.recurrence_on_month as recurrenceOnMonth,");
sqlBuilder.append("atd.id as accountDetailId,atd.transfer_type as transferType,");
sqlBuilder.append("fromoff.id as fromOfficeId, fromoff.name as fromOfficeName,");
sqlBuilder.append("tooff.id as toOfficeId, tooff.name as toOfficeName,");
sqlBuilder.append("fromclient.id as fromClientId, fromclient.display_name as fromClientName,");
sqlBuilder.append("toclient.id as toClientId, toclient.display_name as toClientName,");
sqlBuilder.append("fromsavacc.id as fromSavingsAccountId, fromsavacc.account_no as fromSavingsAccountNo,");
sqlBuilder.append("fromsp.id as fromProductId, fromsp.name as fromProductName, ");
sqlBuilder.append("fromloanacc.id as fromLoanAccountId, fromloanacc.account_no as fromLoanAccountNo,");
sqlBuilder.append("fromlp.id as fromLoanProductId, fromlp.name as fromLoanProductName,");
sqlBuilder.append("tosavacc.id as toSavingsAccountId, tosavacc.account_no as toSavingsAccountNo,");
sqlBuilder.append("tosp.id as toProductId, tosp.name as toProductName, ");
sqlBuilder.append("toloanacc.id as toLoanAccountId, toloanacc.account_no as toLoanAccountNo, ");
sqlBuilder.append("tolp.id as toLoanProductId, tolp.name as toLoanProductName ");
sqlBuilder.append(" FROM m_account_transfer_standing_instructions atsi ");
sqlBuilder.append("join m_account_transfer_details atd on atd.id = atsi.account_transfer_details_id ");
sqlBuilder.append("join m_office fromoff on fromoff.id = atd.from_office_id ");
sqlBuilder.append("join m_office tooff on tooff.id = atd.to_office_id ");
sqlBuilder.append("join m_client fromclient on fromclient.id = atd.from_client_id ");
sqlBuilder.append("join m_client toclient on toclient.id = atd.to_client_id ");
sqlBuilder.append("left join m_savings_account fromsavacc on fromsavacc.id = atd.from_savings_account_id ");
sqlBuilder.append("left join m_savings_product fromsp ON fromsavacc.product_id = fromsp.id ");
sqlBuilder.append("left join m_loan fromloanacc on fromloanacc.id = atd.from_loan_account_id ");
sqlBuilder.append("left join m_product_loan fromlp ON fromloanacc.product_id = fromlp.id ");
sqlBuilder.append("left join m_savings_account tosavacc on tosavacc.id = atd.to_savings_account_id ");
sqlBuilder.append("left join m_savings_product tosp ON tosavacc.product_id = tosp.id ");
sqlBuilder.append("left join m_loan toloanacc on toloanacc.id = atd.to_loan_account_id ");
sqlBuilder.append("left join m_product_loan tolp ON toloanacc.product_id = tolp.id ");
this.schemaSql = sqlBuilder.toString();
}
public String schema() {
return this.schemaSql;
}
@Override
public StandingInstructionData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final Long id = rs.getLong("id");
final Long accountDetailId = rs.getLong("accountDetailId");
final String name = rs.getString("name");
final Integer priority = JdbcSupport.getInteger(rs, "priority");
EnumOptionData priorityEnum = AccountTransferEnumerations.standingInstructionPriority(priority);
final Integer status = JdbcSupport.getInteger(rs, "status");
EnumOptionData statusEnum = AccountTransferEnumerations.standingInstructionStatus(status);
final Integer instructionType = JdbcSupport.getInteger(rs, "instructionType");
EnumOptionData instructionTypeEnum = AccountTransferEnumerations.standingInstructionType(instructionType);
final LocalDate validFrom = JdbcSupport.getLocalDate(rs, "validFrom");
final LocalDate validTill = JdbcSupport.getLocalDate(rs, "validTill");
final BigDecimal transferAmount = JdbcSupport.getBigDecimalDefaultToNullIfZero(rs, "amount");
final Integer recurrenceType = JdbcSupport.getInteger(rs, "recurrenceType");
EnumOptionData recurrenceTypeEnum = AccountTransferEnumerations.recurrenceType(recurrenceType);
final Integer recurrenceFrequency = JdbcSupport.getInteger(rs, "recurrenceFrequency");
EnumOptionData recurrenceFrequencyEnum = null;
if (recurrenceFrequency != null) {
recurrenceFrequencyEnum = CommonEnumerations.termFrequencyType(recurrenceFrequency, "recurrence");
}
final Integer recurrenceInterval = JdbcSupport.getInteger(rs, "recurrenceInterval");
MonthDay recurrenceOnMonthDay = null;
final Integer recurrenceOnDay = JdbcSupport.getInteger(rs, "recurrenceOnDay");
final Integer recurrenceOnMonth = JdbcSupport.getInteger(rs, "recurrenceOnMonth");
if (recurrenceOnDay != null) {
recurrenceOnMonthDay = MonthDay.now(DateUtils.getDateTimeZoneOfTenant()).withMonth(recurrenceOnMonth)
.withDayOfMonth(recurrenceOnDay);
}
final Integer transferType = rs.getInt("transferType");
EnumOptionData transferTypeEnum = AccountTransferEnumerations.transferType(transferType);
/*
* final String currencyCode = rs.getString("currencyCode"); final String currencyName =
* rs.getString("currencyName"); final String currencyNameCode = rs.getString("currencyNameCode"); final
* String currencyDisplaySymbol = rs.getString("currencyDisplaySymbol"); final Integer currencyDigits =
* JdbcSupport.getInteger(rs, "currencyDigits"); final Integer inMultiplesOf = JdbcSupport.getInteger(rs,
* "inMultiplesOf"); final CurrencyData currency = new CurrencyData(currencyCode, currencyName,
* currencyDigits, inMultiplesOf, currencyDisplaySymbol, currencyNameCode);
*/
final Long fromOfficeId = JdbcSupport.getLong(rs, "fromOfficeId");
final String fromOfficeName = rs.getString("fromOfficeName");
final OfficeData fromOffice = OfficeData.dropdown(fromOfficeId, fromOfficeName, null);
final Long toOfficeId = JdbcSupport.getLong(rs, "toOfficeId");
final String toOfficeName = rs.getString("toOfficeName");
final OfficeData toOffice = OfficeData.dropdown(toOfficeId, toOfficeName, null);
final Long fromClientId = JdbcSupport.getLong(rs, "fromClientId");
final String fromClientName = rs.getString("fromClientName");
final ClientData fromClient = ClientData.lookup(fromClientId, fromClientName, fromOfficeId, fromOfficeName);
final Long toClientId = JdbcSupport.getLong(rs, "toClientId");
final String toClientName = rs.getString("toClientName");
final ClientData toClient = ClientData.lookup(toClientId, toClientName, toOfficeId, toOfficeName);
final Long fromSavingsAccountId = JdbcSupport.getLong(rs, "fromSavingsAccountId");
final String fromSavingsAccountNo = rs.getString("fromSavingsAccountNo");
final Long fromProductId = JdbcSupport.getLong(rs, "fromProductId");
final String fromProductName = rs.getString("fromProductName");
final Long fromLoanAccountId = JdbcSupport.getLong(rs, "fromLoanAccountId");
final String fromLoanAccountNo = rs.getString("fromLoanAccountNo");
final Long fromLoanProductId = JdbcSupport.getLong(rs, "fromLoanProductId");
final String fromLoanProductName = rs.getString("fromLoanProductName");
PortfolioAccountData fromAccount = null;
EnumOptionData fromAccountType = null;
if (fromSavingsAccountId != null) {
fromAccount = new PortfolioAccountData(fromSavingsAccountId, fromSavingsAccountNo, null, null, null, null, null,
fromProductId, fromProductName, null, null, null);
fromAccountType = accountType(PortfolioAccountType.SAVINGS);
} else if (fromLoanAccountId != null) {
fromAccount = new PortfolioAccountData(fromLoanAccountId, fromLoanAccountNo, null, null, null, null, null,
fromLoanProductId, fromLoanProductName, null, null, null);
fromAccountType = accountType(PortfolioAccountType.LOAN);
}
PortfolioAccountData toAccount = null;
EnumOptionData toAccountType = null;
final Long toSavingsAccountId = JdbcSupport.getLong(rs, "toSavingsAccountId");
final String toSavingsAccountNo = rs.getString("toSavingsAccountNo");
final Long toProductId = JdbcSupport.getLong(rs, "toProductId");
final String toProductName = rs.getString("toProductName");
final Long toLoanAccountId = JdbcSupport.getLong(rs, "toLoanAccountId");
final String toLoanAccountNo = rs.getString("toLoanAccountNo");
final Long toLoanProductId = JdbcSupport.getLong(rs, "toLoanProductId");
final String toLoanProductName = rs.getString("toLoanProductName");
if (toSavingsAccountId != null) {
toAccount = new PortfolioAccountData(toSavingsAccountId, toSavingsAccountNo, null, null, null, null, null, toProductId,
toProductName, null, null, null);
toAccountType = accountType(PortfolioAccountType.SAVINGS);
} else if (toLoanAccountId != null) {
toAccount = new PortfolioAccountData(toLoanAccountId, toLoanAccountNo, null, null, null, null, null, toLoanProductId,
toLoanProductName, null, null, null);
toAccountType = accountType(PortfolioAccountType.LOAN);
}
return StandingInstructionData.instance(id, accountDetailId, name, fromOffice, toOffice, fromClient, toClient, fromAccountType,
fromAccount, toAccountType, toAccount, transferTypeEnum, priorityEnum, instructionTypeEnum, statusEnum, transferAmount,
validFrom, validTill, recurrenceTypeEnum, recurrenceFrequencyEnum, recurrenceInterval, recurrenceOnMonthDay);
}
}
private static final class StandingInstructionLoanDuesMapper implements RowMapper<StandingInstructionDuesData> {
private final String schemaSql;
StandingInstructionLoanDuesMapper() {
final StringBuilder sqlBuilder = new StringBuilder(400);
sqlBuilder.append("max(ls.duedate) as dueDate,sum(ls.principal_amount) as principalAmount,");
sqlBuilder.append("sum(ls.principal_completed_derived) as principalCompleted,");
sqlBuilder.append("sum(ls.principal_writtenoff_derived) as principalWrittenOff,");
sqlBuilder.append("sum(ls.interest_amount) as interestAmount,");
sqlBuilder.append("sum(ls.interest_completed_derived) as interestCompleted,");
sqlBuilder.append("sum(ls.interest_writtenoff_derived) as interestWrittenOff,");
sqlBuilder.append("sum(ls.interest_waived_derived) as interestWaived,");
sqlBuilder.append("sum(ls.penalty_charges_amount) as penalityAmount,");
sqlBuilder.append("sum(ls.penalty_charges_completed_derived) as penalityCompleted,");
sqlBuilder.append("sum(ls.penalty_charges_writtenoff_derived)as penaltyWrittenOff,");
sqlBuilder.append("sum(ls.penalty_charges_waived_derived) as penaltyWaived,");
sqlBuilder.append("sum(ls.fee_charges_amount) as feeAmount,");
sqlBuilder.append("sum(ls.fee_charges_completed_derived) as feecompleted,");
sqlBuilder.append("sum(ls.fee_charges_writtenoff_derived) as feeWrittenOff,");
sqlBuilder.append("sum(ls.fee_charges_waived_derived) as feeWaived ");
sqlBuilder.append("from m_loan_repayment_schedule ls ");
sqlBuilder.append(" join m_loan ml on ml.id = ls.loan_id ");
this.schemaSql = sqlBuilder.toString();
}
public String schema() {
return this.schemaSql;
}
@Override
public StandingInstructionDuesData mapRow(final ResultSet rs, @SuppressWarnings("unused") final int rowNum) throws SQLException {
final LocalDate dueDate = JdbcSupport.getLocalDate(rs, "dueDate");
final BigDecimal principalDue = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "principalAmount");
final BigDecimal principalPaid = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "principalCompleted");
final BigDecimal principalWrittenOff = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "principalWrittenOff");
final BigDecimal principalOutstanding = principalDue.subtract(principalPaid).subtract(principalWrittenOff);
final BigDecimal interestExpectedDue = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "interestAmount");
final BigDecimal interestPaid = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "interestCompleted");
final BigDecimal interestWrittenOff = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "interestWrittenOff");
final BigDecimal interestWaived = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "interestWaived");
final BigDecimal interestActualDue = interestExpectedDue.subtract(interestWaived).subtract(interestWrittenOff);
final BigDecimal interestOutstanding = interestActualDue.subtract(interestPaid);
final BigDecimal penaltyChargesExpectedDue = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "penalityAmount");
final BigDecimal penaltyChargesPaid = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "penalityCompleted");
final BigDecimal penaltyChargesWrittenOff = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "penaltyWrittenOff");
final BigDecimal penaltyChargesWaived = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "penaltyWaived");
final BigDecimal penaltyChargesActualDue = penaltyChargesExpectedDue.subtract(penaltyChargesWaived)
.subtract(penaltyChargesWrittenOff);
final BigDecimal penaltyChargesOutstanding = penaltyChargesActualDue.subtract(penaltyChargesPaid);
final BigDecimal feeChargesExpectedDue = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "feeAmount");
final BigDecimal feeChargesPaid = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "feecompleted");
final BigDecimal feeChargesWrittenOff = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "feeWrittenOff");
final BigDecimal feeChargesWaived = JdbcSupport.getBigDecimalDefaultToZeroIfNull(rs, "feeWaived");
final BigDecimal feeChargesActualDue = feeChargesExpectedDue.subtract(feeChargesWaived).subtract(feeChargesWrittenOff);
final BigDecimal feeChargesOutstanding = feeChargesActualDue.subtract(feeChargesPaid);
final BigDecimal totalOutstanding = principalOutstanding.add(interestOutstanding).add(feeChargesOutstanding)
.add(penaltyChargesOutstanding);
return new StandingInstructionDuesData(dueDate, totalOutstanding);
}
}
}
|
apache/felix-dev | 32,757 | framework/src/main/java/org/osgi/framework/FrameworkUtil.java | /*
* Copyright (c) OSGi Alliance (2005, 2020). 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 org.osgi.framework;
import static java.util.Objects.requireNonNull;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.Set;
import javax.security.auth.x500.X500Principal;
import org.osgi.framework.connect.FrameworkUtilHelper;
/**
* Framework Utility class.
*
* <p>
* This class contains utility methods which access Framework functions that may
* be useful to bundles.
*
* @since 1.3
* @ThreadSafe
* @author $Id: 71423feb17277b685e6d5d7864907e768da8cd0b $
*/
public class FrameworkUtil {
/**
* FrameworkUtil objects may not be constructed.
*/
private FrameworkUtil() {
// private empty constructor to prevent construction
}
/**
* Creates a {@code Filter} object. This {@code Filter} object may be used
* to match a {@code ServiceReference} object or a {@code Dictionary}
* object.
*
* <p>
* If the filter cannot be parsed, an {@link InvalidSyntaxException} will be
* thrown with a human readable message where the filter became unparsable.
*
* <p>
* This method returns a Filter implementation which may not perform as well
* as the framework implementation-specific Filter implementation returned
* by {@link BundleContext#createFilter(String)}.
*
* @param filter The filter string.
* @return A {@code Filter} object encapsulating the filter string.
* @throws InvalidSyntaxException If {@code filter} contains an invalid
* filter string that cannot be parsed.
* @throws NullPointerException If {@code filter} is null.
*
* @see Filter
*/
public static Filter createFilter(String filter) throws InvalidSyntaxException {
return FilterImpl.createFilter(filter);
}
/**
* Match a Distinguished Name (DN) chain against a pattern. DNs can be
* matched using wildcards. A wildcard ({@code '*'} \u002A) replaces all
* possible values. Due to the structure of the DN, the comparison is more
* complicated than string-based wildcard matching.
* <p>
* A wildcard can stand for zero or more DNs in a chain, a number of
* relative distinguished names (RDNs) within a DN, or the value of a single
* RDN. The DNs in the chain and the matching pattern are canonicalized
* before processing. This means, among other things, that spaces must be
* ignored, except in values.
* <p>
* The format of a wildcard match pattern is:
*
* <pre>
* matchPattern ::= dn-match ( ';' dn-match ) *
* dn-match ::= ( '*' | rdn-match ) ( ',' rdn-match ) * | '-'
* rdn-match ::= name '=' value-match
* value-match ::= '*' | value-star
* value-star ::= < value, requires escaped '*' and '-' >
* </pre>
* <p>
* The most simple case is a single wildcard; it must match any DN. A
* wildcard can also replace the first list of RDNs of a DN. The first RDNs
* are the least significant. Such lists of matched RDNs can be empty.
* <p>
* For example, a match pattern with a wildcard that matches all DNs that
* end with RDNs of o=ACME and c=US would look like this:
*
* <pre>
* *, o=ACME, c=US
* </pre>
*
* This match pattern would match the following DNs:
*
* <pre>
* cn = Bugs Bunny, o = ACME, c = US
* ou = Carrots, cn=Daffy Duck, o=ACME, c=US
* street = 9C\, Avenue St. Drézéry, o=ACME, c=US
* dc=www, dc=acme, dc=com, o=ACME, c=US
* o=ACME, c=US
* </pre>
*
* The following DNs would not match:
*
* <pre>
* street = 9C\, Avenue St. Drézéry, o=ACME, c=FR
* dc=www, dc=acme, dc=com, c=US
* </pre>
*
* If a wildcard is used for a value of an RDN, the value must be exactly *.
* The wildcard must match any value, and no substring matching must be
* done. For example:
*
* <pre>
* cn=*,o=ACME,c=*
* </pre>
*
* This match pattern with wildcard must match the following DNs:
*
* <pre>
* cn=Bugs Bunny,o=ACME,c=US
* cn = Daffy Duck , o = ACME , c = US
* cn=Road Runner, o=ACME, c=NL
* </pre>
*
* But not:
*
* <pre>
* o=ACME, c=NL
* dc=acme.com, cn=Bugs Bunny, o=ACME, c=US
* </pre>
*
* <p>
* A match pattern may contain a chain of DN match patterns. The semicolon(
* {@code ';'} \u003B) must be used to separate DN match patterns in a
* chain. Wildcards can also be used to match against a complete DN within a
* chain.
* <p>
* The following example matches a certificate signed by Tweety Inc. in the
* US.
* </p>
*
* <pre>
* * ; ou=S & V, o=Tweety Inc., c=US
* </pre>
* <p>
* The wildcard ('*') matches zero or one DN in the chain, however,
* sometimes it is necessary to match a longer chain. The minus sign (
* {@code '-'} \u002D) represents zero or more DNs, whereas the asterisk
* only represents a single DN. For example, to match a DN where the Tweety
* Inc. is in the DN chain, use the following expression:
* </p>
*
* <pre>
* - ; *, o=Tweety Inc., c=US
* </pre>
*
* @param matchPattern The pattern against which to match the DN chain.
* @param dnChain The DN chain to match against the specified pattern. Each
* element of the chain must be of type {@code String} and use the
* format defined in <a
* href="http://www.ietf.org/rfc/rfc2253.txt">RFC 2253</a>.
* @return {@code true} If the pattern matches the DN chain; otherwise
* {@code false} is returned.
* @throws IllegalArgumentException If the specified match pattern or DN
* chain is invalid.
* @since 1.5
*/
public static boolean matchDistinguishedNameChain(String matchPattern, List<String> dnChain) {
return DNChainMatching.match(matchPattern, dnChain);
}
/**
* Return a {@code Bundle} for the specified bundle class loader.
*
* @param bundleClassLoader A bundle class loader.
* @return An Optional containing {@code Bundle} for the specified bundle
* class loader or an empty Optional if the specified class loader
* is not associated with a specific bundle.
* @since 1.10
*/
public static Optional<Bundle> getBundle(ClassLoader bundleClassLoader) {
requireNonNull(bundleClassLoader);
return Optional
.ofNullable((bundleClassLoader instanceof BundleReference)
? ((BundleReference) bundleClassLoader).getBundle()
: null);
}
/**
* Return a {@code Bundle} for the specified bundle class.
*
* @param classFromBundle A class defined by a bundle.
* @return A {@code Bundle} for the specified bundle class or {@code null}
* if the specified class was not defined by a bundle.
* @since 1.5
*/
public static Bundle getBundle(Class< ? > classFromBundle) {
// We use doPriv since the caller may not have permission
// to call getClassLoader.
Optional<ClassLoader> cl = Optional
.ofNullable(AccessController.doPrivileged(
(PrivilegedAction<ClassLoader>) () -> classFromBundle
.getClassLoader()));
return cl.flatMap(FrameworkUtil::getBundle)
.orElseGet(() -> helpers.stream()
.map(helper -> helper.getBundle(classFromBundle))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst()
.orElse(null));
}
private final static List<FrameworkUtilHelper> helpers;
static {
List<FrameworkUtilHelper> l = new ArrayList<>();
try {
ServiceLoader<FrameworkUtilHelper> helperLoader = AccessController
.doPrivileged(
(PrivilegedAction<ServiceLoader<FrameworkUtilHelper>>) () -> ServiceLoader
.load(FrameworkUtilHelper.class,
FrameworkUtilHelper.class
.getClassLoader()));
helperLoader.forEach(l::add);
} catch (Throwable error) {
// try hard not to fail static <clinit>
try {
Thread t = Thread.currentThread();
t.getUncaughtExceptionHandler().uncaughtException(t, error);
} catch (Throwable ignored) {
// we ignore this
}
}
helpers = Collections.unmodifiableList(l);
}
/**
* This class contains a method to match a distinguished name (DN) chain
* against and DN chain pattern.
* <p>
* The format of DNs are given in RFC 2253. We represent a signature chain
* for an X.509 certificate as a semicolon separated list of DNs. This is
* what we refer to as the DN chain. Each DN is made up of relative
* distinguished names (RDN) which in turn are made up of key value pairs.
* For example:
*
* <pre>
* cn=ben+ou=research,o=ACME,c=us;ou=Super CA,c=CA
* </pre>
*
* is made up of two DNs: "{@code cn=ben+ou=research,o=ACME,c=us} " and "
* {@code ou=Super CA,c=CA} ". The first DN is made of of three RDNs: "
* {@code cn=ben+ou=research}" and "{@code o=ACME}" and " {@code c=us}
* ". The first RDN has two name value pairs: " {@code cn=ben}" and "
* {@code ou=research}".
* <p>
* A chain pattern makes use of wildcards ('*' or '-') to match against DNs,
* and wildcards ('*') to match againts DN prefixes, and value. If a DN in a
* match pattern chain is made up of a wildcard ("*"), that wildcard will
* match zero or one DNs in the chain. If a DN in a match pattern chain is
* made up of a wildcard ("-"), that wildcard will match zero or more DNs in
* the chain. If the first RDN of a DN is the wildcard ("*"), that DN will
* match any other DN with the same suffix (the DN with the wildcard RDN
* removed). If a value of a name/value pair is a wildcard ("*"), the value
* will match any value for that name.
*/
static private final class DNChainMatching {
private static final String MINUS_WILDCARD = "-";
private static final String STAR_WILDCARD = "*";
/**
* Check the name/value pairs of the rdn against the pattern.
*
* @param rdn List of name value pairs for a given RDN.
* @param rdnPattern List of name value pattern pairs.
* @return true if the list of name value pairs match the pattern.
*/
private static boolean rdnmatch(List<?> rdn, List<?> rdnPattern) {
if (rdn.size() != rdnPattern.size()) {
return false;
}
for (int i = 0; i < rdn.size(); i++) {
String rdnNameValue = (String) rdn.get(i);
String patNameValue = (String) rdnPattern.get(i);
int rdnNameEnd = rdnNameValue.indexOf('=');
int patNameEnd = patNameValue.indexOf('=');
if (rdnNameEnd != patNameEnd || !rdnNameValue.regionMatches(0, patNameValue, 0, rdnNameEnd)) {
return false;
}
String patValue = patNameValue.substring(patNameEnd);
String rdnValue = rdnNameValue.substring(rdnNameEnd);
if (!rdnValue.equals(patValue) && !patValue.equals("=*") && !patValue.equals("=#16012a")) {
return false;
}
}
return true;
}
private static boolean dnmatch(List<?> dn, List<?> dnPattern) {
int dnStart = 0;
int patStart = 0;
int patLen = dnPattern.size();
if (patLen == 0) {
return false;
}
if (dnPattern.get(0).equals(STAR_WILDCARD)) {
patStart = 1;
patLen--;
}
if (dn.size() < patLen) {
return false;
} else {
if (dn.size() > patLen) {
if (!dnPattern.get(0).equals(STAR_WILDCARD)) {
// If the number of rdns do not match we must have a
// prefix map
return false;
}
// The rdnPattern and rdn must have the same number of
// elements
dnStart = dn.size() - patLen;
}
}
for (int i = 0; i < patLen; i++) {
if (!rdnmatch((List<?>) dn.get(i + dnStart), (List<?>) dnPattern.get(i + patStart))) {
return false;
}
}
return true;
}
/**
* Parses a distinguished name chain pattern and returns a List where
* each element represents a distinguished name (DN) in the chain of
* DNs. Each element will be either a String, if the element represents
* a wildcard ("*" or "-"), or a List representing an RDN. Each element
* in the RDN List will be a String, if the element represents a
* wildcard ("*"), or a List of Strings, each String representing a
* name/value pair in the RDN.
*
* @param pattern
* @return a list of DNs.
* @throws IllegalArgumentException
*/
private static List<Object> parseDNchainPattern(String pattern) {
if (pattern == null) {
throw new IllegalArgumentException("The pattern must not be null.");
}
List<Object> parsed = new ArrayList<Object>();
final int length = pattern.length();
char c = ';'; // start with semi-colon to detect empty pattern
for (int startIndex = skipSpaces(pattern, 0); startIndex < length;) {
int cursor = startIndex;
int endIndex = startIndex;
out: for (boolean inQuote = false; cursor < length; cursor++) {
c = pattern.charAt(cursor);
switch (c) {
case '"' :
inQuote = !inQuote;
break;
case '\\' :
cursor++; // skip the escaped char
if (cursor == length) {
throw new IllegalArgumentException("unterminated escape");
}
break;
case ';' :
if (!inQuote) {
break out; // end of pattern
}
break;
}
if (c != ' ') { // ignore trailing whitespace
endIndex = cursor + 1;
}
}
parsed.add(pattern.substring(startIndex, endIndex));
startIndex = skipSpaces(pattern, cursor + 1);
}
if (c == ';') { // last non-whitespace character was a semi-colon
throw new IllegalArgumentException("empty pattern");
}
// Now we have parsed into a list of strings, lets make List of rdn
// out of them
for (int i = 0; i < parsed.size(); i++) {
String dn = (String) parsed.get(i);
if (dn.equals(STAR_WILDCARD) || dn.equals(MINUS_WILDCARD)) {
continue;
}
List<Object> rdns = new ArrayList<Object>();
if (dn.charAt(0) == '*') {
int index = skipSpaces(dn, 1);
if (dn.charAt(index) != ',') {
throw new IllegalArgumentException("invalid wildcard prefix");
}
rdns.add(STAR_WILDCARD);
dn = new X500Principal(dn.substring(index + 1)).getName(X500Principal.CANONICAL);
} else {
dn = new X500Principal(dn).getName(X500Principal.CANONICAL);
}
// Now dn is a nice CANONICAL DN
parseDN(dn, rdns);
parsed.set(i, rdns);
}
return parsed;
}
private static List<Object> parseDNchain(List<String> chain) {
if (chain == null) {
throw new IllegalArgumentException("DN chain must not be null.");
}
List<Object> result = new ArrayList<Object>(chain.size());
// Now we parse is a list of strings, lets make List of rdn out
// of them
for (String dn : chain) {
dn = new X500Principal(dn).getName(X500Principal.CANONICAL);
// Now dn is a nice CANONICAL DN
List<Object> rdns = new ArrayList<Object>();
parseDN(dn, rdns);
result.add(rdns);
}
if (result.size() == 0) {
throw new IllegalArgumentException("empty DN chain");
}
return result;
}
/**
* Increment startIndex until the end of dnChain is hit or until it is
* the index of a non-space character.
*/
private static int skipSpaces(String dnChain, int startIndex) {
while (startIndex < dnChain.length() && dnChain.charAt(startIndex) == ' ') {
startIndex++;
}
return startIndex;
}
/**
* Takes a distinguished name in canonical form and fills in the
* rdnArray with the extracted RDNs.
*
* @param dn the distinguished name in canonical form.
* @param rdn the list to fill in with RDNs extracted from the dn
* @throws IllegalArgumentException if a formatting error is found.
*/
private static void parseDN(String dn, List<Object> rdn) {
int startIndex = 0;
char c = '\0';
List<String> nameValues = new ArrayList<String>();
while (startIndex < dn.length()) {
int endIndex;
for (endIndex = startIndex; endIndex < dn.length(); endIndex++) {
c = dn.charAt(endIndex);
if (c == ',' || c == '+') {
break;
}
if (c == '\\') {
endIndex++; // skip the escaped char
}
}
if (endIndex > dn.length()) {
throw new IllegalArgumentException("unterminated escape " + dn);
}
nameValues.add(dn.substring(startIndex, endIndex));
if (c != '+') {
rdn.add(nameValues);
if (endIndex != dn.length()) {
nameValues = new ArrayList<String>();
} else {
nameValues = null;
}
}
startIndex = endIndex + 1;
}
if (nameValues != null) {
throw new IllegalArgumentException("improperly terminated DN " + dn);
}
}
/**
* This method will return an 'index' which points to a non-wildcard DN
* or the end-of-list.
*/
private static int skipWildCards(List<Object> dnChainPattern, int dnChainPatternIndex) {
int i;
for (i = dnChainPatternIndex; i < dnChainPattern.size(); i++) {
Object dnPattern = dnChainPattern.get(i);
if (dnPattern instanceof String) {
if (!dnPattern.equals(STAR_WILDCARD) && !dnPattern.equals(MINUS_WILDCARD)) {
throw new IllegalArgumentException("expected wildcard in DN pattern");
}
// otherwise continue skipping over wild cards
} else {
if (dnPattern instanceof List<?>) {
// if its a list then we have our 'non-wildcard' DN
break;
} else {
// unknown member of the DNChainPattern
throw new IllegalArgumentException("expected String or List in DN Pattern");
}
}
}
// i either points to end-of-list, or to the first
// non-wildcard pattern after dnChainPatternIndex
return i;
}
/**
* recursively attempt to match the DNChain, and the DNChainPattern
* where DNChain is of the format: "DN;DN;DN;" and DNChainPattern is of
* the format: "DNPattern;*;DNPattern" (or combinations of this)
*/
private static boolean dnChainMatch(List<Object> dnChain, int dnChainIndex, List<Object> dnChainPattern, int dnChainPatternIndex) throws IllegalArgumentException {
if (dnChainIndex >= dnChain.size()) {
return false;
}
if (dnChainPatternIndex >= dnChainPattern.size()) {
return false;
}
// check to see what the pattern starts with
Object dnPattern = dnChainPattern.get(dnChainPatternIndex);
if (dnPattern instanceof String) {
if (!dnPattern.equals(STAR_WILDCARD) && !dnPattern.equals(MINUS_WILDCARD)) {
throw new IllegalArgumentException("expected wildcard in DN pattern");
}
// here we are processing a wild card as the first DN
// skip all wildcard DN's
if (dnPattern.equals(MINUS_WILDCARD)) {
dnChainPatternIndex = skipWildCards(dnChainPattern, dnChainPatternIndex);
} else {
dnChainPatternIndex++; // only skip the '*' wildcard
}
if (dnChainPatternIndex >= dnChainPattern.size()) {
// return true iff the wild card is '-' or if we are at the
// end of the chain
return dnPattern.equals(MINUS_WILDCARD) ? true : dnChain.size() - 1 == dnChainIndex;
}
//
// we will now recursively call to see if the rest of the
// DNChainPattern matches increasingly smaller portions of the
// rest of the DNChain
//
if (dnPattern.equals(STAR_WILDCARD)) {
// '*' option: only wildcard on 0 or 1
return dnChainMatch(dnChain, dnChainIndex, dnChainPattern, dnChainPatternIndex) || dnChainMatch(dnChain, dnChainIndex + 1, dnChainPattern, dnChainPatternIndex);
}
for (int i = dnChainIndex; i < dnChain.size(); i++) {
// '-' option: wildcard 0 or more
if (dnChainMatch(dnChain, i, dnChainPattern, dnChainPatternIndex)) {
return true;
}
}
// if we are here, then we didn't find a match.. fall through to
// failure
} else {
if (dnPattern instanceof List<?>) {
// here we have to do a deeper check for each DN in the
// pattern until we hit a wild card
do {
if (!dnmatch((List<?>) dnChain.get(dnChainIndex), (List<?>) dnPattern)) {
return false;
}
// go to the next set of DN's in both chains
dnChainIndex++;
dnChainPatternIndex++;
// if we finished the pattern then it all matched
if ((dnChainIndex >= dnChain.size()) && (dnChainPatternIndex >= dnChainPattern.size())) {
return true;
}
// if the DN Chain is finished, but the pattern isn't
// finished then if the rest of the pattern is not
// wildcard then we are done
if (dnChainIndex >= dnChain.size()) {
dnChainPatternIndex = skipWildCards(dnChainPattern, dnChainPatternIndex);
// return TRUE iff the pattern index moved past the
// list-size (implying that the rest of the pattern
// is all wildcards)
return dnChainPatternIndex >= dnChainPattern.size();
}
// if the pattern finished, but the chain continues then
// we have a mis-match
if (dnChainPatternIndex >= dnChainPattern.size()) {
return false;
}
// get the next DN Pattern
dnPattern = dnChainPattern.get(dnChainPatternIndex);
if (dnPattern instanceof String) {
if (!dnPattern.equals(STAR_WILDCARD) && !dnPattern.equals(MINUS_WILDCARD)) {
throw new IllegalArgumentException("expected wildcard in DN pattern");
}
// if the next DN is a 'wildcard', then we will
// recurse
return dnChainMatch(dnChain, dnChainIndex, dnChainPattern, dnChainPatternIndex);
} else {
if (!(dnPattern instanceof List<?>)) {
throw new IllegalArgumentException("expected String or List in DN Pattern");
}
}
// if we are here, then we will just continue to the
// match the next set of DN's from the DNChain, and the
// DNChainPattern since both are lists
} while (true);
// should never reach here?
} else {
throw new IllegalArgumentException("expected String or List in DN Pattern");
}
}
// if we get here, the the default return is 'mis-match'
return false;
}
/**
* Matches a distinguished name chain against a pattern of a
* distinguished name chain.
*
* @param dnChain
* @param pattern the pattern of distinguished name (DN) chains to match
* against the dnChain. Wildcards ("*" or "-") can be used in
* three cases:
* <ol>
* <li>As a DN. In this case, the DN will consist of just the "*"
* or "-". When "*" is used it will match zero or one DNs. When
* "-" is used it will match zero or more DNs. For example,
* "cn=me,c=US;*;cn=you" will match
* "cn=me,c=US";cn=you" and "cn=me,c=US;cn=her;cn=you". The
* pattern "cn=me,c=US;-;cn=you" will match "cn=me,c=US";cn=you"
* and "cn=me,c=US;cn=her;cn=him;cn=you".</li>
* <li>As a DN prefix. In this case, the DN must start with "*,".
* The wild card will match zero or more RDNs at the start of a
* DN. For example, "*,cn=me,c=US;cn=you" will match
* "cn=me,c=US";cn=you" and
* "ou=my org unit,o=my org,cn=me,c=US;cn=you"</li>
* <li>As a value. In this case the value of a name value pair in
* an RDN will be a "*". The wildcard will match any value for
* the given name. For example, "cn=*,c=US;cn=you" will match
* "cn=me,c=US";cn=you" and "cn=her,c=US;cn=you", but it will not
* match "ou=my org unit,c=US;cn=you". If the wildcard does not
* occur by itself in the value, it will not be used as a
* wildcard. In other words, "cn=m*,c=US;cn=you" represents the
* common name of "m*" not any common name starting with "m".</li>
* </ol>
* @return true if dnChain matches the pattern.
* @throws IllegalArgumentException
*/
static boolean match(String pattern, List<String> dnChain) {
List<Object> parsedDNChain;
List<Object> parsedDNPattern;
try {
parsedDNChain = parseDNchain(dnChain);
} catch (RuntimeException e) {
throw new IllegalArgumentException(
"Invalid DN chain: " + toString(dnChain), e);
}
try {
parsedDNPattern = parseDNchainPattern(pattern);
} catch (RuntimeException e) {
throw new IllegalArgumentException(
"Invalid match pattern: " + pattern, e);
}
return dnChainMatch(parsedDNChain, 0, parsedDNPattern, 0);
}
private static String toString(List<?> dnChain) {
if (dnChain == null) {
return null;
}
StringBuilder sb = new StringBuilder();
for (Iterator<?> iChain = dnChain.iterator(); iChain.hasNext();) {
sb.append(iChain.next());
if (iChain.hasNext()) {
sb.append("; ");
}
}
return sb.toString();
}
}
/**
* Return a Map wrapper around a Dictionary.
*
* @param <K> The type of the key.
* @param <V> The type of the value.
* @param dictionary The dictionary to wrap.
* @return A Map object which wraps the specified dictionary. If the
* specified dictionary can be cast to a Map, then the specified
* dictionary is returned.
* @since 1.10
*/
public static <K, V> Map<K,V> asMap(
Dictionary< ? extends K, ? extends V> dictionary) {
if (dictionary instanceof Map) {
@SuppressWarnings("unchecked")
Map<K,V> coerced = (Map<K,V>) dictionary;
return coerced;
}
return new DictionaryAsMap<>(dictionary);
}
private static class DictionaryAsMap<K, V> extends AbstractMap<K,V> {
private final Dictionary<K,V> dict;
@SuppressWarnings("unchecked")
DictionaryAsMap(Dictionary< ? extends K, ? extends V> dict) {
this.dict = (Dictionary<K,V>) requireNonNull(dict);
}
Iterator<K> keys() {
List<K> keys = new ArrayList<>(dict.size());
for (Enumeration<K> e = dict.keys(); e.hasMoreElements();) {
keys.add(e.nextElement());
}
return keys.iterator();
}
@Override
public int size() {
return dict.size();
}
@Override
public boolean isEmpty() {
return dict.isEmpty();
}
@Override
public boolean containsKey(Object key) {
if (key == null) {
return false;
}
return dict.get(key) != null;
}
@Override
public V get(Object key) {
if (key == null) {
return null;
}
return dict.get(key);
}
@Override
public V put(K key, V value) {
return dict.put(
requireNonNull(key,
"a Dictionary cannot contain a null key"),
requireNonNull(value,
"a Dictionary cannot contain a null value"));
}
@Override
public V remove(Object key) {
if (key == null) {
return null;
}
return dict.remove(key);
}
@Override
public void clear() {
for (Iterator<K> iter = keys(); iter.hasNext();) {
dict.remove(iter.next());
}
}
@Override
public Set<K> keySet() {
return new KeySet();
}
@Override
public Set<Map.Entry<K,V>> entrySet() {
return new EntrySet();
}
@Override
public String toString() {
return dict.toString();
}
final class KeySet extends AbstractSet<K> {
@Override
public Iterator<K> iterator() {
return new KeyIterator();
}
@Override
public int size() {
return DictionaryAsMap.this.size();
}
@Override
public boolean isEmpty() {
return DictionaryAsMap.this.isEmpty();
}
@Override
public boolean contains(Object key) {
return DictionaryAsMap.this.containsKey(key);
}
@Override
public boolean remove(Object key) {
return DictionaryAsMap.this.remove(key) != null;
}
@Override
public void clear() {
DictionaryAsMap.this.clear();
}
}
final class KeyIterator implements Iterator<K> {
private final Iterator<K> keys = DictionaryAsMap.this.keys();
private K key = null;
@Override
public boolean hasNext() {
return keys.hasNext();
}
@Override
public K next() {
return key = keys.next();
}
@Override
public void remove() {
if (key == null) {
throw new IllegalStateException();
}
DictionaryAsMap.this.remove(key);
key = null;
}
}
final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
@Override
public Iterator<Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
@Override
public int size() {
return DictionaryAsMap.this.size();
}
@Override
public boolean isEmpty() {
return DictionaryAsMap.this.isEmpty();
}
@Override
public boolean contains(Object o) {
if (o instanceof Map.Entry) {
Map.Entry< ? , ? > e = (Map.Entry< ? , ? >) o;
return containsEntry(e);
}
return false;
}
private boolean containsEntry(Map.Entry< ? , ? > e) {
Object key = e.getKey();
if (key == null) {
return false;
}
Object value = e.getValue();
if (value == null) {
return false;
}
return Objects.equals(DictionaryAsMap.this.get(key), value);
}
@Override
public boolean remove(Object o) {
if (o instanceof Map.Entry) {
Map.Entry< ? , ? > e = (Map.Entry< ? , ? >) o;
if (containsEntry(e)) {
DictionaryAsMap.this.remove(e.getKey());
return true;
}
}
return false;
}
@Override
public void clear() {
DictionaryAsMap.this.clear();
}
}
final class EntryIterator implements Iterator<Map.Entry<K,V>> {
private final Iterator<K> keys = DictionaryAsMap.this.keys();
private K key = null;
@Override
public boolean hasNext() {
return keys.hasNext();
}
@Override
public Map.Entry<K,V> next() {
return new Entry(key = keys.next());
}
@Override
public void remove() {
if (key == null) {
throw new IllegalStateException();
}
DictionaryAsMap.this.remove(key);
key = null;
}
}
final class Entry extends SimpleEntry<K,V> {
private static final long serialVersionUID = 1L;
Entry(K key) {
super(key, DictionaryAsMap.this.get(key));
}
@Override
public V setValue(V value) {
DictionaryAsMap.this.put(getKey(), value);
return super.setValue(value);
}
}
}
/**
* Return a Dictionary wrapper around a Map.
*
* @param <K> The type of the key.
* @param <V> The type of the value.
* @param map The map to wrap.
* @return A Dictionary object which wraps the specified map. If the
* specified map can be cast to a Dictionary, then the specified map
* is returned.
* @since 1.10
*/
public static <K, V> Dictionary<K,V> asDictionary(
Map< ? extends K, ? extends V> map) {
if (map instanceof Dictionary) {
@SuppressWarnings("unchecked")
Dictionary<K,V> coerced = (Dictionary<K,V>) map;
return coerced;
}
return new MapAsDictionary<>(map);
}
private static class MapAsDictionary<K, V> extends Dictionary<K,V> {
private final Map<K,V> map;
@SuppressWarnings("unchecked")
MapAsDictionary(Map< ? extends K, ? extends V> map) {
this.map = (Map<K,V>) requireNonNull(map);
boolean nullKey;
try {
nullKey = map.containsKey(null);
} catch (NullPointerException e) {
nullKey = false; // map does not allow null key
}
if (nullKey) {
throw new NullPointerException(
"a Dictionary cannot contain a null key");
}
boolean nullValue;
try {
nullValue = map.containsValue(null);
} catch (NullPointerException e) {
nullValue = false; // map does not allow null value
}
if (nullValue) {
throw new NullPointerException(
"a Dictionary cannot contain a null value");
}
}
@Override
public int size() {
return map.size();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public Enumeration<K> keys() {
return Collections.enumeration(map.keySet());
}
@Override
public Enumeration<V> elements() {
return Collections.enumeration(map.values());
}
@Override
public V get(Object key) {
if (key == null) {
return null;
}
return map.get(key);
}
@Override
public V put(K key, V value) {
return map.put(
requireNonNull(key,
"a Dictionary cannot contain a null key"),
requireNonNull(value,
"a Dictionary cannot contain a null value"));
}
@Override
public V remove(Object key) {
if (key == null) {
return null;
}
return map.remove(key);
}
@Override
public String toString() {
return map.toString();
}
}
}
|
apache/harmony | 32,210 | classlib/modules/luni/src/test/api/common/org/apache/harmony/luni/tests/java/util/TimerTest.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.luni.tests.java.util;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicReference;
public class TimerTest extends junit.framework.TestCase {
int timerCounter = 0;
Object sync = new Object();
/**
* Warning: These tests have the possibility to leave a VM hanging if the
* Timer is not cancelled.
*/
class TimerTestTask extends TimerTask {
int wasRun = 0;
// Should we sleep for 200 ms each run()?
boolean sleepInRun = false;
// Should we increment the timerCounter?
boolean incrementCount = false;
// Should we terminate the timer at a specific timerCounter?
int terminateCount = -1;
// The timer we belong to
Timer timer = null;
public TimerTestTask() {
}
public TimerTestTask(Timer t) {
timer = t;
}
public void run() {
synchronized (this) {
wasRun++;
}
if (incrementCount)
timerCounter++;
if (terminateCount == timerCounter && timer != null)
timer.cancel();
if (sleepInRun) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
}
synchronized (sync) {
sync.notify();
}
}
public synchronized int wasRun() {
return wasRun;
}
public void sleepInRun(boolean sleepInRun) {
this.sleepInRun = sleepInRun;
}
public void incrementCount(boolean incrementCount) {
this.incrementCount = incrementCount;
}
public void terminateCount(int terminateCount) {
this.terminateCount = terminateCount;
}
}
/**
* @tests java.util.Timer#Timer(boolean)
*/
public void test_ConstructorZ() {
Timer t = null;
try {
// Ensure a task is run
t = new Timer(true);
TimerTestTask testTask = new TimerTestTask();
t.schedule(testTask, 200);
synchronized (sync) {
try {
sync.wait(1000);
} catch (InterruptedException e) {
}
}
assertEquals("TimerTask.run() method not called after 200ms",
1, testTask.wasRun());
t.cancel();
} finally {
if (t != null)
t.cancel();
}
}
/**
* @tests java.util.Timer#Timer()
*/
public void test_Constructor() {
Timer t = null;
try {
// Ensure a task is run
t = new Timer();
TimerTestTask testTask = new TimerTestTask();
t.schedule(testTask, 200);
synchronized (sync) {
try {
sync.wait(1000);
} catch (InterruptedException e) {
}
}
assertEquals("TimerTask.run() method not called after 200ms",
1, testTask.wasRun());
t.cancel();
} finally {
if (t != null)
t.cancel();
}
}
/**
* @tests java.util.Timer#Timer(String, boolean)
*/
public void test_ConstructorSZ() {
Timer t = null;
try {
// Ensure a task is run
t = new Timer("test_ConstructorSZThread", true);
TimerTestTask testTask = new TimerTestTask();
t.schedule(testTask, 200);
synchronized (sync) {
try {
sync.wait(1000);
} catch (InterruptedException e) {}
}
assertEquals("TimerTask.run() method not called after 200ms", 1,
testTask.wasRun());
t.cancel();
} finally {
if (t != null)
t.cancel();
}
}
/**
* @tests java.util.Timer#Timer(String)
*/
public void test_ConstructorS() {
Timer t = null;
try {
// Ensure a task is run
t = new Timer("test_ConstructorSThread");
TimerTestTask testTask = new TimerTestTask();
t.schedule(testTask, 200);
synchronized (sync) {
try {
sync.wait(1000);
} catch (InterruptedException e) {}
}
assertEquals("TimerTask.run() method not called after 200ms", 1,
testTask.wasRun());
t.cancel();
} finally {
if (t != null)
t.cancel();
}
}
public void testConstructorThrowsException() {
try {
new Timer(null, true);
fail("NullPointerException expected");
} catch (NullPointerException e) {
//expected
}
try {
new Timer(null, false);
fail("NullPointerException expected");
} catch (NullPointerException e) {
//expected
}
}
/**
* @tests java.util.Timer#cancel()
*/
public void test_cancel() {
Timer t = null;
try {
// Ensure a task throws an IllegalStateException after cancelled
t = new Timer();
TimerTestTask testTask = new TimerTestTask();
t.cancel();
boolean exception = false;
try {
t.schedule(testTask, 100, 200);
} catch (IllegalStateException e) {
exception = true;
}
assertTrue(
"Scheduling a task after Timer.cancel() should throw exception",
exception);
// Ensure a task is run but not after cancel
t = new Timer();
testTask = new TimerTestTask();
t.schedule(testTask, 100, 500);
synchronized (sync) {
try {
sync.wait(1000);
} catch (InterruptedException e) {
}
}
assertEquals("TimerTask.run() method not called after 200ms",
1, testTask.wasRun());
t.cancel();
synchronized (sync) {
try {
sync.wait(500);
} catch (InterruptedException e) {
}
}
assertEquals("TimerTask.run() method should not have been called after cancel",
1, testTask.wasRun());
// Ensure you can call cancel more than once
t = new Timer();
testTask = new TimerTestTask();
t.schedule(testTask, 100, 500);
synchronized (sync) {
try {
sync.wait(500);
} catch (InterruptedException e) {
}
}
assertEquals("TimerTask.run() method not called after 200ms",
1, testTask.wasRun());
t.cancel();
t.cancel();
t.cancel();
synchronized (sync) {
try {
sync.wait(500);
} catch (InterruptedException e) {
}
}
assertEquals("TimerTask.run() method should not have been called after cancel",
1, testTask.wasRun());
// Ensure that a call to cancel from within a timer ensures no more
// run
t = new Timer();
testTask = new TimerTestTask(t);
testTask.incrementCount(true);
testTask.terminateCount(5); // Terminate after 5 runs
t.schedule(testTask, 100, 100);
synchronized (sync) {
try {
sync.wait(200);
sync.wait(200);
sync.wait(200);
sync.wait(200);
sync.wait(200);
sync.wait(200);
} catch (InterruptedException e) {
}
}
assertTrue("TimerTask.run() method should be called 5 times not "
+ testTask.wasRun(), testTask.wasRun() == 5);
t.cancel();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
} finally {
if (t != null)
t.cancel();
}
}
/**
* @tests java.util.Timer#purge()
*/
public void test_purge() throws Exception {
Timer t = null;
try {
t = new Timer();
assertEquals(0, t.purge());
TimerTestTask[] tasks = new TimerTestTask[100];
int[] delayTime = { 50, 80, 20, 70, 40, 10, 90, 30, 60 };
int j = 0;
for (int i = 0; i < 100; i++) {
tasks[i] = new TimerTestTask();
t.schedule(tasks[i], delayTime[j++], 200);
if (j == 9) {
j = 0;
}
}
for (int i = 0; i < 50; i++) {
tasks[i].cancel();
}
assertTrue(t.purge() <= 50);
assertEquals(0, t.purge());
} finally {
if (t != null) {
t.cancel();
}
}
}
/**
* @tests java.util.Timer#schedule(java.util.TimerTask, java.util.Date)
*/
public void test_scheduleLjava_util_TimerTaskLjava_util_Date() {
Timer t = null;
try {
// Ensure a Timer throws an IllegalStateException after cancelled
t = new Timer();
TimerTestTask testTask = new TimerTestTask();
Date d = new Date(System.currentTimeMillis() + 100);
t.cancel();
boolean exception = false;
try {
t.schedule(testTask, d);
} catch (IllegalStateException e) {
exception = true;
}
assertTrue(
"Scheduling a task after Timer.cancel() should throw exception",
exception);
// Ensure a Timer throws an IllegalStateException if task already
// cancelled
t = new Timer();
testTask = new TimerTestTask();
d = new Date(System.currentTimeMillis() + 100);
testTask.cancel();
exception = false;
try {
t.schedule(testTask, d);
} catch (IllegalStateException e) {
exception = true;
}
assertTrue(
"Scheduling a task after cancelling it should throw exception",
exception);
t.cancel();
// Ensure a Timer throws an IllegalArgumentException if delay is
// negative
t = new Timer();
testTask = new TimerTestTask();
d = new Date(-100);
exception = false;
try {
t.schedule(testTask, d);
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a task with negative date should throw IllegalArgumentException",
exception);
t.cancel();
// Ensure a Timer throws a NullPointerException if the task is null
t = new Timer();
exception = false;
d = new Date(System.currentTimeMillis() + 100);
try {
t.schedule(null, d);
} catch (NullPointerException e) {
exception = true;
}
assertTrue(
"Scheduling a null task should throw NullPointerException",
exception);
t.cancel();
// Ensure a Timer throws a NullPointerException if the date is null
t = new Timer();
testTask = new TimerTestTask();
exception = false;
try {
t.schedule(testTask, null);
} catch (NullPointerException e) {
exception = true;
}
assertTrue(
"Scheduling a null date should throw NullPointerException",
exception);
t.cancel();
// Ensure proper sequence of exceptions
t = new Timer();
d = new Date(-100);
exception = false;
try {
t.schedule(null, d);
} catch (NullPointerException e) {
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a null task with negative date should throw IllegalArgumentException first",
exception);
t.cancel();
// Ensure a task is run
t = new Timer();
testTask = new TimerTestTask();
d = new Date(System.currentTimeMillis() + 200);
t.schedule(testTask, d);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
}
assertEquals("TimerTask.run() method not called after 200ms",
1, testTask.wasRun());
t.cancel();
// Ensure multiple tasks are run
t = new Timer();
testTask = new TimerTestTask();
testTask.incrementCount(true);
d = new Date(System.currentTimeMillis() + 100);
t.schedule(testTask, d);
testTask = new TimerTestTask();
testTask.incrementCount(true);
d = new Date(System.currentTimeMillis() + 150);
t.schedule(testTask, d);
testTask = new TimerTestTask();
testTask.incrementCount(true);
d = new Date(System.currentTimeMillis() + 70);
t.schedule(testTask, d);
testTask = new TimerTestTask();
testTask.incrementCount(true);
d = new Date(System.currentTimeMillis() + 10);
t.schedule(testTask, d);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
}
assertTrue(
"Multiple tasks should have incremented counter 4 times not "
+ timerCounter, timerCounter == 4);
t.cancel();
} finally {
if (t != null)
t.cancel();
}
}
/**
* @tests java.util.Timer#schedule(java.util.TimerTask, long)
*/
public void test_scheduleLjava_util_TimerTaskJ() {
Timer t = null;
try {
// Ensure a Timer throws an IllegalStateException after cancelled
t = new Timer();
TimerTestTask testTask = new TimerTestTask();
t.cancel();
boolean exception = false;
try {
t.schedule(testTask, 100);
} catch (IllegalStateException e) {
exception = true;
}
assertTrue(
"Scheduling a task after Timer.cancel() should throw exception",
exception);
// Ensure a Timer throws an IllegalStateException if task already
// cancelled
t = new Timer();
testTask = new TimerTestTask();
testTask.cancel();
exception = false;
try {
t.schedule(testTask, 100);
} catch (IllegalStateException e) {
exception = true;
}
assertTrue(
"Scheduling a task after cancelling it should throw exception",
exception);
t.cancel();
// Ensure a Timer throws an IllegalArgumentException if delay is
// negative
t = new Timer();
testTask = new TimerTestTask();
exception = false;
try {
t.schedule(testTask, -100);
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a task with negative delay should throw IllegalArgumentException",
exception);
t.cancel();
// Ensure a Timer throws a NullPointerException if the task is null
t = new Timer();
exception = false;
try {
t.schedule(null, 10);
} catch (NullPointerException e) {
exception = true;
}
assertTrue(
"Scheduling a null task should throw NullPointerException",
exception);
t.cancel();
// Ensure proper sequence of exceptions
t = new Timer();
exception = false;
try {
t.schedule(null, -10);
} catch (NullPointerException e) {
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a null task with negative delays should throw IllegalArgumentException first",
exception);
t.cancel();
// Ensure a task is run
t = new Timer();
testTask = new TimerTestTask();
t.schedule(testTask, 200);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
}
assertEquals("TimerTask.run() method not called after 200ms",
1, testTask.wasRun());
t.cancel();
// Ensure multiple tasks are run
t = new Timer();
testTask = new TimerTestTask();
testTask.incrementCount(true);
t.schedule(testTask, 100);
testTask = new TimerTestTask();
testTask.incrementCount(true);
t.schedule(testTask, 150);
testTask = new TimerTestTask();
testTask.incrementCount(true);
t.schedule(testTask, 70);
testTask = new TimerTestTask();
testTask.incrementCount(true);
t.schedule(testTask, 10);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
}
assertTrue(
"Multiple tasks should have incremented counter 4 times not "
+ timerCounter, timerCounter == 4);
t.cancel();
} finally {
if (t != null)
t.cancel();
}
}
/**
* @tests java.util.Timer#schedule(java.util.TimerTask, long, long)
*/
public void test_scheduleLjava_util_TimerTaskJJ() {
Timer t = null;
try {
// Ensure a Timer throws an IllegalStateException after cancelled
t = new Timer();
TimerTestTask testTask = new TimerTestTask();
t.cancel();
boolean exception = false;
try {
t.schedule(testTask, 100, 100);
} catch (IllegalStateException e) {
exception = true;
}
assertTrue(
"Scheduling a task after Timer.cancel() should throw exception",
exception);
// Ensure a Timer throws an IllegalStateException if task already
// cancelled
t = new Timer();
testTask = new TimerTestTask();
testTask.cancel();
exception = false;
try {
t.schedule(testTask, 100, 100);
} catch (IllegalStateException e) {
exception = true;
}
assertTrue(
"Scheduling a task after cancelling it should throw exception",
exception);
t.cancel();
// Ensure a Timer throws an IllegalArgumentException if delay is
// negative
t = new Timer();
testTask = new TimerTestTask();
exception = false;
try {
t.schedule(testTask, -100, 100);
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a task with negative delay should throw IllegalArgumentException",
exception);
t.cancel();
// Ensure a Timer throws an IllegalArgumentException if period is
// negative
t = new Timer();
testTask = new TimerTestTask();
exception = false;
try {
t.schedule(testTask, 100, -100);
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a task with negative period should throw IllegalArgumentException",
exception);
t.cancel();
// Ensure a Timer throws an IllegalArgumentException if period is
// zero
t = new Timer();
testTask = new TimerTestTask();
exception = false;
try {
t.schedule(testTask, 100, 0);
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a task with 0 period should throw IllegalArgumentException",
exception);
t.cancel();
// Ensure a Timer throws a NullPointerException if the task is null
t = new Timer();
exception = false;
try {
t.schedule(null, 10, 10);
} catch (NullPointerException e) {
exception = true;
}
assertTrue(
"Scheduling a null task should throw NullPointerException",
exception);
t.cancel();
// Ensure proper sequence of exceptions
t = new Timer();
exception = false;
try {
t.schedule(null, -10, -10);
} catch (NullPointerException e) {
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a null task with negative delays should throw IllegalArgumentException first",
exception);
t.cancel();
// Ensure a task is run at least twice
t = new Timer();
testTask = new TimerTestTask();
t.schedule(testTask, 100, 100);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
}
assertTrue(
"TimerTask.run() method should have been called at least twice ("
+ testTask.wasRun() + ")", testTask.wasRun() >= 2);
t.cancel();
// Ensure multiple tasks are run
t = new Timer();
testTask = new TimerTestTask();
testTask.incrementCount(true);
t.schedule(testTask, 100, 100); // at least 9 times
testTask = new TimerTestTask();
testTask.incrementCount(true);
t.schedule(testTask, 200, 100); // at least 7 times
testTask = new TimerTestTask();
testTask.incrementCount(true);
t.schedule(testTask, 300, 200); // at least 4 times
testTask = new TimerTestTask();
testTask.incrementCount(true);
t.schedule(testTask, 100, 200); // at least 4 times
try {
Thread.sleep(1200); // Allowed more room for error
} catch (InterruptedException e) {
}
assertTrue(
"Multiple tasks should have incremented counter 24 times not "
+ timerCounter, timerCounter >= 24);
t.cancel();
} finally {
if (t != null)
t.cancel();
}
}
/**
* @tests java.util.Timer#schedule(java.util.TimerTask, java.util.Date,
* long)
*/
public void test_scheduleLjava_util_TimerTaskLjava_util_DateJ() {
Timer t = null;
try {
// Ensure a Timer throws an IllegalStateException after cancelled
t = new Timer();
TimerTestTask testTask = new TimerTestTask();
Date d = new Date(System.currentTimeMillis() + 100);
t.cancel();
boolean exception = false;
try {
t.schedule(testTask, d, 100);
} catch (IllegalStateException e) {
exception = true;
}
assertTrue(
"Scheduling a task after Timer.cancel() should throw exception",
exception);
// Ensure a Timer throws an IllegalStateException if task already
// cancelled
t = new Timer();
d = new Date(System.currentTimeMillis() + 100);
testTask = new TimerTestTask();
testTask.cancel();
exception = false;
try {
t.schedule(testTask, d, 100);
} catch (IllegalStateException e) {
exception = true;
}
assertTrue(
"Scheduling a task after cancelling it should throw exception",
exception);
t.cancel();
// Ensure a Timer throws an IllegalArgumentException if delay is
// negative
t = new Timer();
d = new Date(-100);
testTask = new TimerTestTask();
exception = false;
try {
t.schedule(testTask, d, 100);
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a task with negative delay should throw IllegalArgumentException",
exception);
t.cancel();
// Ensure a Timer throws an IllegalArgumentException if period is
// negative
t = new Timer();
d = new Date(System.currentTimeMillis() + 100);
testTask = new TimerTestTask();
exception = false;
try {
t.schedule(testTask, d, -100);
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a task with negative period should throw IllegalArgumentException",
exception);
t.cancel();
// Ensure a Timer throws a NullPointerException if the task is null
t = new Timer();
d = new Date(System.currentTimeMillis() + 100);
exception = false;
try {
t.schedule(null, d, 10);
} catch (NullPointerException e) {
exception = true;
}
assertTrue(
"Scheduling a null task should throw NullPointerException",
exception);
t.cancel();
// Ensure a Timer throws a NullPointerException if the date is null
t = new Timer();
testTask = new TimerTestTask();
exception = false;
try {
t.schedule(testTask, null, 10);
} catch (NullPointerException e) {
exception = true;
}
assertTrue(
"Scheduling a null task should throw NullPointerException",
exception);
t.cancel();
// Ensure proper sequence of exceptions
t = new Timer();
d = new Date(-100);
exception = false;
try {
t.schedule(null, d, 10);
} catch (NullPointerException e) {
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a null task with negative dates should throw IllegalArgumentException first",
exception);
t.cancel();
// Ensure a task is run at least twice
t = new Timer();
d = new Date(System.currentTimeMillis() + 100);
testTask = new TimerTestTask();
t.schedule(testTask, d, 100);
try {
Thread.sleep(800);
} catch (InterruptedException e) {
}
assertTrue(
"TimerTask.run() method should have been called at least twice ("
+ testTask.wasRun() + ")", testTask.wasRun() >= 2);
t.cancel();
// Ensure multiple tasks are run
t = new Timer();
testTask = new TimerTestTask();
testTask.incrementCount(true);
d = new Date(System.currentTimeMillis() + 100);
t.schedule(testTask, d, 100); // at least 9 times
testTask = new TimerTestTask();
testTask.incrementCount(true);
d = new Date(System.currentTimeMillis() + 200);
t.schedule(testTask, d, 100); // at least 7 times
testTask = new TimerTestTask();
testTask.incrementCount(true);
d = new Date(System.currentTimeMillis() + 300);
t.schedule(testTask, d, 200); // at least 4 times
testTask = new TimerTestTask();
testTask.incrementCount(true);
d = new Date(System.currentTimeMillis() + 100);
t.schedule(testTask, d, 200); // at least 4 times
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
assertTrue(
"Multiple tasks should have incremented counter 24 times not "
+ timerCounter, timerCounter >= 24);
t.cancel();
} finally {
if (t != null)
t.cancel();
}
}
/**
* @tests java.util.Timer#scheduleAtFixedRate(java.util.TimerTask, long,
* long)
*/
public void test_scheduleAtFixedRateLjava_util_TimerTaskJJ() {
Timer t = null;
try {
// Ensure a Timer throws an IllegalStateException after cancelled
t = new Timer();
TimerTestTask testTask = new TimerTestTask();
t.cancel();
boolean exception = false;
try {
t.scheduleAtFixedRate(testTask, 100, 100);
} catch (IllegalStateException e) {
exception = true;
}
assertTrue(
"scheduleAtFixedRate after Timer.cancel() should throw exception",
exception);
// Ensure a Timer throws an IllegalArgumentException if delay is
// negative
t = new Timer();
testTask = new TimerTestTask();
exception = false;
try {
t.scheduleAtFixedRate(testTask, -100, 100);
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"scheduleAtFixedRate with negative delay should throw IllegalArgumentException",
exception);
t.cancel();
// Ensure a Timer throws an IllegalArgumentException if period is
// negative
t = new Timer();
testTask = new TimerTestTask();
exception = false;
try {
t.scheduleAtFixedRate(testTask, 100, -100);
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"scheduleAtFixedRate with negative period should throw IllegalArgumentException",
exception);
t.cancel();
// Ensure a task is run at least twice
t = new Timer();
testTask = new TimerTestTask();
t.scheduleAtFixedRate(testTask, 100, 100);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
}
assertTrue(
"TimerTask.run() method should have been called at least twice ("
+ testTask.wasRun() + ")", testTask.wasRun() >= 2);
t.cancel();
class SlowThenFastTask extends TimerTask {
int wasRun = 0;
long startedAt;
long lastDelta;
public void run() {
if (wasRun == 0)
startedAt = System.currentTimeMillis();
lastDelta = System.currentTimeMillis()
- (startedAt + (100 * wasRun));
wasRun++;
if (wasRun == 2) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
}
}
public long lastDelta() {
return lastDelta;
}
public int wasRun() {
return wasRun;
}
}
// Ensure multiple tasks are run
t = new Timer();
SlowThenFastTask slowThenFastTask = new SlowThenFastTask();
// at least 9 times even when asleep
t.scheduleAtFixedRate(slowThenFastTask, 100, 100);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
long lastDelta = slowThenFastTask.lastDelta();
assertTrue("Fixed Rate Schedule should catch up, but is off by "
+ lastDelta + " ms", slowThenFastTask.lastDelta < 300);
t.cancel();
} finally {
if (t != null)
t.cancel();
}
}
/**
* @tests java.util.Timer#scheduleAtFixedRate(java.util.TimerTask,
* java.util.Date, long)
*/
public void test_scheduleAtFixedRateLjava_util_TimerTaskLjava_util_DateJ() {
Timer t = null;
try {
// Ensure a Timer throws an IllegalStateException after cancelled
t = new Timer();
TimerTestTask testTask = new TimerTestTask();
t.cancel();
boolean exception = false;
Date d = new Date(System.currentTimeMillis() + 100);
try {
t.scheduleAtFixedRate(testTask, d, 100);
} catch (IllegalStateException e) {
exception = true;
}
assertTrue(
"scheduleAtFixedRate after Timer.cancel() should throw exception",
exception);
// Ensure a Timer throws an IllegalArgumentException if delay is
// negative
t = new Timer();
testTask = new TimerTestTask();
exception = false;
d = new Date(-100);
try {
t.scheduleAtFixedRate(testTask, d, 100);
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"scheduleAtFixedRate with negative Date should throw IllegalArgumentException",
exception);
t.cancel();
// Ensure a Timer throws an IllegalArgumentException if period is
// negative
t = new Timer();
testTask = new TimerTestTask();
exception = false;
try {
t.scheduleAtFixedRate(testTask, d, -100);
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"scheduleAtFixedRate with negative period should throw IllegalArgumentException",
exception);
t.cancel();
// Ensure a Timer throws an NullPointerException if date is Null
t = new Timer();
testTask = new TimerTestTask();
exception = false;
try {
t.scheduleAtFixedRate(testTask, null, 100);
} catch (NullPointerException e) {
exception = true;
}
assertTrue(
"scheduleAtFixedRate with null date should throw NullPointerException",
exception);
t.cancel();
// Ensure proper sequence of exceptions
t = new Timer();
exception = false;
d = new Date(-100);
try {
t.scheduleAtFixedRate(null, d, 10);
} catch (NullPointerException e) {
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a null task with negative date should throw IllegalArgumentException first",
exception);
t.cancel();
// Ensure proper sequence of exceptions
t = new Timer();
exception = false;
try {
t.scheduleAtFixedRate(null, null, -10);
} catch (NullPointerException e) {
} catch (IllegalArgumentException e) {
exception = true;
}
assertTrue(
"Scheduling a null task & null date & negative period should throw IllegalArgumentException first",
exception);
t.cancel();
// Ensure a task is run at least twice
t = new Timer();
testTask = new TimerTestTask();
d = new Date(System.currentTimeMillis() + 100);
t.scheduleAtFixedRate(testTask, d, 100);
try {
Thread.sleep(400);
} catch (InterruptedException e) {
}
assertTrue(
"TimerTask.run() method should have been called at least twice ("
+ testTask.wasRun() + ")", testTask.wasRun() >= 2);
t.cancel();
class SlowThenFastTask extends TimerTask {
int wasRun = 0;
long startedAt;
long lastDelta;
public void run() {
if (wasRun == 0)
startedAt = System.currentTimeMillis();
lastDelta = System.currentTimeMillis()
- (startedAt + (100 * wasRun));
wasRun++;
if (wasRun == 2) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
}
}
}
public long lastDelta() {
return lastDelta;
}
public int wasRun() {
return wasRun;
}
}
// Ensure multiple tasks are run
t = new Timer();
SlowThenFastTask slowThenFastTask = new SlowThenFastTask();
d = new Date(System.currentTimeMillis() + 100);
// at least 9 times even when asleep
t.scheduleAtFixedRate(slowThenFastTask, d, 100);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
long lastDelta = slowThenFastTask.lastDelta();
assertTrue("Fixed Rate Schedule should catch up, but is off by "
+ lastDelta + " ms", lastDelta < 300);
t.cancel();
} finally {
if (t != null)
t.cancel();
}
}
/**
* We used to swallow RuntimeExceptions thrown by tasks. Instead, we need to
* let those exceptions bubble up, where they will both notify the thread's
* uncaught exception handler and terminate the timer's thread.
*/
public void testThrowingTaskKillsTimerThread() throws InterruptedException {
final AtomicReference<Thread> threadRef = new AtomicReference<Thread>();
new Timer().schedule(new TimerTask() {
@Override public void run() {
threadRef.set(Thread.currentThread());
throw new RuntimeException("task failure!");
}
}, 1);
Thread.sleep(400);
Thread timerThread = threadRef.get();
assertFalse(timerThread.isAlive());
}
protected void setUp() {
timerCounter = 0;
}
protected void tearDown() {
}
}
|
googleapis/google-cloud-java | 35,548 | java-geminidataanalytics/proto-google-cloud-geminidataanalytics-v1beta/src/main/java/com/google/cloud/geminidataanalytics/v1beta/SchemaMessage.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/geminidataanalytics/v1beta/data_chat_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.geminidataanalytics.v1beta;
/**
*
*
* <pre>
* A message produced during schema resolution.
* </pre>
*
* Protobuf type {@code google.cloud.geminidataanalytics.v1beta.SchemaMessage}
*/
public final class SchemaMessage extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.geminidataanalytics.v1beta.SchemaMessage)
SchemaMessageOrBuilder {
private static final long serialVersionUID = 0L;
// Use SchemaMessage.newBuilder() to construct.
private SchemaMessage(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SchemaMessage() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SchemaMessage();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.geminidataanalytics.v1beta.DataChatServiceProto
.internal_static_google_cloud_geminidataanalytics_v1beta_SchemaMessage_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.geminidataanalytics.v1beta.DataChatServiceProto
.internal_static_google_cloud_geminidataanalytics_v1beta_SchemaMessage_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.geminidataanalytics.v1beta.SchemaMessage.class,
com.google.cloud.geminidataanalytics.v1beta.SchemaMessage.Builder.class);
}
private int kindCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object kind_;
public enum KindCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
QUERY(1),
RESULT(2),
KIND_NOT_SET(0);
private final int value;
private KindCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static KindCase valueOf(int value) {
return forNumber(value);
}
public static KindCase forNumber(int value) {
switch (value) {
case 1:
return QUERY;
case 2:
return RESULT;
case 0:
return KIND_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public KindCase getKindCase() {
return KindCase.forNumber(kindCase_);
}
public static final int QUERY_FIELD_NUMBER = 1;
/**
*
*
* <pre>
* A schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaQuery query = 1;</code>
*
* @return Whether the query field is set.
*/
@java.lang.Override
public boolean hasQuery() {
return kindCase_ == 1;
}
/**
*
*
* <pre>
* A schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaQuery query = 1;</code>
*
* @return The query.
*/
@java.lang.Override
public com.google.cloud.geminidataanalytics.v1beta.SchemaQuery getQuery() {
if (kindCase_ == 1) {
return (com.google.cloud.geminidataanalytics.v1beta.SchemaQuery) kind_;
}
return com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.getDefaultInstance();
}
/**
*
*
* <pre>
* A schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaQuery query = 1;</code>
*/
@java.lang.Override
public com.google.cloud.geminidataanalytics.v1beta.SchemaQueryOrBuilder getQueryOrBuilder() {
if (kindCase_ == 1) {
return (com.google.cloud.geminidataanalytics.v1beta.SchemaQuery) kind_;
}
return com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.getDefaultInstance();
}
public static final int RESULT_FIELD_NUMBER = 2;
/**
*
*
* <pre>
* The result of a schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaResult result = 2;</code>
*
* @return Whether the result field is set.
*/
@java.lang.Override
public boolean hasResult() {
return kindCase_ == 2;
}
/**
*
*
* <pre>
* The result of a schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaResult result = 2;</code>
*
* @return The result.
*/
@java.lang.Override
public com.google.cloud.geminidataanalytics.v1beta.SchemaResult getResult() {
if (kindCase_ == 2) {
return (com.google.cloud.geminidataanalytics.v1beta.SchemaResult) kind_;
}
return com.google.cloud.geminidataanalytics.v1beta.SchemaResult.getDefaultInstance();
}
/**
*
*
* <pre>
* The result of a schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaResult result = 2;</code>
*/
@java.lang.Override
public com.google.cloud.geminidataanalytics.v1beta.SchemaResultOrBuilder getResultOrBuilder() {
if (kindCase_ == 2) {
return (com.google.cloud.geminidataanalytics.v1beta.SchemaResult) kind_;
}
return com.google.cloud.geminidataanalytics.v1beta.SchemaResult.getDefaultInstance();
}
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 (kindCase_ == 1) {
output.writeMessage(1, (com.google.cloud.geminidataanalytics.v1beta.SchemaQuery) kind_);
}
if (kindCase_ == 2) {
output.writeMessage(2, (com.google.cloud.geminidataanalytics.v1beta.SchemaResult) kind_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (kindCase_ == 1) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, (com.google.cloud.geminidataanalytics.v1beta.SchemaQuery) kind_);
}
if (kindCase_ == 2) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
2, (com.google.cloud.geminidataanalytics.v1beta.SchemaResult) kind_);
}
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.geminidataanalytics.v1beta.SchemaMessage)) {
return super.equals(obj);
}
com.google.cloud.geminidataanalytics.v1beta.SchemaMessage other =
(com.google.cloud.geminidataanalytics.v1beta.SchemaMessage) obj;
if (!getKindCase().equals(other.getKindCase())) return false;
switch (kindCase_) {
case 1:
if (!getQuery().equals(other.getQuery())) return false;
break;
case 2:
if (!getResult().equals(other.getResult())) return false;
break;
case 0:
default:
}
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();
switch (kindCase_) {
case 1:
hash = (37 * hash) + QUERY_FIELD_NUMBER;
hash = (53 * hash) + getQuery().hashCode();
break;
case 2:
hash = (37 * hash) + RESULT_FIELD_NUMBER;
hash = (53 * hash) + getResult().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.geminidataanalytics.v1beta.SchemaMessage parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.geminidataanalytics.v1beta.SchemaMessage 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.geminidataanalytics.v1beta.SchemaMessage parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.geminidataanalytics.v1beta.SchemaMessage 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.geminidataanalytics.v1beta.SchemaMessage parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.geminidataanalytics.v1beta.SchemaMessage parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.geminidataanalytics.v1beta.SchemaMessage parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.geminidataanalytics.v1beta.SchemaMessage 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.geminidataanalytics.v1beta.SchemaMessage parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.geminidataanalytics.v1beta.SchemaMessage 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.geminidataanalytics.v1beta.SchemaMessage parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.geminidataanalytics.v1beta.SchemaMessage 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.geminidataanalytics.v1beta.SchemaMessage 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 message produced during schema resolution.
* </pre>
*
* Protobuf type {@code google.cloud.geminidataanalytics.v1beta.SchemaMessage}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.geminidataanalytics.v1beta.SchemaMessage)
com.google.cloud.geminidataanalytics.v1beta.SchemaMessageOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.geminidataanalytics.v1beta.DataChatServiceProto
.internal_static_google_cloud_geminidataanalytics_v1beta_SchemaMessage_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.geminidataanalytics.v1beta.DataChatServiceProto
.internal_static_google_cloud_geminidataanalytics_v1beta_SchemaMessage_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.geminidataanalytics.v1beta.SchemaMessage.class,
com.google.cloud.geminidataanalytics.v1beta.SchemaMessage.Builder.class);
}
// Construct using com.google.cloud.geminidataanalytics.v1beta.SchemaMessage.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (queryBuilder_ != null) {
queryBuilder_.clear();
}
if (resultBuilder_ != null) {
resultBuilder_.clear();
}
kindCase_ = 0;
kind_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.geminidataanalytics.v1beta.DataChatServiceProto
.internal_static_google_cloud_geminidataanalytics_v1beta_SchemaMessage_descriptor;
}
@java.lang.Override
public com.google.cloud.geminidataanalytics.v1beta.SchemaMessage getDefaultInstanceForType() {
return com.google.cloud.geminidataanalytics.v1beta.SchemaMessage.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.geminidataanalytics.v1beta.SchemaMessage build() {
com.google.cloud.geminidataanalytics.v1beta.SchemaMessage result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.geminidataanalytics.v1beta.SchemaMessage buildPartial() {
com.google.cloud.geminidataanalytics.v1beta.SchemaMessage result =
new com.google.cloud.geminidataanalytics.v1beta.SchemaMessage(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.geminidataanalytics.v1beta.SchemaMessage result) {
int from_bitField0_ = bitField0_;
}
private void buildPartialOneofs(
com.google.cloud.geminidataanalytics.v1beta.SchemaMessage result) {
result.kindCase_ = kindCase_;
result.kind_ = this.kind_;
if (kindCase_ == 1 && queryBuilder_ != null) {
result.kind_ = queryBuilder_.build();
}
if (kindCase_ == 2 && resultBuilder_ != null) {
result.kind_ = resultBuilder_.build();
}
}
@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.geminidataanalytics.v1beta.SchemaMessage) {
return mergeFrom((com.google.cloud.geminidataanalytics.v1beta.SchemaMessage) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.geminidataanalytics.v1beta.SchemaMessage other) {
if (other == com.google.cloud.geminidataanalytics.v1beta.SchemaMessage.getDefaultInstance())
return this;
switch (other.getKindCase()) {
case QUERY:
{
mergeQuery(other.getQuery());
break;
}
case RESULT:
{
mergeResult(other.getResult());
break;
}
case KIND_NOT_SET:
{
break;
}
}
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(getQueryFieldBuilder().getBuilder(), extensionRegistry);
kindCase_ = 1;
break;
} // case 10
case 18:
{
input.readMessage(getResultFieldBuilder().getBuilder(), extensionRegistry);
kindCase_ = 2;
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 kindCase_ = 0;
private java.lang.Object kind_;
public KindCase getKindCase() {
return KindCase.forNumber(kindCase_);
}
public Builder clearKind() {
kindCase_ = 0;
kind_ = null;
onChanged();
return this;
}
private int bitField0_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.geminidataanalytics.v1beta.SchemaQuery,
com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.Builder,
com.google.cloud.geminidataanalytics.v1beta.SchemaQueryOrBuilder>
queryBuilder_;
/**
*
*
* <pre>
* A schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaQuery query = 1;</code>
*
* @return Whether the query field is set.
*/
@java.lang.Override
public boolean hasQuery() {
return kindCase_ == 1;
}
/**
*
*
* <pre>
* A schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaQuery query = 1;</code>
*
* @return The query.
*/
@java.lang.Override
public com.google.cloud.geminidataanalytics.v1beta.SchemaQuery getQuery() {
if (queryBuilder_ == null) {
if (kindCase_ == 1) {
return (com.google.cloud.geminidataanalytics.v1beta.SchemaQuery) kind_;
}
return com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.getDefaultInstance();
} else {
if (kindCase_ == 1) {
return queryBuilder_.getMessage();
}
return com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.getDefaultInstance();
}
}
/**
*
*
* <pre>
* A schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaQuery query = 1;</code>
*/
public Builder setQuery(com.google.cloud.geminidataanalytics.v1beta.SchemaQuery value) {
if (queryBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
kind_ = value;
onChanged();
} else {
queryBuilder_.setMessage(value);
}
kindCase_ = 1;
return this;
}
/**
*
*
* <pre>
* A schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaQuery query = 1;</code>
*/
public Builder setQuery(
com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.Builder builderForValue) {
if (queryBuilder_ == null) {
kind_ = builderForValue.build();
onChanged();
} else {
queryBuilder_.setMessage(builderForValue.build());
}
kindCase_ = 1;
return this;
}
/**
*
*
* <pre>
* A schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaQuery query = 1;</code>
*/
public Builder mergeQuery(com.google.cloud.geminidataanalytics.v1beta.SchemaQuery value) {
if (queryBuilder_ == null) {
if (kindCase_ == 1
&& kind_
!= com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.getDefaultInstance()) {
kind_ =
com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.newBuilder(
(com.google.cloud.geminidataanalytics.v1beta.SchemaQuery) kind_)
.mergeFrom(value)
.buildPartial();
} else {
kind_ = value;
}
onChanged();
} else {
if (kindCase_ == 1) {
queryBuilder_.mergeFrom(value);
} else {
queryBuilder_.setMessage(value);
}
}
kindCase_ = 1;
return this;
}
/**
*
*
* <pre>
* A schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaQuery query = 1;</code>
*/
public Builder clearQuery() {
if (queryBuilder_ == null) {
if (kindCase_ == 1) {
kindCase_ = 0;
kind_ = null;
onChanged();
}
} else {
if (kindCase_ == 1) {
kindCase_ = 0;
kind_ = null;
}
queryBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* A schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaQuery query = 1;</code>
*/
public com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.Builder getQueryBuilder() {
return getQueryFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* A schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaQuery query = 1;</code>
*/
@java.lang.Override
public com.google.cloud.geminidataanalytics.v1beta.SchemaQueryOrBuilder getQueryOrBuilder() {
if ((kindCase_ == 1) && (queryBuilder_ != null)) {
return queryBuilder_.getMessageOrBuilder();
} else {
if (kindCase_ == 1) {
return (com.google.cloud.geminidataanalytics.v1beta.SchemaQuery) kind_;
}
return com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.getDefaultInstance();
}
}
/**
*
*
* <pre>
* A schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaQuery query = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.geminidataanalytics.v1beta.SchemaQuery,
com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.Builder,
com.google.cloud.geminidataanalytics.v1beta.SchemaQueryOrBuilder>
getQueryFieldBuilder() {
if (queryBuilder_ == null) {
if (!(kindCase_ == 1)) {
kind_ = com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.getDefaultInstance();
}
queryBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.geminidataanalytics.v1beta.SchemaQuery,
com.google.cloud.geminidataanalytics.v1beta.SchemaQuery.Builder,
com.google.cloud.geminidataanalytics.v1beta.SchemaQueryOrBuilder>(
(com.google.cloud.geminidataanalytics.v1beta.SchemaQuery) kind_,
getParentForChildren(),
isClean());
kind_ = null;
}
kindCase_ = 1;
onChanged();
return queryBuilder_;
}
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.geminidataanalytics.v1beta.SchemaResult,
com.google.cloud.geminidataanalytics.v1beta.SchemaResult.Builder,
com.google.cloud.geminidataanalytics.v1beta.SchemaResultOrBuilder>
resultBuilder_;
/**
*
*
* <pre>
* The result of a schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaResult result = 2;</code>
*
* @return Whether the result field is set.
*/
@java.lang.Override
public boolean hasResult() {
return kindCase_ == 2;
}
/**
*
*
* <pre>
* The result of a schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaResult result = 2;</code>
*
* @return The result.
*/
@java.lang.Override
public com.google.cloud.geminidataanalytics.v1beta.SchemaResult getResult() {
if (resultBuilder_ == null) {
if (kindCase_ == 2) {
return (com.google.cloud.geminidataanalytics.v1beta.SchemaResult) kind_;
}
return com.google.cloud.geminidataanalytics.v1beta.SchemaResult.getDefaultInstance();
} else {
if (kindCase_ == 2) {
return resultBuilder_.getMessage();
}
return com.google.cloud.geminidataanalytics.v1beta.SchemaResult.getDefaultInstance();
}
}
/**
*
*
* <pre>
* The result of a schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaResult result = 2;</code>
*/
public Builder setResult(com.google.cloud.geminidataanalytics.v1beta.SchemaResult value) {
if (resultBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
kind_ = value;
onChanged();
} else {
resultBuilder_.setMessage(value);
}
kindCase_ = 2;
return this;
}
/**
*
*
* <pre>
* The result of a schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaResult result = 2;</code>
*/
public Builder setResult(
com.google.cloud.geminidataanalytics.v1beta.SchemaResult.Builder builderForValue) {
if (resultBuilder_ == null) {
kind_ = builderForValue.build();
onChanged();
} else {
resultBuilder_.setMessage(builderForValue.build());
}
kindCase_ = 2;
return this;
}
/**
*
*
* <pre>
* The result of a schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaResult result = 2;</code>
*/
public Builder mergeResult(com.google.cloud.geminidataanalytics.v1beta.SchemaResult value) {
if (resultBuilder_ == null) {
if (kindCase_ == 2
&& kind_
!= com.google.cloud.geminidataanalytics.v1beta.SchemaResult.getDefaultInstance()) {
kind_ =
com.google.cloud.geminidataanalytics.v1beta.SchemaResult.newBuilder(
(com.google.cloud.geminidataanalytics.v1beta.SchemaResult) kind_)
.mergeFrom(value)
.buildPartial();
} else {
kind_ = value;
}
onChanged();
} else {
if (kindCase_ == 2) {
resultBuilder_.mergeFrom(value);
} else {
resultBuilder_.setMessage(value);
}
}
kindCase_ = 2;
return this;
}
/**
*
*
* <pre>
* The result of a schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaResult result = 2;</code>
*/
public Builder clearResult() {
if (resultBuilder_ == null) {
if (kindCase_ == 2) {
kindCase_ = 0;
kind_ = null;
onChanged();
}
} else {
if (kindCase_ == 2) {
kindCase_ = 0;
kind_ = null;
}
resultBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The result of a schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaResult result = 2;</code>
*/
public com.google.cloud.geminidataanalytics.v1beta.SchemaResult.Builder getResultBuilder() {
return getResultFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The result of a schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaResult result = 2;</code>
*/
@java.lang.Override
public com.google.cloud.geminidataanalytics.v1beta.SchemaResultOrBuilder getResultOrBuilder() {
if ((kindCase_ == 2) && (resultBuilder_ != null)) {
return resultBuilder_.getMessageOrBuilder();
} else {
if (kindCase_ == 2) {
return (com.google.cloud.geminidataanalytics.v1beta.SchemaResult) kind_;
}
return com.google.cloud.geminidataanalytics.v1beta.SchemaResult.getDefaultInstance();
}
}
/**
*
*
* <pre>
* The result of a schema resolution query.
* </pre>
*
* <code>.google.cloud.geminidataanalytics.v1beta.SchemaResult result = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.geminidataanalytics.v1beta.SchemaResult,
com.google.cloud.geminidataanalytics.v1beta.SchemaResult.Builder,
com.google.cloud.geminidataanalytics.v1beta.SchemaResultOrBuilder>
getResultFieldBuilder() {
if (resultBuilder_ == null) {
if (!(kindCase_ == 2)) {
kind_ = com.google.cloud.geminidataanalytics.v1beta.SchemaResult.getDefaultInstance();
}
resultBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.geminidataanalytics.v1beta.SchemaResult,
com.google.cloud.geminidataanalytics.v1beta.SchemaResult.Builder,
com.google.cloud.geminidataanalytics.v1beta.SchemaResultOrBuilder>(
(com.google.cloud.geminidataanalytics.v1beta.SchemaResult) kind_,
getParentForChildren(),
isClean());
kind_ = null;
}
kindCase_ = 2;
onChanged();
return resultBuilder_;
}
@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.geminidataanalytics.v1beta.SchemaMessage)
}
// @@protoc_insertion_point(class_scope:google.cloud.geminidataanalytics.v1beta.SchemaMessage)
private static final com.google.cloud.geminidataanalytics.v1beta.SchemaMessage DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.geminidataanalytics.v1beta.SchemaMessage();
}
public static com.google.cloud.geminidataanalytics.v1beta.SchemaMessage getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SchemaMessage> PARSER =
new com.google.protobuf.AbstractParser<SchemaMessage>() {
@java.lang.Override
public SchemaMessage 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<SchemaMessage> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SchemaMessage> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.geminidataanalytics.v1beta.SchemaMessage getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,589 | java-analytics-admin/proto-google-analytics-admin-v1beta/src/main/java/com/google/analytics/admin/v1beta/UpdateGoogleAdsLinkRequest.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/analytics/admin/v1beta/analytics_admin.proto
// Protobuf Java Version: 3.25.8
package com.google.analytics.admin.v1beta;
/**
*
*
* <pre>
* Request message for UpdateGoogleAdsLink RPC
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest}
*/
public final class UpdateGoogleAdsLinkRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest)
UpdateGoogleAdsLinkRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateGoogleAdsLinkRequest.newBuilder() to construct.
private UpdateGoogleAdsLinkRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateGoogleAdsLinkRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateGoogleAdsLinkRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1beta.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1beta_UpdateGoogleAdsLinkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1beta.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1beta_UpdateGoogleAdsLinkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest.class,
com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest.Builder.class);
}
private int bitField0_;
public static final int GOOGLE_ADS_LINK_FIELD_NUMBER = 1;
private com.google.analytics.admin.v1beta.GoogleAdsLink googleAdsLink_;
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 1;</code>
*
* @return Whether the googleAdsLink field is set.
*/
@java.lang.Override
public boolean hasGoogleAdsLink() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 1;</code>
*
* @return The googleAdsLink.
*/
@java.lang.Override
public com.google.analytics.admin.v1beta.GoogleAdsLink getGoogleAdsLink() {
return googleAdsLink_ == null
? com.google.analytics.admin.v1beta.GoogleAdsLink.getDefaultInstance()
: googleAdsLink_;
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 1;</code>
*/
@java.lang.Override
public com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder getGoogleAdsLinkOrBuilder() {
return googleAdsLink_ == null
? com.google.analytics.admin.v1beta.GoogleAdsLink.getDefaultInstance()
: googleAdsLink_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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, getGoogleAdsLink());
}
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, getGoogleAdsLink());
}
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.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest)) {
return super.equals(obj);
}
com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest other =
(com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest) obj;
if (hasGoogleAdsLink() != other.hasGoogleAdsLink()) return false;
if (hasGoogleAdsLink()) {
if (!getGoogleAdsLink().equals(other.getGoogleAdsLink())) 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 (hasGoogleAdsLink()) {
hash = (37 * hash) + GOOGLE_ADS_LINK_FIELD_NUMBER;
hash = (53 * hash) + getGoogleAdsLink().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.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest 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.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest 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.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest 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.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest 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.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest 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 UpdateGoogleAdsLink RPC
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest)
com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1beta.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1beta_UpdateGoogleAdsLinkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1beta.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1beta_UpdateGoogleAdsLinkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest.class,
com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest.Builder.class);
}
// Construct using com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getGoogleAdsLinkFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
googleAdsLink_ = null;
if (googleAdsLinkBuilder_ != null) {
googleAdsLinkBuilder_.dispose();
googleAdsLinkBuilder_ = 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.analytics.admin.v1beta.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1beta_UpdateGoogleAdsLinkRequest_descriptor;
}
@java.lang.Override
public com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest
getDefaultInstanceForType() {
return com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest build() {
com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest buildPartial() {
com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest result =
new com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.googleAdsLink_ =
googleAdsLinkBuilder_ == null ? googleAdsLink_ : googleAdsLinkBuilder_.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.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest) {
return mergeFrom((com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest other) {
if (other
== com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest.getDefaultInstance())
return this;
if (other.hasGoogleAdsLink()) {
mergeGoogleAdsLink(other.getGoogleAdsLink());
}
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(getGoogleAdsLinkFieldBuilder().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.analytics.admin.v1beta.GoogleAdsLink googleAdsLink_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1beta.GoogleAdsLink,
com.google.analytics.admin.v1beta.GoogleAdsLink.Builder,
com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder>
googleAdsLinkBuilder_;
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 1;</code>
*
* @return Whether the googleAdsLink field is set.
*/
public boolean hasGoogleAdsLink() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 1;</code>
*
* @return The googleAdsLink.
*/
public com.google.analytics.admin.v1beta.GoogleAdsLink getGoogleAdsLink() {
if (googleAdsLinkBuilder_ == null) {
return googleAdsLink_ == null
? com.google.analytics.admin.v1beta.GoogleAdsLink.getDefaultInstance()
: googleAdsLink_;
} else {
return googleAdsLinkBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 1;</code>
*/
public Builder setGoogleAdsLink(com.google.analytics.admin.v1beta.GoogleAdsLink value) {
if (googleAdsLinkBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
googleAdsLink_ = value;
} else {
googleAdsLinkBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 1;</code>
*/
public Builder setGoogleAdsLink(
com.google.analytics.admin.v1beta.GoogleAdsLink.Builder builderForValue) {
if (googleAdsLinkBuilder_ == null) {
googleAdsLink_ = builderForValue.build();
} else {
googleAdsLinkBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 1;</code>
*/
public Builder mergeGoogleAdsLink(com.google.analytics.admin.v1beta.GoogleAdsLink value) {
if (googleAdsLinkBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& googleAdsLink_ != null
&& googleAdsLink_
!= com.google.analytics.admin.v1beta.GoogleAdsLink.getDefaultInstance()) {
getGoogleAdsLinkBuilder().mergeFrom(value);
} else {
googleAdsLink_ = value;
}
} else {
googleAdsLinkBuilder_.mergeFrom(value);
}
if (googleAdsLink_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 1;</code>
*/
public Builder clearGoogleAdsLink() {
bitField0_ = (bitField0_ & ~0x00000001);
googleAdsLink_ = null;
if (googleAdsLinkBuilder_ != null) {
googleAdsLinkBuilder_.dispose();
googleAdsLinkBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 1;</code>
*/
public com.google.analytics.admin.v1beta.GoogleAdsLink.Builder getGoogleAdsLinkBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getGoogleAdsLinkFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 1;</code>
*/
public com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder getGoogleAdsLinkOrBuilder() {
if (googleAdsLinkBuilder_ != null) {
return googleAdsLinkBuilder_.getMessageOrBuilder();
} else {
return googleAdsLink_ == null
? com.google.analytics.admin.v1beta.GoogleAdsLink.getDefaultInstance()
: googleAdsLink_;
}
}
/**
*
*
* <pre>
* The GoogleAdsLink to update
* </pre>
*
* <code>.google.analytics.admin.v1beta.GoogleAdsLink google_ads_link = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1beta.GoogleAdsLink,
com.google.analytics.admin.v1beta.GoogleAdsLink.Builder,
com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder>
getGoogleAdsLinkFieldBuilder() {
if (googleAdsLinkBuilder_ == null) {
googleAdsLinkBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.analytics.admin.v1beta.GoogleAdsLink,
com.google.analytics.admin.v1beta.GoogleAdsLink.Builder,
com.google.analytics.admin.v1beta.GoogleAdsLinkOrBuilder>(
getGoogleAdsLink(), getParentForChildren(), isClean());
googleAdsLink_ = null;
}
return googleAdsLinkBuilder_;
}
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>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Required. The list of fields to be updated. Field names must be in snake
* case (e.g., "field_to_update"). Omitted fields will not be updated. To
* replace the entire entity, use one path with the string "*" to match all
* fields.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest)
}
// @@protoc_insertion_point(class_scope:google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest)
private static final com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest();
}
public static com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateGoogleAdsLinkRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateGoogleAdsLinkRequest>() {
@java.lang.Override
public UpdateGoogleAdsLinkRequest 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<UpdateGoogleAdsLinkRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateGoogleAdsLinkRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.analytics.admin.v1beta.UpdateGoogleAdsLinkRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/ofbiz-framework | 35,232 | applications/order/src/main/java/org/apache/ofbiz/order/order/OrderLookupServices.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.order.order;
import java.math.BigDecimal;
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 org.apache.ofbiz.base.util.Debug;
import org.apache.ofbiz.base.util.GeneralException;
import org.apache.ofbiz.base.util.ObjectType;
import org.apache.ofbiz.base.util.StringUtil;
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.base.util.collections.PagedList;
import org.apache.ofbiz.entity.Delegator;
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.EntityExpr;
import org.apache.ofbiz.entity.condition.EntityOperator;
import org.apache.ofbiz.entity.model.DynamicViewEntity;
import org.apache.ofbiz.entity.model.ModelKeyMap;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.security.Security;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ServiceUtil;
import org.apache.ofbiz.widget.renderer.Paginator;
/**
* OrderLookupServices
*/
public class OrderLookupServices {
private static final String MODULE = OrderLookupServices.class.getName();
public static Map<String, Object> findOrders(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
Security security = dctx.getSecurity();
GenericValue userLogin = (GenericValue) context.get("userLogin");
Integer viewIndex = Paginator.getViewIndex(context, "viewIndex", 1);
Integer viewSize = Paginator.getViewSize(context, "viewSize");
String showAll = (String) context.get("showAll");
String useEntryDate = (String) context.get("useEntryDate");
Locale locale = (Locale) context.get("locale");
if (showAll == null) {
showAll = "N";
}
// list of fields to select (initial list)
Set<String> fieldsToSelect = new LinkedHashSet<>();
fieldsToSelect.add("orderId");
fieldsToSelect.add("orderName");
fieldsToSelect.add("statusId");
fieldsToSelect.add("orderTypeId");
fieldsToSelect.add("orderDate");
fieldsToSelect.add("currencyUom");
fieldsToSelect.add("grandTotal");
fieldsToSelect.add("remainingSubTotal");
// sorting by order date newest first
List<String> orderBy = UtilMisc.toList("-orderDate", "-orderId");
// list to hold the parameters
List<String> paramList = new LinkedList<>();
// list of conditions
List<EntityCondition> conditions = new LinkedList<>();
// check security flag for purchase orders
boolean canViewPo = security.hasEntityPermission("ORDERMGR", "_PURCHASE_VIEW", userLogin);
if (!canViewPo) {
conditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.NOT_EQUAL, "PURCHASE_ORDER"));
}
// dynamic view entity
DynamicViewEntity dve = new DynamicViewEntity();
dve.addMemberEntity("OH", "OrderHeader");
dve.addAliasAll("OH", "", null); // no prefix
dve.addRelation("one-nofk", "", "OrderType", UtilMisc.toList(new ModelKeyMap("orderTypeId", "orderTypeId")));
dve.addRelation("one-nofk", "", "StatusItem", UtilMisc.toList(new ModelKeyMap("statusId", "statusId")));
// start the lookup
String orderId = (String) context.get("orderId");
if (UtilValidate.isNotEmpty(orderId)) {
paramList.add("orderId=" + orderId);
conditions.add(makeExpr("orderId", orderId));
}
// the base order header fields
List<String> orderTypeList = UtilGenerics.cast(context.get("orderTypeId"));
if (orderTypeList != null) {
List<EntityExpr> orExprs = new LinkedList<>();
for (String orderTypeId : orderTypeList) {
paramList.add("orderTypeId=" + orderTypeId);
if (!("PURCHASE_ORDER".equals(orderTypeId)) || (("PURCHASE_ORDER".equals(orderTypeId) && canViewPo))) {
orExprs.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, orderTypeId));
}
}
conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
}
String orderName = (String) context.get("orderName");
if (UtilValidate.isNotEmpty(orderName)) {
paramList.add("orderName=" + orderName);
conditions.add(makeExpr("orderName", orderName, true));
}
List<String> orderStatusList = UtilGenerics.cast(context.get("orderStatusId"));
if (orderStatusList != null) {
List<EntityCondition> orExprs = new LinkedList<>();
for (String orderStatusId : orderStatusList) {
paramList.add("orderStatusId=" + orderStatusId);
if ("PENDING".equals(orderStatusId)) {
List<EntityExpr> pendExprs = new LinkedList<>();
pendExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_CREATED"));
pendExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_PROCESSING"));
pendExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_APPROVED"));
orExprs.add(EntityCondition.makeCondition(pendExprs, EntityOperator.OR));
} else {
orExprs.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, orderStatusId));
}
}
conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
}
List<String> productStoreList = UtilGenerics.cast(context.get("productStoreId"));
if (productStoreList != null) {
List<EntityExpr> orExprs = new LinkedList<>();
for (String productStoreId : productStoreList) {
paramList.add("productStoreId=" + productStoreId);
orExprs.add(EntityCondition.makeCondition("productStoreId", EntityOperator.EQUALS, productStoreId));
}
conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
}
List<String> webSiteList = UtilGenerics.cast(context.get("orderWebSiteId"));
if (webSiteList != null) {
List<EntityExpr> orExprs = new LinkedList<>();
for (String webSiteId : webSiteList) {
paramList.add("webSiteId=" + webSiteId);
orExprs.add(EntityCondition.makeCondition("webSiteId", EntityOperator.EQUALS, webSiteId));
}
conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
}
List<String> saleChannelList = UtilGenerics.cast(context.get("salesChannelEnumId"));
if (saleChannelList != null) {
List<EntityExpr> orExprs = new LinkedList<>();
for (String salesChannelEnumId : saleChannelList) {
paramList.add("salesChannelEnumId=" + salesChannelEnumId);
orExprs.add(EntityCondition.makeCondition("salesChannelEnumId", EntityOperator.EQUALS, salesChannelEnumId));
}
conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
}
String createdBy = (String) context.get("createdBy");
if (UtilValidate.isNotEmpty(createdBy)) {
paramList.add("createdBy=" + createdBy);
conditions.add(makeExpr("createdBy", createdBy));
}
String terminalId = (String) context.get("terminalId");
if (UtilValidate.isNotEmpty(terminalId)) {
paramList.add("terminalId=" + terminalId);
conditions.add(makeExpr("terminalId", terminalId));
}
String transactionId = (String) context.get("transactionId");
if (UtilValidate.isNotEmpty(transactionId)) {
paramList.add("transactionId=" + transactionId);
conditions.add(makeExpr("transactionId", transactionId));
}
String externalId = (String) context.get("externalId");
if (UtilValidate.isNotEmpty(externalId)) {
paramList.add("externalId=" + externalId);
conditions.add(makeExpr("externalId", externalId));
}
String internalCode = (String) context.get("internalCode");
if (UtilValidate.isNotEmpty(internalCode)) {
paramList.add("internalCode=" + internalCode);
conditions.add(makeExpr("internalCode", internalCode));
}
String dateField = "Y".equals(useEntryDate) ? "entryDate" : "orderDate";
String minDate = (String) context.get("minDate");
if (UtilValidate.isNotEmpty(minDate) && minDate.length() > 8) {
minDate = minDate.trim();
if (minDate.length() < 14) {
minDate = minDate + " " + "00:00:00.000";
}
paramList.add("minDate=" + minDate);
try {
Object converted = ObjectType.simpleTypeOrObjectConvert(minDate, "Timestamp", null, null);
if (converted != null) {
conditions.add(EntityCondition.makeCondition(dateField, EntityOperator.GREATER_THAN_EQUAL_TO, converted));
}
} catch (GeneralException e) {
Debug.logWarning(e.getMessage(), MODULE);
}
}
String maxDate = (String) context.get("maxDate");
if (UtilValidate.isNotEmpty(maxDate) && maxDate.length() > 8) {
maxDate = maxDate.trim();
if (maxDate.length() < 14) {
maxDate = maxDate + " " + "23:59:59.999";
}
paramList.add("maxDate=" + maxDate);
try {
Object converted = ObjectType.simpleTypeOrObjectConvert(maxDate, "Timestamp", null, null);
if (converted != null) {
conditions.add(EntityCondition.makeCondition("orderDate", EntityOperator.LESS_THAN_EQUAL_TO, converted));
}
} catch (GeneralException e) {
Debug.logWarning(e.getMessage(), MODULE);
}
}
// party (role) fields
String userLoginId = (String) context.get("userLoginId");
String partyId = (String) context.get("partyId");
List<String> roleTypeList = UtilGenerics.cast(context.get("roleTypeId"));
if (UtilValidate.isNotEmpty(userLoginId) && UtilValidate.isEmpty(partyId)) {
GenericValue ul = null;
try {
ul = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).cache().queryOne();
} catch (GenericEntityException e) {
Debug.logWarning(e.getMessage(), MODULE);
}
if (ul != null) {
partyId = ul.getString("partyId");
}
}
String isViewed = (String) context.get("isViewed");
if (UtilValidate.isNotEmpty(isViewed)) {
paramList.add("isViewed=" + isViewed);
conditions.add(makeExpr("isViewed", isViewed));
}
// Shipment Method
String shipmentMethod = (String) context.get("shipmentMethod");
if (UtilValidate.isNotEmpty(shipmentMethod)) {
String carrierPartyId = shipmentMethod.substring(0, shipmentMethod.indexOf('@'));
String shippingMethodTypeId = shipmentMethod.substring(shipmentMethod.indexOf('@') + 1);
dve.addMemberEntity("OISG", "OrderItemShipGroup");
dve.addAlias("OISG", "shipmentMethodTypeId");
dve.addAlias("OISG", "carrierPartyId");
dve.addViewLink("OH", "OISG", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
if (UtilValidate.isNotEmpty(carrierPartyId)) {
paramList.add("carrierPartyId=" + carrierPartyId);
conditions.add(makeExpr("carrierPartyId", carrierPartyId));
}
if (UtilValidate.isNotEmpty(shippingMethodTypeId)) {
paramList.add("shippingMethodTypeId=" + shippingMethodTypeId);
conditions.add(makeExpr("shipmentMethodTypeId", shippingMethodTypeId));
}
}
// PaymentGatewayResponse
String gatewayAvsResult = (String) context.get("gatewayAvsResult");
String gatewayScoreResult = (String) context.get("gatewayScoreResult");
if (UtilValidate.isNotEmpty(gatewayAvsResult) || UtilValidate.isNotEmpty(gatewayScoreResult)) {
dve.addMemberEntity("OPP", "OrderPaymentPreference");
dve.addMemberEntity("PGR", "PaymentGatewayResponse");
dve.addAlias("OPP", "orderPaymentPreferenceId");
dve.addAlias("PGR", "gatewayAvsResult");
dve.addAlias("PGR", "gatewayScoreResult");
dve.addViewLink("OH", "OPP", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
dve.addViewLink("OPP", "PGR", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderPaymentPreferenceId", "orderPaymentPreferenceId")));
}
if (UtilValidate.isNotEmpty(gatewayAvsResult)) {
paramList.add("gatewayAvsResult=" + gatewayAvsResult);
conditions.add(EntityCondition.makeCondition("gatewayAvsResult", gatewayAvsResult));
}
if (UtilValidate.isNotEmpty(gatewayScoreResult)) {
paramList.add("gatewayScoreResult=" + gatewayScoreResult);
conditions.add(EntityCondition.makeCondition("gatewayScoreResult", gatewayScoreResult));
}
// add the role data to the view
if (roleTypeList != null || partyId != null) {
dve.addMemberEntity("OT", "OrderRole");
dve.addAlias("OT", "partyId");
dve.addAlias("OT", "roleTypeId");
dve.addViewLink("OH", "OT", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
}
if (UtilValidate.isNotEmpty(partyId)) {
paramList.add("partyId=" + partyId);
fieldsToSelect.add("partyId");
conditions.add(makeExpr("partyId", partyId));
}
if (roleTypeList != null) {
fieldsToSelect.add("roleTypeId");
List<EntityExpr> orExprs = new LinkedList<>();
for (String roleTypeId : roleTypeList) {
paramList.add("roleTypeId=" + roleTypeId);
orExprs.add(makeExpr("roleTypeId", roleTypeId));
}
conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
}
// order item fields
String correspondingPoId = (String) context.get("correspondingPoId");
String subscriptionId = (String) context.get("subscriptionId");
String productId = (String) context.get("productId");
String budgetId = (String) context.get("budgetId");
String quoteId = (String) context.get("quoteId");
String goodIdentificationTypeId = (String) context.get("goodIdentificationTypeId");
String goodIdentificationIdValue = (String) context.get("goodIdentificationIdValue");
boolean hasGoodIdentification = UtilValidate.isNotEmpty(goodIdentificationTypeId) && UtilValidate.isNotEmpty(goodIdentificationIdValue);
if (correspondingPoId != null || subscriptionId != null || productId != null || budgetId != null || quoteId != null
|| hasGoodIdentification) {
dve.addMemberEntity("OI", "OrderItem");
dve.addAlias("OI", "correspondingPoId");
dve.addAlias("OI", "subscriptionId");
dve.addAlias("OI", "productId");
dve.addAlias("OI", "budgetId");
dve.addAlias("OI", "quoteId");
dve.addViewLink("OH", "OI", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
if (hasGoodIdentification) {
dve.addMemberEntity("GOODID", "GoodIdentification");
dve.addAlias("GOODID", "goodIdentificationTypeId");
dve.addAlias("GOODID", "idValue");
dve.addViewLink("OI", "GOODID", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("productId", "productId")));
paramList.add("goodIdentificationTypeId=" + goodIdentificationTypeId);
conditions.add(makeExpr("goodIdentificationTypeId", goodIdentificationTypeId));
paramList.add("goodIdentificationIdValue=" + goodIdentificationIdValue);
conditions.add(makeExpr("idValue", goodIdentificationIdValue));
}
}
if (UtilValidate.isNotEmpty(correspondingPoId)) {
paramList.add("correspondingPoId=" + correspondingPoId);
conditions.add(makeExpr("correspondingPoId", correspondingPoId));
}
if (UtilValidate.isNotEmpty(subscriptionId)) {
paramList.add("subscriptionId=" + subscriptionId);
conditions.add(makeExpr("subscriptionId", subscriptionId));
}
if (UtilValidate.isNotEmpty(productId)) {
paramList.add("productId=" + productId);
if (productId.startsWith("%") || productId.startsWith("*") || productId.endsWith("%") || productId.endsWith("*")) {
conditions.add(makeExpr("productId", productId));
} else {
GenericValue product = null;
try {
product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
} catch (GenericEntityException e) {
Debug.logWarning(e.getMessage(), MODULE);
}
if (product != null) {
String isVirtual = product.getString("isVirtual");
if (isVirtual != null && "Y".equals(isVirtual)) {
List<EntityExpr> orExprs = new LinkedList<>();
orExprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId));
Map<String, Object> varLookup = null;
List<GenericValue> variants = null;
try {
varLookup = dispatcher.runSync("getAllProductVariants", UtilMisc.toMap("productId", productId));
if (ServiceUtil.isError(varLookup)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(varLookup));
}
variants = UtilGenerics.cast(varLookup.get("assocProducts"));
} catch (GenericServiceException e) {
Debug.logWarning(e.getMessage(), MODULE);
}
if (variants != null) {
for (GenericValue v : variants) {
orExprs.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, v.getString("productIdTo")));
}
}
conditions.add(EntityCondition.makeCondition(orExprs, EntityOperator.OR));
} else {
conditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId));
}
} else {
String failMsg = UtilProperties.getMessage("OrderErrorUiLabels", "OrderFindOrderProductInvalid",
UtilMisc.toMap("productId", productId), locale);
return ServiceUtil.returnFailure(failMsg);
}
}
}
if (UtilValidate.isNotEmpty(budgetId)) {
paramList.add("budgetId=" + budgetId);
conditions.add(makeExpr("budgetId", budgetId));
}
if (UtilValidate.isNotEmpty(quoteId)) {
paramList.add("quoteId=" + quoteId);
conditions.add(makeExpr("quoteId", quoteId));
}
// payment preference fields
String billingAccountId = (String) context.get("billingAccountId");
String finAccountId = (String) context.get("finAccountId");
String cardNumber = (String) context.get("cardNumber");
String accountNumber = (String) context.get("accountNumber");
String paymentStatusId = (String) context.get("paymentStatusId");
if (UtilValidate.isNotEmpty(paymentStatusId)) {
paramList.add("paymentStatusId=" + paymentStatusId);
conditions.add(makeExpr("paymentStatusId", paymentStatusId));
}
if (finAccountId != null || cardNumber != null || accountNumber != null || paymentStatusId != null) {
dve.addMemberEntity("OP", "OrderPaymentPreference");
dve.addAlias("OP", "finAccountId");
dve.addAlias("OP", "paymentMethodId");
dve.addAlias("OP", "paymentStatusId", "statusId", null, false, false, null);
dve.addViewLink("OH", "OP", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
}
// search by billing account ID
if (UtilValidate.isNotEmpty(billingAccountId)) {
paramList.add("billingAccountId=" + billingAccountId);
conditions.add(makeExpr("billingAccountId", billingAccountId));
}
// search by fin account ID
if (UtilValidate.isNotEmpty(finAccountId)) {
paramList.add("finAccountId=" + finAccountId);
conditions.add(makeExpr("finAccountId", finAccountId));
}
// search by card number
if (UtilValidate.isNotEmpty(cardNumber)) {
dve.addMemberEntity("CC", "CreditCard");
dve.addAlias("CC", "cardNumber");
dve.addViewLink("OP", "CC", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("paymentMethodId", "paymentMethodId")));
paramList.add("cardNumber=" + cardNumber);
conditions.add(makeExpr("cardNumber", cardNumber));
}
// search by eft account number
if (UtilValidate.isNotEmpty(accountNumber)) {
dve.addMemberEntity("EF", "EftAccount");
dve.addAlias("EF", "accountNumber");
dve.addViewLink("OP", "EF", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("paymentMethodId", "paymentMethodId")));
paramList.add("accountNumber=" + accountNumber);
conditions.add(makeExpr("accountNumber", accountNumber));
}
// shipment/inventory item
String inventoryItemId = (String) context.get("inventoryItemId");
String softIdentifier = (String) context.get("softIdentifier");
String serialNumber = (String) context.get("serialNumber");
String shipmentId = (String) context.get("shipmentId");
if (shipmentId != null || inventoryItemId != null || softIdentifier != null || serialNumber != null) {
dve.addMemberEntity("II", "ItemIssuance");
dve.addAlias("II", "shipmentId");
dve.addAlias("II", "inventoryItemId");
dve.addViewLink("OH", "II", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
if (softIdentifier != null || serialNumber != null) {
dve.addMemberEntity("IV", "InventoryItem");
dve.addAlias("IV", "softIdentifier");
dve.addAlias("IV", "serialNumber");
dve.addViewLink("II", "IV", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("inventoryItemId", "inventoryItemId")));
}
}
if (UtilValidate.isNotEmpty(inventoryItemId)) {
paramList.add("inventoryItemId=" + inventoryItemId);
conditions.add(makeExpr("inventoryItemId", inventoryItemId));
}
if (UtilValidate.isNotEmpty(softIdentifier)) {
paramList.add("softIdentifier=" + softIdentifier);
conditions.add(makeExpr("softIdentifier", softIdentifier, true));
}
if (UtilValidate.isNotEmpty(serialNumber)) {
paramList.add("serialNumber=" + serialNumber);
conditions.add(makeExpr("serialNumber", serialNumber, true));
}
if (UtilValidate.isNotEmpty(shipmentId)) {
paramList.add("shipmentId=" + shipmentId);
conditions.add(makeExpr("shipmentId", shipmentId));
}
// back order checking
String hasBackOrders = (String) context.get("hasBackOrders");
if (UtilValidate.isNotEmpty(hasBackOrders)) {
dve.addMemberEntity("IR", "OrderItemShipGrpInvRes");
dve.addAlias("IR", "quantityNotAvailable");
dve.addViewLink("OH", "IR", Boolean.FALSE, UtilMisc.toList(new ModelKeyMap("orderId", "orderId")));
paramList.add("hasBackOrders=" + hasBackOrders);
if ("Y".equals(hasBackOrders)) {
conditions.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.NOT_EQUAL, null));
conditions.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.GREATER_THAN, BigDecimal.ZERO));
} else if ("N".equals(hasBackOrders)) {
List<EntityExpr> orExpr = new LinkedList<>();
orExpr.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.EQUALS, null));
orExpr.add(EntityCondition.makeCondition("quantityNotAvailable", EntityOperator.EQUALS, BigDecimal.ZERO));
conditions.add(EntityCondition.makeCondition(orExpr, EntityOperator.OR));
}
}
// Get all orders according to specific ship to country with "Only Include" or "Do not Include".
String countryGeoId = (String) context.get("countryGeoId");
String includeCountry = (String) context.get("includeCountry");
if (UtilValidate.isNotEmpty(countryGeoId) && UtilValidate.isNotEmpty(includeCountry)) {
paramList.add("countryGeoId=" + countryGeoId);
paramList.add("includeCountry=" + includeCountry);
// add condition to dynamic view
dve.addMemberEntity("OCM", "OrderContactMech");
dve.addMemberEntity("PA", "PostalAddress");
dve.addAlias("OCM", "contactMechId");
dve.addAlias("OCM", "contactMechPurposeTypeId");
dve.addAlias("PA", "countryGeoId");
dve.addViewLink("OH", "OCM", Boolean.FALSE, ModelKeyMap.makeKeyMapList("orderId"));
dve.addViewLink("OCM", "PA", Boolean.FALSE, ModelKeyMap.makeKeyMapList("contactMechId"));
EntityConditionList<EntityExpr> exprs = null;
if ("Y".equals(includeCountry)) {
exprs = EntityCondition.makeCondition(UtilMisc.toList(
EntityCondition.makeCondition("contactMechPurposeTypeId", "SHIPPING_LOCATION"),
EntityCondition.makeCondition("countryGeoId", countryGeoId)), EntityOperator.AND);
} else {
exprs = EntityCondition.makeCondition(UtilMisc.toList(
EntityCondition.makeCondition("contactMechPurposeTypeId", "SHIPPING_LOCATION"),
EntityCondition.makeCondition("countryGeoId", EntityOperator.NOT_EQUAL, countryGeoId)), EntityOperator.AND);
}
conditions.add(exprs);
}
// create the main condition
EntityCondition cond = null;
if (!conditions.isEmpty() || "Y".equalsIgnoreCase(showAll)) {
cond = EntityCondition.makeCondition(conditions, EntityOperator.AND);
}
if (Debug.verboseOn()) {
Debug.logInfo("Find order query: " + cond.toString(), MODULE);
}
List<GenericValue> orderList = new LinkedList<>();
int orderCount = 0;
// get the index for the partial list
int lowIndex = 0;
int highIndex = 0;
if (cond != null) {
PagedList<GenericValue> pagedOrderList = null;
try {
// do the lookup
pagedOrderList = EntityQuery.use(delegator)
.select(fieldsToSelect)
.from(dve)
.where(cond)
.orderBy(orderBy)
.distinct() // set distinct on so we only get one row per order
.cursorScrollInsensitive()
.queryPagedList(viewIndex - 1, viewSize);
orderCount = pagedOrderList.getSize();
lowIndex = pagedOrderList.getStartIndex();
highIndex = pagedOrderList.getEndIndex();
orderList = pagedOrderList.getData();
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), MODULE);
return ServiceUtil.returnError(e.getMessage());
}
}
// create the result map
Map<String, Object> result = ServiceUtil.returnSuccess();
// filter out requested inventory problems
filterInventoryProblems(context, result, orderList, paramList);
// format the param list
String paramString = StringUtil.join(paramList, "&");
result.put("highIndex", highIndex);
result.put("lowIndex", lowIndex);
result.put("viewIndex", viewIndex);
result.put("viewSize", viewSize);
result.put("showAll", showAll);
result.put("paramList", (paramString != null ? paramString : ""));
result.put("orderList", orderList);
result.put("orderListSize", orderCount);
return result;
}
public static void filterInventoryProblems(Map<String, ? extends Object> context, Map<String, Object> result, List<GenericValue>
orderList, List<String> paramList) {
List<String> filterInventoryProblems = new LinkedList<>();
String doFilter = (String) context.get("filterInventoryProblems");
if (doFilter == null) {
doFilter = "N";
}
if ("Y".equals(doFilter) && !orderList.isEmpty()) {
paramList.add("filterInventoryProblems=Y");
for (GenericValue orderHeader : orderList) {
OrderReadHelper orh = new OrderReadHelper(orderHeader);
BigDecimal backorderQty = orh.getOrderBackorderQuantity();
if (backorderQty.compareTo(BigDecimal.ZERO) == 1) {
filterInventoryProblems.add(orh.getOrderId());
}
}
}
List<String> filterPOsOpenPastTheirETA = new LinkedList<>();
List<String> filterPOsWithRejectedItems = new LinkedList<>();
List<String> filterPartiallyReceivedPOs = new LinkedList<>();
String filterPOReject = (String) context.get("filterPOsWithRejectedItems");
String filterPOPast = (String) context.get("filterPOsOpenPastTheirETA");
String filterPartRec = (String) context.get("filterPartiallyReceivedPOs");
if (filterPOReject == null) {
filterPOReject = "N";
}
if (filterPOPast == null) {
filterPOPast = "N";
}
if (filterPartRec == null) {
filterPartRec = "N";
}
boolean doPoFilter = false;
if ("Y".equals(filterPOReject)) {
paramList.add("filterPOsWithRejectedItems=Y");
doPoFilter = true;
}
if ("Y".equals(filterPOPast)) {
paramList.add("filterPOsOpenPastTheirETA=Y");
doPoFilter = true;
}
if ("Y".equals(filterPartRec)) {
paramList.add("filterPartiallyReceivedPOs=Y");
doPoFilter = true;
}
if (doPoFilter && !orderList.isEmpty()) {
for (GenericValue orderHeader : orderList) {
OrderReadHelper orh = new OrderReadHelper(orderHeader);
String orderType = orh.getOrderTypeId();
String orderId = orh.getOrderId();
if ("PURCHASE_ORDER".equals(orderType)) {
if ("Y".equals(filterPOReject) && orh.getRejectedOrderItems()) {
filterPOsWithRejectedItems.add(orderId);
} else if ("Y".equals(filterPOPast) && orh.getPastEtaOrderItems(orderId)) {
filterPOsOpenPastTheirETA.add(orderId);
} else if ("Y".equals(filterPartRec) && orh.getPartiallyReceivedItems()) {
filterPartiallyReceivedPOs.add(orderId);
}
}
}
}
result.put("filterInventoryProblemsList", filterInventoryProblems);
result.put("filterPOsWithRejectedItemsList", filterPOsWithRejectedItems);
result.put("filterPOsOpenPastTheirETAList", filterPOsOpenPastTheirETA);
result.put("filterPartiallyReceivedPOsList", filterPartiallyReceivedPOs);
}
protected static EntityExpr makeExpr(String fieldName, String value) {
return makeExpr(fieldName, value, false);
}
protected static EntityExpr makeExpr(String fieldName, String value, boolean forceLike) {
EntityComparisonOperator<?, ?> op = forceLike ? EntityOperator.LIKE : EntityOperator.EQUALS;
if (value.startsWith("*")) {
op = EntityOperator.LIKE;
value = "%" + value.substring(1);
} else if (value.startsWith("%")) {
op = EntityOperator.LIKE;
}
if (value.endsWith("*")) {
op = EntityOperator.LIKE;
value = value.substring(0, value.length() - 1) + "%";
} else if (value.endsWith("%")) {
op = EntityOperator.LIKE;
}
if (forceLike) {
if (!value.startsWith("%")) {
value = "%" + value;
}
if (!value.endsWith("%")) {
value = value + "%";
}
}
return EntityCondition.makeCondition(fieldName, op, value);
}
}
|
googleapis/google-cloud-java | 35,539 | java-datacatalog/proto-google-cloud-datacatalog-v1beta1/src/main/java/com/google/cloud/datacatalog/v1beta1/ListEntriesResponse.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/datacatalog/v1beta1/datacatalog.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.datacatalog.v1beta1;
/**
*
*
* <pre>
* Response message for
* [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries].
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.v1beta1.ListEntriesResponse}
*/
public final class ListEntriesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.datacatalog.v1beta1.ListEntriesResponse)
ListEntriesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListEntriesResponse.newBuilder() to construct.
private ListEntriesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListEntriesResponse() {
entries_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListEntriesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.v1beta1.Datacatalog
.internal_static_google_cloud_datacatalog_v1beta1_ListEntriesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.v1beta1.Datacatalog
.internal_static_google_cloud_datacatalog_v1beta1_ListEntriesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.v1beta1.ListEntriesResponse.class,
com.google.cloud.datacatalog.v1beta1.ListEntriesResponse.Builder.class);
}
public static final int ENTRIES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.datacatalog.v1beta1.Entry> entries_;
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.datacatalog.v1beta1.Entry> getEntriesList() {
return entries_;
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.datacatalog.v1beta1.EntryOrBuilder>
getEntriesOrBuilderList() {
return entries_;
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
@java.lang.Override
public int getEntriesCount() {
return entries_.size();
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
@java.lang.Override
public com.google.cloud.datacatalog.v1beta1.Entry getEntries(int index) {
return entries_.get(index);
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
@java.lang.Override
public com.google.cloud.datacatalog.v1beta1.EntryOrBuilder getEntriesOrBuilder(int index) {
return entries_.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. It is set to empty if no items
* remain in results.
* </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. It is set to empty if no items
* remain in results.
* </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 < entries_.size(); i++) {
output.writeMessage(1, entries_.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 < entries_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, entries_.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.datacatalog.v1beta1.ListEntriesResponse)) {
return super.equals(obj);
}
com.google.cloud.datacatalog.v1beta1.ListEntriesResponse other =
(com.google.cloud.datacatalog.v1beta1.ListEntriesResponse) obj;
if (!getEntriesList().equals(other.getEntriesList())) 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 (getEntriesCount() > 0) {
hash = (37 * hash) + ENTRIES_FIELD_NUMBER;
hash = (53 * hash) + getEntriesList().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.datacatalog.v1beta1.ListEntriesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1beta1.ListEntriesResponse 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.datacatalog.v1beta1.ListEntriesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1beta1.ListEntriesResponse 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.datacatalog.v1beta1.ListEntriesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.datacatalog.v1beta1.ListEntriesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.datacatalog.v1beta1.ListEntriesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1beta1.ListEntriesResponse 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.datacatalog.v1beta1.ListEntriesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1beta1.ListEntriesResponse 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.datacatalog.v1beta1.ListEntriesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.datacatalog.v1beta1.ListEntriesResponse 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.datacatalog.v1beta1.ListEntriesResponse 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
* [ListEntries][google.cloud.datacatalog.v1beta1.DataCatalog.ListEntries].
* </pre>
*
* Protobuf type {@code google.cloud.datacatalog.v1beta1.ListEntriesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.datacatalog.v1beta1.ListEntriesResponse)
com.google.cloud.datacatalog.v1beta1.ListEntriesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.datacatalog.v1beta1.Datacatalog
.internal_static_google_cloud_datacatalog_v1beta1_ListEntriesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.datacatalog.v1beta1.Datacatalog
.internal_static_google_cloud_datacatalog_v1beta1_ListEntriesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.datacatalog.v1beta1.ListEntriesResponse.class,
com.google.cloud.datacatalog.v1beta1.ListEntriesResponse.Builder.class);
}
// Construct using com.google.cloud.datacatalog.v1beta1.ListEntriesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (entriesBuilder_ == null) {
entries_ = java.util.Collections.emptyList();
} else {
entries_ = null;
entriesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.datacatalog.v1beta1.Datacatalog
.internal_static_google_cloud_datacatalog_v1beta1_ListEntriesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1beta1.ListEntriesResponse getDefaultInstanceForType() {
return com.google.cloud.datacatalog.v1beta1.ListEntriesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.datacatalog.v1beta1.ListEntriesResponse build() {
com.google.cloud.datacatalog.v1beta1.ListEntriesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1beta1.ListEntriesResponse buildPartial() {
com.google.cloud.datacatalog.v1beta1.ListEntriesResponse result =
new com.google.cloud.datacatalog.v1beta1.ListEntriesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.datacatalog.v1beta1.ListEntriesResponse result) {
if (entriesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
entries_ = java.util.Collections.unmodifiableList(entries_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.entries_ = entries_;
} else {
result.entries_ = entriesBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.datacatalog.v1beta1.ListEntriesResponse 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.datacatalog.v1beta1.ListEntriesResponse) {
return mergeFrom((com.google.cloud.datacatalog.v1beta1.ListEntriesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.datacatalog.v1beta1.ListEntriesResponse other) {
if (other == com.google.cloud.datacatalog.v1beta1.ListEntriesResponse.getDefaultInstance())
return this;
if (entriesBuilder_ == null) {
if (!other.entries_.isEmpty()) {
if (entries_.isEmpty()) {
entries_ = other.entries_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureEntriesIsMutable();
entries_.addAll(other.entries_);
}
onChanged();
}
} else {
if (!other.entries_.isEmpty()) {
if (entriesBuilder_.isEmpty()) {
entriesBuilder_.dispose();
entriesBuilder_ = null;
entries_ = other.entries_;
bitField0_ = (bitField0_ & ~0x00000001);
entriesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getEntriesFieldBuilder()
: null;
} else {
entriesBuilder_.addAllMessages(other.entries_);
}
}
}
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.datacatalog.v1beta1.Entry m =
input.readMessage(
com.google.cloud.datacatalog.v1beta1.Entry.parser(), extensionRegistry);
if (entriesBuilder_ == null) {
ensureEntriesIsMutable();
entries_.add(m);
} else {
entriesBuilder_.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.datacatalog.v1beta1.Entry> entries_ =
java.util.Collections.emptyList();
private void ensureEntriesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
entries_ = new java.util.ArrayList<com.google.cloud.datacatalog.v1beta1.Entry>(entries_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1beta1.Entry,
com.google.cloud.datacatalog.v1beta1.Entry.Builder,
com.google.cloud.datacatalog.v1beta1.EntryOrBuilder>
entriesBuilder_;
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public java.util.List<com.google.cloud.datacatalog.v1beta1.Entry> getEntriesList() {
if (entriesBuilder_ == null) {
return java.util.Collections.unmodifiableList(entries_);
} else {
return entriesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public int getEntriesCount() {
if (entriesBuilder_ == null) {
return entries_.size();
} else {
return entriesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public com.google.cloud.datacatalog.v1beta1.Entry getEntries(int index) {
if (entriesBuilder_ == null) {
return entries_.get(index);
} else {
return entriesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public Builder setEntries(int index, com.google.cloud.datacatalog.v1beta1.Entry value) {
if (entriesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEntriesIsMutable();
entries_.set(index, value);
onChanged();
} else {
entriesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public Builder setEntries(
int index, com.google.cloud.datacatalog.v1beta1.Entry.Builder builderForValue) {
if (entriesBuilder_ == null) {
ensureEntriesIsMutable();
entries_.set(index, builderForValue.build());
onChanged();
} else {
entriesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public Builder addEntries(com.google.cloud.datacatalog.v1beta1.Entry value) {
if (entriesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEntriesIsMutable();
entries_.add(value);
onChanged();
} else {
entriesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public Builder addEntries(int index, com.google.cloud.datacatalog.v1beta1.Entry value) {
if (entriesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureEntriesIsMutable();
entries_.add(index, value);
onChanged();
} else {
entriesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public Builder addEntries(com.google.cloud.datacatalog.v1beta1.Entry.Builder builderForValue) {
if (entriesBuilder_ == null) {
ensureEntriesIsMutable();
entries_.add(builderForValue.build());
onChanged();
} else {
entriesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public Builder addEntries(
int index, com.google.cloud.datacatalog.v1beta1.Entry.Builder builderForValue) {
if (entriesBuilder_ == null) {
ensureEntriesIsMutable();
entries_.add(index, builderForValue.build());
onChanged();
} else {
entriesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public Builder addAllEntries(
java.lang.Iterable<? extends com.google.cloud.datacatalog.v1beta1.Entry> values) {
if (entriesBuilder_ == null) {
ensureEntriesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, entries_);
onChanged();
} else {
entriesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public Builder clearEntries() {
if (entriesBuilder_ == null) {
entries_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
entriesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public Builder removeEntries(int index) {
if (entriesBuilder_ == null) {
ensureEntriesIsMutable();
entries_.remove(index);
onChanged();
} else {
entriesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public com.google.cloud.datacatalog.v1beta1.Entry.Builder getEntriesBuilder(int index) {
return getEntriesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public com.google.cloud.datacatalog.v1beta1.EntryOrBuilder getEntriesOrBuilder(int index) {
if (entriesBuilder_ == null) {
return entries_.get(index);
} else {
return entriesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public java.util.List<? extends com.google.cloud.datacatalog.v1beta1.EntryOrBuilder>
getEntriesOrBuilderList() {
if (entriesBuilder_ != null) {
return entriesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(entries_);
}
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public com.google.cloud.datacatalog.v1beta1.Entry.Builder addEntriesBuilder() {
return getEntriesFieldBuilder()
.addBuilder(com.google.cloud.datacatalog.v1beta1.Entry.getDefaultInstance());
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public com.google.cloud.datacatalog.v1beta1.Entry.Builder addEntriesBuilder(int index) {
return getEntriesFieldBuilder()
.addBuilder(index, com.google.cloud.datacatalog.v1beta1.Entry.getDefaultInstance());
}
/**
*
*
* <pre>
* Entry details.
* </pre>
*
* <code>repeated .google.cloud.datacatalog.v1beta1.Entry entries = 1;</code>
*/
public java.util.List<com.google.cloud.datacatalog.v1beta1.Entry.Builder>
getEntriesBuilderList() {
return getEntriesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1beta1.Entry,
com.google.cloud.datacatalog.v1beta1.Entry.Builder,
com.google.cloud.datacatalog.v1beta1.EntryOrBuilder>
getEntriesFieldBuilder() {
if (entriesBuilder_ == null) {
entriesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.datacatalog.v1beta1.Entry,
com.google.cloud.datacatalog.v1beta1.Entry.Builder,
com.google.cloud.datacatalog.v1beta1.EntryOrBuilder>(
entries_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
entries_ = null;
}
return entriesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Token to retrieve the next page of results. It is set to empty if no items
* remain in results.
* </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. It is set to empty if no items
* remain in results.
* </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. It is set to empty if no items
* remain in results.
* </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. It is set to empty if no items
* remain in results.
* </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. It is set to empty if no items
* remain in results.
* </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.datacatalog.v1beta1.ListEntriesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.datacatalog.v1beta1.ListEntriesResponse)
private static final com.google.cloud.datacatalog.v1beta1.ListEntriesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.datacatalog.v1beta1.ListEntriesResponse();
}
public static com.google.cloud.datacatalog.v1beta1.ListEntriesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListEntriesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListEntriesResponse>() {
@java.lang.Override
public ListEntriesResponse 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<ListEntriesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListEntriesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.datacatalog.v1beta1.ListEntriesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/hadoop | 35,626 | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/metrics2/sink/RollingFileSystemSink.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.metrics2.sink;
import org.apache.hadoop.classification.VisibleForTesting;
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.configuration2.SubsetConfiguration;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.metrics2.AbstractMetric;
import org.apache.hadoop.metrics2.MetricsException;
import org.apache.hadoop.metrics2.MetricsRecord;
import org.apache.hadoop.metrics2.MetricsSink;
import org.apache.hadoop.metrics2.MetricsTag;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
/**
* <p>This class is a metrics sink that uses
* {@link org.apache.hadoop.fs.FileSystem} to write the metrics logs. Every
* roll interval a new directory will be created under the path specified by the
* <code>basepath</code> property. All metrics will be logged to a file in the
* current interval's directory in a file named <hostname>.log, where
* <hostname> is the name of the host on which the metrics logging
* process is running. The base path is set by the
* <code><prefix>.sink.<instance>.basepath</code> property. The
* time zone used to create the current interval's directory name is GMT. If
* the <code>basepath</code> property isn't specified, it will default to
* "/tmp", which is the temp directory on whatever default file
* system is configured for the cluster.</p>
*
* <p>The <code><prefix>.sink.<instance>.ignore-error</code>
* property controls whether an exception is thrown when an error is encountered
* writing a log file. The default value is <code>true</code>. When set to
* <code>false</code>, file errors are quietly swallowed.</p>
*
* <p>The <code>roll-interval</code> property sets the amount of time before
* rolling the directory. The default value is 1 hour. The roll interval may
* not be less than 1 minute. The property's value should be given as
* <i>number unit</i>, where <i>number</i> is an integer value, and
* <i>unit</i> is a valid unit. Valid units are <i>minute</i>, <i>hour</i>,
* and <i>day</i>. The units are case insensitive and may be abbreviated or
* plural. If no units are specified, hours are assumed. For example,
* "2", "2h", "2 hour", and
* "2 hours" are all valid ways to specify two hours.</p>
*
* <p>The <code>roll-offset-interval-millis</code> property sets the upper
* bound on a random time interval (in milliseconds) that is used to delay
* before the initial roll. All subsequent rolls will happen an integer
* number of roll intervals after the initial roll, hence retaining the original
* offset. The purpose of this property is to insert some variance in the roll
* times so that large clusters using this sink on every node don't cause a
* performance impact on HDFS by rolling simultaneously. The default value is
* 30000 (30s). When writing to HDFS, as a rule of thumb, the roll offset in
* millis should be no less than the number of sink instances times 5.
*
* <p>The primary use of this class is for logging to HDFS. As it uses
* {@link org.apache.hadoop.fs.FileSystem} to access the target file system,
* however, it can be used to write to the local file system, Amazon S3, or any
* other supported file system. The base path for the sink will determine the
* file system used. An unqualified path will write to the default file system
* set by the configuration.</p>
*
* <p>Not all file systems support the ability to append to files. In file
* systems without the ability to append to files, only one writer can write to
* a file at a time. To allow for concurrent writes from multiple daemons on a
* single host, the <code>source</code> property is used to set unique headers
* for the log files. The property should be set to the name of
* the source daemon, e.g. <i>namenode</i>. The value of the
* <code>source</code> property should typically be the same as the property's
* prefix. If this property is not set, the source is taken to be
* <i>unknown</i>.</p>
*
* <p>Instead of appending to an existing file, by default the sink
* will create a new file with a suffix of ".<n>", where
* <i>n</i> is the next lowest integer that isn't already used in a file name,
* similar to the Hadoop daemon logs. NOTE: the file with the <b>highest</b>
* sequence number is the <b>newest</b> file, unlike the Hadoop daemon logs.</p>
*
* <p>For file systems that allow append, the sink supports appending to the
* existing file instead. If the <code>allow-append</code> property is set to
* true, the sink will instead append to the existing file on file systems that
* support appends. By default, the <code>allow-append</code> property is
* false.</p>
*
* <p>Note that when writing to HDFS with <code>allow-append</code> set to true,
* there is a minimum acceptable number of data nodes. If the number of data
* nodes drops below that minimum, the append will succeed, but reading the
* data will fail with an IOException in the DataStreamer class. The minimum
* number of data nodes required for a successful append is generally 2 or
* 3.</p>
*
* <p>Note also that when writing to HDFS, the file size information is not
* updated until the file is closed (at the end of the interval) even though
* the data is being written successfully. This is a known HDFS limitation that
* exists because of the performance cost of updating the metadata. See
* <a href="https://issues.apache.org/jira/browse/HDFS-5478">HDFS-5478</a>.</p>
*
* <p>When using this sink in a secure (Kerberos) environment, two additional
* properties must be set: <code>keytab-key</code> and
* <code>principal-key</code>. <code>keytab-key</code> should contain the key by
* which the keytab file can be found in the configuration, for example,
* <code>yarn.nodemanager.keytab</code>. <code>principal-key</code> should
* contain the key by which the principal can be found in the configuration,
* for example, <code>yarn.nodemanager.principal</code>.
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
public class RollingFileSystemSink implements MetricsSink, Closeable {
private static final String BASEPATH_KEY = "basepath";
private static final String SOURCE_KEY = "source";
private static final String IGNORE_ERROR_KEY = "ignore-error";
private static final boolean DEFAULT_IGNORE_ERROR = false;
private static final String ALLOW_APPEND_KEY = "allow-append";
private static final boolean DEFAULT_ALLOW_APPEND = false;
private static final String KEYTAB_PROPERTY_KEY = "keytab-key";
private static final String USERNAME_PROPERTY_KEY = "principal-key";
private static final String ROLL_INTERVAL_KEY = "roll-interval";
private static final String DEFAULT_ROLL_INTERVAL = "1h";
private static final String ROLL_OFFSET_INTERVAL_MILLIS_KEY =
"roll-offset-interval-millis";
private static final int DEFAULT_ROLL_OFFSET_INTERVAL_MILLIS = 30000;
private static final String SOURCE_DEFAULT = "unknown";
private static final String BASEPATH_DEFAULT = "/tmp";
private static final FastDateFormat DATE_FORMAT =
FastDateFormat.getInstance("yyyyMMddHHmm", TimeZone.getTimeZone("GMT"));
private final Object lock = new Object();
private boolean initialized = false;
private SubsetConfiguration properties;
private Configuration conf;
@VisibleForTesting
protected String source;
@VisibleForTesting
protected boolean ignoreError;
@VisibleForTesting
protected boolean allowAppend;
@VisibleForTesting
protected Path basePath;
private FileSystem fileSystem;
// The current directory path into which we're writing files
private Path currentDirPath;
// The path to the current file into which we're writing data
private Path currentFilePath;
// The stream to which we're currently writing.
private PrintStream currentOutStream;
// We keep this only to be able to call hsynch() on it.
private FSDataOutputStream currentFSOutStream;
private Timer flushTimer;
// The amount of time between rolls
@VisibleForTesting
protected long rollIntervalMillis;
// The maximum amount of random time to add to the initial roll
@VisibleForTesting
protected long rollOffsetIntervalMillis;
// The time for the nextFlush
@VisibleForTesting
protected Calendar nextFlush = null;
// This flag when true causes a metrics write to schedule a flush thread to
// run immediately, but only if a flush thread is already scheduled. (It's a
// timing thing. If the first write forces the flush, it will strand the
// second write.)
@VisibleForTesting
protected static boolean forceFlush = false;
// This flag is used by the flusher thread to indicate that it has run. Used
// only for testing purposes.
@VisibleForTesting
protected static volatile boolean hasFlushed = false;
// Use this configuration instead of loading a new one.
@VisibleForTesting
protected static Configuration suppliedConf = null;
// Use this file system instead of getting a new one.
@VisibleForTesting
protected static FileSystem suppliedFilesystem = null;
/**
* Create an empty instance. Required for reflection.
*/
public RollingFileSystemSink() {
}
/**
* Create an instance for testing.
*
* @param flushIntervalMillis the roll interval in millis
* @param flushOffsetIntervalMillis the roll offset interval in millis
*/
@VisibleForTesting
protected RollingFileSystemSink(long flushIntervalMillis,
long flushOffsetIntervalMillis) {
this.rollIntervalMillis = flushIntervalMillis;
this.rollOffsetIntervalMillis = flushOffsetIntervalMillis;
}
@Override
public void init(SubsetConfiguration metrics2Properties) {
properties = metrics2Properties;
basePath = new Path(properties.getString(BASEPATH_KEY, BASEPATH_DEFAULT));
source = properties.getString(SOURCE_KEY, SOURCE_DEFAULT);
ignoreError = properties.getBoolean(IGNORE_ERROR_KEY, DEFAULT_IGNORE_ERROR);
allowAppend = properties.getBoolean(ALLOW_APPEND_KEY, DEFAULT_ALLOW_APPEND);
rollOffsetIntervalMillis =
getNonNegative(ROLL_OFFSET_INTERVAL_MILLIS_KEY,
DEFAULT_ROLL_OFFSET_INTERVAL_MILLIS);
rollIntervalMillis = getRollInterval();
conf = loadConf();
UserGroupInformation.setConfiguration(conf);
// Don't do secure setup if it's not needed.
if (UserGroupInformation.isSecurityEnabled()) {
// Validate config so that we don't get an NPE
checkIfPropertyExists(KEYTAB_PROPERTY_KEY);
checkIfPropertyExists(USERNAME_PROPERTY_KEY);
try {
// Login as whoever we're supposed to be and let the hostname be pulled
// from localhost. If security isn't enabled, this does nothing.
SecurityUtil.login(conf, properties.getString(KEYTAB_PROPERTY_KEY),
properties.getString(USERNAME_PROPERTY_KEY));
} catch (IOException ex) {
throw new MetricsException("Error logging in securely: ["
+ ex.toString() + "]", ex);
}
}
}
/**
* Initialize the connection to HDFS and create the base directory. Also
* launch the flush thread.
*/
private boolean initFs() {
boolean success = false;
fileSystem = getFileSystem();
// This step isn't strictly necessary, but it makes debugging issues much
// easier. We try to create the base directory eagerly and fail with
// copious debug info if it fails.
try {
fileSystem.mkdirs(basePath);
success = true;
} catch (Exception ex) {
if (!ignoreError) {
throw new MetricsException("Failed to create " + basePath + "["
+ SOURCE_KEY + "=" + source + ", "
+ ALLOW_APPEND_KEY + "=" + allowAppend + ", "
+ stringifySecurityProperty(KEYTAB_PROPERTY_KEY) + ", "
+ stringifySecurityProperty(USERNAME_PROPERTY_KEY)
+ "] -- " + ex.toString(), ex);
}
}
if (success) {
// If we're permitted to append, check if we actually can
if (allowAppend) {
allowAppend = checkAppend(fileSystem);
}
flushTimer = new Timer("RollingFileSystemSink Flusher", true);
setInitialFlushTime(new Date());
}
return success;
}
/**
* Turn a security property into a nicely formatted set of <i>name=value</i>
* strings, allowing for either the property or the configuration not to be
* set.
*
* @param property the property to stringify
* @return the stringified property
*/
private String stringifySecurityProperty(String property) {
String securityProperty;
if (properties.containsKey(property)) {
String propertyValue = properties.getString(property);
String confValue = conf.get(properties.getString(property));
if (confValue != null) {
securityProperty = property + "=" + propertyValue
+ ", " + properties.getString(property) + "=" + confValue;
} else {
securityProperty = property + "=" + propertyValue
+ ", " + properties.getString(property) + "=<NOT SET>";
}
} else {
securityProperty = property + "=<NOT SET>";
}
return securityProperty;
}
/**
* Extract the roll interval from the configuration and return it in
* milliseconds.
*
* @return the roll interval in millis
*/
@VisibleForTesting
protected long getRollInterval() {
String rollInterval =
properties.getString(ROLL_INTERVAL_KEY, DEFAULT_ROLL_INTERVAL);
Pattern pattern = Pattern.compile("^\\s*(\\d+)\\s*([A-Za-z]*)\\s*$");
Matcher match = pattern.matcher(rollInterval);
long millis;
if (match.matches()) {
String flushUnit = match.group(2);
int rollIntervalInt;
try {
rollIntervalInt = Integer.parseInt(match.group(1));
} catch (NumberFormatException ex) {
throw new MetricsException("Unrecognized flush interval: "
+ rollInterval + ". Must be a number followed by an optional "
+ "unit. The unit must be one of: minute, hour, day", ex);
}
if ("".equals(flushUnit)) {
millis = TimeUnit.HOURS.toMillis(rollIntervalInt);
} else {
switch (flushUnit.toLowerCase()) {
case "m":
case "min":
case "minute":
case "minutes":
millis = TimeUnit.MINUTES.toMillis(rollIntervalInt);
break;
case "h":
case "hr":
case "hour":
case "hours":
millis = TimeUnit.HOURS.toMillis(rollIntervalInt);
break;
case "d":
case "day":
case "days":
millis = TimeUnit.DAYS.toMillis(rollIntervalInt);
break;
default:
throw new MetricsException("Unrecognized unit for flush interval: "
+ flushUnit + ". Must be one of: minute, hour, day");
}
}
} else {
throw new MetricsException("Unrecognized flush interval: "
+ rollInterval + ". Must be a number followed by an optional unit."
+ " The unit must be one of: minute, hour, day");
}
if (millis < 60000) {
throw new MetricsException("The flush interval property must be "
+ "at least 1 minute. Value was " + rollInterval);
}
return millis;
}
/**
* Return the property value if it's non-negative and throw an exception if
* it's not.
*
* @param key the property key
* @param defaultValue the default value
*/
private long getNonNegative(String key, int defaultValue) {
int flushOffsetIntervalMillis = properties.getInt(key, defaultValue);
if (flushOffsetIntervalMillis < 0) {
throw new MetricsException("The " + key + " property must be "
+ "non-negative. Value was " + flushOffsetIntervalMillis);
}
return flushOffsetIntervalMillis;
}
/**
* Throw a {@link MetricsException} if the given property is not set.
*
* @param key the key to validate
*/
private void checkIfPropertyExists(String key) {
if (!properties.containsKey(key)) {
throw new MetricsException("Metrics2 configuration is missing " + key
+ " property");
}
}
/**
* Return the supplied configuration for testing or otherwise load a new
* configuration.
*
* @return the configuration to use
*/
private Configuration loadConf() {
Configuration c;
if (suppliedConf != null) {
c = suppliedConf;
} else {
// The config we're handed in init() isn't the one we want here, so we
// create a new one to pick up the full settings.
c = new Configuration();
}
return c;
}
/**
* Return the supplied file system for testing or otherwise get a new file
* system.
*
* @return the file system to use
* @throws MetricsException thrown if the file system could not be retrieved
*/
private FileSystem getFileSystem() throws MetricsException {
FileSystem fs = null;
if (suppliedFilesystem != null) {
fs = suppliedFilesystem;
} else {
try {
fs = FileSystem.get(new URI(basePath.toString()), conf);
} catch (URISyntaxException ex) {
throw new MetricsException("The supplied filesystem base path URI"
+ " is not a valid URI: " + basePath.toString(), ex);
} catch (IOException ex) {
throw new MetricsException("Error connecting to file system: "
+ basePath + " [" + ex.toString() + "]", ex);
}
}
return fs;
}
/**
* Test whether the file system supports append and return the answer.
*
* @param fs the target file system
*/
private boolean checkAppend(FileSystem fs) {
boolean canAppend = true;
try {
fs.append(basePath);
} catch (UnsupportedOperationException ex) {
canAppend = false;
} catch (IOException ex) {
// Ignore. The operation is supported.
}
return canAppend;
}
/**
* Check the current directory against the time stamp. If they're not
* the same, create a new directory and a new log file in that directory.
*
* @throws MetricsException thrown if an error occurs while creating the
* new directory or new log file
*/
private void rollLogDirIfNeeded() throws MetricsException {
// Because we're working relative to the clock, we use a Date instead
// of Time.monotonicNow().
Date now = new Date();
// We check whether currentOutStream is null instead of currentDirPath,
// because if currentDirPath is null, then currentOutStream is null, but
// currentOutStream can be null for other reasons. Same for nextFlush.
if ((currentOutStream == null) || now.after(nextFlush.getTime())) {
// If we're not yet connected to HDFS, create the connection
if (!initialized) {
initialized = initFs();
}
if (initialized) {
// Close the stream. This step could have been handled already by the
// flusher thread, but if it has, the PrintStream will just swallow the
// exception, which is fine.
if (currentOutStream != null) {
currentOutStream.close();
}
currentDirPath = findCurrentDirectory(now);
try {
rollLogDir();
} catch (IOException ex) {
throwMetricsException("Failed to create new log file", ex);
}
// Update the time of the next flush
updateFlushTime(now);
// Schedule the next flush at that time
scheduleFlush(nextFlush.getTime());
}
} else if (forceFlush) {
scheduleFlush(new Date());
}
}
/**
* Use the given time to determine the current directory. The current
* directory will be based on the {@link #rollIntervalMinutes}.
*
* @param now the current time
* @return the current directory
*/
private Path findCurrentDirectory(Date now) {
long offset = ((now.getTime() - nextFlush.getTimeInMillis())
/ rollIntervalMillis) * rollIntervalMillis;
String currentDir =
DATE_FORMAT.format(new Date(nextFlush.getTimeInMillis() + offset));
return new Path(basePath, currentDir);
}
/**
* Schedule the current interval's directory to be flushed. If this ends up
* running after the top of the next interval, it will execute immediately.
*
* @param when the time the thread should run
*/
private void scheduleFlush(Date when) {
// Store the current currentDirPath to close later
final PrintStream toClose = currentOutStream;
flushTimer.schedule(new TimerTask() {
@Override
public void run() {
synchronized (lock) {
// This close may have already been done by a putMetrics() call. If it
// has, the PrintStream will swallow the exception, which is fine.
toClose.close();
}
hasFlushed = true;
}
}, when);
}
/**
* Update the {@link #nextFlush} variable to the next flush time. Add
* an integer number of flush intervals, preserving the initial random offset.
*
* @param now the current time
*/
@VisibleForTesting
protected void updateFlushTime(Date now) {
// In non-initial rounds, add an integer number of intervals to the last
// flush until a time in the future is achieved, thus preserving the
// original random offset.
int millis =
(int) (((now.getTime() - nextFlush.getTimeInMillis())
/ rollIntervalMillis + 1) * rollIntervalMillis);
nextFlush.add(Calendar.MILLISECOND, millis);
}
/**
* Set the {@link #nextFlush} variable to the initial flush time. The initial
* flush will be an integer number of flush intervals past the beginning of
* the current hour and will have a random offset added, up to
* {@link #rollOffsetIntervalMillis}. The initial flush will be a time in
* past that can be used from which to calculate future flush times.
*
* @param now the current time
*/
@VisibleForTesting
protected void setInitialFlushTime(Date now) {
// Start with the beginning of the current hour
nextFlush = Calendar.getInstance();
nextFlush.setTime(now);
nextFlush.set(Calendar.MILLISECOND, 0);
nextFlush.set(Calendar.SECOND, 0);
nextFlush.set(Calendar.MINUTE, 0);
// In the first round, calculate the first flush as the largest number of
// intervals from the beginning of the current hour that's not in the
// future by:
// 1. Subtract the beginning of the hour from the current time
// 2. Divide by the roll interval and round down to get the number of whole
// intervals that have passed since the beginning of the hour
// 3. Multiply by the roll interval to get the number of millis between
// the beginning of the current hour and the beginning of the current
// interval.
int millis = (int) (((now.getTime() - nextFlush.getTimeInMillis())
/ rollIntervalMillis) * rollIntervalMillis);
// Then add some noise to help prevent all the nodes from
// closing their files at the same time.
if (rollOffsetIntervalMillis > 0) {
millis += ThreadLocalRandom.current().nextLong(rollOffsetIntervalMillis);
// If the added time puts us into the future, step back one roll interval
// because the code to increment nextFlush to the next flush expects that
// nextFlush is the next flush from the previous interval. There wasn't
// a previous interval, so we just fake it with the time in the past that
// would have been the previous interval if there had been one.
//
// It's OK if millis comes out negative.
while (nextFlush.getTimeInMillis() + millis > now.getTime()) {
millis -= rollIntervalMillis;
}
}
// Adjust the next flush time by millis to get the time of our ficticious
// previous next flush
nextFlush.add(Calendar.MILLISECOND, millis);
}
/**
* Create a new directory based on the current interval and a new log file in
* that directory.
*
* @throws IOException thrown if an error occurs while creating the
* new directory or new log file
*/
private void rollLogDir() throws IOException {
String fileName =
source + "-" + InetAddress.getLocalHost().getHostName() + ".log";
Path targetFile = new Path(currentDirPath, fileName);
fileSystem.mkdirs(currentDirPath);
if (allowAppend) {
createOrAppendLogFile(targetFile);
} else {
createLogFile(targetFile);
}
}
/**
* Create a new log file and return the {@link FSDataOutputStream}. If a
* file with the specified path already exists, add a suffix, starting with 1
* and try again. Keep incrementing the suffix until a nonexistent target
* path is found.
*
* Once the file is open, update {@link #currentFSOutStream},
* {@link #currentOutStream}, and {@#link #currentFilePath} are set
* appropriately.
*
* @param initial the target path
* @throws IOException thrown if the call to see if the exists fails
*/
private void createLogFile(Path initial) throws IOException {
Path currentAttempt = initial;
// Start at 0 so that if the base filname exists, we start with the suffix
// ".1".
int id = 0;
while (true) {
// First try blindly creating the file. If we fail, it either means
// the file exists, or the operation actually failed. We do it this way
// because if we check whether the file exists, it might still be created
// by the time we try to create it. Creating first works like a
// test-and-set.
try {
currentFSOutStream = fileSystem.create(currentAttempt, false);
currentOutStream = new PrintStream(currentFSOutStream, true,
StandardCharsets.UTF_8.name());
currentFilePath = currentAttempt;
break;
} catch (IOException ex) {
// Now we can check to see if the file exists to know why we failed
if (fileSystem.exists(currentAttempt)) {
id = getNextIdToTry(initial, id);
currentAttempt = new Path(initial.toString() + "." + id);
} else {
throw ex;
}
}
}
}
/**
* Return the next ID suffix to use when creating the log file. This method
* will look at the files in the directory, find the one with the highest
* ID suffix, and 1 to that suffix, and return it. This approach saves a full
* linear probe, which matters in the case where there are a large number of
* log files.
*
* @param initial the base file path
* @param lastId the last ID value that was used
* @return the next ID to try
* @throws IOException thrown if there's an issue querying the files in the
* directory
*/
private int getNextIdToTry(Path initial, int lastId)
throws IOException {
RemoteIterator<LocatedFileStatus> files =
fileSystem.listFiles(currentDirPath, true);
String base = initial.toString();
int id = lastId;
while (files.hasNext()) {
String file = files.next().getPath().getName();
if (file.startsWith(base)) {
int fileId = extractId(file);
if (fileId > id) {
id = fileId;
}
}
}
// Return either 1 more than the highest we found or 1 more than the last
// ID used (if no ID was found).
return id + 1;
}
/**
* Extract the ID from the suffix of the given file name.
*
* @param file the file name
* @return the ID or -1 if no ID could be extracted
*/
private int extractId(String file) {
int index = file.lastIndexOf(".");
int id = -1;
// A hostname has to have at least 1 character
if (index > 0) {
try {
id = Integer.parseInt(file.substring(index + 1));
} catch (NumberFormatException ex) {
// This can happen if there's no suffix, but there is a dot in the
// hostname. Just ignore it.
}
}
return id;
}
/**
* Create a new log file and return the {@link FSDataOutputStream}. If a
* file with the specified path already exists, open the file for append
* instead.
*
* Once the file is open, update {@link #currentFSOutStream},
* {@link #currentOutStream}, and {@#link #currentFilePath}.
*
* @param initial the target path
* @throws IOException thrown if the call to see the append operation fails.
*/
private void createOrAppendLogFile(Path targetFile) throws IOException {
// First try blindly creating the file. If we fail, it either means
// the file exists, or the operation actually failed. We do it this way
// because if we check whether the file exists, it might still be created
// by the time we try to create it. Creating first works like a
// test-and-set.
try {
currentFSOutStream = fileSystem.create(targetFile, false);
currentOutStream = new PrintStream(currentFSOutStream, true,
StandardCharsets.UTF_8.name());
} catch (IOException ex) {
// Try appending instead. If we fail, if means the file doesn't
// actually exist yet or the operation actually failed.
try {
currentFSOutStream = fileSystem.append(targetFile);
currentOutStream = new PrintStream(currentFSOutStream, true,
StandardCharsets.UTF_8.name());
} catch (IOException ex2) {
// If the original create failed for a legit but transitory
// reason, the append will fail because the file now doesn't exist,
// resulting in a confusing stack trace. To avoid that, we set
// the cause of the second exception to be the first exception.
// It's still a tiny bit confusing, but it's enough
// information that someone should be able to figure it out.
ex2.initCause(ex);
throw ex2;
}
}
currentFilePath = targetFile;
}
@Override
public void putMetrics(MetricsRecord record) {
synchronized (lock) {
rollLogDirIfNeeded();
if (currentOutStream != null) {
currentOutStream.printf("%d %s.%s", record.timestamp(),
record.context(), record.name());
String separator = ": ";
for (MetricsTag tag : record.tags()) {
currentOutStream.printf("%s%s=%s", separator, tag.name(),
tag.value());
separator = ", ";
}
for (AbstractMetric metric : record.metrics()) {
currentOutStream.printf("%s%s=%s", separator, metric.name(),
metric.value());
}
currentOutStream.println();
// If we don't hflush(), the data may not be written until the file is
// closed. The file won't be closed until the end of the interval *AND*
// another record is received. Calling hflush() makes sure that the data
// is complete at the end of the interval.
try {
currentFSOutStream.hflush();
} catch (IOException ex) {
throwMetricsException("Failed flushing the stream", ex);
}
checkForErrors("Unable to write to log file");
} else if (!ignoreError) {
throwMetricsException("Unable to write to log file");
}
}
}
@Override
public void flush() {
synchronized (lock) {
// currentOutStream is null if currentFSOutStream is null
if (currentFSOutStream != null) {
try {
currentFSOutStream.hflush();
} catch (IOException ex) {
throwMetricsException("Unable to flush log file", ex);
}
}
}
}
@Override
public void close() {
synchronized (lock) {
if (currentOutStream != null) {
currentOutStream.close();
try {
checkForErrors("Unable to close log file");
} finally {
// Null out the streams just in case someone tries to reuse us.
currentOutStream = null;
currentFSOutStream = null;
}
}
}
}
/**
* If the sink isn't set to ignore errors, throw a {@link MetricsException}
* if the stream encountered an exception. The message parameter will be used
* as the new exception's message with the current file name
* ({@link #currentFilePath}) appended to it.
*
* @param message the exception message. The message will have a colon and
* the current file name ({@link #currentFilePath}) appended to it.
* @throws MetricsException thrown if there was an error and the sink isn't
* ignoring errors
*/
private void checkForErrors(String message)
throws MetricsException {
if (!ignoreError && currentOutStream.checkError()) {
throw new MetricsException(message + ": " + currentFilePath);
}
}
/**
* If the sink isn't set to ignore errors, wrap the Throwable in a
* {@link MetricsException} and throw it. The message parameter will be used
* as the new exception's message with the current file name
* ({@link #currentFilePath}) and the Throwable's string representation
* appended to it.
*
* @param message the exception message. The message will have a colon, the
* current file name ({@link #currentFilePath}), and the Throwable's string
* representation (wrapped in square brackets) appended to it.
* @param t the Throwable to wrap
*/
private void throwMetricsException(String message, Throwable t) {
if (!ignoreError) {
throw new MetricsException(message + ": " + currentFilePath + " ["
+ t.toString() + "]", t);
}
}
/**
* If the sink isn't set to ignore errors, throw a new
* {@link MetricsException}. The message parameter will be used as the
* new exception's message with the current file name
* ({@link #currentFilePath}) appended to it.
*
* @param message the exception message. The message will have a colon and
* the current file name ({@link #currentFilePath}) appended to it.
*/
private void throwMetricsException(String message) {
if (!ignoreError) {
throw new MetricsException(message + ": " + currentFilePath);
}
}
}
|
apache/helix | 35,850 | helix-core/src/main/java/org/apache/helix/manager/zk/CallbackHandler.java | package org.apache.helix.manager.zk;
/*
* 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.
*/
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.helix.BaseDataAccessor;
import org.apache.helix.HelixConstants.ChangeType;
import org.apache.helix.HelixDataAccessor;
import org.apache.helix.HelixException;
import org.apache.helix.HelixManager;
import org.apache.helix.HelixProperty;
import org.apache.helix.NotificationContext;
import org.apache.helix.NotificationContext.Type;
import org.apache.helix.PropertyKey;
import org.apache.helix.PropertyPathConfig;
import org.apache.helix.SystemPropertyKeys;
import org.apache.helix.api.exceptions.HelixMetaDataAccessException;
import org.apache.helix.api.listeners.BatchMode;
import org.apache.helix.api.listeners.ClusterConfigChangeListener;
import org.apache.helix.api.listeners.ConfigChangeListener;
import org.apache.helix.api.listeners.ControllerChangeListener;
import org.apache.helix.api.listeners.CurrentStateChangeListener;
import org.apache.helix.api.listeners.CustomizedStateChangeListener;
import org.apache.helix.api.listeners.CustomizedStateConfigChangeListener;
import org.apache.helix.api.listeners.CustomizedStateRootChangeListener;
import org.apache.helix.api.listeners.CustomizedViewChangeListener;
import org.apache.helix.api.listeners.CustomizedViewRootChangeListener;
import org.apache.helix.api.listeners.ExternalViewChangeListener;
import org.apache.helix.api.listeners.IdealStateChangeListener;
import org.apache.helix.api.listeners.InstanceConfigChangeListener;
import org.apache.helix.api.listeners.LiveInstanceChangeListener;
import org.apache.helix.api.listeners.MessageListener;
import org.apache.helix.api.listeners.PreFetch;
import org.apache.helix.api.listeners.ResourceConfigChangeListener;
import org.apache.helix.api.listeners.ScopedConfigChangeListener;
import org.apache.helix.api.listeners.TaskCurrentStateChangeListener;
import org.apache.helix.model.ClusterConfig;
import org.apache.helix.model.CurrentState;
import org.apache.helix.model.CustomizedState;
import org.apache.helix.model.CustomizedStateConfig;
import org.apache.helix.model.CustomizedView;
import org.apache.helix.model.ExternalView;
import org.apache.helix.model.IdealState;
import org.apache.helix.model.InstanceConfig;
import org.apache.helix.model.LiveInstance;
import org.apache.helix.model.Message;
import org.apache.helix.model.ResourceConfig;
import org.apache.helix.monitoring.mbeans.HelixCallbackMonitor;
import org.apache.helix.zookeeper.api.client.ChildrenSubscribeResult;
import org.apache.helix.zookeeper.api.client.RealmAwareZkClient;
import org.apache.helix.zookeeper.datamodel.ZNRecord;
import org.apache.helix.zookeeper.zkclient.IZkChildListener;
import org.apache.helix.zookeeper.zkclient.IZkDataListener;
import org.apache.helix.zookeeper.zkclient.annotation.PreFetchChangedData;
import org.apache.helix.zookeeper.zkclient.exception.ZkNoNodeException;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.helix.HelixConstants.ChangeType.CLUSTER_CONFIG;
import static org.apache.helix.HelixConstants.ChangeType.CONFIG;
import static org.apache.helix.HelixConstants.ChangeType.CONTROLLER;
import static org.apache.helix.HelixConstants.ChangeType.CURRENT_STATE;
import static org.apache.helix.HelixConstants.ChangeType.CUSTOMIZED_STATE;
import static org.apache.helix.HelixConstants.ChangeType.CUSTOMIZED_STATE_CONFIG;
import static org.apache.helix.HelixConstants.ChangeType.CUSTOMIZED_STATE_ROOT;
import static org.apache.helix.HelixConstants.ChangeType.CUSTOMIZED_VIEW;
import static org.apache.helix.HelixConstants.ChangeType.CUSTOMIZED_VIEW_ROOT;
import static org.apache.helix.HelixConstants.ChangeType.EXTERNAL_VIEW;
import static org.apache.helix.HelixConstants.ChangeType.IDEAL_STATE;
import static org.apache.helix.HelixConstants.ChangeType.INSTANCE_CONFIG;
import static org.apache.helix.HelixConstants.ChangeType.LIVE_INSTANCE;
import static org.apache.helix.HelixConstants.ChangeType.MESSAGE;
import static org.apache.helix.HelixConstants.ChangeType.MESSAGES_CONTROLLER;
import static org.apache.helix.HelixConstants.ChangeType.RESOURCE_CONFIG;
import static org.apache.helix.HelixConstants.ChangeType.TARGET_EXTERNAL_VIEW;
import static org.apache.helix.HelixConstants.ChangeType.TASK_CURRENT_STATE;
@PreFetchChangedData(enabled = false)
public class CallbackHandler implements IZkChildListener, IZkDataListener {
private static Logger logger = LoggerFactory.getLogger(CallbackHandler.class);
private static final AtomicLong CALLBACK_HANDLER_UID = new AtomicLong();
private final long _uid;
/**
* define the next possible notification types
*/
private static Map<Type, List<Type>> nextNotificationType = new HashMap<>();
static {
nextNotificationType.put(Type.INIT, Arrays.asList(Type.CALLBACK, Type.FINALIZE));
nextNotificationType.put(Type.CALLBACK, Arrays.asList(Type.CALLBACK, Type.FINALIZE));
nextNotificationType.put(Type.FINALIZE, Arrays.asList(Type.INIT));
}
private final String _path;
private final Object _listener;
private final Set<EventType> _eventTypes;
private final HelixDataAccessor _accessor;
private final ChangeType _changeType;
private final RealmAwareZkClient _zkClient;
private final AtomicLong _lastNotificationTimeStamp;
private final HelixManager _manager;
private final PropertyKey _propertyKey;
private boolean _batchModeEnabled = false;
private boolean _preFetchEnabled = true;
private HelixCallbackMonitor _monitor;
private AtomicReference<CallbackEventExecutor> _batchCallbackExecutorRef = new AtomicReference<>();
private boolean _watchChild = true; // Whether we should subscribe to the child znode's data
// change.
// indicated whether this CallbackHandler is ready to serve event callback from ZkClient.
private boolean _ready = false;
/**
* maintain the expected notification types
* this is fix for HELIX-195: race condition between FINALIZE callbacks and Zk callbacks
*/
private List<NotificationContext.Type> _expectTypes = nextNotificationType.get(Type.FINALIZE);
public CallbackHandler(HelixManager manager, RealmAwareZkClient client, PropertyKey propertyKey,
Object listener, EventType[] eventTypes, ChangeType changeType) {
this(manager, client, propertyKey, listener, eventTypes, changeType, null);
}
public CallbackHandler(HelixManager manager, RealmAwareZkClient client, PropertyKey propertyKey,
Object listener, EventType[] eventTypes, ChangeType changeType,
HelixCallbackMonitor monitor) {
if (listener == null) {
throw new HelixException("listener could not be null");
}
if (monitor != null && !monitor.getChangeType().equals(changeType)) {
throw new HelixException("The specified callback monitor is for different change type: "
+ monitor.getChangeType().name());
}
_uid = CALLBACK_HANDLER_UID.getAndIncrement();
_manager = manager;
_accessor = manager.getHelixDataAccessor();
_zkClient = client;
_propertyKey = propertyKey;
_path = propertyKey.getPath();
_listener = listener;
_eventTypes = new HashSet<>(Arrays.asList(eventTypes));
_changeType = changeType;
_lastNotificationTimeStamp = new AtomicLong(System.nanoTime());
_monitor = monitor;
if (_changeType == MESSAGE || _changeType == MESSAGES_CONTROLLER || _changeType == CONTROLLER) {
_watchChild = false;
} else {
_watchChild = true;
}
parseListenerProperties();
init();
}
private void parseListenerProperties() {
BatchMode batchMode = _listener.getClass().getAnnotation(BatchMode.class);
PreFetch preFetch = _listener.getClass().getAnnotation(PreFetch.class);
String asyncBatchModeEnabled = System.getProperty(SystemPropertyKeys.ASYNC_BATCH_MODE_ENABLED);
if (asyncBatchModeEnabled == null) {
// for backcompatible, the old property name is deprecated.
asyncBatchModeEnabled =
System.getProperty(SystemPropertyKeys.LEGACY_ASYNC_BATCH_MODE_ENABLED);
}
if (asyncBatchModeEnabled != null) {
_batchModeEnabled = Boolean.parseBoolean(asyncBatchModeEnabled);
logger.info("isAsyncBatchModeEnabled by default: {}", _batchModeEnabled);
}
if (batchMode != null) {
_batchModeEnabled = batchMode.enabled();
}
if (preFetch != null) {
_preFetchEnabled = preFetch.enabled();
}
Class listenerClass = null;
switch (_changeType) {
case IDEAL_STATE:
listenerClass = IdealStateChangeListener.class;
break;
case INSTANCE_CONFIG:
if (_listener instanceof ConfigChangeListener) {
listenerClass = ConfigChangeListener.class;
} else if (_listener instanceof InstanceConfigChangeListener) {
listenerClass = InstanceConfigChangeListener.class;
}
break;
case CLUSTER_CONFIG:
listenerClass = ClusterConfigChangeListener.class;
break;
case RESOURCE_CONFIG:
listenerClass = ResourceConfigChangeListener.class;
break;
case CUSTOMIZED_STATE_CONFIG:
listenerClass = CustomizedStateConfigChangeListener.class;
break;
case CONFIG:
listenerClass = ConfigChangeListener.class;
break;
case LIVE_INSTANCE:
listenerClass = LiveInstanceChangeListener.class;
break;
case CURRENT_STATE:
listenerClass = CurrentStateChangeListener.class;
break;
case TASK_CURRENT_STATE:
listenerClass = TaskCurrentStateChangeListener.class;
break;
case CUSTOMIZED_STATE_ROOT:
listenerClass = CustomizedStateRootChangeListener.class;
break;
case CUSTOMIZED_STATE:
listenerClass = CustomizedStateChangeListener.class;
break;
case MESSAGE:
case MESSAGES_CONTROLLER:
listenerClass = MessageListener.class;
break;
case EXTERNAL_VIEW:
case TARGET_EXTERNAL_VIEW:
listenerClass = ExternalViewChangeListener.class;
break;
case CUSTOMIZED_VIEW:
listenerClass = CustomizedViewChangeListener.class;
break;
case CUSTOMIZED_VIEW_ROOT:
listenerClass = CustomizedViewRootChangeListener.class;
break;
case CONTROLLER:
listenerClass = ControllerChangeListener.class;
}
Method callbackMethod = listenerClass.getMethods()[0];
try {
Method method = _listener.getClass().getMethod(callbackMethod.getName(),
callbackMethod.getParameterTypes());
BatchMode batchModeInMethod = method.getAnnotation(BatchMode.class);
PreFetch preFetchInMethod = method.getAnnotation(PreFetch.class);
if (batchModeInMethod != null) {
_batchModeEnabled = batchModeInMethod.enabled();
}
if (preFetchInMethod != null) {
_preFetchEnabled = preFetchInMethod.enabled();
}
} catch (NoSuchMethodException e) {
logger.warn("No method {} defined in listener {}", callbackMethod.getName(),
_listener.getClass().getCanonicalName());
}
}
public Object getListener() {
return _listener;
}
public String getPath() {
return _path;
}
public void enqueueTask(NotificationContext changeContext) throws Exception {
// async mode only applicable to CALLBACK from ZK, During INIT and FINALIZE invoke the
// callback's immediately.
if (_batchModeEnabled && changeContext.getType() == NotificationContext.Type.CALLBACK) {
logger.debug("Callbackhandler {}, Enqueuing callback", _uid );
if (!isReady()) {
logger.info("CallbackHandler {} is not ready, ignore change callback from path: {}, for "
+ "listener: {}", _uid, _path, _listener);
} else {
// submit
CallbackEventExecutor callbackProcessor = _batchCallbackExecutorRef.get();
if (callbackProcessor != null) {
callbackProcessor.submitEventToExecutor(changeContext.getType(), changeContext, this);
} else {
throw new HelixException(
"Failed to process callback in batch mode. Batch Callback Processor does not exist.");
}
}
} else {
invoke(changeContext);
}
if (_monitor != null) {
_monitor.increaseCallbackUnbatchedCounters();
}
}
public void invoke(NotificationContext changeContext) throws Exception {
Type type = changeContext.getType();
long start = System.currentTimeMillis();
if (logger.isInfoEnabled()) {
logger.info("{} START: CallbackHandler {}, INVOKE {} listener: {} type: {}",
Thread.currentThread().getId(), _uid, _path, _listener, type);
}
synchronized (this) {
if (!_expectTypes.contains(type)) {
logger.warn("Callback handler {} received event in wrong order. Listener: {}, path: {}, "
+ "expected types: {}, but was {}", _uid, _listener, _path, _expectTypes, type);
return;
}
_expectTypes = nextNotificationType.get(type);
if (type == Type.INIT || type == Type.FINALIZE || changeContext.getIsChildChange()) {
subscribeForChanges(changeContext.getType(), _path, _watchChild);
}
}
// This allows the Helix Manager to work with one change at a time
// TODO: Maybe we don't need to sync on _manager for all types of listener. PCould be a
// potential improvement candidate.
synchronized (_manager) {
if (_changeType == IDEAL_STATE) {
IdealStateChangeListener idealStateChangeListener = (IdealStateChangeListener) _listener;
List<IdealState> idealStates = preFetch(_propertyKey);
idealStateChangeListener.onIdealStateChange(idealStates, changeContext);
} else if (_changeType == INSTANCE_CONFIG) {
if (_listener instanceof ConfigChangeListener) {
ConfigChangeListener configChangeListener = (ConfigChangeListener) _listener;
List<InstanceConfig> configs = preFetch(_propertyKey);
configChangeListener.onConfigChange(configs, changeContext);
} else if (_listener instanceof InstanceConfigChangeListener) {
InstanceConfigChangeListener listener = (InstanceConfigChangeListener) _listener;
List<InstanceConfig> configs = Collections.emptyList();
if (_propertyKey.getParams().length > 2 && _preFetchEnabled) {
// If there are more than 2 params, that means the property key is for a specific instance
// and will not have children.
InstanceConfig config = _accessor.getProperty(_propertyKey);
configs = config != null ? Collections.singletonList(config) : Collections.emptyList();
} else {
configs = preFetch(_propertyKey);
}
listener.onInstanceConfigChange(configs, changeContext);
}
} else if (_changeType == RESOURCE_CONFIG) {
ResourceConfigChangeListener listener = (ResourceConfigChangeListener) _listener;
List<ResourceConfig> configs = preFetch(_propertyKey);
listener.onResourceConfigChange(configs, changeContext);
} else if (_changeType == CUSTOMIZED_STATE_CONFIG) {
CustomizedStateConfigChangeListener listener = (CustomizedStateConfigChangeListener) _listener;
CustomizedStateConfig config = null;
if (_preFetchEnabled) {
config = _accessor.getProperty(_propertyKey);
}
listener.onCustomizedStateConfigChange(config, changeContext);
} else if (_changeType == CLUSTER_CONFIG) {
ClusterConfigChangeListener listener = (ClusterConfigChangeListener) _listener;
ClusterConfig config = null;
if (_preFetchEnabled) {
config = _accessor.getProperty(_propertyKey);
}
listener.onClusterConfigChange(config, changeContext);
} else if (_changeType == CONFIG) {
ScopedConfigChangeListener listener = (ScopedConfigChangeListener) _listener;
List<HelixProperty> configs = preFetch(_propertyKey);
listener.onConfigChange(configs, changeContext);
} else if (_changeType == LIVE_INSTANCE) {
LiveInstanceChangeListener liveInstanceChangeListener =
(LiveInstanceChangeListener) _listener;
List<LiveInstance> liveInstances = preFetch(_propertyKey);
liveInstanceChangeListener.onLiveInstanceChange(liveInstances, changeContext);
} else if (_changeType == CURRENT_STATE) {
CurrentStateChangeListener currentStateChangeListener =
(CurrentStateChangeListener) _listener;
String instanceName = PropertyPathConfig.getInstanceNameFromPath(_path);
List<CurrentState> currentStates = preFetch(_propertyKey);
currentStateChangeListener.onStateChange(instanceName, currentStates, changeContext);
} else if (_changeType == TASK_CURRENT_STATE) {
TaskCurrentStateChangeListener taskCurrentStateChangeListener =
(TaskCurrentStateChangeListener) _listener;
String instanceName = PropertyPathConfig.getInstanceNameFromPath(_path);
List<CurrentState> currentStates = preFetch(_propertyKey);
taskCurrentStateChangeListener
.onTaskCurrentStateChange(instanceName, currentStates, changeContext);
} else if (_changeType == CUSTOMIZED_STATE_ROOT) {
CustomizedStateRootChangeListener customizedStateRootChangeListener =
(CustomizedStateRootChangeListener) _listener;
String instanceName = PropertyPathConfig.getInstanceNameFromPath(_path);
List<String> customizedStateTypes = new ArrayList<>();
if (_preFetchEnabled) {
customizedStateTypes =
_accessor.getChildNames(_accessor.keyBuilder().customizedStatesRoot(instanceName));
}
customizedStateRootChangeListener
.onCustomizedStateRootChange(instanceName, customizedStateTypes, changeContext);
} else if (_changeType == CUSTOMIZED_STATE) {
CustomizedStateChangeListener customizedStateChangeListener =
(CustomizedStateChangeListener) _listener;
String instanceName = PropertyPathConfig.getInstanceNameFromPath(_path);
List<CustomizedState> customizedStates = preFetch(_propertyKey);
customizedStateChangeListener.onCustomizedStateChange(instanceName, customizedStates, changeContext);
} else if (_changeType == MESSAGE) {
MessageListener messageListener = (MessageListener) _listener;
String instanceName = PropertyPathConfig.getInstanceNameFromPath(_path);
List<Message> messages = preFetch(_propertyKey);
messageListener.onMessage(instanceName, messages, changeContext);
} else if (_changeType == MESSAGES_CONTROLLER) {
MessageListener messageListener = (MessageListener) _listener;
List<Message> messages = preFetch(_propertyKey);
messageListener.onMessage(_manager.getInstanceName(), messages, changeContext);
} else if (_changeType == EXTERNAL_VIEW || _changeType == TARGET_EXTERNAL_VIEW) {
ExternalViewChangeListener externalViewListener = (ExternalViewChangeListener) _listener;
List<ExternalView> externalViewList = preFetch(_propertyKey);
externalViewListener.onExternalViewChange(externalViewList, changeContext);
} else if (_changeType == CUSTOMIZED_VIEW_ROOT) {
CustomizedViewRootChangeListener customizedViewRootChangeListener =
(CustomizedViewRootChangeListener) _listener;
List<String> customizedViewTypes = new ArrayList<>();
if (_preFetchEnabled) {
customizedViewTypes = _accessor.getChildNames(_accessor.keyBuilder().customizedViews());
}
customizedViewRootChangeListener.onCustomizedViewRootChange(customizedViewTypes,
changeContext);
} else if (_changeType == CUSTOMIZED_VIEW) {
CustomizedViewChangeListener customizedViewListener = (CustomizedViewChangeListener) _listener;
List<CustomizedView> customizedViewListList = preFetch(_propertyKey);
customizedViewListener.onCustomizedViewChange(customizedViewListList, changeContext);
} else if (_changeType == CONTROLLER) {
ControllerChangeListener controllerChangelistener = (ControllerChangeListener) _listener;
controllerChangelistener.onControllerChange(changeContext);
} else {
logger.warn("Callbackhandler {}, Unknown change type: {}", _uid, _changeType);
}
long end = System.currentTimeMillis();
if (logger.isInfoEnabled()) {
logger.info("{} END:INVOKE CallbackHandler {}, {} listener: {} type: {} Took: {}ms",
Thread.currentThread().getId(), _uid, _path, _listener, type, (end - start));
}
if (_monitor != null) {
_monitor.increaseCallbackCounters(end - start);
}
}
}
private <T extends HelixProperty> List<T> preFetch(PropertyKey key) {
if (_preFetchEnabled) {
return _accessor.getChildValues(key, true);
} else {
return Collections.emptyList();
}
}
/*
* If callback type is INIT or CALLBACK, subscribes child change listener to the path
* and returns the path's children names. The children list might be null when the path
* doesn't exist or callback type is INIT/CALLBACK.
*/
private List<String> subscribeChildChange(String path, NotificationContext.Type callbackType) {
if (callbackType == NotificationContext.Type.INIT
|| callbackType == NotificationContext.Type.CALLBACK) {
logger.debug("CallbackHandler {}, {} subscribes child-change. path: {} , listener: {}",
_uid, _manager.getInstanceName(), path, _listener );
// In the lifecycle of CallbackHandler, INIT is the first stage of registration of watch.
// For some usage case such as current state, the path can be created later. Thus we would
// install watch anyway event the path is not yet created.
// Later, CALLBACK type, the CallbackHandler already registered the watch and knows the
// path was created. Here, to avoid leaking path in ZooKeeper server, we would not let
// CallbackHandler to install exists watch, namely watch for path not existing.
// Note when path is removed, the CallbackHandler would remove itself from ZkHelixManager too
// to avoid leaking a CallbackHandler.
ChildrenSubscribeResult childrenSubscribeResult =
_zkClient.subscribeChildChanges(path, this, callbackType != Type.INIT);
logger.debug("CallbackHandler {} subscribe data path {} result {}", _uid, path,
childrenSubscribeResult.isInstalled());
if (!childrenSubscribeResult.isInstalled()) {
logger.info("CallbackHandler {} subscribe data path {} failed!", _uid, path);
}
// getChildren() might be null: when path doesn't exist.
return childrenSubscribeResult.getChildren();
} else if (callbackType == NotificationContext.Type.FINALIZE) {
logger.info("CallbackHandler{}, {} unsubscribe child-change. path: {}, listener: {}",
_uid ,_manager.getInstanceName(), path, _listener);
_zkClient.unsubscribeChildChanges(path, this);
}
try {
return _zkClient.getChildren(path);
} catch (ZkNoNodeException e) {
return null;
}
}
private void subscribeDataChange(String path, NotificationContext.Type callbackType) {
if (callbackType == NotificationContext.Type.INIT
|| callbackType == NotificationContext.Type.CALLBACK) {
logger.debug("CallbackHandler {}, {} subscribe data-change. path: {}, listener: {}",
_uid, _manager.getInstanceName(), path, _listener);
boolean subStatus = _zkClient.subscribeDataChanges(path, this, callbackType != Type.INIT);
logger.debug("CallbackHandler {} subscribe data path {} result {}", _uid, path, subStatus);
if (!subStatus) {
logger.info("CallbackHandler {} subscribe data path {} failed!", _uid, path);
}
} else if (callbackType == NotificationContext.Type.FINALIZE) {
logger.info("CallbackHandler{}, {} unsubscribe data-change. path: {}, listener: {}",
_uid, _manager.getInstanceName(), path, _listener);
_zkClient.unsubscribeDataChanges(path, this);
}
}
private void subscribeForChanges(NotificationContext.Type callbackType, String path,
boolean watchChild) {
logger.info("CallbackHandler {} subscribing changes listener to path: {}, callback type: {}, "
+ "event types: {}, listener: {}, watchChild: {}",
_uid, path, callbackType, _eventTypes, _listener, watchChild);
long start = System.currentTimeMillis();
if (_eventTypes.contains(EventType.NodeDataChanged)
|| _eventTypes.contains(EventType.NodeCreated)
|| _eventTypes.contains(EventType.NodeDeleted)) {
logger.info("CallbackHandler {} subscribing data change listener to path: {}", _uid, path);
subscribeDataChange(path, callbackType);
}
if (_eventTypes.contains(EventType.NodeChildrenChanged)) {
List<String> children = subscribeChildChange(path, callbackType);
if (watchChild) {
try {
switch (_changeType) {
case CURRENT_STATE:
case TASK_CURRENT_STATE:
case CUSTOMIZED_STATE:
case IDEAL_STATE:
case EXTERNAL_VIEW:
case CUSTOMIZED_VIEW:
case TARGET_EXTERNAL_VIEW: {
// check if bucketized
BaseDataAccessor<ZNRecord> baseAccessor = new ZkBaseDataAccessor<>(_zkClient);
List<ZNRecord> records = baseAccessor.getChildren(path, null, 0, 0, 0);
for (ZNRecord record : records) {
HelixProperty property = new HelixProperty(record);
String childPath = path + "/" + record.getId();
int bucketSize = property.getBucketSize();
if (bucketSize > 0) {
// subscribe both data-change and child-change on bucketized parent node
// data-change gives a delete-callback which is used to remove watch
List<String> bucketizedChildNames = subscribeChildChange(childPath, callbackType);
subscribeDataChange(childPath, callbackType);
// subscribe data-change on bucketized child
if (bucketizedChildNames != null) {
for (String bucketizedChildName : bucketizedChildNames) {
String bucketizedChildPath = childPath + "/" + bucketizedChildName;
subscribeDataChange(bucketizedChildPath, callbackType);
}
}
} else {
subscribeDataChange(childPath, callbackType);
}
}
break;
}
default: {
if (children != null) {
for (String child : children) {
String childPath = path + "/" + child;
subscribeDataChange(childPath, callbackType);
}
}
break;
}
}
} catch (ZkNoNodeException | HelixMetaDataAccessException e) {
//TODO: avoid calling getChildren for path that does not exist
if (_changeType == CUSTOMIZED_STATE_ROOT) {
logger.warn(
"CallbackHandler {}, Failed to subscribe child/data change on path: {}, listener: {}. Instance "
+ "does not support Customized State!", _uid, path, _listener);
} else {
logger.warn("CallbackHandler {}, Failed to subscribe child/data change. path: {}, listener: {}",
_uid, path, _listener, e);
}
}
}
}
long end = System.currentTimeMillis();
logger.info("CallbackHandler{}, Subscribing to path: {} took: {}", _uid, path, (end - start));
}
public EventType[] getEventTypes() {
return (EventType[]) _eventTypes.toArray();
}
/**
* Invoke the listener so that it sets up the initial values from the zookeeper if any
* exists
*/
public void init() {
logger.info("initializing CallbackHandler: {}, content: {} ", _uid, getContent());
try {
if (_batchModeEnabled) {
CallbackEventExecutor callbackExecutor = _batchCallbackExecutorRef.get();
if (callbackExecutor != null) {
callbackExecutor.reset();
} else {
callbackExecutor = new CallbackEventExecutor(_manager);
if (!_batchCallbackExecutorRef.compareAndSet(null, callbackExecutor)) {
callbackExecutor.unregisterFromFactory();
}
}
}
updateNotificationTime(System.nanoTime());
NotificationContext changeContext = new NotificationContext(_manager);
changeContext.setType(NotificationContext.Type.INIT);
changeContext.setChangeType(_changeType);
_ready = true;
invoke(changeContext);
} catch (Exception e) {
String msg = "Exception while invoking init callback for listener:" + _listener;
ZKExceptionHandler.getInstance().handle(msg, e);
}
}
@Override
public void handleDataChange(String dataPath, Object data) {
logger.debug("Data change callbackhandler {}: paths changed: {}", _uid, dataPath);
try {
updateNotificationTime(System.nanoTime());
if (dataPath != null && dataPath.startsWith(_path)) {
NotificationContext changeContext = new NotificationContext(_manager);
changeContext.setType(NotificationContext.Type.CALLBACK);
changeContext.setPathChanged(dataPath);
changeContext.setChangeType(_changeType);
changeContext.setIsChildChange(false);
enqueueTask(changeContext);
}
} catch (Exception e) {
String msg =
"exception in handling data-change. path: " + dataPath + ", listener: " + _listener;
ZKExceptionHandler.getInstance().handle(msg, e);
}
}
@Override
public void handleDataDeleted(String dataPath) {
logger.debug("Data change callbackhandler {}: path deleted: {}", _uid, dataPath);
try {
updateNotificationTime(System.nanoTime());
if (dataPath != null && dataPath.startsWith(_path)) {
logger.info("CallbackHandler {}, {} unsubscribe data-change. path: {}, listener: {}",
_uid, _manager.getInstanceName(), dataPath, _listener);
_zkClient.unsubscribeDataChanges(dataPath, this);
// only needed for bucketized parent, but OK if we don't have child-change
// watch on the bucketized parent path
logger.info("CallbackHandler {}, {} unsubscribe child-change. path: {}, listener: {}",
_uid, _manager.getInstanceName(), dataPath, _listener);
_zkClient.unsubscribeChildChanges(dataPath, this);
// No need to invoke() since this event will handled by child-change on parent-node
}
} catch (Exception e) {
String msg = "exception in handling data-delete-change. path: " + dataPath + ", listener: "
+ _listener;
ZKExceptionHandler.getInstance().handle(msg, e);
}
}
@Override
public void handleChildChange(String parentPath, List<String> currentChilds) {
logger.debug("Data change callback: child changed, path: {} , current child count: {}",
parentPath, currentChilds == null ? 0 : currentChilds.size());
try {
updateNotificationTime(System.nanoTime());
if (parentPath != null && parentPath.startsWith(_path)) {
if (currentChilds == null && parentPath.equals(_path)) {
// _path has been removed, remove this listener
// removeListener will call handler.reset(), which in turn call invoke() on FINALIZE type
boolean rt = _manager.removeListener(_propertyKey, _listener);
logger.info("CallbackHandler {} removed with status {}", _uid, rt);
} else {
if (!isReady()) {
// avoid leaking CallbackHandler
logger.info("Callbackhandler {} with path {} is in reset state. Stop subscription to ZK client to avoid leaking",
this, parentPath);
return;
}
NotificationContext changeContext = new NotificationContext(_manager);
changeContext.setType(NotificationContext.Type.CALLBACK);
changeContext.setPathChanged(parentPath);
changeContext.setChangeType(_changeType);
changeContext.setIsChildChange(true);
enqueueTask(changeContext);
}
}
} catch (Exception e) {
String msg = "exception in handling child-change. instance: " + _manager.getInstanceName()
+ ", parentPath: " + parentPath + ", listener: " + _listener;
ZKExceptionHandler.getInstance().handle(msg, e);
}
}
/**
* Invoke the listener for the last time so that the listener could clean up resources
*/
@Deprecated
public void reset() {
reset(true);
}
public void reset(boolean isShutdown) {
logger.info("Resetting CallbackHandler: {}. Is resetting for shutdown: {}.", _uid, isShutdown);
try {
_ready = false;
CallbackEventExecutor callbackExecutor = _batchCallbackExecutorRef.get();
if (callbackExecutor != null) {
if (isShutdown) {
if (_batchCallbackExecutorRef.compareAndSet(callbackExecutor, null)) {
callbackExecutor.unregisterFromFactory();
}
} else {
callbackExecutor.reset();
}
}
NotificationContext changeContext = new NotificationContext(_manager);
changeContext.setType(NotificationContext.Type.FINALIZE);
changeContext.setChangeType(_changeType);
invoke(changeContext);
} catch (Exception e) {
ZKExceptionHandler.getInstance().handle("Exception while resetting the listener:" + _listener, e);
}
}
private void updateNotificationTime(long nanoTime) {
long l = _lastNotificationTimeStamp.get();
while (nanoTime > l) {
boolean b = _lastNotificationTimeStamp.compareAndSet(l, nanoTime);
if (b) {
break;
} else {
l = _lastNotificationTimeStamp.get();
}
}
}
public boolean isReady() {
return _ready;
}
public String getContent() {
StringBuilder sb = new StringBuilder("CallbackHandler{_watchChild=");
sb.append(_watchChild);
sb.append(", _preFetchEnabled=");
sb.append(_preFetchEnabled);
sb.append(", _batchModeEnabled=");
sb.append(_batchModeEnabled);
sb.append(", _path='");
sb.append(_path);
sb.append("', _listener=");
sb.append(_listener);
sb.append(", _changeType=");
sb.append(_changeType);
sb.append(", _manager=");
sb.append(_manager);
sb.append(", _zkClient=");
sb.append(_zkClient);
sb.append("}");
return sb.toString();
}
}
|
apache/lucene | 35,508 | lucene/queryparser/src/java/org/apache/lucene/queryparser/classic/QueryParserTokenManager.java | /* QueryParserTokenManager.java */
/* Generated By:JavaCC: Do not edit this line. QueryParserTokenManager.java */
package org.apache.lucene.queryparser.classic;
import org.apache.lucene.queryparser.charstream.CharStream;
/** Token Manager. */
@SuppressWarnings ("unused")
public class QueryParserTokenManager implements QueryParserConstants {
// Debug output.
// (debugStream omitted).
// Set debug output.
// (setDebugStream omitted).
private final int jjStopStringLiteralDfa_2(int pos, long active0){
switch (pos)
{
default :
return -1;
}
}
private final int jjStartNfa_2(int pos, long active0){
return jjMoveNfa_2(jjStopStringLiteralDfa_2(pos, active0), pos + 1);
}
private int jjStopAtPos(int pos, int kind)
{
jjmatchedKind = kind;
jjmatchedPos = pos;
return pos + 1;
}
private int jjMoveStringLiteralDfa0_2(){
switch(curChar)
{
case 40:
return jjStopAtPos(0, 14);
case 41:
return jjStopAtPos(0, 15);
case 42:
return jjStartNfaWithStates_2(0, 17, 49);
case 43:
return jjStartNfaWithStates_2(0, 11, 15);
case 45:
return jjStartNfaWithStates_2(0, 12, 15);
case 58:
return jjStopAtPos(0, 16);
case 91:
return jjStopAtPos(0, 25);
case 94:
return jjStopAtPos(0, 18);
case 123:
return jjStopAtPos(0, 26);
default :
return jjMoveNfa_2(0, 0);
}
}
private int jjStartNfaWithStates_2(int pos, int kind, int state)
{
jjmatchedKind = kind;
jjmatchedPos = pos;
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) { return pos + 1; }
return jjMoveNfa_2(state, pos + 1);
}
static final long[] jjbitVec0 = {
0x1L, 0x0L, 0x0L, 0x0L
};
static final long[] jjbitVec1 = {
0xfffffffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec3 = {
0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
};
static final long[] jjbitVec4 = {
0xfffefffffffffffeL, 0xffffffffffffffffL, 0xffffffffffffffffL, 0xffffffffffffffffL
};
private int jjMoveNfa_2(int startState, int curPos)
{
int startsAt = 0;
jjnewStateCnt = 49;
int i = 1;
jjstateSet[0] = startState;
int kind = 0x7fffffff;
for (;;)
{
if (++jjround == 0x7fffffff)
ReInitRounds();
if (curChar < 64)
{
long l = 1L << curChar;
do
{
switch(jjstateSet[--i])
{
case 49:
case 33:
if ((0xfbff7cf8ffffd9ffL & l) == 0L)
break;
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
break;
case 0:
if ((0xfbff54f8ffffd9ffL & l) != 0L)
{
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
}
else if ((0x100002600L & l) != 0L)
{
if (kind > 7)
kind = 7;
}
else if ((0x280200000000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 15;
else if (curChar == 47)
{ jjCheckNAddStates(0, 2); }
else if (curChar == 34)
{ jjCheckNAddStates(3, 5); }
if ((0x7bff50f8ffffd9ffL & l) != 0L)
{
if (kind > 20)
kind = 20;
{ jjCheckNAddStates(6, 10); }
}
else if (curChar == 42)
{
if (kind > 22)
kind = 22;
}
else if (curChar == 33)
{
if (kind > 10)
kind = 10;
}
if (curChar == 38)
jjstateSet[jjnewStateCnt++] = 4;
break;
case 4:
if (curChar == 38 && kind > 8)
kind = 8;
break;
case 5:
if (curChar == 38)
jjstateSet[jjnewStateCnt++] = 4;
break;
case 13:
if (curChar == 33 && kind > 10)
kind = 10;
break;
case 14:
if ((0x280200000000L & l) != 0L)
jjstateSet[jjnewStateCnt++] = 15;
break;
case 15:
if ((0x100002600L & l) != 0L && kind > 13)
kind = 13;
break;
case 16:
if (curChar == 34)
{ jjCheckNAddStates(3, 5); }
break;
case 17:
if ((0xfffffffbffffffffL & l) != 0L)
{ jjCheckNAddStates(3, 5); }
break;
case 19:
{ jjCheckNAddStates(3, 5); }
break;
case 20:
if (curChar == 34 && kind > 19)
kind = 19;
break;
case 22:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 21)
kind = 21;
{ jjCheckNAddStates(11, 14); }
break;
case 23:
if (curChar == 46)
{ jjCheckNAdd(24); }
break;
case 24:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 21)
kind = 21;
{ jjCheckNAddStates(15, 17); }
break;
case 25:
if ((0x7bff78f8ffffd9ffL & l) == 0L)
break;
if (kind > 21)
kind = 21;
{ jjCheckNAddTwoStates(25, 26); }
break;
case 27:
if (kind > 21)
kind = 21;
{ jjCheckNAddTwoStates(25, 26); }
break;
case 28:
if ((0x7bff78f8ffffd9ffL & l) == 0L)
break;
if (kind > 21)
kind = 21;
{ jjCheckNAddTwoStates(28, 29); }
break;
case 30:
if (kind > 21)
kind = 21;
{ jjCheckNAddTwoStates(28, 29); }
break;
case 31:
if (curChar == 42 && kind > 22)
kind = 22;
break;
case 32:
if ((0xfbff54f8ffffd9ffL & l) == 0L)
break;
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
break;
case 35:
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
break;
case 36:
case 38:
if (curChar == 47)
{ jjCheckNAddStates(0, 2); }
break;
case 37:
if ((0xffff7fffffffffffL & l) != 0L)
{ jjCheckNAddStates(0, 2); }
break;
case 40:
if (curChar == 47 && kind > 24)
kind = 24;
break;
case 41:
if ((0x7bff50f8ffffd9ffL & l) == 0L)
break;
if (kind > 20)
kind = 20;
{ jjCheckNAddStates(6, 10); }
break;
case 42:
if ((0x7bff78f8ffffd9ffL & l) == 0L)
break;
if (kind > 20)
kind = 20;
{ jjCheckNAddTwoStates(42, 43); }
break;
case 44:
if (kind > 20)
kind = 20;
{ jjCheckNAddTwoStates(42, 43); }
break;
case 45:
if ((0x7bff78f8ffffd9ffL & l) != 0L)
{ jjCheckNAddStates(18, 20); }
break;
case 47:
{ jjCheckNAddStates(18, 20); }
break;
default : break;
}
} while(i != startsAt);
}
else if (curChar < 128)
{
long l = 1L << (curChar & 077);
do
{
switch(jjstateSet[--i])
{
case 49:
if ((0x97ffffff87ffffffL & l) != 0L)
{
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
}
else if (curChar == 92)
{ jjCheckNAdd(35); }
break;
case 0:
if ((0x97ffffff87ffffffL & l) != 0L)
{
if (kind > 20)
kind = 20;
{ jjCheckNAddStates(6, 10); }
}
else if (curChar == 92)
{ jjCheckNAddStates(21, 23); }
else if (curChar == 126)
{
if (kind > 21)
kind = 21;
{ jjCheckNAddStates(24, 26); }
}
if ((0x97ffffff87ffffffL & l) != 0L)
{
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
}
if (curChar == 78)
jjstateSet[jjnewStateCnt++] = 11;
else if (curChar == 124)
jjstateSet[jjnewStateCnt++] = 8;
else if (curChar == 79)
jjstateSet[jjnewStateCnt++] = 6;
else if (curChar == 65)
jjstateSet[jjnewStateCnt++] = 2;
break;
case 1:
if (curChar == 68 && kind > 8)
kind = 8;
break;
case 2:
if (curChar == 78)
jjstateSet[jjnewStateCnt++] = 1;
break;
case 3:
if (curChar == 65)
jjstateSet[jjnewStateCnt++] = 2;
break;
case 6:
if (curChar == 82 && kind > 9)
kind = 9;
break;
case 7:
if (curChar == 79)
jjstateSet[jjnewStateCnt++] = 6;
break;
case 8:
if (curChar == 124 && kind > 9)
kind = 9;
break;
case 9:
if (curChar == 124)
jjstateSet[jjnewStateCnt++] = 8;
break;
case 10:
if (curChar == 84 && kind > 10)
kind = 10;
break;
case 11:
if (curChar == 79)
jjstateSet[jjnewStateCnt++] = 10;
break;
case 12:
if (curChar == 78)
jjstateSet[jjnewStateCnt++] = 11;
break;
case 17:
if ((0xffffffffefffffffL & l) != 0L)
{ jjCheckNAddStates(3, 5); }
break;
case 18:
if (curChar == 92)
jjstateSet[jjnewStateCnt++] = 19;
break;
case 19:
{ jjCheckNAddStates(3, 5); }
break;
case 21:
if (curChar != 126)
break;
if (kind > 21)
kind = 21;
{ jjCheckNAddStates(24, 26); }
break;
case 25:
if ((0x97ffffff87ffffffL & l) == 0L)
break;
if (kind > 21)
kind = 21;
{ jjCheckNAddTwoStates(25, 26); }
break;
case 26:
if (curChar == 92)
jjstateSet[jjnewStateCnt++] = 27;
break;
case 27:
if (kind > 21)
kind = 21;
{ jjCheckNAddTwoStates(25, 26); }
break;
case 28:
if ((0x97ffffff87ffffffL & l) == 0L)
break;
if (kind > 21)
kind = 21;
{ jjCheckNAddTwoStates(28, 29); }
break;
case 29:
if (curChar == 92)
jjstateSet[jjnewStateCnt++] = 30;
break;
case 30:
if (kind > 21)
kind = 21;
{ jjCheckNAddTwoStates(28, 29); }
break;
case 32:
if ((0x97ffffff87ffffffL & l) == 0L)
break;
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
break;
case 33:
if ((0x97ffffff87ffffffL & l) == 0L)
break;
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
break;
case 34:
if (curChar == 92)
{ jjCheckNAdd(35); }
break;
case 35:
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
break;
case 37:
{ jjAddStates(0, 2); }
break;
case 39:
if (curChar == 92)
jjstateSet[jjnewStateCnt++] = 38;
break;
case 41:
if ((0x97ffffff87ffffffL & l) == 0L)
break;
if (kind > 20)
kind = 20;
{ jjCheckNAddStates(6, 10); }
break;
case 42:
if ((0x97ffffff87ffffffL & l) == 0L)
break;
if (kind > 20)
kind = 20;
{ jjCheckNAddTwoStates(42, 43); }
break;
case 43:
if (curChar == 92)
{ jjCheckNAdd(44); }
break;
case 44:
if (kind > 20)
kind = 20;
{ jjCheckNAddTwoStates(42, 43); }
break;
case 45:
if ((0x97ffffff87ffffffL & l) != 0L)
{ jjCheckNAddStates(18, 20); }
break;
case 46:
if (curChar == 92)
{ jjCheckNAdd(47); }
break;
case 47:
{ jjCheckNAddStates(18, 20); }
break;
case 48:
if (curChar == 92)
{ jjCheckNAddStates(21, 23); }
break;
default : break;
}
} while(i != startsAt);
}
else
{
int hiByte = (curChar >> 8);
int i1 = hiByte >> 6;
long l1 = 1L << (hiByte & 077);
int i2 = (curChar & 0xff) >> 6;
long l2 = 1L << (curChar & 077);
do
{
switch(jjstateSet[--i])
{
case 49:
case 33:
if (!jjCanMove_2(hiByte, i1, i2, l1, l2))
break;
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
break;
case 0:
if (jjCanMove_0(hiByte, i1, i2, l1, l2))
{
if (kind > 7)
kind = 7;
}
if (jjCanMove_2(hiByte, i1, i2, l1, l2))
{
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
}
if (jjCanMove_2(hiByte, i1, i2, l1, l2))
{
if (kind > 20)
kind = 20;
{ jjCheckNAddStates(6, 10); }
}
break;
case 15:
if (jjCanMove_0(hiByte, i1, i2, l1, l2) && kind > 13)
kind = 13;
break;
case 17:
case 19:
if (jjCanMove_1(hiByte, i1, i2, l1, l2))
{ jjCheckNAddStates(3, 5); }
break;
case 25:
if (!jjCanMove_2(hiByte, i1, i2, l1, l2))
break;
if (kind > 21)
kind = 21;
{ jjCheckNAddTwoStates(25, 26); }
break;
case 27:
if (!jjCanMove_1(hiByte, i1, i2, l1, l2))
break;
if (kind > 21)
kind = 21;
{ jjCheckNAddTwoStates(25, 26); }
break;
case 28:
if (!jjCanMove_2(hiByte, i1, i2, l1, l2))
break;
if (kind > 21)
kind = 21;
{ jjCheckNAddTwoStates(28, 29); }
break;
case 30:
if (!jjCanMove_1(hiByte, i1, i2, l1, l2))
break;
if (kind > 21)
kind = 21;
{ jjCheckNAddTwoStates(28, 29); }
break;
case 32:
if (!jjCanMove_2(hiByte, i1, i2, l1, l2))
break;
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
break;
case 35:
if (!jjCanMove_1(hiByte, i1, i2, l1, l2))
break;
if (kind > 23)
kind = 23;
{ jjCheckNAddTwoStates(33, 34); }
break;
case 37:
if (jjCanMove_1(hiByte, i1, i2, l1, l2))
{ jjAddStates(0, 2); }
break;
case 41:
if (!jjCanMove_2(hiByte, i1, i2, l1, l2))
break;
if (kind > 20)
kind = 20;
{ jjCheckNAddStates(6, 10); }
break;
case 42:
if (!jjCanMove_2(hiByte, i1, i2, l1, l2))
break;
if (kind > 20)
kind = 20;
{ jjCheckNAddTwoStates(42, 43); }
break;
case 44:
if (!jjCanMove_1(hiByte, i1, i2, l1, l2))
break;
if (kind > 20)
kind = 20;
{ jjCheckNAddTwoStates(42, 43); }
break;
case 45:
if (jjCanMove_2(hiByte, i1, i2, l1, l2))
{ jjCheckNAddStates(18, 20); }
break;
case 47:
if (jjCanMove_1(hiByte, i1, i2, l1, l2))
{ jjCheckNAddStates(18, 20); }
break;
default : if (i1 == 0 || l1 == 0 || i2 == 0 || l2 == 0) break; else break;
}
} while(i != startsAt);
}
if (kind != 0x7fffffff)
{
jjmatchedKind = kind;
jjmatchedPos = curPos;
kind = 0x7fffffff;
}
++curPos;
if ((i = jjnewStateCnt) == (startsAt = 49 - (jjnewStateCnt = startsAt)))
return curPos;
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) { return curPos; }
}
}
private int jjMoveStringLiteralDfa0_0()
{
return jjMoveNfa_0(0, 0);
}
private int jjMoveNfa_0(int startState, int curPos)
{
int startsAt = 0;
jjnewStateCnt = 3;
int i = 1;
jjstateSet[0] = startState;
int kind = 0x7fffffff;
for (;;)
{
if (++jjround == 0x7fffffff)
ReInitRounds();
if (curChar < 64)
{
long l = 1L << curChar;
do
{
switch(jjstateSet[--i])
{
case 0:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 27)
kind = 27;
{ jjAddStates(27, 28); }
break;
case 1:
if (curChar == 46)
{ jjCheckNAdd(2); }
break;
case 2:
if ((0x3ff000000000000L & l) == 0L)
break;
if (kind > 27)
kind = 27;
{ jjCheckNAdd(2); }
break;
default : break;
}
} while(i != startsAt);
}
else if (curChar < 128)
{
long l = 1L << (curChar & 077);
do
{
switch(jjstateSet[--i])
{
default : break;
}
} while(i != startsAt);
}
else
{
int hiByte = (curChar >> 8);
int i1 = hiByte >> 6;
long l1 = 1L << (hiByte & 077);
int i2 = (curChar & 0xff) >> 6;
long l2 = 1L << (curChar & 077);
do
{
switch(jjstateSet[--i])
{
default : if (i1 == 0 || l1 == 0 || i2 == 0 || l2 == 0) break; else break;
}
} while(i != startsAt);
}
if (kind != 0x7fffffff)
{
jjmatchedKind = kind;
jjmatchedPos = curPos;
kind = 0x7fffffff;
}
++curPos;
if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
return curPos;
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) { return curPos; }
}
}
private final int jjStopStringLiteralDfa_1(int pos, long active0){
switch (pos)
{
case 0:
if ((active0 & 0x10000000L) != 0L)
{
jjmatchedKind = 32;
return 6;
}
return -1;
default :
return -1;
}
}
private final int jjStartNfa_1(int pos, long active0){
return jjMoveNfa_1(jjStopStringLiteralDfa_1(pos, active0), pos + 1);
}
private int jjMoveStringLiteralDfa0_1(){
switch(curChar)
{
case 84:
return jjMoveStringLiteralDfa1_1(0x10000000L);
case 93:
return jjStopAtPos(0, 29);
case 125:
return jjStopAtPos(0, 30);
default :
return jjMoveNfa_1(0, 0);
}
}
private int jjMoveStringLiteralDfa1_1(long active0){
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_1(0, active0);
return 1;
}
switch(curChar)
{
case 79:
if ((active0 & 0x10000000L) != 0L)
return jjStartNfaWithStates_1(1, 28, 6);
break;
default :
break;
}
return jjStartNfa_1(0, active0);
}
private int jjStartNfaWithStates_1(int pos, int kind, int state)
{
jjmatchedKind = kind;
jjmatchedPos = pos;
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) { return pos + 1; }
return jjMoveNfa_1(state, pos + 1);
}
private int jjMoveNfa_1(int startState, int curPos)
{
int startsAt = 0;
jjnewStateCnt = 7;
int i = 1;
jjstateSet[0] = startState;
int kind = 0x7fffffff;
for (;;)
{
if (++jjround == 0x7fffffff)
ReInitRounds();
if (curChar < 64)
{
long l = 1L << curChar;
do
{
switch(jjstateSet[--i])
{
case 0:
if ((0xfffffffeffffffffL & l) != 0L)
{
if (kind > 32)
kind = 32;
{ jjCheckNAdd(6); }
}
if ((0x100002600L & l) != 0L)
{
if (kind > 7)
kind = 7;
}
else if (curChar == 34)
{ jjCheckNAddTwoStates(2, 4); }
break;
case 1:
if (curChar == 34)
{ jjCheckNAddTwoStates(2, 4); }
break;
case 2:
if ((0xfffffffbffffffffL & l) != 0L)
{ jjCheckNAddStates(29, 31); }
break;
case 3:
if (curChar == 34)
{ jjCheckNAddStates(29, 31); }
break;
case 5:
if (curChar == 34 && kind > 31)
kind = 31;
break;
case 6:
if ((0xfffffffeffffffffL & l) == 0L)
break;
if (kind > 32)
kind = 32;
{ jjCheckNAdd(6); }
break;
default : break;
}
} while(i != startsAt);
}
else if (curChar < 128)
{
long l = 1L << (curChar & 077);
do
{
switch(jjstateSet[--i])
{
case 0:
case 6:
if ((0xdfffffffdfffffffL & l) == 0L)
break;
if (kind > 32)
kind = 32;
{ jjCheckNAdd(6); }
break;
case 2:
{ jjAddStates(29, 31); }
break;
case 4:
if (curChar == 92)
jjstateSet[jjnewStateCnt++] = 3;
break;
default : break;
}
} while(i != startsAt);
}
else
{
int hiByte = (curChar >> 8);
int i1 = hiByte >> 6;
long l1 = 1L << (hiByte & 077);
int i2 = (curChar & 0xff) >> 6;
long l2 = 1L << (curChar & 077);
do
{
switch(jjstateSet[--i])
{
case 0:
if (jjCanMove_0(hiByte, i1, i2, l1, l2))
{
if (kind > 7)
kind = 7;
}
if (jjCanMove_1(hiByte, i1, i2, l1, l2))
{
if (kind > 32)
kind = 32;
{ jjCheckNAdd(6); }
}
break;
case 2:
if (jjCanMove_1(hiByte, i1, i2, l1, l2))
{ jjAddStates(29, 31); }
break;
case 6:
if (!jjCanMove_1(hiByte, i1, i2, l1, l2))
break;
if (kind > 32)
kind = 32;
{ jjCheckNAdd(6); }
break;
default : if (i1 == 0 || l1 == 0 || i2 == 0 || l2 == 0) break; else break;
}
} while(i != startsAt);
}
if (kind != 0x7fffffff)
{
jjmatchedKind = kind;
jjmatchedPos = curPos;
kind = 0x7fffffff;
}
++curPos;
if ((i = jjnewStateCnt) == (startsAt = 7 - (jjnewStateCnt = startsAt)))
return curPos;
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) { return curPos; }
}
}
/** Token literal values. */
public static final String[] jjstrLiteralImages = {
"", null, null, null, null, null, null, null, null, null, null, "\53", "\55",
null, "\50", "\51", "\72", "\52", "\136", null, null, null, null, null, null,
"\133", "\173", null, "\124\117", "\135", "\175", null, null, };
protected Token jjFillToken()
{
final Token t;
final String curTokenImage;
final int beginLine;
final int endLine;
final int beginColumn;
final int endColumn;
String im = jjstrLiteralImages[jjmatchedKind];
curTokenImage = (im == null) ? input_stream.GetImage() : im;
beginLine = input_stream.getBeginLine();
beginColumn = input_stream.getBeginColumn();
endLine = input_stream.getEndLine();
endColumn = input_stream.getEndColumn();
t = Token.newToken(jjmatchedKind, curTokenImage);
t.beginLine = beginLine;
t.endLine = endLine;
t.beginColumn = beginColumn;
t.endColumn = endColumn;
return t;
}
static final int[] jjnextStates = {
37, 39, 40, 17, 18, 20, 42, 43, 45, 46, 31, 22, 23, 25, 26, 24,
25, 26, 45, 46, 31, 44, 47, 35, 22, 28, 29, 0, 1, 2, 4, 5,
};
private static final boolean jjCanMove_0(int hiByte, int i1, int i2, long l1, long l2)
{
switch(hiByte)
{
case 48:
return ((jjbitVec0[i2] & l2) != 0L);
default :
return false;
}
}
private static final boolean jjCanMove_1(int hiByte, int i1, int i2, long l1, long l2)
{
switch(hiByte)
{
case 0:
return ((jjbitVec3[i2] & l2) != 0L);
default :
if ((jjbitVec1[i1] & l1) != 0L)
return true;
return false;
}
}
private static final boolean jjCanMove_2(int hiByte, int i1, int i2, long l1, long l2)
{
switch(hiByte)
{
case 0:
return ((jjbitVec3[i2] & l2) != 0L);
case 48:
return ((jjbitVec1[i2] & l2) != 0L);
default :
if ((jjbitVec4[i1] & l1) != 0L)
return true;
return false;
}
}
int curLexState = 2;
int defaultLexState = 2;
int jjnewStateCnt;
int jjround;
int jjmatchedPos;
int jjmatchedKind;
/** Get the next Token. */
public Token getNextToken()
{
Token matchedToken;
int curPos = 0;
EOFLoop :
for (;;)
{
try
{
curChar = input_stream.BeginToken();
}
catch(Exception e)
{
jjmatchedKind = 0;
jjmatchedPos = -1;
matchedToken = jjFillToken();
return matchedToken;
}
switch(curLexState)
{
case 0:
jjmatchedKind = 0x7fffffff;
jjmatchedPos = 0;
curPos = jjMoveStringLiteralDfa0_0();
break;
case 1:
jjmatchedKind = 0x7fffffff;
jjmatchedPos = 0;
curPos = jjMoveStringLiteralDfa0_1();
break;
case 2:
jjmatchedKind = 0x7fffffff;
jjmatchedPos = 0;
curPos = jjMoveStringLiteralDfa0_2();
break;
}
if (jjmatchedKind != 0x7fffffff)
{
if (jjmatchedPos + 1 < curPos)
input_stream.backup(curPos - jjmatchedPos - 1);
if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
{
matchedToken = jjFillToken();
if (jjnewLexState[jjmatchedKind] != -1)
curLexState = jjnewLexState[jjmatchedKind];
return matchedToken;
}
else
{
if (jjnewLexState[jjmatchedKind] != -1)
curLexState = jjnewLexState[jjmatchedKind];
continue EOFLoop;
}
}
int error_line = input_stream.getEndLine();
int error_column = input_stream.getEndColumn();
String error_after = null;
boolean EOFSeen = false;
try { input_stream.readChar(); input_stream.backup(1); }
catch (java.io.IOException e1) {
EOFSeen = true;
error_after = curPos <= 1 ? "" : input_stream.GetImage();
if (curChar == '\n' || curChar == '\r') {
error_line++;
error_column = 0;
}
else
error_column++;
}
if (!EOFSeen) {
input_stream.backup(1);
error_after = curPos <= 1 ? "" : input_stream.GetImage();
}
throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);
}
}
void SkipLexicalActions(Token matchedToken)
{
switch(jjmatchedKind)
{
default :
break;
}
}
void MoreLexicalActions()
{
jjimageLen += (lengthOfMatch = jjmatchedPos + 1);
switch(jjmatchedKind)
{
default :
break;
}
}
void TokenLexicalActions(Token matchedToken)
{
switch(jjmatchedKind)
{
default :
break;
}
}
private void jjCheckNAdd(int state)
{
if (jjrounds[state] != jjround)
{
jjstateSet[jjnewStateCnt++] = state;
jjrounds[state] = jjround;
}
}
private void jjAddStates(int start, int end)
{
do {
jjstateSet[jjnewStateCnt++] = jjnextStates[start];
} while (start++ != end);
}
private void jjCheckNAddTwoStates(int state1, int state2)
{
jjCheckNAdd(state1);
jjCheckNAdd(state2);
}
private void jjCheckNAddStates(int start, int end)
{
do {
jjCheckNAdd(jjnextStates[start]);
} while (start++ != end);
}
/** Constructor. */
public QueryParserTokenManager(CharStream stream){
input_stream = stream;
}
/** Constructor. */
public QueryParserTokenManager (CharStream stream, int lexState){
ReInit(stream);
SwitchTo(lexState);
}
/** Reinitialise parser. */
public void ReInit(CharStream stream)
{
jjmatchedPos =
jjnewStateCnt =
0;
curLexState = defaultLexState;
input_stream = stream;
ReInitRounds();
}
private void ReInitRounds()
{
int i;
jjround = 0x80000001;
for (i = 49; i-- > 0;)
jjrounds[i] = 0x80000000;
}
/** Reinitialise parser. */
public void ReInit(CharStream stream, int lexState)
{
ReInit(stream);
SwitchTo(lexState);
}
/** Switch to specified lex state. */
public void SwitchTo(int lexState)
{
if (lexState >= 3 || lexState < 0)
throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);
else
curLexState = lexState;
}
/** Lexer state names. */
public static final String[] lexStateNames = {
"Boost",
"Range",
"DEFAULT",
};
/** Lex State array. */
public static final int[] jjnewLexState = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1,
1, 1, 2, -1, 2, 2, -1, -1,
};
static final long[] jjtoToken = {
0x1ffffff01L,
};
static final long[] jjtoSkip = {
0x80L,
};
static final long[] jjtoSpecial = {
0x0L,
};
static final long[] jjtoMore = {
0x0L,
};
protected CharStream input_stream;
private final int[] jjrounds = new int[49];
private final int[] jjstateSet = new int[2 * 49];
private final StringBuilder jjimage = new StringBuilder();
private StringBuilder image = jjimage;
private int jjimageLen;
private int lengthOfMatch;
protected int curChar;
}
|
googleapis/google-cloud-java | 35,856 | java-resourcemanager/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/v3/stub/TagKeysStubSettings.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.resourcemanager.v3.stub;
import static com.google.cloud.resourcemanager.v3.TagKeysClient.ListTagKeysPagedResponse;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.BetaApi;
import com.google.api.core.ObsoleteApi;
import com.google.api.gax.core.GaxProperties;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.GaxGrpcProperties;
import com.google.api.gax.grpc.GrpcTransportChannel;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.grpc.ProtoOperationTransformers;
import com.google.api.gax.httpjson.GaxHttpJsonProperties;
import com.google.api.gax.httpjson.HttpJsonTransportChannel;
import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider;
import com.google.api.gax.longrunning.OperationSnapshot;
import com.google.api.gax.longrunning.OperationTimedPollAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.gax.rpc.ApiCallContext;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.PageContext;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.PagedListDescriptor;
import com.google.api.gax.rpc.PagedListResponseFactory;
import com.google.api.gax.rpc.StatusCode;
import com.google.api.gax.rpc.StubSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.api.gax.rpc.UnaryCallable;
import com.google.cloud.resourcemanager.v3.CreateTagKeyMetadata;
import com.google.cloud.resourcemanager.v3.CreateTagKeyRequest;
import com.google.cloud.resourcemanager.v3.DeleteTagKeyMetadata;
import com.google.cloud.resourcemanager.v3.DeleteTagKeyRequest;
import com.google.cloud.resourcemanager.v3.GetNamespacedTagKeyRequest;
import com.google.cloud.resourcemanager.v3.GetTagKeyRequest;
import com.google.cloud.resourcemanager.v3.ListTagKeysRequest;
import com.google.cloud.resourcemanager.v3.ListTagKeysResponse;
import com.google.cloud.resourcemanager.v3.TagKey;
import com.google.cloud.resourcemanager.v3.UpdateTagKeyMetadata;
import com.google.cloud.resourcemanager.v3.UpdateTagKeyRequest;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
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.longrunning.Operation;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link TagKeysStub}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (cloudresourcemanager.googleapis.com) and default port (443)
* are used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the
* [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings)
* of getTagKey:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* TagKeysStubSettings.Builder tagKeysSettingsBuilder = TagKeysStubSettings.newBuilder();
* tagKeysSettingsBuilder
* .getTagKeySettings()
* .setRetrySettings(
* tagKeysSettingsBuilder
* .getTagKeySettings()
* .getRetrySettings()
* .toBuilder()
* .setInitialRetryDelayDuration(Duration.ofSeconds(1))
* .setInitialRpcTimeoutDuration(Duration.ofSeconds(5))
* .setMaxAttempts(5)
* .setMaxRetryDelayDuration(Duration.ofSeconds(30))
* .setMaxRpcTimeoutDuration(Duration.ofSeconds(60))
* .setRetryDelayMultiplier(1.3)
* .setRpcTimeoutMultiplier(1.5)
* .setTotalTimeoutDuration(Duration.ofSeconds(300))
* .build());
* TagKeysStubSettings tagKeysSettings = tagKeysSettingsBuilder.build();
* }</pre>
*
* Please refer to the [Client Side Retry
* Guide](https://github.com/googleapis/google-cloud-java/blob/main/docs/client_retries.md) for
* additional support in setting retries.
*
* <p>To configure the RetrySettings of a Long Running Operation method, create an
* OperationTimedPollAlgorithm object and update the RPC's polling algorithm. For example, to
* configure the RetrySettings for createTagKey:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* TagKeysStubSettings.Builder tagKeysSettingsBuilder = TagKeysStubSettings.newBuilder();
* TimedRetryAlgorithm timedRetryAlgorithm =
* OperationalTimedPollAlgorithm.create(
* RetrySettings.newBuilder()
* .setInitialRetryDelayDuration(Duration.ofMillis(500))
* .setRetryDelayMultiplier(1.5)
* .setMaxRetryDelayDuration(Duration.ofMillis(5000))
* .setTotalTimeoutDuration(Duration.ofHours(24))
* .build());
* tagKeysSettingsBuilder
* .createClusterOperationSettings()
* .setPollingAlgorithm(timedRetryAlgorithm)
* .build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class TagKeysStubSettings extends StubSettings<TagKeysStubSettings> {
/** The default scopes of the service. */
private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES =
ImmutableList.<String>builder()
.add("https://www.googleapis.com/auth/cloud-platform")
.add("https://www.googleapis.com/auth/cloud-platform.read-only")
.build();
private final PagedCallSettings<ListTagKeysRequest, ListTagKeysResponse, ListTagKeysPagedResponse>
listTagKeysSettings;
private final UnaryCallSettings<GetTagKeyRequest, TagKey> getTagKeySettings;
private final UnaryCallSettings<GetNamespacedTagKeyRequest, TagKey> getNamespacedTagKeySettings;
private final UnaryCallSettings<CreateTagKeyRequest, Operation> createTagKeySettings;
private final OperationCallSettings<CreateTagKeyRequest, TagKey, CreateTagKeyMetadata>
createTagKeyOperationSettings;
private final UnaryCallSettings<UpdateTagKeyRequest, Operation> updateTagKeySettings;
private final OperationCallSettings<UpdateTagKeyRequest, TagKey, UpdateTagKeyMetadata>
updateTagKeyOperationSettings;
private final UnaryCallSettings<DeleteTagKeyRequest, Operation> deleteTagKeySettings;
private final OperationCallSettings<DeleteTagKeyRequest, TagKey, DeleteTagKeyMetadata>
deleteTagKeyOperationSettings;
private final UnaryCallSettings<GetIamPolicyRequest, Policy> getIamPolicySettings;
private final UnaryCallSettings<SetIamPolicyRequest, Policy> setIamPolicySettings;
private final UnaryCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsSettings;
private static final PagedListDescriptor<ListTagKeysRequest, ListTagKeysResponse, TagKey>
LIST_TAG_KEYS_PAGE_STR_DESC =
new PagedListDescriptor<ListTagKeysRequest, ListTagKeysResponse, TagKey>() {
@Override
public String emptyToken() {
return "";
}
@Override
public ListTagKeysRequest injectToken(ListTagKeysRequest payload, String token) {
return ListTagKeysRequest.newBuilder(payload).setPageToken(token).build();
}
@Override
public ListTagKeysRequest injectPageSize(ListTagKeysRequest payload, int pageSize) {
return ListTagKeysRequest.newBuilder(payload).setPageSize(pageSize).build();
}
@Override
public Integer extractPageSize(ListTagKeysRequest payload) {
return payload.getPageSize();
}
@Override
public String extractNextToken(ListTagKeysResponse payload) {
return payload.getNextPageToken();
}
@Override
public Iterable<TagKey> extractResources(ListTagKeysResponse payload) {
return payload.getTagKeysList();
}
};
private static final PagedListResponseFactory<
ListTagKeysRequest, ListTagKeysResponse, ListTagKeysPagedResponse>
LIST_TAG_KEYS_PAGE_STR_FACT =
new PagedListResponseFactory<
ListTagKeysRequest, ListTagKeysResponse, ListTagKeysPagedResponse>() {
@Override
public ApiFuture<ListTagKeysPagedResponse> getFuturePagedResponse(
UnaryCallable<ListTagKeysRequest, ListTagKeysResponse> callable,
ListTagKeysRequest request,
ApiCallContext context,
ApiFuture<ListTagKeysResponse> futureResponse) {
PageContext<ListTagKeysRequest, ListTagKeysResponse, TagKey> pageContext =
PageContext.create(callable, LIST_TAG_KEYS_PAGE_STR_DESC, request, context);
return ListTagKeysPagedResponse.createAsync(pageContext, futureResponse);
}
};
/** Returns the object with the settings used for calls to listTagKeys. */
public PagedCallSettings<ListTagKeysRequest, ListTagKeysResponse, ListTagKeysPagedResponse>
listTagKeysSettings() {
return listTagKeysSettings;
}
/** Returns the object with the settings used for calls to getTagKey. */
public UnaryCallSettings<GetTagKeyRequest, TagKey> getTagKeySettings() {
return getTagKeySettings;
}
/** Returns the object with the settings used for calls to getNamespacedTagKey. */
public UnaryCallSettings<GetNamespacedTagKeyRequest, TagKey> getNamespacedTagKeySettings() {
return getNamespacedTagKeySettings;
}
/** Returns the object with the settings used for calls to createTagKey. */
public UnaryCallSettings<CreateTagKeyRequest, Operation> createTagKeySettings() {
return createTagKeySettings;
}
/** Returns the object with the settings used for calls to createTagKey. */
public OperationCallSettings<CreateTagKeyRequest, TagKey, CreateTagKeyMetadata>
createTagKeyOperationSettings() {
return createTagKeyOperationSettings;
}
/** Returns the object with the settings used for calls to updateTagKey. */
public UnaryCallSettings<UpdateTagKeyRequest, Operation> updateTagKeySettings() {
return updateTagKeySettings;
}
/** Returns the object with the settings used for calls to updateTagKey. */
public OperationCallSettings<UpdateTagKeyRequest, TagKey, UpdateTagKeyMetadata>
updateTagKeyOperationSettings() {
return updateTagKeyOperationSettings;
}
/** Returns the object with the settings used for calls to deleteTagKey. */
public UnaryCallSettings<DeleteTagKeyRequest, Operation> deleteTagKeySettings() {
return deleteTagKeySettings;
}
/** Returns the object with the settings used for calls to deleteTagKey. */
public OperationCallSettings<DeleteTagKeyRequest, TagKey, DeleteTagKeyMetadata>
deleteTagKeyOperationSettings() {
return deleteTagKeyOperationSettings;
}
/** Returns the object with the settings used for calls to getIamPolicy. */
public UnaryCallSettings<GetIamPolicyRequest, Policy> getIamPolicySettings() {
return getIamPolicySettings;
}
/** Returns the object with the settings used for calls to setIamPolicy. */
public UnaryCallSettings<SetIamPolicyRequest, Policy> setIamPolicySettings() {
return setIamPolicySettings;
}
/** Returns the object with the settings used for calls to testIamPermissions. */
public UnaryCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsSettings() {
return testIamPermissionsSettings;
}
public TagKeysStub createStub() throws IOException {
if (getTransportChannelProvider()
.getTransportName()
.equals(GrpcTransportChannel.getGrpcTransportName())) {
return GrpcTagKeysStub.create(this);
}
if (getTransportChannelProvider()
.getTransportName()
.equals(HttpJsonTransportChannel.getHttpJsonTransportName())) {
return HttpJsonTagKeysStub.create(this);
}
throw new UnsupportedOperationException(
String.format(
"Transport not supported: %s", getTransportChannelProvider().getTransportName()));
}
/** Returns the default service name. */
@Override
public String getServiceName() {
return "cloudresourcemanager";
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return InstantiatingExecutorProvider.newBuilder();
}
/** Returns the default service endpoint. */
@ObsoleteApi("Use getEndpoint() instead")
public static String getDefaultEndpoint() {
return "cloudresourcemanager.googleapis.com:443";
}
/** Returns the default mTLS service endpoint. */
public static String getDefaultMtlsEndpoint() {
return "cloudresourcemanager.mtls.googleapis.com:443";
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return DEFAULT_SERVICE_SCOPES;
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return GoogleCredentialsProvider.newBuilder()
.setScopesToApply(DEFAULT_SERVICE_SCOPES)
.setUseJwtAccessWithScope(true);
}
/** Returns a builder for the default gRPC ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return InstantiatingGrpcChannelProvider.newBuilder()
.setMaxInboundMessageSize(Integer.MAX_VALUE);
}
/** Returns a builder for the default REST ChannelProvider for this service. */
@BetaApi
public static InstantiatingHttpJsonChannelProvider.Builder
defaultHttpJsonTransportProviderBuilder() {
return InstantiatingHttpJsonChannelProvider.newBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return defaultGrpcTransportProviderBuilder().build();
}
public static ApiClientHeaderProvider.Builder defaultGrpcApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken("gapic", GaxProperties.getLibraryVersion(TagKeysStubSettings.class))
.setTransportToken(
GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion());
}
public static ApiClientHeaderProvider.Builder defaultHttpJsonApiClientHeaderProviderBuilder() {
return ApiClientHeaderProvider.newBuilder()
.setGeneratedLibToken("gapic", GaxProperties.getLibraryVersion(TagKeysStubSettings.class))
.setTransportToken(
GaxHttpJsonProperties.getHttpJsonTokenName(),
GaxHttpJsonProperties.getHttpJsonVersion());
}
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return TagKeysStubSettings.defaultGrpcApiClientHeaderProviderBuilder();
}
/** Returns a new gRPC builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new REST builder for this class. */
public static Builder newHttpJsonBuilder() {
return Builder.createHttpJsonDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected TagKeysStubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
listTagKeysSettings = settingsBuilder.listTagKeysSettings().build();
getTagKeySettings = settingsBuilder.getTagKeySettings().build();
getNamespacedTagKeySettings = settingsBuilder.getNamespacedTagKeySettings().build();
createTagKeySettings = settingsBuilder.createTagKeySettings().build();
createTagKeyOperationSettings = settingsBuilder.createTagKeyOperationSettings().build();
updateTagKeySettings = settingsBuilder.updateTagKeySettings().build();
updateTagKeyOperationSettings = settingsBuilder.updateTagKeyOperationSettings().build();
deleteTagKeySettings = settingsBuilder.deleteTagKeySettings().build();
deleteTagKeyOperationSettings = settingsBuilder.deleteTagKeyOperationSettings().build();
getIamPolicySettings = settingsBuilder.getIamPolicySettings().build();
setIamPolicySettings = settingsBuilder.setIamPolicySettings().build();
testIamPermissionsSettings = settingsBuilder.testIamPermissionsSettings().build();
}
/** Builder for TagKeysStubSettings. */
public static class Builder extends StubSettings.Builder<TagKeysStubSettings, Builder> {
private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders;
private final PagedCallSettings.Builder<
ListTagKeysRequest, ListTagKeysResponse, ListTagKeysPagedResponse>
listTagKeysSettings;
private final UnaryCallSettings.Builder<GetTagKeyRequest, TagKey> getTagKeySettings;
private final UnaryCallSettings.Builder<GetNamespacedTagKeyRequest, TagKey>
getNamespacedTagKeySettings;
private final UnaryCallSettings.Builder<CreateTagKeyRequest, Operation> createTagKeySettings;
private final OperationCallSettings.Builder<CreateTagKeyRequest, TagKey, CreateTagKeyMetadata>
createTagKeyOperationSettings;
private final UnaryCallSettings.Builder<UpdateTagKeyRequest, Operation> updateTagKeySettings;
private final OperationCallSettings.Builder<UpdateTagKeyRequest, TagKey, UpdateTagKeyMetadata>
updateTagKeyOperationSettings;
private final UnaryCallSettings.Builder<DeleteTagKeyRequest, Operation> deleteTagKeySettings;
private final OperationCallSettings.Builder<DeleteTagKeyRequest, TagKey, DeleteTagKeyMetadata>
deleteTagKeyOperationSettings;
private final UnaryCallSettings.Builder<GetIamPolicyRequest, Policy> getIamPolicySettings;
private final UnaryCallSettings.Builder<SetIamPolicyRequest, Policy> setIamPolicySettings;
private final UnaryCallSettings.Builder<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsSettings;
private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>>
RETRYABLE_CODE_DEFINITIONS;
static {
ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions =
ImmutableMap.builder();
definitions.put(
"retry_policy_0_codes",
ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList(StatusCode.Code.UNAVAILABLE)));
definitions.put("no_retry_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
definitions.put(
"no_retry_1_codes", ImmutableSet.copyOf(Lists.<StatusCode.Code>newArrayList()));
RETRYABLE_CODE_DEFINITIONS = definitions.build();
}
private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS;
static {
ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder();
RetrySettings settings = null;
settings =
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(100L))
.setRetryDelayMultiplier(1.3)
.setMaxRetryDelayDuration(Duration.ofMillis(60000L))
.setInitialRpcTimeoutDuration(Duration.ofMillis(60000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(60000L))
.setTotalTimeoutDuration(Duration.ofMillis(60000L))
.build();
definitions.put("retry_policy_0_params", settings);
settings = RetrySettings.newBuilder().setRpcTimeoutMultiplier(1.0).build();
definitions.put("no_retry_params", settings);
settings =
RetrySettings.newBuilder()
.setInitialRpcTimeoutDuration(Duration.ofMillis(60000L))
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ofMillis(60000L))
.setTotalTimeoutDuration(Duration.ofMillis(60000L))
.build();
definitions.put("no_retry_1_params", settings);
RETRY_PARAM_DEFINITIONS = definitions.build();
}
protected Builder() {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(clientContext);
listTagKeysSettings = PagedCallSettings.newBuilder(LIST_TAG_KEYS_PAGE_STR_FACT);
getTagKeySettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
getNamespacedTagKeySettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
createTagKeySettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
createTagKeyOperationSettings = OperationCallSettings.newBuilder();
updateTagKeySettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
updateTagKeyOperationSettings = OperationCallSettings.newBuilder();
deleteTagKeySettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
deleteTagKeyOperationSettings = OperationCallSettings.newBuilder();
getIamPolicySettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
setIamPolicySettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
testIamPermissionsSettings = UnaryCallSettings.newUnaryCallSettingsBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
listTagKeysSettings,
getTagKeySettings,
getNamespacedTagKeySettings,
createTagKeySettings,
updateTagKeySettings,
deleteTagKeySettings,
getIamPolicySettings,
setIamPolicySettings,
testIamPermissionsSettings);
initDefaults(this);
}
protected Builder(TagKeysStubSettings settings) {
super(settings);
listTagKeysSettings = settings.listTagKeysSettings.toBuilder();
getTagKeySettings = settings.getTagKeySettings.toBuilder();
getNamespacedTagKeySettings = settings.getNamespacedTagKeySettings.toBuilder();
createTagKeySettings = settings.createTagKeySettings.toBuilder();
createTagKeyOperationSettings = settings.createTagKeyOperationSettings.toBuilder();
updateTagKeySettings = settings.updateTagKeySettings.toBuilder();
updateTagKeyOperationSettings = settings.updateTagKeyOperationSettings.toBuilder();
deleteTagKeySettings = settings.deleteTagKeySettings.toBuilder();
deleteTagKeyOperationSettings = settings.deleteTagKeyOperationSettings.toBuilder();
getIamPolicySettings = settings.getIamPolicySettings.toBuilder();
setIamPolicySettings = settings.setIamPolicySettings.toBuilder();
testIamPermissionsSettings = settings.testIamPermissionsSettings.toBuilder();
unaryMethodSettingsBuilders =
ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(
listTagKeysSettings,
getTagKeySettings,
getNamespacedTagKeySettings,
createTagKeySettings,
updateTagKeySettings,
deleteTagKeySettings,
getIamPolicySettings,
setIamPolicySettings,
testIamPermissionsSettings);
}
private static Builder createDefault() {
Builder builder = new Builder(((ClientContext) null));
builder.setTransportChannelProvider(defaultTransportChannelProvider());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build());
builder.setMtlsEndpoint(getDefaultMtlsEndpoint());
builder.setSwitchToMtlsEndpointAllowed(true);
return initDefaults(builder);
}
private static Builder createHttpJsonDefault() {
Builder builder = new Builder(((ClientContext) null));
builder.setTransportChannelProvider(defaultHttpJsonTransportProviderBuilder().build());
builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
builder.setInternalHeaderProvider(defaultHttpJsonApiClientHeaderProviderBuilder().build());
builder.setMtlsEndpoint(getDefaultMtlsEndpoint());
builder.setSwitchToMtlsEndpointAllowed(true);
return initDefaults(builder);
}
private static Builder initDefaults(Builder builder) {
builder
.listTagKeysSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.getTagKeySettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.getNamespacedTagKeySettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params"));
builder
.createTagKeySettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.updateTagKeySettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.deleteTagKeySettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.getIamPolicySettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params"));
builder
.setIamPolicySettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"));
builder
.testIamPermissionsSettings()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_params"));
builder
.createTagKeyOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<CreateTagKeyRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(TagKey.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(CreateTagKeyMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(45000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(300000L))
.build()));
builder
.updateTagKeyOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<UpdateTagKeyRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(TagKey.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(UpdateTagKeyMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(45000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(300000L))
.build()));
builder
.deleteTagKeyOperationSettings()
.setInitialCallSettings(
UnaryCallSettings
.<DeleteTagKeyRequest, OperationSnapshot>newUnaryCallSettingsBuilder()
.setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("no_retry_1_codes"))
.setRetrySettings(RETRY_PARAM_DEFINITIONS.get("no_retry_1_params"))
.build())
.setResponseTransformer(
ProtoOperationTransformers.ResponseTransformer.create(TagKey.class))
.setMetadataTransformer(
ProtoOperationTransformers.MetadataTransformer.create(DeleteTagKeyMetadata.class))
.setPollingAlgorithm(
OperationTimedPollAlgorithm.create(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ofMillis(5000L))
.setRetryDelayMultiplier(1.5)
.setMaxRetryDelayDuration(Duration.ofMillis(45000L))
.setInitialRpcTimeoutDuration(Duration.ZERO)
.setRpcTimeoutMultiplier(1.0)
.setMaxRpcTimeoutDuration(Duration.ZERO)
.setTotalTimeoutDuration(Duration.ofMillis(300000L))
.build()));
return builder;
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater);
return this;
}
public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() {
return unaryMethodSettingsBuilders;
}
/** Returns the builder for the settings used for calls to listTagKeys. */
public PagedCallSettings.Builder<
ListTagKeysRequest, ListTagKeysResponse, ListTagKeysPagedResponse>
listTagKeysSettings() {
return listTagKeysSettings;
}
/** Returns the builder for the settings used for calls to getTagKey. */
public UnaryCallSettings.Builder<GetTagKeyRequest, TagKey> getTagKeySettings() {
return getTagKeySettings;
}
/** Returns the builder for the settings used for calls to getNamespacedTagKey. */
public UnaryCallSettings.Builder<GetNamespacedTagKeyRequest, TagKey>
getNamespacedTagKeySettings() {
return getNamespacedTagKeySettings;
}
/** Returns the builder for the settings used for calls to createTagKey. */
public UnaryCallSettings.Builder<CreateTagKeyRequest, Operation> createTagKeySettings() {
return createTagKeySettings;
}
/** Returns the builder for the settings used for calls to createTagKey. */
public OperationCallSettings.Builder<CreateTagKeyRequest, TagKey, CreateTagKeyMetadata>
createTagKeyOperationSettings() {
return createTagKeyOperationSettings;
}
/** Returns the builder for the settings used for calls to updateTagKey. */
public UnaryCallSettings.Builder<UpdateTagKeyRequest, Operation> updateTagKeySettings() {
return updateTagKeySettings;
}
/** Returns the builder for the settings used for calls to updateTagKey. */
public OperationCallSettings.Builder<UpdateTagKeyRequest, TagKey, UpdateTagKeyMetadata>
updateTagKeyOperationSettings() {
return updateTagKeyOperationSettings;
}
/** Returns the builder for the settings used for calls to deleteTagKey. */
public UnaryCallSettings.Builder<DeleteTagKeyRequest, Operation> deleteTagKeySettings() {
return deleteTagKeySettings;
}
/** Returns the builder for the settings used for calls to deleteTagKey. */
public OperationCallSettings.Builder<DeleteTagKeyRequest, TagKey, DeleteTagKeyMetadata>
deleteTagKeyOperationSettings() {
return deleteTagKeyOperationSettings;
}
/** Returns the builder for the settings used for calls to getIamPolicy. */
public UnaryCallSettings.Builder<GetIamPolicyRequest, Policy> getIamPolicySettings() {
return getIamPolicySettings;
}
/** Returns the builder for the settings used for calls to setIamPolicy. */
public UnaryCallSettings.Builder<SetIamPolicyRequest, Policy> setIamPolicySettings() {
return setIamPolicySettings;
}
/** Returns the builder for the settings used for calls to testIamPermissions. */
public UnaryCallSettings.Builder<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsSettings() {
return testIamPermissionsSettings;
}
@Override
public TagKeysStubSettings build() throws IOException {
return new TagKeysStubSettings(this);
}
}
}
|
apache/stanbol | 35,863 | entityhub/yard/sesame/src/main/java/org/apache/stanbol/entityhub/yard/sesame/SesameYard.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.stanbol.entityhub.yard.sesame;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.stanbol.entityhub.core.query.QueryResultListImpl;
import org.apache.stanbol.entityhub.core.query.QueryUtils;
import org.apache.stanbol.entityhub.core.yard.AbstractYard;
import org.apache.stanbol.entityhub.model.sesame.RdfRepresentation;
import org.apache.stanbol.entityhub.model.sesame.RdfValueFactory;
import org.apache.stanbol.entityhub.query.sparql.SparqlEndpointTypeEnum;
import org.apache.stanbol.entityhub.query.sparql.SparqlFieldQuery;
import org.apache.stanbol.entityhub.query.sparql.SparqlFieldQueryFactory;
import org.apache.stanbol.entityhub.query.sparql.SparqlQueryUtils;
import org.apache.stanbol.entityhub.servicesapi.model.Representation;
import org.apache.stanbol.entityhub.servicesapi.model.rdf.RdfResourceEnum;
import org.apache.stanbol.entityhub.servicesapi.query.FieldQuery;
import org.apache.stanbol.entityhub.servicesapi.query.QueryResultList;
import org.apache.stanbol.entityhub.servicesapi.query.UnsupportedQueryTypeException;
import org.apache.stanbol.entityhub.servicesapi.yard.Yard;
import org.apache.stanbol.entityhub.servicesapi.yard.YardException;
import org.openrdf.model.BNode;
import org.openrdf.model.Model;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.TreeModel;
import org.openrdf.query.BindingSet;
import org.openrdf.query.Dataset;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.impl.DatasetImpl;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.RepositoryResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of the Yard Interface based on a Sesame {@link Repository}.
* <p>
* This is NOT an OSGI component nor service. It is intended to be used by
* Components that do allow users to configure a Repository implementation.
* Such components will than create a SesameYard instance and register it as
* a OSGI service.
* <p>
* <b>NOTE</b> This Yard does not {@link Repository#initialize() initialize}
* nor {@link Repository#shutDown() shutdown} the Sesame repository. Callers
* are responsible for that. This is because this Yard implementation does
* NOT assume exclusive access to the repository. The same repository can be
* used by multiple Yards (e.g. configured for different
* {@link SesameYardConfig#setContexts(String[]) contexts}) or even other
* components.
*
* @author Rupert Westenthaler
*
*/
public class SesameYard extends AbstractYard implements Yard {
private static Logger log = LoggerFactory.getLogger(SesameYard.class);
/**
* Property used to mark empty Representations managed by this Graph. This is
* needed to workaround the fact, that the Entityhub supports the storage of
* empty Representations but this Yard uses the search for any outgoing
* relation (triple with the id of the representation as Subject) for the
* implementation of {@link #isRepresentation(String)}. Therefore for an
* empty Representation {@link #isRepresentation(String)} would return false
* even if the representation was {@link #store(Representation)} previously.
* <p>
* Adding the Triple<br>
* <code> ?representationId <{@value #MANAGED_REPRESENTATION}> true^^xsd:boolean </code>
* <br> for any empty Representation avoids this unwanted behaviour.
*/
private static final String MANAGED_REPRESENTATION_URI = "urn:org.apache.stanbol:entityhub.yard:rdf.sesame:managesRepresentation";
/**
* used as property for a triple to ensure existence for representations that
* do not define yet any triples
*/
private final URI managedRepresentation;
/**
* used as value for a triple to ensure existence for representations that
* do not define yet any triples
*/
private final Value managedRepresentationState;
/**
* If inferred Triples are included in operations on this Yard.
*/
public static final String INCLUDE_INFERRED = "org.apache.stanbol.entityhub.yard.sesame.includeInferred";
/**
* By default {@link #INCLUDE_INFERRED} is enabled.
*/
public static final boolean DEFAULT_INCLUDE_INFERRED = true;
/**
* Property used to enable/disable Sesame Context. If <code>false</code> the
* {@link #CONTEXT_URI} property gets ignored. If <code>true</code> and
* {@link #CONTEXT_URI} is missing the default context (<code>null</code>) is
* used. Otherwise the contexts as configured for {@link #CONTEXT_URI} are
* used.
*/
public static final String CONTEXT_ENABLED = "org.apache.stanbol.entityhub.yard.sesame.enableContext";
/**
* By default the {@link #CONTEXT_ENABLED} feature is disabled.
*/
public static final boolean DEFAULT_CONTEXT_ENABLED = false;
/**
* Property used to optionally configure one or more context URIs. empty
* values are interpreted as <code>null</code>
*/
public static final String CONTEXT_URI = "org.apache.stanbol.entityhub.yard.sesame.contextUri";
/**
* The context used by this yard. Parsed from {@link SesameYardConfig#getContexts()}
* if <code>{@link SesameYardConfig#isContextEnabled()} == true</code>
*/
private final URI[] contexts;
/**
* The {@link Dataset} similar to {@link #contexts}. Dataset is used for
* SPARQL queries to enforce results to be restricted to the {@link #contexts}
*/
private final Dataset dataset;
/**
* If inferred triples should be included or not. Configured via
* {@link SesameYardConfig#isIncludeInferred()}
*/
private boolean includeInferred;
/**
* The {@link Repository} as parsed in the constructor
*/
private final Repository repository;
/**
* The Entityhub ValueFactory used to create Sesame specific Representations,
* References and Text instances
*/
private final RdfValueFactory valueFactory;
/**
* The Sesame ValueFactory. Shortcut for {@link Repository#getValueFactory()}.
*/
private final ValueFactory sesameFactory;
/**
* The {@link URI} for {@link RdfResourceEnum#QueryResultSet}
*/
private final URI queryRoot;
/**
* The {@link URI} for {@link RdfResourceEnum#queryResult}
*/
private final URI queryResult;
/**
* Constructs a SesameYard for the parsed Repository and configuration.
* @param repo The Repository used by this Yard. The parsed Repository is
* expected to be initialised.
* @param config the configuration for the Yard.
*/
public SesameYard(Repository repo, SesameYardConfig config) {
super();
if(repo == null){
throw new IllegalArgumentException("The parsed repository MUST NOT be NULL!");
}
if(!repo.isInitialized()){
throw new IllegalArgumentException("The parsed repository MUST BE initialised!");
}
this.repository = repo;
if(config == null){
throw new IllegalArgumentException("The parsed configuration MUST NOT be NULL!");
}
this.sesameFactory = repo.getValueFactory();
this.valueFactory = new RdfValueFactory(null, sesameFactory);
this.managedRepresentation = sesameFactory.createURI(MANAGED_REPRESENTATION_URI);
this.managedRepresentationState = sesameFactory.createLiteral(true);
this.includeInferred = config.isIncludeInferred();
//init the super class
activate(this.valueFactory, SparqlFieldQueryFactory.getInstance(), config);
if(config.isContextEnabled()){
//Set the contexts
String[] contexts = config.getContexts();
this.contexts = new URI[contexts.length];
for(int i = 0; i < contexts.length; i++){
this.contexts[i] = contexts[i] == null ? null :
sesameFactory.createURI(contexts[i]);
}
} else {
this.contexts = new URI[]{};
}
//also init the dataset required for SPARQL queries
if(contexts.length > 0){
DatasetImpl dataset = new DatasetImpl();
for(URI context : this.contexts){
dataset.addNamedGraph(context);
dataset.addDefaultGraph(context);
}
this.dataset = dataset;
} else {
this.dataset = null;
}
queryRoot = sesameFactory.createURI(RdfResourceEnum.QueryResultSet.getUri());
queryResult = sesameFactory.createURI(RdfResourceEnum.queryResult.getUri());
}
/**
* Closes this Yard, but <b>does not</b> close the Sesame Repository!
*/
public void close(){
//init the super class
deactivate();
}
/**
* Getter for the context URI used by this yard.
* @return the URI used for the RDF graph that stores all the data of this
* yard.
*/
public final URI[] getContexts(){
return contexts;
}
@Override
public Representation getRepresentation(String id) throws YardException{
if(id == null){
throw new IllegalArgumentException("The parsed representation id MUST NOT be NULL!");
}
if(id.isEmpty()){
throw new IllegalArgumentException("The parsed representation id MUST NOT be EMTPY!");
}
RepositoryConnection con = null;
try {
con = repository.getConnection();
con.begin();
Representation rep = getRepresentation(con, sesameFactory.createURI(id), true);
con.commit();
return rep;
} catch (RepositoryException e) {
throw new YardException("Unable to get Representation "+id, e);
} finally {
if(con != null){
try {
con.close();
} catch (RepositoryException ignore) {}
}
}
}
/**
* Internally used to create Representations for URIs
* @param uri the uri
* @param check if <code>false</code> than there is no check if the URI
* refers to a Resource in the graph that is of type {@link #REPRESENTATION}
* @return the Representation
*/
protected final Representation getRepresentation(RepositoryConnection con, URI uri, boolean check) throws RepositoryException {
if(!check || isRepresentation(con,uri)){
return createRepresentationGraph(con, valueFactory, uri);
} else {
return null; //not found
}
}
/**
* Extracts the triples that belong to the {@link Representation} with the
* parsed id from the Sesame repository.
* @param con the repository connection
* @param valueFactory the {@link RdfValueFactory} to use
* @param uri the subject of the Representation to extract
* @return the representation with the extracted data.
* @throws RepositoryException
*/
protected RdfRepresentation createRepresentationGraph(RepositoryConnection con, RdfValueFactory valueFactory, URI uri) throws RepositoryException{
RdfRepresentation rep = valueFactory.createRdfRepresentation(uri);
Model model = rep.getModel();
extractRepresentation(con, model, uri, new HashSet<BNode>());
return rep;
}
/**
* Recursive Method internally doing all the work for
* {@link #createRepresentationGraph(UriRef, TripleCollection)}
* @param con the repository connection to read the data from
* @param model The model to add the statements retrieved
* @param node the current node. Changes in recursive calls as it follows
* @param visited holding all the visited BNodes to avoid cycles. Other nodes
* need not be added because this implementation would not follow it anyway
* outgoing relations if the object is a {@link BNode} instance.
* @throws RepositoryException
*/
private void extractRepresentation(RepositoryConnection con,Model model, Resource node, Set<BNode> visited) throws RepositoryException{
//we need all the outgoing relations and also want to follow bNodes until
//the next UriRef. However we are not interested in incoming relations!
RepositoryResult<Statement> outgoing = con.getStatements(node, null, null, includeInferred, contexts);
Statement statement;
Set<BNode> bnodes = new HashSet<BNode>();
while(outgoing.hasNext()){
statement = outgoing.next();
model.add(statement);
Value object = statement.getObject();
if(object instanceof BNode && !visited.contains(object)){
bnodes.add((BNode)object);
}
}
outgoing.close();
for(BNode bnode : bnodes){
visited.add(bnode);
//TODO: recursive calls could cause stackoverflows with wired graphs
extractRepresentation(con, model, bnode, visited);
}
}
@Override
public boolean isRepresentation(String id) throws YardException {
if(id == null) {
throw new IllegalArgumentException("The parsed id MUST NOT be NULL!");
}
if(id.isEmpty()){
throw new IllegalArgumentException("The parsed id MUST NOT be EMPTY!");
}
RepositoryConnection con = null;
try {
con = repository.getConnection();
con.begin();
boolean state = isRepresentation(con, sesameFactory.createURI(id));
con.commit();
return state;
} catch (RepositoryException e) {
throw new YardException("Unable to check for Representation "+id, e);
} finally {
if(con != null){
try {
con.close();
} catch (RepositoryException ignore) {}
}
}
}
/**
* Internally used to check if a URI resource represents an representation
* @param con the repository connection
* @param subject the subject URI of the representation to check
* @return the state
* @throws RepositoryException
*/
protected final boolean isRepresentation(RepositoryConnection con , URI subject) throws RepositoryException{
return con.hasStatement(subject, null, null, includeInferred, contexts);
}
@Override
public void remove(String id) throws YardException, IllegalArgumentException {
if(id == null) {
throw new IllegalArgumentException("The parsed Representation id MUST NOT be NULL!");
}
RepositoryConnection con = null;
try {
con = repository.getConnection();
con.begin();
remove(con, sesameFactory.createURI(id));
con.commit();
} catch (RepositoryException e) {
throw new YardException("Unable to remove for Representation "+id, e);
} finally {
if(con != null){
try {
con.close();
} catch (RepositoryException ignore) {}
}
}
}
/**
* Internally used to remove a Representation from the Repository. <p>
* NOTE: this does not remove any {@link Statement}s for {@link BNode}s
* beeing {@link Statement#getObject() object}s of the parsed subjects.
* @param con the connection
* @param subject the subject of the Representation to remove
* @throws RepositoryException
*/
protected void remove(RepositoryConnection con, URI subject) throws RepositoryException{
con.remove(subject, null, null, contexts);
}
@Override
public final void remove(Iterable<String> ids) throws IllegalArgumentException, YardException {
if(ids == null){
throw new IllegalArgumentException("The parsed Iterable over the IDs to remove MUST NOT be NULL!");
}
RepositoryConnection con = null;
try {
con = repository.getConnection();
con.begin();
for(String id : ids){
if(id != null){
remove(con, sesameFactory.createURI(id));
}
}
con.commit();
} catch (RepositoryException e) {
throw new YardException("Unable to remove parsed Representations", e);
} finally {
if(con != null){
try {
con.close();
} catch (RepositoryException ignore) {}
}
}
}
@Override
public final void removeAll() throws YardException {
RepositoryConnection con = null;
try {
con = repository.getConnection();
con.begin();
con.clear(contexts); //removes everything
con.commit();
} catch (RepositoryException e) {
throw new YardException("Unable to remove parsed Representations", e);
} finally {
if(con != null){
try {
con.close();
} catch (RepositoryException ignore) {}
}
}
}
@Override
public final Representation store(Representation representation) throws IllegalArgumentException, YardException {
if(representation == null){
throw new IllegalArgumentException("The parsed Representation MUST NOT be NULL!");
}
return store(representation,true,true);
}
@Override
public final Iterable<Representation> store(Iterable<Representation> representations) throws IllegalArgumentException, YardException {
if(representations == null){
throw new IllegalArgumentException("The parsed Iterable over the Representations to store MUST NOT be NULL!");
}
return store(representations, true);
}
@Override
public final Representation update(Representation representation) throws IllegalArgumentException, YardException {
if(representation == null){
throw new IllegalArgumentException("The parsed Representation MUST NOT be NULL!");
}
return store(representation,false,true);
}
@Override
public final Iterable<Representation> update(Iterable<Representation> representations) throws YardException, IllegalArgumentException {
if(representations == null){
throw new IllegalArgumentException("The parsed Iterable over the Representations to update MUST NOT be NULL!");
}
return store(representations,false);
}
protected final Iterable<Representation> store(Iterable<Representation> representations,boolean allowCreate) throws IllegalArgumentException, YardException{
RepositoryConnection con = null;
try {
con = repository.getConnection();
con.begin();
ArrayList<Representation> added = new ArrayList<Representation>();
for(Representation representation : representations){
if(representation != null){
Representation stored = store(con, representation,allowCreate,false); //reassign
//to check if the store was successful
if(stored != null){
added.add(stored);
} else { //can only be the case if allowCreate==false (update was called)
log.warn(String.format("Unable to update Representation %s in Yard %s because it is not present!",
representation.getId(),getId()));
}
} //ignore null values in the parsed Iterable!
}
con.commit();
return added;
} catch (RepositoryException e) {
throw new YardException("Unable to remove parsed Representations", e);
} catch (IllegalArgumentException e) {
try {
//to avoid Exception logs in case store(..) throws an Exception
//in the case allowCreate and canNotCreateIsError do not allow
//the store operation
con.rollback();
} catch (RepositoryException ignore) {}
throw e;
} finally {
if(con != null){
try {
con.close();
} catch (RepositoryException ignore) {}
}
}
}
/**
* Generic store method used by store and update methods
* @param representation the representation to store/update
* @param allowCreate if new representation are allowed to be created
* @param canNotCreateIsError if updates to existing one are allowed
* @return the representation as added to the yard
* @throws IllegalArgumentException
* @throws YardException
*/
protected final Representation store(Representation representation,boolean allowCreate,boolean canNotCreateIsError) throws IllegalArgumentException, YardException{
RepositoryConnection con = null;
try {
con = repository.getConnection();
con.begin();
Representation added = store(con,representation,allowCreate,canNotCreateIsError);
con.commit();
return added;
} catch (RepositoryException e) {
throw new YardException("Unable to remove parsed Representations", e);
} catch (IllegalArgumentException e) {
try {
//to avoid Exception logs in case store(..) throws an Exception
//in the case allowCreate and canNotCreateIsError do not allow
//the store operation
con.rollback();
} catch (RepositoryException ignore) {}
throw e;
} finally {
if(con != null){
try {
con.close();
} catch (RepositoryException ignore) {}
}
}
}
protected final Representation store(RepositoryConnection con, Representation representation,boolean allowCreate,boolean canNotCreateIsError) throws IllegalArgumentException, RepositoryException {
if(representation == null) {
return null;
}
log.debug("store Representation " + representation.getId());
URI subject = sesameFactory.createURI(representation.getId());
boolean contains = con.hasStatement(subject, null, null, includeInferred, contexts);
con.remove(subject, null, null, contexts);
if(!contains && !allowCreate){
if(canNotCreateIsError) {
throw new IllegalArgumentException("Parsed Representation "+representation.getId()+" in not managed by this Yard "+getName()+"(id="+getId()+")");
} else {
return null;
}
}
//get the graph for the Representation and add it to the store
RdfRepresentation toAdd = valueFactory.toRdfRepresentation(representation);
if(toAdd.getModel().isEmpty()){
con.add(toAdd.getURI(),managedRepresentation,managedRepresentationState, contexts);
} else {
con.add(toAdd.getModel(), contexts);
}
return toAdd;
}
@Override
public QueryResultList<String> findReferences(FieldQuery parsedQuery) throws YardException, IllegalArgumentException {
if(parsedQuery == null){
throw new IllegalArgumentException("The parsed query MUST NOT be NULL!");
}
final SparqlFieldQuery query = SparqlFieldQueryFactory.getSparqlFieldQuery(parsedQuery);
RepositoryConnection con = null;
TupleQueryResult results = null;
try {
con = repository.getConnection();
con.begin();
//execute the query
int limit = QueryUtils.getLimit(query, getConfig().getDefaultQueryResultNumber(),
getConfig().getMaxQueryResultNumber());
results = executeSparqlFieldQuery(con, query, limit, false);
//parse the results
List<String> ids = limit > 0 ? new ArrayList<String>(limit) : new ArrayList<String>();
while(results.hasNext()){
BindingSet result = results.next();
Value value = result.getValue(query.getRootVariableName());
if(value instanceof Resource){
ids.add(value.stringValue());
}
}
con.commit();
return new QueryResultListImpl<String>(query,ids,String.class);
} catch (RepositoryException e) {
throw new YardException("Unable to execute findReferences query", e);
} catch (QueryEvaluationException e) {
throw new YardException("Unable to execute findReferences query", e);
} finally {
if(results != null) { //close the result if present
try {
results.close();
} catch (QueryEvaluationException ignore) {/* ignore */}
}
if(con != null){
try {
con.close();
} catch (RepositoryException ignore) {/* ignore */}
}
}
}
/**
* Returns the SPARQL result set for a given {@link SparqlFieldQuery} that
* was executed on this yard
* @param con the repository connection to use
* @param fieldQuery the SparqlFieldQuery instance
* @param limit the maximum number of results
* @return the results of the SPARQL query in the {@link #contexts} of the
* Sesame Repository
* @throws RepositoryException on any error while using the parsed connection
* @throws QueryEvaluationException on any error while executing the query
* @throws YardException if the SPARQL query created for the parsed FieldQuery
* was illegal formatted or if the {@link #repository} does not support
* SPARQL.
*/
private TupleQueryResult executeSparqlFieldQuery(RepositoryConnection con, final SparqlFieldQuery fieldQuery, int limit, boolean select) throws RepositoryException, YardException, QueryEvaluationException {
log.debug("> execute FieldQuery: {}", fieldQuery);
String sparqlQueryString = SparqlQueryUtils.createSparqlSelectQuery(
fieldQuery, select, limit, SparqlEndpointTypeEnum.Sesame);
log.debug(" - SPARQL Query: {}", sparqlQueryString);
TupleQuery sparqlOuery;
try {
sparqlOuery = con.prepareTupleQuery(QueryLanguage.SPARQL, sparqlQueryString);
} catch (MalformedQueryException e) {
log.error("Unable to pparse SPARQL Query generated for a FieldQuery");
log.error("FieldQuery: {}",fieldQuery);
log.error("SPARQL Query: {}",sparqlQueryString);
log.error("Exception ", e);
throw new YardException("Unable to parse SPARQL query generated for the parse FieldQuery", e);
} catch (UnsupportedQueryTypeException e) {
String message = "The Sesame Repository '" + repository + "'(class: "
+ repository.getClass().getName() + ") does not support SPARQL!";
log.error(message, e);
throw new YardException(message, e);
}
if(dataset != null){ //respect the configured contexts
sparqlOuery.setDataset(dataset);
}
return sparqlOuery.evaluate();
}
@Override
public QueryResultList<Representation> findRepresentation(FieldQuery parsedQuery) throws YardException, IllegalArgumentException {
if(parsedQuery == null){
throw new IllegalArgumentException("The parsed query MUST NOT be NULL!");
}
final SparqlFieldQuery query = SparqlFieldQueryFactory.getSparqlFieldQuery(parsedQuery);
RepositoryConnection con = null;
TupleQueryResult results = null;
try {
con = repository.getConnection();
con.begin();
//execute the query
int limit = QueryUtils.getLimit(query, getConfig().getDefaultQueryResultNumber(),
getConfig().getMaxQueryResultNumber());
results = executeSparqlFieldQuery(con,query, limit, false);
//parse the results and generate the Representations
//create an own valueFactors so that all the data of the query results
//are added to the same Sesame Model
Model model = new TreeModel();
RdfValueFactory valueFactory = new RdfValueFactory(model, sesameFactory);
List<Representation> representations = limit > 0 ?
new ArrayList<Representation>(limit) : new ArrayList<Representation>();
while(results.hasNext()){
BindingSet result = results.next();
Value value = result.getValue(query.getRootVariableName());
if(value instanceof URI){
//copy all data to the model and create the representation
RdfRepresentation rep = createRepresentationGraph(con, valueFactory, (URI)value);
model.add(queryRoot, queryResult, value); //link the result with the query result
representations.add(rep);
} //ignore non URI results
}
con.commit();
return new SesameQueryResultList(model, query, representations);
} catch (RepositoryException e) {
throw new YardException("Unable to execute findReferences query", e);
} catch (QueryEvaluationException e) {
throw new YardException("Unable to execute findReferences query", e);
} finally {
if(results != null) { //close the result if present
try {
results.close();
} catch (QueryEvaluationException ignore) {/* ignore */}
}
if(con != null){
try {
con.close();
} catch (RepositoryException ignore) {/* ignore */}
}
}
}
@Override
public final QueryResultList<Representation> find(FieldQuery parsedQuery) throws YardException, IllegalArgumentException {
if(parsedQuery == null){
throw new IllegalArgumentException("The parsed query MUST NOT be NULL!");
}
final SparqlFieldQuery query = SparqlFieldQueryFactory.getSparqlFieldQuery(parsedQuery);
RepositoryConnection con = null;
TupleQueryResult results = null;
try {
con = repository.getConnection();
con.begin();
//execute the query
int limit = QueryUtils.getLimit(query, getConfig().getDefaultQueryResultNumber(),
getConfig().getMaxQueryResultNumber());
results = executeSparqlFieldQuery(con,query, limit, true);
//parse the results and generate the Representations
//create an own valueFactors so that all the data of the query results
//are added to the same Sesame Model
Model model = new TreeModel();
RdfValueFactory valueFactory = new RdfValueFactory(model, sesameFactory);
List<Representation> representations = limit > 0 ? new ArrayList<Representation>(limit)
: new ArrayList<Representation>();
Map<String,URI> bindings = new HashMap<String,URI>(query.getFieldVariableMappings().size());
for(Entry<String,String> mapping : query.getFieldVariableMappings().entrySet()){
bindings.put(mapping.getValue(), sesameFactory.createURI(mapping.getKey()));
}
while(results.hasNext()){
BindingSet result = results.next();
Value value = result.getValue(query.getRootVariableName());
if(value instanceof URI){
URI subject = (URI) value;
//link the result with the query result
model.add(queryRoot, queryResult, subject);
//now copy over the other selected data
for(String binding : result.getBindingNames()){
URI property = bindings.get(binding);
if(property != null){
model.add(subject, property, result.getValue(binding));
} //else no mapping for the query.getRootVariableName()
}
//create a representation and add it to the results
representations.add(valueFactory.createRdfRepresentation(subject));
} //ignore non URI results
}
con.commit();
return new SesameQueryResultList(model, query, representations);
} catch (RepositoryException e) {
throw new YardException("Unable to execute findReferences query", e);
} catch (QueryEvaluationException e) {
throw new YardException("Unable to execute findReferences query", e);
} finally {
if(results != null) { //close the result if present
try {
results.close();
} catch (QueryEvaluationException ignore) {/* ignore */}
}
if(con != null){
try {
con.close();
} catch (RepositoryException ignore) {/* ignore */}
}
}
}
/**
* Wrapper that converts a Sesame {@link TupleQueryResult} to a {@link Iterator}.
* <b>NOTE</b> this will not close the {@link TupleQueryResult}!
* @author Rupert westenthaler
*
*/
static class TupleResultIterator implements Iterator<BindingSet> {
private final TupleQueryResult resultList;
public TupleResultIterator(TupleQueryResult resultList) {
this.resultList = resultList;
}
@Override
public boolean hasNext() {
try {
return resultList.hasNext();
} catch (QueryEvaluationException e) {
throw new IllegalStateException(e);
}
}
@Override
public BindingSet next() {
try {
return resultList.next();
} catch (QueryEvaluationException e) {
throw new IllegalStateException(e);
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("Remove is not supported by Sesame TupleQueryResult");
}
}
}
|
apache/fluss | 35,990 | fluss-flink/fluss-flink-common/src/test/java/org/apache/fluss/flink/tiering/source/enumerator/TieringSourceEnumeratorTest.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.fluss.flink.tiering.source.enumerator;
import org.apache.fluss.config.Configuration;
import org.apache.fluss.flink.tiering.event.FailedTieringEvent;
import org.apache.fluss.flink.tiering.event.FinishedTieringEvent;
import org.apache.fluss.flink.tiering.source.TieringTestBase;
import org.apache.fluss.flink.tiering.source.split.TieringLogSplit;
import org.apache.fluss.flink.tiering.source.split.TieringSnapshotSplit;
import org.apache.fluss.flink.tiering.source.split.TieringSplit;
import org.apache.fluss.flink.tiering.source.split.TieringSplitGenerator;
import org.apache.fluss.metadata.TableBucket;
import org.apache.fluss.metadata.TablePath;
import org.apache.fluss.rpc.messages.CommitLakeTableSnapshotRequest;
import org.apache.fluss.rpc.messages.PbLakeTableOffsetForBucket;
import org.apache.fluss.rpc.messages.PbLakeTableSnapshotInfo;
import org.apache.flink.api.connector.source.ReaderInfo;
import org.apache.flink.api.connector.source.SplitsAssignment;
import org.apache.flink.api.connector.source.mocks.MockSplitEnumeratorContext;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.apache.fluss.client.table.scanner.log.LogScanner.EARLIEST_OFFSET;
import static org.apache.fluss.config.ConfigOptions.TABLE_AUTO_PARTITION_NUM_PRECREATE;
import static org.assertj.core.api.Assertions.assertThat;
/** Unit tests for {@link TieringSourceEnumerator} and {@link TieringSplitGenerator}. */
class TieringSourceEnumeratorTest extends TieringTestBase {
private static Configuration flussConf;
@BeforeAll
protected static void beforeAll() {
TieringTestBase.beforeAll();
flussConf = new Configuration(clientConf);
}
@BeforeEach
protected void beforeEach() throws Exception {
super.beforeEach();
}
@Test
void testPrimaryKeyTableWithNoSnapshotSplits() throws Throwable {
TablePath tablePath = DEFAULT_TABLE_PATH;
long tableId = createTable(tablePath, DEFAULT_PK_TABLE_DESCRIPTOR);
int numSubtasks = 4;
int expectNumberOfSplits = 3;
// test get snapshot split & log split and the assignment
try (MockSplitEnumeratorContext<TieringSplit> context =
new MockSplitEnumeratorContext<>(numSubtasks)) {
TieringSourceEnumerator enumerator =
new TieringSourceEnumerator(flussConf, context, 500);
enumerator.start();
assertThat(context.getSplitsAssignmentSequence()).isEmpty();
// register all readers
for (int subtaskId = 0; subtaskId < numSubtasks; subtaskId++) {
registerReader(context, enumerator, subtaskId, "localhost-" + subtaskId);
enumerator.handleSplitRequest(subtaskId, "localhost-" + subtaskId);
}
waitUntilTieringTableSplitAssignmentReady(context, DEFAULT_BUCKET_NUM, 200L);
List<TieringSplit> expectedAssignment = new ArrayList<>();
for (int bucketId = 0; bucketId < DEFAULT_BUCKET_NUM; bucketId++) {
expectedAssignment.add(
new TieringLogSplit(
tablePath,
new TableBucket(tableId, bucketId),
null,
EARLIEST_OFFSET,
0,
expectNumberOfSplits));
}
List<TieringSplit> actualAssignment = new ArrayList<>();
context.getSplitsAssignmentSequence()
.forEach(a -> a.assignment().values().forEach(actualAssignment::addAll));
assertThat(actualAssignment).isEqualTo(expectedAssignment);
// mock finished tiered this round, check second round
context.getSplitsAssignmentSequence().clear();
final Map<Integer, Long> bucketOffsetOfEarliest = new HashMap<>();
final Map<Integer, Long> bucketOffsetOfInitialWrite = new HashMap<>();
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
bucketOffsetOfEarliest.put(tableBucket, EARLIEST_OFFSET);
bucketOffsetOfInitialWrite.put(tableBucket, 0L);
}
// commit and notify this table tiering task finished
coordinatorGateway
.commitLakeTableSnapshot(
genCommitLakeTableSnapshotRequest(
tableId,
null,
0,
bucketOffsetOfEarliest,
bucketOffsetOfInitialWrite))
.get();
enumerator.handleSourceEvent(1, new FinishedTieringEvent(tableId));
Map<Integer, Long> bucketOffsetOfSecondWrite =
upsertRow(tablePath, DEFAULT_PK_TABLE_DESCRIPTOR, 0, 10);
long snapshotId = 0;
waitUntilSnapshot(tableId, snapshotId);
// request tiering table splits
for (int subtaskId = 0; subtaskId < 3; subtaskId++) {
enumerator.handleSplitRequest(subtaskId, "localhost-" + subtaskId);
}
waitUntilTieringTableSplitAssignmentReady(context, DEFAULT_BUCKET_NUM, 500L);
Map<Integer, List<TieringSplit>> expectedLogAssignment = new HashMap<>();
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
expectedLogAssignment.put(
tableBucket,
Collections.singletonList(
new TieringLogSplit(
tablePath,
new TableBucket(tableId, tableBucket),
null,
bucketOffsetOfInitialWrite.get(tableBucket),
bucketOffsetOfInitialWrite.get(tableBucket)
+ bucketOffsetOfSecondWrite.get(tableBucket),
expectNumberOfSplits)));
}
Map<Integer, List<TieringSplit>> actualLogAssignment = new HashMap<>();
for (SplitsAssignment<TieringSplit> a : context.getSplitsAssignmentSequence()) {
actualLogAssignment.putAll(a.assignment());
}
assertThat(actualLogAssignment).isEqualTo(expectedLogAssignment);
}
}
@Test
void testPrimaryKeyTableWithSnapshotSplits() throws Throwable {
TablePath tablePath = TablePath.of(DEFAULT_DB, "tiering-test-pk-table");
long tableId = createTable(tablePath, DEFAULT_PK_TABLE_DESCRIPTOR);
int numSubtasks = 3;
final Map<Integer, Long> bucketOffsetOfInitialWrite =
upsertRow(tablePath, DEFAULT_PK_TABLE_DESCRIPTOR, 0, 10);
long snapshotId = 0;
waitUntilSnapshot(tableId, snapshotId);
int expectNumberOfSplits = 3;
// test get snapshot split assignment
try (MockSplitEnumeratorContext<TieringSplit> context =
new MockSplitEnumeratorContext<>(numSubtasks)) {
TieringSourceEnumerator enumerator =
new TieringSourceEnumerator(flussConf, context, 500);
enumerator.start();
assertThat(context.getSplitsAssignmentSequence()).isEmpty();
// register all readers
for (int subtaskId = 0; subtaskId < 3; subtaskId++) {
registerReader(context, enumerator, subtaskId, "localhost-" + subtaskId);
enumerator.handleSplitRequest(subtaskId, "localhost-" + subtaskId);
}
waitUntilTieringTableSplitAssignmentReady(context, DEFAULT_BUCKET_NUM, 3000L);
Map<Integer, List<TieringSplit>> expectedSnapshotAssignment = new HashMap<>();
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
expectedSnapshotAssignment.put(
tableBucket,
Collections.singletonList(
new TieringSnapshotSplit(
tablePath,
new TableBucket(tableId, tableBucket),
null,
snapshotId,
bucketOffsetOfInitialWrite.get(tableBucket),
expectNumberOfSplits)));
}
Map<Integer, List<TieringSplit>> actualSnapshotAssignment = new HashMap<>();
for (SplitsAssignment<TieringSplit> a : context.getSplitsAssignmentSequence()) {
actualSnapshotAssignment.putAll(a.assignment());
}
assertThat(actualSnapshotAssignment).isEqualTo(expectedSnapshotAssignment);
// mock finished tiered this round, check second round
context.getSplitsAssignmentSequence().clear();
final Map<Integer, Long> initialBucketOffsets = new HashMap<>();
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
initialBucketOffsets.put(tableBucket, EARLIEST_OFFSET);
}
// commit and notify this table tiering task finished
coordinatorGateway
.commitLakeTableSnapshot(
genCommitLakeTableSnapshotRequest(
tableId,
null,
1,
initialBucketOffsets,
bucketOffsetOfInitialWrite))
.get();
enumerator.handleSourceEvent(1, new FinishedTieringEvent(tableId));
Map<Integer, Long> bucketOffsetOfSecondWrite =
upsertRow(tablePath, DEFAULT_PK_TABLE_DESCRIPTOR, 10, 20);
snapshotId = 1;
waitUntilSnapshot(tableId, snapshotId);
// request tiering table splits
for (int subtaskId = 0; subtaskId < 3; subtaskId++) {
String hostName = "localhost-" + subtaskId;
enumerator.handleSplitRequest(subtaskId, hostName);
}
// three log splits will be ready soon
waitUntilTieringTableSplitAssignmentReady(context, DEFAULT_BUCKET_NUM, 500L);
Map<Integer, List<TieringSplit>> expectedLogAssignment = new HashMap<>();
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
expectedLogAssignment.put(
tableBucket,
Collections.singletonList(
new TieringLogSplit(
tablePath,
new TableBucket(tableId, tableBucket),
null,
bucketOffsetOfInitialWrite.get(tableBucket),
bucketOffsetOfInitialWrite.get(tableBucket)
+ bucketOffsetOfSecondWrite.get(tableBucket),
expectNumberOfSplits)));
}
Map<Integer, List<TieringSplit>> actualLogAssignment = new HashMap<>();
for (SplitsAssignment<TieringSplit> a : context.getSplitsAssignmentSequence()) {
actualLogAssignment.putAll(a.assignment());
}
assertThat(actualLogAssignment).isEqualTo(expectedLogAssignment);
}
}
@Test
void testLogTableSplits() throws Throwable {
TablePath tablePath = TablePath.of(DEFAULT_DB, "tiering-test-log-table");
long tableId = createTable(tablePath, DEFAULT_LOG_TABLE_DESCRIPTOR);
int numSubtasks = 4;
int expectNumberOfSplits = 3;
// test get log split and the assignment
try (MockSplitEnumeratorContext<TieringSplit> context =
new MockSplitEnumeratorContext<>(numSubtasks)) {
TieringSourceEnumerator enumerator =
new TieringSourceEnumerator(flussConf, context, 500);
enumerator.start();
assertThat(context.getSplitsAssignmentSequence()).isEmpty();
// register all readers
for (int subtaskId = 0; subtaskId < numSubtasks; subtaskId++) {
registerReader(context, enumerator, subtaskId, "localhost-" + subtaskId);
enumerator.handleSplitRequest(subtaskId, "localhost-" + subtaskId);
}
waitUntilTieringTableSplitAssignmentReady(context, DEFAULT_BUCKET_NUM, 200);
List<TieringSplit> expectedAssignment = new ArrayList<>();
for (int bucketId = 0; bucketId < DEFAULT_BUCKET_NUM; bucketId++) {
expectedAssignment.add(
new TieringLogSplit(
tablePath,
new TableBucket(tableId, bucketId),
null,
EARLIEST_OFFSET,
0L,
expectNumberOfSplits));
}
List<TieringSplit> actualAssignment = new ArrayList<>();
context.getSplitsAssignmentSequence()
.forEach(a -> a.assignment().values().forEach(actualAssignment::addAll));
assertThat(actualAssignment).isEqualTo(expectedAssignment);
// mock finished tiered this round, check second round
context.getSplitsAssignmentSequence().clear();
final Map<Integer, Long> bucketOffsetOfEarliest = new HashMap<>();
final Map<Integer, Long> bucketOffsetOfInitialWrite = new HashMap<>();
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
bucketOffsetOfEarliest.put(tableBucket, EARLIEST_OFFSET);
bucketOffsetOfInitialWrite.put(tableBucket, 0L);
}
// commit and notify this table tiering task finished
coordinatorGateway
.commitLakeTableSnapshot(
genCommitLakeTableSnapshotRequest(
tableId,
null,
0,
bucketOffsetOfEarliest,
bucketOffsetOfInitialWrite))
.get();
enumerator.handleSourceEvent(1, new FinishedTieringEvent(tableId));
Map<Integer, Long> bucketOffsetOfSecondWrite =
appendRow(tablePath, DEFAULT_LOG_TABLE_DESCRIPTOR, 0, 10);
// request tiering table splits
for (int subtaskId = 0; subtaskId < numSubtasks; subtaskId++) {
enumerator.handleSplitRequest(subtaskId, "localhost-" + subtaskId);
}
waitUntilTieringTableSplitAssignmentReady(context, DEFAULT_BUCKET_NUM, 500L);
Map<Integer, List<TieringSplit>> expectedLogAssignment = new HashMap<>();
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
expectedLogAssignment.put(
tableBucket,
Collections.singletonList(
new TieringLogSplit(
tablePath,
new TableBucket(tableId, tableBucket),
null,
bucketOffsetOfInitialWrite.get(tableBucket),
bucketOffsetOfInitialWrite.get(tableBucket)
+ bucketOffsetOfSecondWrite.get(tableBucket),
expectNumberOfSplits)));
}
Map<Integer, List<TieringSplit>> actualLogAssignment = new HashMap<>();
for (SplitsAssignment<TieringSplit> a : context.getSplitsAssignmentSequence()) {
actualLogAssignment.putAll(a.assignment());
}
assertThat(actualLogAssignment).isEqualTo(expectedLogAssignment);
}
}
@Test
void testPartitionedPrimaryKeyTable() throws Throwable {
TablePath tablePath = TablePath.of(DEFAULT_DB, "tiering-test-partitioned-pk-table");
long tableId =
createPartitionedTable(tablePath, DEFAULT_AUTO_PARTITIONED_PK_TABLE_DESCRIPTOR);
Map<String, Long> partitionNameByIds =
FLUSS_CLUSTER_EXTENSION.waitUntilPartitionsCreated(
tablePath, TABLE_AUTO_PARTITION_NUM_PRECREATE.defaultValue());
final Map<Long, Map<Integer, Long>> bucketOffsetOfInitialWrite =
upsertRowForPartitionedTable(
tablePath, DEFAULT_PK_TABLE_DESCRIPTOR, partitionNameByIds, 0, 10);
long snapshotId = 0;
waitUntilPartitionTableSnapshot(tableId, partitionNameByIds, snapshotId);
int numSubtasks = 6;
int expectNumberOfSplits = 6;
// test get snapshot split assignment
try (MockSplitEnumeratorContext<TieringSplit> context =
new MockSplitEnumeratorContext<>(numSubtasks)) {
TieringSourceEnumerator enumerator =
new TieringSourceEnumerator(flussConf, context, 500);
enumerator.start();
assertThat(context.getSplitsAssignmentSequence()).isEmpty();
// register all readers
for (int subtaskId = 0; subtaskId < numSubtasks; subtaskId++) {
registerReader(context, enumerator, subtaskId, "localhost-" + subtaskId);
enumerator.handleSplitRequest(subtaskId, "localhost-" + subtaskId);
}
waitUntilTieringTableSplitAssignmentReady(
context, DEFAULT_BUCKET_NUM * partitionNameByIds.size(), 3000L);
List<TieringSplit> expectedSnapshotAssignment = new ArrayList<>();
for (Map.Entry<String, Long> partitionNameById : partitionNameByIds.entrySet()) {
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
long partitionId = partitionNameById.getValue();
expectedSnapshotAssignment.add(
new TieringSnapshotSplit(
tablePath,
new TableBucket(tableId, partitionId, tableBucket),
partitionNameById.getKey(),
snapshotId,
bucketOffsetOfInitialWrite.get(partitionId).get(tableBucket),
expectNumberOfSplits));
}
}
List<TieringSplit> actualSnapshotAssignment = new ArrayList<>();
for (SplitsAssignment<TieringSplit> splitsAssignment :
context.getSplitsAssignmentSequence()) {
splitsAssignment.assignment().values().forEach(actualSnapshotAssignment::addAll);
}
assertThat(sortSplits(actualSnapshotAssignment))
.isEqualTo(sortSplits(expectedSnapshotAssignment));
// mock finished tiered this round, check second round
context.getSplitsAssignmentSequence().clear();
for (Map.Entry<String, Long> partitionNameById : partitionNameByIds.entrySet()) {
Map<Integer, Long> partitionInitialBucketOffsets = new HashMap<>();
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
partitionInitialBucketOffsets.put(tableBucket, EARLIEST_OFFSET);
}
// commit lake table partition
coordinatorGateway
.commitLakeTableSnapshot(
genCommitLakeTableSnapshotRequest(
tableId,
partitionNameById.getValue(),
1,
partitionInitialBucketOffsets,
bucketOffsetOfInitialWrite.get(
partitionNameById.getValue())))
.get();
}
// notify this table tiering task finished
enumerator.handleSourceEvent(1, new FinishedTieringEvent(tableId));
Map<Long, Map<Integer, Long>> bucketOffsetOfSecondWrite =
upsertRowForPartitionedTable(
tablePath, DEFAULT_PK_TABLE_DESCRIPTOR, partitionNameByIds, 10, 20);
snapshotId = 1;
waitUntilPartitionTableSnapshot(tableId, partitionNameByIds, snapshotId);
// request tiering table splits
for (int subtaskId = 0; subtaskId < numSubtasks; subtaskId++) {
enumerator.handleSplitRequest(subtaskId, "localhost-" + subtaskId);
}
waitUntilTieringTableSplitAssignmentReady(
context, DEFAULT_BUCKET_NUM * partitionNameByIds.size(), 500L);
List<TieringSplit> expectedLogAssignment = new ArrayList<>();
for (Map.Entry<String, Long> partitionNameById : partitionNameByIds.entrySet()) {
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
long partionId = partitionNameById.getValue();
expectedLogAssignment.add(
new TieringLogSplit(
tablePath,
new TableBucket(tableId, partionId, tableBucket),
partitionNameById.getKey(),
bucketOffsetOfInitialWrite.get(partionId).get(tableBucket),
bucketOffsetOfInitialWrite.get(partionId).get(tableBucket)
+ bucketOffsetOfSecondWrite
.get(partionId)
.get(tableBucket),
expectNumberOfSplits));
}
}
List<TieringSplit> actualLogAssignment = new ArrayList<>();
for (SplitsAssignment<TieringSplit> splitsAssignment :
context.getSplitsAssignmentSequence()) {
splitsAssignment.assignment().values().forEach(actualLogAssignment::addAll);
}
assertThat(sortSplits(actualLogAssignment))
.isEqualTo(sortSplits(expectedLogAssignment));
}
}
@Test
void testPartitionedLogTableSplits() throws Throwable {
TablePath tablePath = TablePath.of(DEFAULT_DB, "tiering-test-partitioned-log-table");
long tableId =
createPartitionedTable(tablePath, DEFAULT_AUTO_PARTITIONED_LOG_TABLE_DESCRIPTOR);
Map<String, Long> partitionNameByIds =
FLUSS_CLUSTER_EXTENSION.waitUntilPartitionsCreated(
tablePath, TABLE_AUTO_PARTITION_NUM_PRECREATE.defaultValue());
int numSubtasks = 6;
int expectNumberOfSplits = 6;
// test get log split assignment
try (MockSplitEnumeratorContext<TieringSplit> context =
new MockSplitEnumeratorContext<>(numSubtasks)) {
TieringSourceEnumerator enumerator =
new TieringSourceEnumerator(flussConf, context, 500);
enumerator.start();
assertThat(context.getSplitsAssignmentSequence()).isEmpty();
// register all readers
for (int subtaskId = 0; subtaskId < numSubtasks; subtaskId++) {
registerReader(context, enumerator, subtaskId, "localhost-" + subtaskId);
enumerator.handleSplitRequest(subtaskId, "localhost-" + subtaskId);
}
waitUntilTieringTableSplitAssignmentReady(
context, DEFAULT_BUCKET_NUM * partitionNameByIds.size(), 3000L);
List<TieringSplit> expectedAssignment = new ArrayList<>();
for (Map.Entry<String, Long> partitionNameById : partitionNameByIds.entrySet()) {
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
long partitionId = partitionNameById.getValue();
expectedAssignment.add(
new TieringLogSplit(
tablePath,
new TableBucket(tableId, partitionId, tableBucket),
partitionNameById.getKey(),
EARLIEST_OFFSET,
0L,
expectNumberOfSplits));
}
}
List<TieringSplit> actualAssignment = new ArrayList<>();
for (SplitsAssignment<TieringSplit> splitsAssignment :
context.getSplitsAssignmentSequence()) {
splitsAssignment.assignment().values().forEach(actualAssignment::addAll);
}
assertThat(sortSplits(actualAssignment)).isEqualTo(sortSplits(expectedAssignment));
// mock finished tiered this round, check second round
context.getSplitsAssignmentSequence().clear();
final Map<Long, Map<Integer, Long>> bucketOffsetOfInitialWrite = new HashMap<>();
for (Map.Entry<String, Long> partitionNameById : partitionNameByIds.entrySet()) {
long partitionId = partitionNameById.getValue();
Map<Integer, Long> partitionInitialBucketOffsets = new HashMap<>();
Map<Integer, Long> partitionBucketOffsetOfInitialWrite = new HashMap<>();
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
partitionInitialBucketOffsets.put(tableBucket, EARLIEST_OFFSET);
partitionBucketOffsetOfInitialWrite.put(tableBucket, 0L);
}
bucketOffsetOfInitialWrite.put(partitionId, partitionBucketOffsetOfInitialWrite);
// commit lake table partition
coordinatorGateway
.commitLakeTableSnapshot(
genCommitLakeTableSnapshotRequest(
tableId,
partitionId,
1,
partitionInitialBucketOffsets,
bucketOffsetOfInitialWrite.get(partitionId)))
.get();
}
// notify this table tiering task finished
enumerator.handleSourceEvent(1, new FinishedTieringEvent(tableId));
Map<Long, Map<Integer, Long>> bucketOffsetOfSecondWrite =
appendRowForPartitionedTable(
tablePath,
DEFAULT_AUTO_PARTITIONED_LOG_TABLE_DESCRIPTOR,
partitionNameByIds,
0,
10);
// request tiering table splits
for (int subtaskId = 0; subtaskId < numSubtasks; subtaskId++) {
enumerator.handleSplitRequest(subtaskId, "localhost-" + subtaskId);
}
waitUntilTieringTableSplitAssignmentReady(
context, DEFAULT_BUCKET_NUM * partitionNameByIds.size(), 500L);
List<TieringSplit> expectedLogAssignment = new ArrayList<>();
for (Map.Entry<String, Long> partitionNameById : partitionNameByIds.entrySet()) {
for (int tableBucket = 0; tableBucket < DEFAULT_BUCKET_NUM; tableBucket++) {
long partionId = partitionNameById.getValue();
expectedLogAssignment.add(
new TieringLogSplit(
tablePath,
new TableBucket(tableId, partionId, tableBucket),
partitionNameById.getKey(),
bucketOffsetOfInitialWrite.get(partionId).get(tableBucket),
bucketOffsetOfInitialWrite.get(partionId).get(tableBucket)
+ bucketOffsetOfSecondWrite
.get(partionId)
.get(tableBucket),
expectNumberOfSplits));
}
}
List<TieringSplit> actualLogAssignment = new ArrayList<>();
for (SplitsAssignment<TieringSplit> splitsAssignment :
context.getSplitsAssignmentSequence()) {
splitsAssignment.assignment().values().forEach(actualLogAssignment::addAll);
}
assertThat(sortSplits(actualLogAssignment))
.isEqualTo(sortSplits(expectedLogAssignment));
}
}
@Test
void testHandleFailedTieringTableEvent() throws Throwable {
TablePath tablePath = TablePath.of(DEFAULT_DB, "tiering-fail-test-log-table");
long tableId = createTable(tablePath, DEFAULT_LOG_TABLE_DESCRIPTOR);
int numSubtasks = 4;
int expectNumberOfSplits = 3;
Map<Integer, Long> bucketOffsetOfWrite =
appendRow(tablePath, DEFAULT_LOG_TABLE_DESCRIPTOR, 0, 10);
// test get log split and the assignment
try (MockSplitEnumeratorContext<TieringSplit> context =
new MockSplitEnumeratorContext<>(numSubtasks)) {
TieringSourceEnumerator enumerator =
new TieringSourceEnumerator(flussConf, context, 500);
enumerator.start();
assertThat(context.getSplitsAssignmentSequence()).isEmpty();
// register all readers
for (int subtaskId = 0; subtaskId < numSubtasks; subtaskId++) {
registerReader(context, enumerator, subtaskId, "localhost-" + subtaskId);
enumerator.handleSplitRequest(subtaskId, "localhost-" + subtaskId);
}
waitUntilTieringTableSplitAssignmentReady(context, DEFAULT_BUCKET_NUM, 200);
List<TieringSplit> expectedAssignment = new ArrayList<>();
for (int bucketId = 0; bucketId < DEFAULT_BUCKET_NUM; bucketId++) {
expectedAssignment.add(
new TieringLogSplit(
tablePath,
new TableBucket(tableId, bucketId),
null,
EARLIEST_OFFSET,
bucketOffsetOfWrite.get(bucketId),
expectNumberOfSplits));
}
List<TieringSplit> actualAssignment = new ArrayList<>();
context.getSplitsAssignmentSequence()
.forEach(a -> a.assignment().values().forEach(actualAssignment::addAll));
assertThat(actualAssignment).isEqualTo(expectedAssignment);
// mock tiering fail by send tiering fail event
context.getSplitsAssignmentSequence().clear();
enumerator.handleSourceEvent(1, new FailedTieringEvent(tableId, "test_reason"));
// request tiering table splits, should get splits
for (int subtaskId = 0; subtaskId < numSubtasks; subtaskId++) {
enumerator.handleSplitRequest(subtaskId, "localhost-" + subtaskId);
}
waitUntilTieringTableSplitAssignmentReady(context, DEFAULT_BUCKET_NUM, 500L);
List<TieringSplit> actualAssignment1 = new ArrayList<>();
context.getSplitsAssignmentSequence()
.forEach(a -> a.assignment().values().forEach(actualAssignment1::addAll));
assertThat(actualAssignment1).isEqualTo(expectedAssignment);
}
}
private static CommitLakeTableSnapshotRequest genCommitLakeTableSnapshotRequest(
long tableId,
@Nullable Long partitionId,
long snapshotId,
Map<Integer, Long> bucketLogStartOffsets,
Map<Integer, Long> bucketLogEndOffsets) {
CommitLakeTableSnapshotRequest commitLakeTableSnapshotRequest =
new CommitLakeTableSnapshotRequest();
PbLakeTableSnapshotInfo reqForTable = commitLakeTableSnapshotRequest.addTablesReq();
reqForTable.setTableId(tableId);
reqForTable.setSnapshotId(snapshotId);
for (Map.Entry<Integer, Long> bucketLogStartOffset : bucketLogStartOffsets.entrySet()) {
int bucketId = bucketLogStartOffset.getKey();
TableBucket tb = new TableBucket(tableId, partitionId, bucketId);
PbLakeTableOffsetForBucket lakeTableOffsetForBucket = reqForTable.addBucketsReq();
if (tb.getPartitionId() != null) {
lakeTableOffsetForBucket.setPartitionId(tb.getPartitionId());
}
lakeTableOffsetForBucket.setBucketId(tb.getBucket());
lakeTableOffsetForBucket.setLogStartOffset(bucketLogStartOffset.getValue());
lakeTableOffsetForBucket.setLogEndOffset(bucketLogEndOffsets.get(bucketId));
}
return commitLakeTableSnapshotRequest;
}
// --------------------- Test Utils ---------------------
private void registerReader(
MockSplitEnumeratorContext<TieringSplit> context,
TieringSourceEnumerator enumerator,
int readerId,
String hostname) {
context.registerReader(new ReaderInfo(readerId, hostname));
enumerator.addReader(readerId);
}
private void waitUntilTieringTableSplitAssignmentReady(
MockSplitEnumeratorContext<TieringSplit> context, int expectedSplitsNum, long sleepMs)
throws Throwable {
while (context.getSplitsAssignmentSequence().size() < expectedSplitsNum) {
if (!context.getPeriodicCallables().isEmpty()) {
context.runPeriodicCallable(0);
} else {
context.runNextOneTimeCallable();
}
Thread.sleep(sleepMs);
}
}
private static List<TieringSplit> sortSplits(List<TieringSplit> splits) {
return splits.stream()
.sorted(Comparator.comparing(Object::toString))
.collect(Collectors.toList());
}
}
|
apache/hive | 35,602 | standalone-metastore/metastore-common/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/metastore/api/GrantRevokeRoleRequest.java | /**
* Autogenerated by Thrift Compiler (0.16.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package org.apache.hadoop.hive.metastore.api;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.16.0)")
@org.apache.hadoop.classification.InterfaceAudience.Public @org.apache.hadoop.classification.InterfaceStability.Stable public class GrantRevokeRoleRequest implements org.apache.thrift.TBase<GrantRevokeRoleRequest, GrantRevokeRoleRequest._Fields>, java.io.Serializable, Cloneable, Comparable<GrantRevokeRoleRequest> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("GrantRevokeRoleRequest");
private static final org.apache.thrift.protocol.TField REQUEST_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("requestType", org.apache.thrift.protocol.TType.I32, (short)1);
private static final org.apache.thrift.protocol.TField ROLE_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("roleName", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final org.apache.thrift.protocol.TField PRINCIPAL_NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("principalName", org.apache.thrift.protocol.TType.STRING, (short)3);
private static final org.apache.thrift.protocol.TField PRINCIPAL_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("principalType", org.apache.thrift.protocol.TType.I32, (short)4);
private static final org.apache.thrift.protocol.TField GRANTOR_FIELD_DESC = new org.apache.thrift.protocol.TField("grantor", org.apache.thrift.protocol.TType.STRING, (short)5);
private static final org.apache.thrift.protocol.TField GRANTOR_TYPE_FIELD_DESC = new org.apache.thrift.protocol.TField("grantorType", org.apache.thrift.protocol.TType.I32, (short)6);
private static final org.apache.thrift.protocol.TField GRANT_OPTION_FIELD_DESC = new org.apache.thrift.protocol.TField("grantOption", org.apache.thrift.protocol.TType.BOOL, (short)7);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new GrantRevokeRoleRequestStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new GrantRevokeRoleRequestTupleSchemeFactory();
private @org.apache.thrift.annotation.Nullable GrantRevokeType requestType; // required
private @org.apache.thrift.annotation.Nullable java.lang.String roleName; // required
private @org.apache.thrift.annotation.Nullable java.lang.String principalName; // required
private @org.apache.thrift.annotation.Nullable PrincipalType principalType; // required
private @org.apache.thrift.annotation.Nullable java.lang.String grantor; // optional
private @org.apache.thrift.annotation.Nullable PrincipalType grantorType; // optional
private boolean grantOption; // optional
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
/**
*
* @see GrantRevokeType
*/
REQUEST_TYPE((short)1, "requestType"),
ROLE_NAME((short)2, "roleName"),
PRINCIPAL_NAME((short)3, "principalName"),
/**
*
* @see PrincipalType
*/
PRINCIPAL_TYPE((short)4, "principalType"),
GRANTOR((short)5, "grantor"),
/**
*
* @see PrincipalType
*/
GRANTOR_TYPE((short)6, "grantorType"),
GRANT_OPTION((short)7, "grantOption");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // REQUEST_TYPE
return REQUEST_TYPE;
case 2: // ROLE_NAME
return ROLE_NAME;
case 3: // PRINCIPAL_NAME
return PRINCIPAL_NAME;
case 4: // PRINCIPAL_TYPE
return PRINCIPAL_TYPE;
case 5: // GRANTOR
return GRANTOR;
case 6: // GRANTOR_TYPE
return GRANTOR_TYPE;
case 7: // GRANT_OPTION
return GRANT_OPTION;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
@org.apache.thrift.annotation.Nullable
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __GRANTOPTION_ISSET_ID = 0;
private byte __isset_bitfield = 0;
private static final _Fields optionals[] = {_Fields.GRANTOR,_Fields.GRANTOR_TYPE,_Fields.GRANT_OPTION};
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.REQUEST_TYPE, new org.apache.thrift.meta_data.FieldMetaData("requestType", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, GrantRevokeType.class)));
tmpMap.put(_Fields.ROLE_NAME, new org.apache.thrift.meta_data.FieldMetaData("roleName", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.PRINCIPAL_NAME, new org.apache.thrift.meta_data.FieldMetaData("principalName", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.PRINCIPAL_TYPE, new org.apache.thrift.meta_data.FieldMetaData("principalType", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, PrincipalType.class)));
tmpMap.put(_Fields.GRANTOR, new org.apache.thrift.meta_data.FieldMetaData("grantor", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.GRANTOR_TYPE, new org.apache.thrift.meta_data.FieldMetaData("grantorType", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, PrincipalType.class)));
tmpMap.put(_Fields.GRANT_OPTION, new org.apache.thrift.meta_data.FieldMetaData("grantOption", org.apache.thrift.TFieldRequirementType.OPTIONAL,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(GrantRevokeRoleRequest.class, metaDataMap);
}
public GrantRevokeRoleRequest() {
}
public GrantRevokeRoleRequest(
GrantRevokeType requestType,
java.lang.String roleName,
java.lang.String principalName,
PrincipalType principalType)
{
this();
this.requestType = requestType;
this.roleName = roleName;
this.principalName = principalName;
this.principalType = principalType;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public GrantRevokeRoleRequest(GrantRevokeRoleRequest other) {
__isset_bitfield = other.__isset_bitfield;
if (other.isSetRequestType()) {
this.requestType = other.requestType;
}
if (other.isSetRoleName()) {
this.roleName = other.roleName;
}
if (other.isSetPrincipalName()) {
this.principalName = other.principalName;
}
if (other.isSetPrincipalType()) {
this.principalType = other.principalType;
}
if (other.isSetGrantor()) {
this.grantor = other.grantor;
}
if (other.isSetGrantorType()) {
this.grantorType = other.grantorType;
}
this.grantOption = other.grantOption;
}
public GrantRevokeRoleRequest deepCopy() {
return new GrantRevokeRoleRequest(this);
}
@Override
public void clear() {
this.requestType = null;
this.roleName = null;
this.principalName = null;
this.principalType = null;
this.grantor = null;
this.grantorType = null;
setGrantOptionIsSet(false);
this.grantOption = false;
}
/**
*
* @see GrantRevokeType
*/
@org.apache.thrift.annotation.Nullable
public GrantRevokeType getRequestType() {
return this.requestType;
}
/**
*
* @see GrantRevokeType
*/
public void setRequestType(@org.apache.thrift.annotation.Nullable GrantRevokeType requestType) {
this.requestType = requestType;
}
public void unsetRequestType() {
this.requestType = null;
}
/** Returns true if field requestType is set (has been assigned a value) and false otherwise */
public boolean isSetRequestType() {
return this.requestType != null;
}
public void setRequestTypeIsSet(boolean value) {
if (!value) {
this.requestType = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getRoleName() {
return this.roleName;
}
public void setRoleName(@org.apache.thrift.annotation.Nullable java.lang.String roleName) {
this.roleName = roleName;
}
public void unsetRoleName() {
this.roleName = null;
}
/** Returns true if field roleName is set (has been assigned a value) and false otherwise */
public boolean isSetRoleName() {
return this.roleName != null;
}
public void setRoleNameIsSet(boolean value) {
if (!value) {
this.roleName = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getPrincipalName() {
return this.principalName;
}
public void setPrincipalName(@org.apache.thrift.annotation.Nullable java.lang.String principalName) {
this.principalName = principalName;
}
public void unsetPrincipalName() {
this.principalName = null;
}
/** Returns true if field principalName is set (has been assigned a value) and false otherwise */
public boolean isSetPrincipalName() {
return this.principalName != null;
}
public void setPrincipalNameIsSet(boolean value) {
if (!value) {
this.principalName = null;
}
}
/**
*
* @see PrincipalType
*/
@org.apache.thrift.annotation.Nullable
public PrincipalType getPrincipalType() {
return this.principalType;
}
/**
*
* @see PrincipalType
*/
public void setPrincipalType(@org.apache.thrift.annotation.Nullable PrincipalType principalType) {
this.principalType = principalType;
}
public void unsetPrincipalType() {
this.principalType = null;
}
/** Returns true if field principalType is set (has been assigned a value) and false otherwise */
public boolean isSetPrincipalType() {
return this.principalType != null;
}
public void setPrincipalTypeIsSet(boolean value) {
if (!value) {
this.principalType = null;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.String getGrantor() {
return this.grantor;
}
public void setGrantor(@org.apache.thrift.annotation.Nullable java.lang.String grantor) {
this.grantor = grantor;
}
public void unsetGrantor() {
this.grantor = null;
}
/** Returns true if field grantor is set (has been assigned a value) and false otherwise */
public boolean isSetGrantor() {
return this.grantor != null;
}
public void setGrantorIsSet(boolean value) {
if (!value) {
this.grantor = null;
}
}
/**
*
* @see PrincipalType
*/
@org.apache.thrift.annotation.Nullable
public PrincipalType getGrantorType() {
return this.grantorType;
}
/**
*
* @see PrincipalType
*/
public void setGrantorType(@org.apache.thrift.annotation.Nullable PrincipalType grantorType) {
this.grantorType = grantorType;
}
public void unsetGrantorType() {
this.grantorType = null;
}
/** Returns true if field grantorType is set (has been assigned a value) and false otherwise */
public boolean isSetGrantorType() {
return this.grantorType != null;
}
public void setGrantorTypeIsSet(boolean value) {
if (!value) {
this.grantorType = null;
}
}
public boolean isGrantOption() {
return this.grantOption;
}
public void setGrantOption(boolean grantOption) {
this.grantOption = grantOption;
setGrantOptionIsSet(true);
}
public void unsetGrantOption() {
__isset_bitfield = org.apache.thrift.EncodingUtils.clearBit(__isset_bitfield, __GRANTOPTION_ISSET_ID);
}
/** Returns true if field grantOption is set (has been assigned a value) and false otherwise */
public boolean isSetGrantOption() {
return org.apache.thrift.EncodingUtils.testBit(__isset_bitfield, __GRANTOPTION_ISSET_ID);
}
public void setGrantOptionIsSet(boolean value) {
__isset_bitfield = org.apache.thrift.EncodingUtils.setBit(__isset_bitfield, __GRANTOPTION_ISSET_ID, value);
}
public void setFieldValue(_Fields field, @org.apache.thrift.annotation.Nullable java.lang.Object value) {
switch (field) {
case REQUEST_TYPE:
if (value == null) {
unsetRequestType();
} else {
setRequestType((GrantRevokeType)value);
}
break;
case ROLE_NAME:
if (value == null) {
unsetRoleName();
} else {
setRoleName((java.lang.String)value);
}
break;
case PRINCIPAL_NAME:
if (value == null) {
unsetPrincipalName();
} else {
setPrincipalName((java.lang.String)value);
}
break;
case PRINCIPAL_TYPE:
if (value == null) {
unsetPrincipalType();
} else {
setPrincipalType((PrincipalType)value);
}
break;
case GRANTOR:
if (value == null) {
unsetGrantor();
} else {
setGrantor((java.lang.String)value);
}
break;
case GRANTOR_TYPE:
if (value == null) {
unsetGrantorType();
} else {
setGrantorType((PrincipalType)value);
}
break;
case GRANT_OPTION:
if (value == null) {
unsetGrantOption();
} else {
setGrantOption((java.lang.Boolean)value);
}
break;
}
}
@org.apache.thrift.annotation.Nullable
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case REQUEST_TYPE:
return getRequestType();
case ROLE_NAME:
return getRoleName();
case PRINCIPAL_NAME:
return getPrincipalName();
case PRINCIPAL_TYPE:
return getPrincipalType();
case GRANTOR:
return getGrantor();
case GRANTOR_TYPE:
return getGrantorType();
case GRANT_OPTION:
return isGrantOption();
}
throw new java.lang.IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case REQUEST_TYPE:
return isSetRequestType();
case ROLE_NAME:
return isSetRoleName();
case PRINCIPAL_NAME:
return isSetPrincipalName();
case PRINCIPAL_TYPE:
return isSetPrincipalType();
case GRANTOR:
return isSetGrantor();
case GRANTOR_TYPE:
return isSetGrantorType();
case GRANT_OPTION:
return isSetGrantOption();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that instanceof GrantRevokeRoleRequest)
return this.equals((GrantRevokeRoleRequest)that);
return false;
}
public boolean equals(GrantRevokeRoleRequest that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_requestType = true && this.isSetRequestType();
boolean that_present_requestType = true && that.isSetRequestType();
if (this_present_requestType || that_present_requestType) {
if (!(this_present_requestType && that_present_requestType))
return false;
if (!this.requestType.equals(that.requestType))
return false;
}
boolean this_present_roleName = true && this.isSetRoleName();
boolean that_present_roleName = true && that.isSetRoleName();
if (this_present_roleName || that_present_roleName) {
if (!(this_present_roleName && that_present_roleName))
return false;
if (!this.roleName.equals(that.roleName))
return false;
}
boolean this_present_principalName = true && this.isSetPrincipalName();
boolean that_present_principalName = true && that.isSetPrincipalName();
if (this_present_principalName || that_present_principalName) {
if (!(this_present_principalName && that_present_principalName))
return false;
if (!this.principalName.equals(that.principalName))
return false;
}
boolean this_present_principalType = true && this.isSetPrincipalType();
boolean that_present_principalType = true && that.isSetPrincipalType();
if (this_present_principalType || that_present_principalType) {
if (!(this_present_principalType && that_present_principalType))
return false;
if (!this.principalType.equals(that.principalType))
return false;
}
boolean this_present_grantor = true && this.isSetGrantor();
boolean that_present_grantor = true && that.isSetGrantor();
if (this_present_grantor || that_present_grantor) {
if (!(this_present_grantor && that_present_grantor))
return false;
if (!this.grantor.equals(that.grantor))
return false;
}
boolean this_present_grantorType = true && this.isSetGrantorType();
boolean that_present_grantorType = true && that.isSetGrantorType();
if (this_present_grantorType || that_present_grantorType) {
if (!(this_present_grantorType && that_present_grantorType))
return false;
if (!this.grantorType.equals(that.grantorType))
return false;
}
boolean this_present_grantOption = true && this.isSetGrantOption();
boolean that_present_grantOption = true && that.isSetGrantOption();
if (this_present_grantOption || that_present_grantOption) {
if (!(this_present_grantOption && that_present_grantOption))
return false;
if (this.grantOption != that.grantOption)
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetRequestType()) ? 131071 : 524287);
if (isSetRequestType())
hashCode = hashCode * 8191 + requestType.getValue();
hashCode = hashCode * 8191 + ((isSetRoleName()) ? 131071 : 524287);
if (isSetRoleName())
hashCode = hashCode * 8191 + roleName.hashCode();
hashCode = hashCode * 8191 + ((isSetPrincipalName()) ? 131071 : 524287);
if (isSetPrincipalName())
hashCode = hashCode * 8191 + principalName.hashCode();
hashCode = hashCode * 8191 + ((isSetPrincipalType()) ? 131071 : 524287);
if (isSetPrincipalType())
hashCode = hashCode * 8191 + principalType.getValue();
hashCode = hashCode * 8191 + ((isSetGrantor()) ? 131071 : 524287);
if (isSetGrantor())
hashCode = hashCode * 8191 + grantor.hashCode();
hashCode = hashCode * 8191 + ((isSetGrantorType()) ? 131071 : 524287);
if (isSetGrantorType())
hashCode = hashCode * 8191 + grantorType.getValue();
hashCode = hashCode * 8191 + ((isSetGrantOption()) ? 131071 : 524287);
if (isSetGrantOption())
hashCode = hashCode * 8191 + ((grantOption) ? 131071 : 524287);
return hashCode;
}
@Override
public int compareTo(GrantRevokeRoleRequest other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.compare(isSetRequestType(), other.isSetRequestType());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetRequestType()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.requestType, other.requestType);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetRoleName(), other.isSetRoleName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetRoleName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.roleName, other.roleName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetPrincipalName(), other.isSetPrincipalName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetPrincipalName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.principalName, other.principalName);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetPrincipalType(), other.isSetPrincipalType());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetPrincipalType()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.principalType, other.principalType);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetGrantor(), other.isSetGrantor());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetGrantor()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.grantor, other.grantor);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetGrantorType(), other.isSetGrantorType());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetGrantorType()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.grantorType, other.grantorType);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = java.lang.Boolean.compare(isSetGrantOption(), other.isSetGrantOption());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetGrantOption()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.grantOption, other.grantOption);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
@org.apache.thrift.annotation.Nullable
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("GrantRevokeRoleRequest(");
boolean first = true;
sb.append("requestType:");
if (this.requestType == null) {
sb.append("null");
} else {
sb.append(this.requestType);
}
first = false;
if (!first) sb.append(", ");
sb.append("roleName:");
if (this.roleName == null) {
sb.append("null");
} else {
sb.append(this.roleName);
}
first = false;
if (!first) sb.append(", ");
sb.append("principalName:");
if (this.principalName == null) {
sb.append("null");
} else {
sb.append(this.principalName);
}
first = false;
if (!first) sb.append(", ");
sb.append("principalType:");
if (this.principalType == null) {
sb.append("null");
} else {
sb.append(this.principalType);
}
first = false;
if (isSetGrantor()) {
if (!first) sb.append(", ");
sb.append("grantor:");
if (this.grantor == null) {
sb.append("null");
} else {
sb.append(this.grantor);
}
first = false;
}
if (isSetGrantorType()) {
if (!first) sb.append(", ");
sb.append("grantorType:");
if (this.grantorType == null) {
sb.append("null");
} else {
sb.append(this.grantorType);
}
first = false;
}
if (isSetGrantOption()) {
if (!first) sb.append(", ");
sb.append("grantOption:");
sb.append(this.grantOption);
first = false;
}
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, java.lang.ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class GrantRevokeRoleRequestStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public GrantRevokeRoleRequestStandardScheme getScheme() {
return new GrantRevokeRoleRequestStandardScheme();
}
}
private static class GrantRevokeRoleRequestStandardScheme extends org.apache.thrift.scheme.StandardScheme<GrantRevokeRoleRequest> {
public void read(org.apache.thrift.protocol.TProtocol iprot, GrantRevokeRoleRequest struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // REQUEST_TYPE
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.requestType = org.apache.hadoop.hive.metastore.api.GrantRevokeType.findByValue(iprot.readI32());
struct.setRequestTypeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // ROLE_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.roleName = iprot.readString();
struct.setRoleNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 3: // PRINCIPAL_NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.principalName = iprot.readString();
struct.setPrincipalNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 4: // PRINCIPAL_TYPE
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.principalType = org.apache.hadoop.hive.metastore.api.PrincipalType.findByValue(iprot.readI32());
struct.setPrincipalTypeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 5: // GRANTOR
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.grantor = iprot.readString();
struct.setGrantorIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 6: // GRANTOR_TYPE
if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
struct.grantorType = org.apache.hadoop.hive.metastore.api.PrincipalType.findByValue(iprot.readI32());
struct.setGrantorTypeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 7: // GRANT_OPTION
if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {
struct.grantOption = iprot.readBool();
struct.setGrantOptionIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, GrantRevokeRoleRequest struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.requestType != null) {
oprot.writeFieldBegin(REQUEST_TYPE_FIELD_DESC);
oprot.writeI32(struct.requestType.getValue());
oprot.writeFieldEnd();
}
if (struct.roleName != null) {
oprot.writeFieldBegin(ROLE_NAME_FIELD_DESC);
oprot.writeString(struct.roleName);
oprot.writeFieldEnd();
}
if (struct.principalName != null) {
oprot.writeFieldBegin(PRINCIPAL_NAME_FIELD_DESC);
oprot.writeString(struct.principalName);
oprot.writeFieldEnd();
}
if (struct.principalType != null) {
oprot.writeFieldBegin(PRINCIPAL_TYPE_FIELD_DESC);
oprot.writeI32(struct.principalType.getValue());
oprot.writeFieldEnd();
}
if (struct.grantor != null) {
if (struct.isSetGrantor()) {
oprot.writeFieldBegin(GRANTOR_FIELD_DESC);
oprot.writeString(struct.grantor);
oprot.writeFieldEnd();
}
}
if (struct.grantorType != null) {
if (struct.isSetGrantorType()) {
oprot.writeFieldBegin(GRANTOR_TYPE_FIELD_DESC);
oprot.writeI32(struct.grantorType.getValue());
oprot.writeFieldEnd();
}
}
if (struct.isSetGrantOption()) {
oprot.writeFieldBegin(GRANT_OPTION_FIELD_DESC);
oprot.writeBool(struct.grantOption);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class GrantRevokeRoleRequestTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public GrantRevokeRoleRequestTupleScheme getScheme() {
return new GrantRevokeRoleRequestTupleScheme();
}
}
private static class GrantRevokeRoleRequestTupleScheme extends org.apache.thrift.scheme.TupleScheme<GrantRevokeRoleRequest> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, GrantRevokeRoleRequest struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetRequestType()) {
optionals.set(0);
}
if (struct.isSetRoleName()) {
optionals.set(1);
}
if (struct.isSetPrincipalName()) {
optionals.set(2);
}
if (struct.isSetPrincipalType()) {
optionals.set(3);
}
if (struct.isSetGrantor()) {
optionals.set(4);
}
if (struct.isSetGrantorType()) {
optionals.set(5);
}
if (struct.isSetGrantOption()) {
optionals.set(6);
}
oprot.writeBitSet(optionals, 7);
if (struct.isSetRequestType()) {
oprot.writeI32(struct.requestType.getValue());
}
if (struct.isSetRoleName()) {
oprot.writeString(struct.roleName);
}
if (struct.isSetPrincipalName()) {
oprot.writeString(struct.principalName);
}
if (struct.isSetPrincipalType()) {
oprot.writeI32(struct.principalType.getValue());
}
if (struct.isSetGrantor()) {
oprot.writeString(struct.grantor);
}
if (struct.isSetGrantorType()) {
oprot.writeI32(struct.grantorType.getValue());
}
if (struct.isSetGrantOption()) {
oprot.writeBool(struct.grantOption);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, GrantRevokeRoleRequest struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(7);
if (incoming.get(0)) {
struct.requestType = org.apache.hadoop.hive.metastore.api.GrantRevokeType.findByValue(iprot.readI32());
struct.setRequestTypeIsSet(true);
}
if (incoming.get(1)) {
struct.roleName = iprot.readString();
struct.setRoleNameIsSet(true);
}
if (incoming.get(2)) {
struct.principalName = iprot.readString();
struct.setPrincipalNameIsSet(true);
}
if (incoming.get(3)) {
struct.principalType = org.apache.hadoop.hive.metastore.api.PrincipalType.findByValue(iprot.readI32());
struct.setPrincipalTypeIsSet(true);
}
if (incoming.get(4)) {
struct.grantor = iprot.readString();
struct.setGrantorIsSet(true);
}
if (incoming.get(5)) {
struct.grantorType = org.apache.hadoop.hive.metastore.api.PrincipalType.findByValue(iprot.readI32());
struct.setGrantorTypeIsSet(true);
}
if (incoming.get(6)) {
struct.grantOption = iprot.readBool();
struct.setGrantOptionIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
|
apache/juneau | 33,918 | juneau-bean/juneau-bean-html5/src/main/java/org/apache/juneau/bean/html5/HtmlElement.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.bean.html5;
import static org.apache.juneau.html.annotation.HtmlFormat.*;
import static org.apache.juneau.internal.CollectionUtils.*;
import static org.apache.juneau.xml.annotation.XmlFormat.*;
import java.net.*;
import org.apache.juneau.common.utils.*;
import org.apache.juneau.*;
import org.apache.juneau.annotation.*;
import org.apache.juneau.html.*;
import org.apache.juneau.internal.*;
import org.apache.juneau.xml.annotation.*;
/**
* Superclass for all HTML elements.
*
* <p>
* These are beans that when serialized using {@link HtmlSerializer} generate valid HTML5 elements.
*
* <h5 class='section'>See Also:</h5><ul>
* <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauBeanHtml5">juneau-bean-html5</a>
* </ul>
*/
@org.apache.juneau.html.annotation.Html(format=XML)
@FluentSetters
public abstract class HtmlElement {
private java.util.Map<String,Object> attrs;
/**
* The attributes of this element.
*
* @return The attributes of this element.
*/
@Xml(format=ATTRS)
@Beanp("a")
public java.util.Map<String,Object> getAttrs() {
return attrs;
}
/**
* Sets the attributes for this element.
*
* @param attrs The new attributes for this element.
* @return This object.
*/
@Beanp("a")
public HtmlElement setAttrs(java.util.Map<String,Object> attrs) {
if (attrs != null) {
attrs.entrySet().forEach(x -> {
var key = x.getKey();
if ("url".equals(key) || "href".equals(key) || key.endsWith("action"))
x.setValue(StringUtils.toURI(x.getValue()));
});
}
this.attrs = attrs;
return this;
}
/**
* Adds an arbitrary attribute to this element.
*
* @param key The attribute name.
* @param val The attribute value.
* @return This object.
*/
public HtmlElement attr(String key, Object val) {
if (attrs == null)
attrs = map();
if (val == null)
attrs.remove(key);
else {
if ("url".equals(key) || "href".equals(key) || key.endsWith("action"))
val = StringUtils.toURI(val);
attrs.put(key, val);
}
return this;
}
/**
* Adds an arbitrary URI attribute to this element.
*
* <p>
* Same as {@link #attr(String, Object)}, except if the value is a string that appears to be a URI
* (e.g. <js>"servlet:/xxx"</js>).
*
* <p>
* The value can be of any of the following types: {@link URI}, {@link URL}, {@link String}.
* Strings must be valid URIs.
*
* <p>
* URIs defined by {@link UriResolver} can be used for values.
*
* @param key The attribute name.
* @param val The attribute value.
* @return This object.
*/
public HtmlElement attrUri(String key, Object val) {
if (attrs == null)
attrs = map();
attrs.put(key, StringUtils.toURI(val));
return this;
}
/**
* Returns the attribute with the specified name.
*
* @param key The attribute name.
* @return The attribute value, or <jk>null</jk> if the named attribute does not exist.
*/
public String getAttr(String key) {
return getAttr(String.class, key);
}
/**
* Returns the attribute with the specified name converted to the specified class type.
*
* @param <T> The class type to convert this class to.
* @param type
* The class type to convert this class to.
* See {@link ConverterUtils} for a list of supported conversion types.
* @param key The attribute name.
* @return The attribute value, or <jk>null</jk> if the named attribute does not exist.
*/
public <T> T getAttr(Class<T> type, String key) {
return attrs == null ? null : ConverterUtils.toType(attrs.get(key), type);
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/editing.html#the-accesskey-attribute">accesskey</a>
* attribute.
*
* <p>
* Defines a keyboard shortcut to activate or focus an element.
* The value should be a single character that, when pressed with a modifier key (usually Alt),
* activates the element.
*
* @param accesskey The keyboard shortcut character (e.g., <js>"a"</js>, <js>"1"</js>).
* @return This object.
*/
@FluentSetter
public HtmlElement accesskey(String value) {
attr("accesskey", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/dom.html#classes">class</a> attribute.
*
* <p>
* Specifies one or more CSS class names for the element, separated by spaces.
* These classes can be used for styling and JavaScript selection.
*
* @param _class Space-separated CSS class names (e.g., <js>"btn btn-primary"</js>).
* @return This object.
*/
@FluentSetter
public HtmlElement _class(String value) { // NOSONAR - Intentional naming.
attr("class", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/editing.html#attr-contenteditable">contenteditable</a>
* attribute.
*
* <p>
* Indicates whether the element's content is editable by the user.
*
* <p>
* Possible values:
* <ul>
* <li><js>"true"</js> or empty string - Element content is editable</li>
* <li><js>"false"</js> - Element content is not editable</li>
* <li><js>"plaintext-only"</js> - Element content is editable, but rich text formatting is disabled</li>
* </ul>
*
* @param contenteditable The editability state of the element.
* @return This object.
*/
@FluentSetter
public HtmlElement contenteditable(Object value) {
attr("contenteditable", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/dom.html#the-dir-attribute">dir</a> attribute.
*
* <p>
* Specifies the text direction of the element's content.
*
* <p>
* Possible values:
* <ul>
* <li><js>"ltr"</js> - Left-to-right text direction</li>
* <li><js>"rtl"</js> - Right-to-left text direction</li>
* <li><js>"auto"</js> - Browser determines direction based on content</li>
* </ul>
*
* @param dir The text direction for the element.
* @return This object.
*/
@FluentSetter
public HtmlElement dir(String value) {
attr("dir", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/editing.html#the-hidden-attribute">hidden</a> attribute.
*
* <p>
* This attribute uses deminimized values:
* <ul>
* <li><jk>false</jk> - Attribute is not added</li>
* <li><jk>true</jk> - Attribute is added as <js>"hidden"</js></li>
* <li>Other values - Passed through as-is</li>
* </ul>
*
* @param hidden
* The new value for this attribute.
* Typically a {@link Boolean} or {@link String}.
* @return This object.
*/
@FluentSetter
public HtmlElement hidden(Object value) {
attr("hidden", deminimize(value, "hidden"));
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/dom.html#the-id-attribute">id</a> attribute.
*
* <p>
* Specifies a unique identifier for the element. The ID must be unique within the document
* and can be used for CSS styling, JavaScript selection, and anchor links.
*
* @param id A unique identifier for the element (e.g., <js>"header"</js>, <js>"main-content"</js>).
* @return This object.
*/
@FluentSetter
public HtmlElement id(String value) {
attr("id", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/dom.html#attr-lang">lang</a> attribute.
*
* <p>
* Specifies the primary language of the element's content using a language tag.
* This helps with accessibility, search engines, and browser features like spell checking.
*
* @param lang A language tag (e.g., <js>"en"</js>, <js>"en-US"</js>, <js>"es"</js>, <js>"fr-CA"</js>).
* @return This object.
*/
@FluentSetter
public HtmlElement lang(String value) {
attr("lang", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onabort">onabort</a> attribute.
*
* <p>
* Event handler for when an operation is aborted (e.g., image loading is cancelled).
*
* @param onabort JavaScript code to execute when the abort event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onabort(String value) {
attr("onabort", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onblur">onblur</a> attribute.
*
* <p>
* Event handler for when the element loses focus.
*
* @param onblur JavaScript code to execute when the element loses focus.
* @return This object.
*/
@FluentSetter
public HtmlElement onblur(String value) {
attr("onblur", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-oncancel">oncancel</a> attribute.
*
* <p>
* Event handler for when a dialog is cancelled.
*
* @param oncancel JavaScript code to execute when the cancel event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement oncancel(String value) {
attr("oncancel", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-oncanplay">oncanplay</a> attribute.
*
* <p>
* Event handler for when the media can start playing (enough data has been buffered).
*
* @param oncanplay JavaScript code to execute when the canplay event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement oncanplay(String value) {
attr("oncanplay", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-oncanplaythrough">oncanplaythrough</a>
* attribute.
*
* <p>
* Event handler for when the media can play through to the end without buffering.
*
* @param oncanplaythrough JavaScript code to execute when the canplaythrough event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement oncanplaythrough(String value) {
attr("oncanplaythrough", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onchange">onchange</a> attribute.
*
* <p>
* Event handler for when the value of a form element changes and loses focus.
*
* @param onchange JavaScript code to execute when the change event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onchange(String value) {
attr("onchange", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onclick">onclick</a> attribute.
*
* <p>
* Event handler for when the element is clicked.
*
* @param onclick JavaScript code to execute when the click event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onclick(String value) {
attr("onclick", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-oncuechange">oncuechange</a>
* attribute.
*
* <p>
* Event handler for when a text track cue changes.
*
* @param oncuechange JavaScript code to execute when the cuechange event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement oncuechange(String value) {
attr("oncuechange", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-ondblclick">ondblclick</a> attribute.
*
* <p>
* Event handler for when the element is double-clicked.
*
* @param ondblclick JavaScript code to execute when the dblclick event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement ondblclick(String value) {
attr("ondblclick", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-ondurationchange">ondurationchange</a>
* attribute.
*
* <p>
* Event handler for when the duration of the media changes.
*
* @param ondurationchange JavaScript code to execute when the durationchange event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement ondurationchange(String value) {
attr("ondurationchange", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onemptied">onemptied</a> attribute.
*
* <p>
* Event handler for when the media element becomes empty (e.g., network error).
*
* @param onemptied JavaScript code to execute when the emptied event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onemptied(String value) {
attr("onemptied", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onended">onended</a> attribute.
*
* <p>
* Event handler for when the media playback reaches the end.
*
* @param onended JavaScript code to execute when the ended event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onended(String value) {
attr("onended", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onerror">onerror</a> attribute.
*
* <p>
* Event handler for when an error occurs (e.g., failed resource loading).
*
* @param onerror JavaScript code to execute when the error event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onerror(String value) {
attr("onerror", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onfocus">onfocus</a> attribute.
*
* <p>
* Event handler for when the element receives focus.
*
* @param onfocus JavaScript code to execute when the focus event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onfocus(String value) {
attr("onfocus", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-oninput">oninput</a> attribute.
*
* <p>
* Event handler for when the value of an input element changes (fires on every keystroke).
*
* @param oninput JavaScript code to execute when the input event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement oninput(String value) {
attr("oninput", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-oninvalid">oninvalid</a> attribute.
*
* <p>
* Event handler for when form validation fails.
*
* @param oninvalid JavaScript code to execute when the invalid event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement oninvalid(String value) {
attr("oninvalid", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onkeydown">onkeydown</a> attribute.
*
* <p>
* Event handler for when a key is pressed down.
*
* @param onkeydown JavaScript code to execute when the keydown event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onkeydown(String value) {
attr("onkeydown", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onkeypress">onkeypress</a> attribute.
*
* <p>
* Event handler for when a key is pressed (deprecated, use onkeydown instead).
*
* @param onkeypress JavaScript code to execute when the keypress event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onkeypress(String value) {
attr("onkeypress", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onkeyup">onkeyup</a> attribute.
*
* <p>
* Event handler for when a key is released.
*
* @param onkeyup JavaScript code to execute when the keyup event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onkeyup(String value) {
attr("onkeyup", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onload">onload</a> attribute.
*
* <p>
* Event handler for when the element and its resources have finished loading.
*
* @param onload JavaScript code to execute when the load event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onload(String value) {
attr("onload", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onloadeddata">onloadeddata</a>
* attribute.
*
* <p>
* Event handler for when the first frame of media has finished loading.
*
* @param onloadeddata JavaScript code to execute when the loadeddata event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onloadeddata(String value) {
attr("onloadeddata", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onloadedmetadata">onloadedmetadata</a>
* attribute.
*
* <p>
* Event handler for when metadata (duration, dimensions, etc.) has been loaded.
*
* @param onloadedmetadata JavaScript code to execute when the loadedmetadata event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onloadedmetadata(String value) {
attr("onloadedmetadata", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onloadstart">onloadstart</a>
* attribute.
*
* <p>
* Event handler for when the browser starts loading the media.
*
* @param onloadstart JavaScript code to execute when the loadstart event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onloadstart(String value) {
attr("onloadstart", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onmousedown">onmousedown</a>
* attribute.
*
* <p>
* Event handler for when a mouse button is pressed down on the element.
*
* @param onmousedown JavaScript code to execute when the mousedown event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onmousedown(String value) {
attr("onmousedown", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onmouseenter">onmouseenter</a> attribute.
*
* <p>
* Event handler for when the mouse pointer enters the element (does not bubble).
*
* @param onmouseenter JavaScript code to execute when the mouseenter event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onmouseenter(String value) {
attr("onmouseenter", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onmouseleave">onmouseleave</a>
* attribute.
*
* <p>
* Event handler for when the mouse pointer leaves the element (does not bubble).
*
* @param onmouseleave JavaScript code to execute when the mouseleave event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onmouseleave(String value) {
attr("onmouseleave", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onmousemove">onmousemove</a>
* attribute.
*
* <p>
* Event handler for when the mouse pointer moves over the element.
*
* @param onmousemove JavaScript code to execute when the mousemove event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onmousemove(String value) {
attr("onmousemove", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onmouseout">onmouseout</a> attribute.
*
* <p>
* Event handler for when the mouse pointer moves out of the element (bubbles).
*
* @param onmouseout JavaScript code to execute when the mouseout event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onmouseout(String value) {
attr("onmouseout", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onmouseover">onmouseover</a>
* attribute.
*
* <p>
* Event handler for when the mouse pointer moves over the element (bubbles).
*
* @param onmouseover JavaScript code to execute when the mouseover event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onmouseover(String value) {
attr("onmouseover", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onmouseup">onmouseup</a> attribute.
*
* <p>
* Event handler for when a mouse button is released over the element.
*
* @param onmouseup JavaScript code to execute when the mouseup event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onmouseup(String value) {
attr("onmouseup", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onmousewheel">onmousewheel</a>
* attribute.
*
* <p>
* Event handler for when the mouse wheel is rotated over the element (deprecated, use onwheel).
*
* @param onmousewheel JavaScript code to execute when the mousewheel event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onmousewheel(String value) {
attr("onmousewheel", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onpause">onpause</a> attribute.
*
* <p>
* Event handler for when media playback is paused.
*
* @param onpause JavaScript code to execute when the pause event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onpause(String value) {
attr("onpause", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onplay">onplay</a> attribute.
*
* <p>
* Event handler for when media playback starts.
*
* @param onplay JavaScript code to execute when the play event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onplay(String value) {
attr("onplay", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onplaying">onplaying</a> attribute.
*
* <p>
* Event handler for when media playback starts after being paused or delayed.
*
* @param onplaying JavaScript code to execute when the playing event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onplaying(String value) {
attr("onplaying", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onprogress">onprogress</a> attribute.
*
* <p>
* Event handler for when the browser is downloading media data.
*
* @param onprogress JavaScript code to execute when the progress event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onprogress(String value) {
attr("onprogress", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onratechange">onratechange</a>
* attribute.
*
* <p>
* Event handler for when the playback rate of media changes.
*
* @param onratechange JavaScript code to execute when the ratechange event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onratechange(String value) {
attr("onratechange", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onreset">onreset</a> attribute.
*
* <p>
* Event handler for when a form is reset.
*
* @param onreset JavaScript code to execute when the reset event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onreset(String value) {
attr("onreset", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onresize">onresize</a> attribute.
*
* <p>
* Event handler for when the element is resized.
*
* @param onresize JavaScript code to execute when the resize event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onresize(String value) {
attr("onresize", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onscroll">onscroll</a> attribute.
*
* <p>
* Event handler for when the element's scrollbar is scrolled.
*
* @param onscroll JavaScript code to execute when the scroll event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onscroll(String value) {
attr("onscroll", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onseeked">onseeked</a> attribute.
*
* <p>
* Event handler for when a seek operation completes.
*
* @param onseeked JavaScript code to execute when the seeked event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onseeked(String value) {
attr("onseeked", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onseeking">onseeking</a> attribute.
*
* <p>
* Event handler for when a seek operation begins.
*
* @param onseeking JavaScript code to execute when the seeking event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onseeking(String value) {
attr("onseeking", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onselect">onselect</a> attribute.
*
* <p>
* Event handler for when text is selected in the element.
*
* @param onselect JavaScript code to execute when the select event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onselect(String value) {
attr("onselect", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onshow">onshow</a> attribute.
*
* <p>
* Event handler for when a context menu is shown.
*
* @param onshow JavaScript code to execute when the show event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onshow(String value) {
attr("onshow", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onstalled">onstalled</a> attribute.
*
* <p>
* Event handler for when media loading is stalled.
*
* @param onstalled JavaScript code to execute when the stalled event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onstalled(String value) {
attr("onstalled", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onsubmit">onsubmit</a> attribute.
*
* <p>
* Event handler for when a form is submitted.
*
* @param onsubmit JavaScript code to execute when the submit event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onsubmit(String value) {
attr("onsubmit", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onsuspend">onsuspend</a> attribute.
*
* <p>
* Event handler for when media loading is suspended.
*
* @param onsuspend JavaScript code to execute when the suspend event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onsuspend(String value) {
attr("onsuspend", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-ontimeupdate">ontimeupdate</a>
* attribute.
*
* <p>
* Event handler for when the current playback position changes.
*
* @param ontimeupdate JavaScript code to execute when the timeupdate event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement ontimeupdate(String value) {
attr("ontimeupdate", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-ontoggle">ontoggle</a> attribute.
*
* <p>
* Event handler for when a details element is opened or closed.
*
* @param ontoggle JavaScript code to execute when the toggle event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement ontoggle(String value) {
attr("ontoggle", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onvolumechange">onvolumechange</a>
* attribute.
*
* <p>
* Event handler for when the volume of media changes.
*
* @param onvolumechange JavaScript code to execute when the volumechange event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onvolumechange(String value) {
attr("onvolumechange", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/webappapis.html#handler-onwaiting">onwaiting</a> attribute.
*
* <p>
* Event handler for when media playback stops to buffer more data.
*
* @param onwaiting JavaScript code to execute when the waiting event occurs.
* @return This object.
*/
@FluentSetter
public HtmlElement onwaiting(String value) {
attr("onwaiting", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/editing.html#attr-spellcheck">spellcheck</a> attribute.
*
* <p>
* Indicates whether the element should have its spelling and grammar checked.
*
* <p>
* Possible values:
* <ul>
* <li><js>"true"</js> - Enable spell checking for this element</li>
* <li><js>"false"</js> - Disable spell checking for this element</li>
* </ul>
*
* @param spellcheck Whether spell checking should be enabled.
* @return This object.
*/
@FluentSetter
public HtmlElement spellcheck(Object value) {
attr("spellcheck", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/dom.html#the-style-attribute">style</a> attribute.
*
* <p>
* Specifies inline CSS styles for the element. The value should be valid CSS
* property-value pairs separated by semicolons.
*
* @param style Inline CSS styles (e.g., <js>"color: red; font-size: 14px;"</js>).
* @return This object.
*/
@FluentSetter
public HtmlElement style(String value) {
attr("style", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/editing.html#attr-tabindex">tabindex</a> attribute.
*
* <p>
* Specifies the tab order of the element when navigating with the keyboard.
*
* <p>
* Possible values:
* <ul>
* <li>Positive integer - Element is focusable and participates in tab order</li>
* <li><js>"0"</js> - Element is focusable but not in tab order</li>
* <li>Negative integer - Element is not focusable</li>
* </ul>
*
* @param tabindex The tab order value for keyboard navigation.
* @return This object.
*/
@FluentSetter
public HtmlElement tabindex(Object value) {
attr("tabindex", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/dom.html#attr-title">title</a> attribute.
*
* <p>
* Specifies additional information about the element, typically displayed as a tooltip
* when the user hovers over the element.
*
* @param title Tooltip text to display on hover (e.g., <js>"Click to submit form"</js>).
* @return This object.
*/
@FluentSetter
public HtmlElement title(String value) {
attr("title", value);
return this;
}
/**
* <a class="doclink" href="https://www.w3.org/TR/html5/dom.html#attr-translate">translate</a> attribute.
*
* <p>
* Specifies whether the element's content should be translated when the page is localized.
*
* <p>
* Possible values:
* <ul>
* <li><js>"yes"</js> - Content should be translated (default)</li>
* <li><js>"no"</js> - Content should not be translated</li>
* </ul>
*
* @param translate Whether the element content should be translated.
* @return This object.
*/
@FluentSetter
public HtmlElement translate(Object value) {
attr("translate", value);
return this;
}
/**
* If the specified attribute is a boolean, it gets converted to the attribute name if <jk>true</jk> or <jk>null</jk> if <jk>false</jk>.
*
* @param value The attribute value.
* @param attr The attribute name.
* @return The deminimized value, or the same value if the value wasn't a boolean.
*/
protected Object deminimize(Object value, String attr) {
if (value instanceof Boolean b) {
if (Boolean.TRUE.equals(b))
return attr;
return null;
}
return value;
}
// <FluentSetters>
// </FluentSetters>
@Override /* Object */
public String toString() {
return HtmlSerializer.DEFAULT_SQ.toString(this);
}
} |
apache/qpid-jms | 35,692 | qpid-jms-client/src/test/java/org/apache/qpid/jms/message/JmsMapMessageTest.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.jms.message;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import jakarta.jms.JMSException;
import jakarta.jms.MessageFormatException;
import jakarta.jms.MessageNotWriteableException;
import org.apache.qpid.jms.message.facade.JmsMapMessageFacade;
import org.apache.qpid.jms.message.facade.test.JmsTestMapMessageFacade;
import org.apache.qpid.jms.message.facade.test.JmsTestMessageFactory;
import org.junit.jupiter.api.Test;
/**
* Test that the JMS level JmsMapMessage using a simple default message facade follows
* the JMS spec.
*/
public class JmsMapMessageTest {
private final JmsMessageFactory factory = new JmsTestMessageFactory();
// ======= general =========
@Test
public void testToString() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
assertTrue(mapMessage.toString().startsWith("JmsMapMessage"));
}
@Test
public void testGetMapNamesWithNewMessageToSendReturnsEmptyEnumeration() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
Enumeration<?> names = mapMessage.getMapNames();
assertFalse(names.hasMoreElements(), "Expected new message to have no map names");
}
/**
* Test that we are able to retrieve the names and values of map entries on a received
* message
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testGetMapNamesUsingReceivedMessageReturnsExpectedEnumeration() throws Exception {
JmsMapMessageFacade facade = new JmsTestMapMessageFacade();
String myKey1 = "key1";
String myKey2 = "key2";
facade.put(myKey1, "value1");
facade.put(myKey2, "value2");
JmsMapMessage mapMessage = new JmsMapMessage(facade);
Enumeration<?> names = mapMessage.getMapNames();
int count = 0;
List<Object> elements = new ArrayList<Object>();
while (names.hasMoreElements()) {
count++;
elements.add(names.nextElement());
}
assertEquals(2, count, "expected 2 map keys in enumeration");
assertTrue(elements.contains(myKey1), "expected key was not found: " + myKey1);
assertTrue(elements.contains(myKey2), "expected key was not found: " + myKey2);
}
/**
* Test that we enforce the requirement that map message key names not be null or the empty
* string.
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetObjectWithNullOrEmptyKeyNameThrowsIAE() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
try {
mapMessage.setObject(null, "value");
fail("Expected exception not thrown");
} catch (IllegalArgumentException iae) {
// expected
}
try {
mapMessage.setObject("", "value");
fail("Expected exception not thrown");
} catch (IllegalArgumentException iae) {
// expected
}
}
/**
* Test that we are not able to write to a received message without calling
* {@link JmsMapMessage#clearBody()}
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testReceivedMessageIsReadOnlyAndThrowsMNWE() throws Exception {
JmsMapMessageFacade facade = new JmsTestMapMessageFacade();
String myKey1 = "key1";
facade.put(myKey1, "value1");
JmsMapMessage mapMessage = new JmsMapMessage(facade);
mapMessage.onDispatch();
try {
mapMessage.setObject("name", "value");
fail("expected exception to be thrown");
} catch (MessageNotWriteableException mnwe) {
// expected
}
}
/**
* Test that calling {@link JmsMapMessage#clearBody()} makes a received message writable
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testClearBodyMakesReceivedMessageWritable() throws Exception {
JmsMapMessageFacade facade = new JmsTestMapMessageFacade();
String myKey1 = "key1";
facade.put(myKey1, "value1");
JmsMapMessage mapMessage = new JmsMapMessage(facade);
mapMessage.onDispatch();
assertTrue(mapMessage.isReadOnlyBody(), "expected message to be read-only");
mapMessage.clearBody();
assertFalse(mapMessage.isReadOnlyBody(), "expected message to be writable");
mapMessage.setObject("name", "value");
}
/**
* Test that calling {@link JmsMapMessage#clearBody()} clears the underlying message body
* map.
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testClearBodyClearsUnderlyingMessageMap() throws Exception {
JmsMapMessageFacade facade = new JmsTestMapMessageFacade();
String myKey1 = "key1";
facade.put(myKey1, "value1");
JmsMapMessage mapMessage = new JmsMapMessage(facade);
assertTrue(mapMessage.itemExists(myKey1), "key should exist: " + myKey1);
mapMessage.clearBody();
assertFalse(mapMessage.itemExists(myKey1), "key should not exist");
}
/**
* When a map entry is not set, the behaviour of JMS specifies that it is equivalent to a
* null value, and the accessors should either return null, throw NPE, or behave in the same
* fashion as <primitive>.valueOf(String).
*
* Test that this is the case.
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testGetMissingMapEntryResultsInExpectedBehaviour() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "does_not_exist";
// expect null
assertNull(mapMessage.getBytes(name));
assertNull(mapMessage.getString(name));
// expect false from Boolean.valueOf(null).
assertFalse(mapMessage.getBoolean(name));
// expect an NFE from the primitive integral <type>.valueOf(null) conversions
assertGetMapEntryThrowsNumberFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsNumberFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsNumberFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsNumberFormatException(mapMessage, name, Long.class);
// expect an NPE from the primitive float, double, and char <type>.valuleOf(null)
// conversions
assertGetMapEntryThrowsNullPointerException(mapMessage, name, Float.class);
assertGetMapEntryThrowsNullPointerException(mapMessage, name, Double.class);
assertGetMapEntryThrowsNullPointerException(mapMessage, name, Character.class);
}
// ======= object =========
/**
* Test that the {@link JmsMapMessage#setObject(String, Object)} method rejects Objects of
* unexpected types
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetObjectWithIllegalTypeThrowsMFE() throws Exception {
assertThrows(MessageFormatException.class, () -> {
JmsMapMessage mapMessage = factory.createMapMessage();
mapMessage.setObject("myPKey", new Exception());
});
}
@Test
public void testSetGetObject() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String keyName = "myProperty";
Object entryValue = null;
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Boolean.valueOf(false);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Byte.valueOf((byte) 1);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Short.valueOf((short) 2);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Integer.valueOf(3);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Long.valueOf(4);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Float.valueOf(5.01F);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Double.valueOf(6.01);
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = "string";
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
entryValue = Character.valueOf('c');
mapMessage.setObject(keyName, entryValue);
assertEquals(entryValue, mapMessage.getObject(keyName));
byte[] bytes = new byte[] { (byte) 1, (byte) 0, (byte) 1 };
mapMessage.setObject(keyName, bytes);
Object retrieved = mapMessage.getObject(keyName);
assertTrue(retrieved instanceof byte[]);
assertTrue(Arrays.equals(bytes, (byte[]) retrieved));
}
// ======= Strings =========
@Test
public void testSetGetString() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
// null value
String name = "myNullString";
String value = null;
assertFalse(mapMessage.itemExists(name));
mapMessage.setString(name, value);
assertTrue(mapMessage.itemExists(name));
assertEquals(value, mapMessage.getString(name));
// non-null value
name = "myName";
value = "myValue";
assertFalse(mapMessage.itemExists(name));
mapMessage.setString(name, value);
assertTrue(mapMessage.itemExists(name));
assertEquals(value, mapMessage.getString(name));
}
/**
* Set a String, then retrieve it as all of the legal type combinations to verify it is
* parsed correctly
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetStringGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myStringName";
String value;
// boolean
value = "true";
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Boolean.valueOf(value), Boolean.class);
// byte
value = String.valueOf(Byte.MAX_VALUE);
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Byte.valueOf(value), Byte.class);
// short
value = String.valueOf(Short.MAX_VALUE);
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Short.valueOf(value), Short.class);
// int
value = String.valueOf(Integer.MAX_VALUE);
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Integer.valueOf(value), Integer.class);
// long
value = String.valueOf(Long.MAX_VALUE);
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Long.valueOf(value), Long.class);
// float
value = String.valueOf(Float.MAX_VALUE);
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Float.valueOf(value), Float.class);
// double
value = String.valueOf(Double.MAX_VALUE);
mapMessage.setString(name, value);
assertGetMapEntryEquals(mapMessage, name, Double.valueOf(value), Double.class);
}
/**
* Set a String, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetStringGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
String value = "myStringValue";
mapMessage.setString(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
}
// ======= boolean =========
/**
* Set a boolean, then retrieve it as all of the legal type combinations to verify it is
* parsed correctly
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetBooleanGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
boolean value = true;
mapMessage.setBoolean(name, value);
assertEquals(value, mapMessage.getBoolean(name), "value not as expected");
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
mapMessage.setBoolean(name, !value);
assertEquals(!value, mapMessage.getBoolean(name), "value not as expected");
assertGetMapEntryEquals(mapMessage, name, String.valueOf(!value), String.class);
}
/**
* Set a boolean, then retrieve it as all of the illegal type combinations to verify it
* fails as expected
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetBooleanGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
boolean value = true;
mapMessage.setBoolean(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Long.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// ======= byte =========
/**
* Set a byte, then retrieve it as all of the legal type combinations to verify it is parsed
* correctly
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetByteGetLegalProperty() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte value = (byte) 1;
mapMessage.setByte(name, value);
assertEquals(value, mapMessage.getByte(name));
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
assertGetMapEntryEquals(mapMessage, name, Short.valueOf(value), Short.class);
assertGetMapEntryEquals(mapMessage, name, Integer.valueOf(value), Integer.class);
assertGetMapEntryEquals(mapMessage, name, Long.valueOf(value), Long.class);
}
/**
* Set a byte, then retrieve it as all of the illegal type combinations to verify it is
* fails as expected
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetByteGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte value = (byte) 1;
mapMessage.setByte(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// ======= short =========
/**
* Set a short, then retrieve it as all of the legal type combinations to verify it is
* parsed correctly
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetShortGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
short value = (short) 1;
mapMessage.setShort(name, value);
assertEquals(value, mapMessage.getShort(name));
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
assertGetMapEntryEquals(mapMessage, name, Integer.valueOf(value), Integer.class);
assertGetMapEntryEquals(mapMessage, name, Long.valueOf(value), Long.class);
}
/**
* Set a short, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetShortGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
short value = (short) 1;
mapMessage.setShort(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// ======= int =========
/**
* Set an int, then retrieve it as all of the legal type combinations to verify it is parsed
* correctly
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetIntGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
int value = 1;
mapMessage.setInt(name, value);
assertEquals(value, mapMessage.getInt(name));
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
assertGetMapEntryEquals(mapMessage, name, Long.valueOf(value), Long.class);
}
/**
* Set an int, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetIntGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
int value = 1;
mapMessage.setInt(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// ======= long =========
/**
* Set a long, then retrieve it as all of the legal type combinations to verify it is parsed
* correctly
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetLongGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
long value = Long.MAX_VALUE;
mapMessage.setLong(name, value);
assertEquals(value, mapMessage.getLong(name));
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
}
/**
* Set an long, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetLongGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
long value = Long.MAX_VALUE;
mapMessage.setLong(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// ======= float =========
/**
* Set a float, then retrieve it as all of the legal type combinations to verify it is
* parsed correctly
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetFloatGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
float value = Float.MAX_VALUE;
mapMessage.setFloat(name, value);
assertEquals(value, mapMessage.getFloat(name), 0.0);
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
assertGetMapEntryEquals(mapMessage, name, Double.valueOf(value), Double.class);
}
/**
* Set a float, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetFloatGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
float value = Float.MAX_VALUE;
mapMessage.setFloat(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Long.class);
}
// ======= double =========
/**
* Set a double, then retrieve it as all of the legal type combinations to verify it is
* parsed correctly
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetDoubleGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
double value = Double.MAX_VALUE;
mapMessage.setDouble(name, value);
assertEquals(value, mapMessage.getDouble(name), 0.0);
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
}
/**
* Set a double, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetDoubleGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
double value = Double.MAX_VALUE;
mapMessage.setDouble(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Long.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
}
// ======= character =========
/**
* Set a char, then retrieve it as all of the legal type combinations to verify it is parsed
* correctly
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetCharGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
char value = 'c';
mapMessage.setChar(name, value);
assertEquals(value, mapMessage.getChar(name));
assertGetMapEntryEquals(mapMessage, name, String.valueOf(value), String.class);
}
/**
* Set a char, then retrieve it as all of the illegal type combinations to verify it fails
* as expected
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetCharGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
char value = 'c';
mapMessage.setChar(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, byte[].class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Long.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
// ========= bytes ========
/**
* Set bytes, then retrieve it as all of the legal type combinations to verify it is parsed
* correctly
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetBytesGetLegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte[] value = "myBytes".getBytes();
mapMessage.setBytes(name, value);
assertTrue(Arrays.equals(value, mapMessage.getBytes(name)));
}
/**
* Set bytes, then retrieve it as all of the illegal type combinations to verify it fails as
* expected
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetBytesGetIllegal() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte[] value = "myBytes".getBytes();
mapMessage.setBytes(name, value);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Character.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, String.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Boolean.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Byte.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Short.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Integer.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Long.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Float.class);
assertGetMapEntryThrowsMessageFormatException(mapMessage, name, Double.class);
}
/**
* Verify that setting bytes takes a copy of the array. Set bytes, then modify them, then
* retrieve the map entry and verify the two differ.
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetBytesTakesSnapshot() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte[] orig = "myBytes".getBytes();
byte[] copy = Arrays.copyOf(orig, orig.length);
// set the original bytes
mapMessage.setBytes(name, orig);
// corrupt the original bytes
orig[0] = (byte) 0;
// verify retrieving the bytes still matches the copy but not the original array
byte[] retrieved = mapMessage.getBytes(name);
assertFalse(Arrays.equals(orig, retrieved));
assertTrue(Arrays.equals(copy, retrieved));
}
/**
* Verify that getting bytes returns a copy of the array. Set bytes, then get them, modify
* the retrieved value, then get them again and verify the two differ.
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testGetBytesReturnsSnapshot() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte[] orig = "myBytes".getBytes();
// set the original bytes
mapMessage.setBytes(name, orig);
// retrieve them
byte[] retrieved1 = mapMessage.getBytes(name);
;
// corrupt the retrieved bytes
retrieved1[0] = (byte) 0;
// verify retrieving the bytes again still matches the original array, but not the
// previously retrieved (and now corrupted) bytes.
byte[] retrieved2 = mapMessage.getBytes(name);
assertTrue(Arrays.equals(orig, retrieved2));
assertFalse(Arrays.equals(retrieved1, retrieved2));
}
/**
* Verify that setting bytes takes a copy of the array. Set bytes, then modify them, then
* retrieve the map entry and verify the two differ.
*
* @throws Exception if an error occurs during the test.
*/
@Test
public void testSetBytesWithOffsetAndLength() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
byte[] orig = "myBytesAll".getBytes();
// extract the segment containing 'Bytes'
int offset = 2;
int length = 5;
byte[] segment = Arrays.copyOfRange(orig, offset, offset + length);
// set the same section from the original bytes
mapMessage.setBytes(name, orig, offset, length);
// verify the retrieved bytes from the map match the segment but not the full original
// array
byte[] retrieved = mapMessage.getBytes(name);
assertFalse(Arrays.equals(orig, retrieved));
assertTrue(Arrays.equals(segment, retrieved));
}
@Test
public void testSetBytesWithNull() throws Exception {
JmsMapMessage mapMessage = factory.createMapMessage();
String name = "myName";
mapMessage.setBytes(name, null);
assertNull(mapMessage.getBytes(name));
}
// ========= utility methods ========
private void assertGetMapEntryEquals(JmsMapMessage testMessage, String name, Object expectedValue, Class<?> clazz) throws JMSException {
Object actualValue = getMapEntryUsingTypeMethod(testMessage, name, clazz);
assertEquals(expectedValue, actualValue);
}
private void assertGetMapEntryThrowsMessageFormatException(JmsMapMessage testMessage, String name, Class<?> clazz) throws JMSException {
try {
getMapEntryUsingTypeMethod(testMessage, name, clazz);
fail("expected exception to be thrown");
} catch (MessageFormatException jmsMFE) {
// expected
}
}
private void assertGetMapEntryThrowsNumberFormatException(JmsMapMessage testMessage, String name, Class<?> clazz) throws JMSException {
try {
getMapEntryUsingTypeMethod(testMessage, name, clazz);
fail("expected exception to be thrown");
} catch (NumberFormatException nfe) {
// expected
}
}
private void assertGetMapEntryThrowsNullPointerException(JmsMapMessage testMessage, String name, Class<?> clazz) throws JMSException {
try {
getMapEntryUsingTypeMethod(testMessage, name, clazz);
fail("expected exception to be thrown");
} catch (NullPointerException npe) {
// expected
}
}
private Object getMapEntryUsingTypeMethod(JmsMapMessage testMessage, String name, Class<?> clazz) throws JMSException {
if (clazz == Boolean.class) {
return testMessage.getBoolean(name);
} else if (clazz == Byte.class) {
return testMessage.getByte(name);
} else if (clazz == Character.class) {
return testMessage.getChar(name);
} else if (clazz == Short.class) {
return testMessage.getShort(name);
} else if (clazz == Integer.class) {
return testMessage.getInt(name);
} else if (clazz == Long.class) {
return testMessage.getLong(name);
} else if (clazz == Float.class) {
return testMessage.getFloat(name);
} else if (clazz == Double.class) {
return testMessage.getDouble(name);
} else if (clazz == String.class) {
return testMessage.getString(name);
} else if (clazz == byte[].class) {
return testMessage.getBytes(name);
} else {
throw new RuntimeException("Unexpected entry type class");
}
}
}
|
googleapis/google-cloud-java | 35,561 | java-channel/proto-google-cloud-channel-v1/src/main/java/com/google/cloud/channel/v1/ListSkuGroupsResponse.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/channel/v1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.channel.v1;
/**
*
*
* <pre>
* Response message for ListSkuGroups.
* </pre>
*
* Protobuf type {@code google.cloud.channel.v1.ListSkuGroupsResponse}
*/
public final class ListSkuGroupsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.channel.v1.ListSkuGroupsResponse)
ListSkuGroupsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListSkuGroupsResponse.newBuilder() to construct.
private ListSkuGroupsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListSkuGroupsResponse() {
skuGroups_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListSkuGroupsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.channel.v1.ServiceProto
.internal_static_google_cloud_channel_v1_ListSkuGroupsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.channel.v1.ServiceProto
.internal_static_google_cloud_channel_v1_ListSkuGroupsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.channel.v1.ListSkuGroupsResponse.class,
com.google.cloud.channel.v1.ListSkuGroupsResponse.Builder.class);
}
public static final int SKU_GROUPS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.channel.v1.SkuGroup> skuGroups_;
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.channel.v1.SkuGroup> getSkuGroupsList() {
return skuGroups_;
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.channel.v1.SkuGroupOrBuilder>
getSkuGroupsOrBuilderList() {
return skuGroups_;
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
@java.lang.Override
public int getSkuGroupsCount() {
return skuGroups_.size();
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
@java.lang.Override
public com.google.cloud.channel.v1.SkuGroup getSkuGroups(int index) {
return skuGroups_.get(index);
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
@java.lang.Override
public com.google.cloud.channel.v1.SkuGroupOrBuilder getSkuGroupsOrBuilder(int index) {
return skuGroups_.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 the next page of results.
* Pass to [ListSkuGroups.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 the next page of results.
* Pass to [ListSkuGroups.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 < skuGroups_.size(); i++) {
output.writeMessage(1, skuGroups_.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 < skuGroups_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, skuGroups_.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.channel.v1.ListSkuGroupsResponse)) {
return super.equals(obj);
}
com.google.cloud.channel.v1.ListSkuGroupsResponse other =
(com.google.cloud.channel.v1.ListSkuGroupsResponse) obj;
if (!getSkuGroupsList().equals(other.getSkuGroupsList())) 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 (getSkuGroupsCount() > 0) {
hash = (37 * hash) + SKU_GROUPS_FIELD_NUMBER;
hash = (53 * hash) + getSkuGroupsList().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.channel.v1.ListSkuGroupsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.channel.v1.ListSkuGroupsResponse 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.channel.v1.ListSkuGroupsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.channel.v1.ListSkuGroupsResponse 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.channel.v1.ListSkuGroupsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.channel.v1.ListSkuGroupsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.channel.v1.ListSkuGroupsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.channel.v1.ListSkuGroupsResponse 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.channel.v1.ListSkuGroupsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.channel.v1.ListSkuGroupsResponse 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.channel.v1.ListSkuGroupsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.channel.v1.ListSkuGroupsResponse 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.channel.v1.ListSkuGroupsResponse 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 ListSkuGroups.
* </pre>
*
* Protobuf type {@code google.cloud.channel.v1.ListSkuGroupsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.channel.v1.ListSkuGroupsResponse)
com.google.cloud.channel.v1.ListSkuGroupsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.channel.v1.ServiceProto
.internal_static_google_cloud_channel_v1_ListSkuGroupsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.channel.v1.ServiceProto
.internal_static_google_cloud_channel_v1_ListSkuGroupsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.channel.v1.ListSkuGroupsResponse.class,
com.google.cloud.channel.v1.ListSkuGroupsResponse.Builder.class);
}
// Construct using com.google.cloud.channel.v1.ListSkuGroupsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (skuGroupsBuilder_ == null) {
skuGroups_ = java.util.Collections.emptyList();
} else {
skuGroups_ = null;
skuGroupsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.channel.v1.ServiceProto
.internal_static_google_cloud_channel_v1_ListSkuGroupsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.channel.v1.ListSkuGroupsResponse getDefaultInstanceForType() {
return com.google.cloud.channel.v1.ListSkuGroupsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.channel.v1.ListSkuGroupsResponse build() {
com.google.cloud.channel.v1.ListSkuGroupsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.channel.v1.ListSkuGroupsResponse buildPartial() {
com.google.cloud.channel.v1.ListSkuGroupsResponse result =
new com.google.cloud.channel.v1.ListSkuGroupsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.channel.v1.ListSkuGroupsResponse result) {
if (skuGroupsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
skuGroups_ = java.util.Collections.unmodifiableList(skuGroups_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.skuGroups_ = skuGroups_;
} else {
result.skuGroups_ = skuGroupsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.channel.v1.ListSkuGroupsResponse 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.channel.v1.ListSkuGroupsResponse) {
return mergeFrom((com.google.cloud.channel.v1.ListSkuGroupsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.channel.v1.ListSkuGroupsResponse other) {
if (other == com.google.cloud.channel.v1.ListSkuGroupsResponse.getDefaultInstance())
return this;
if (skuGroupsBuilder_ == null) {
if (!other.skuGroups_.isEmpty()) {
if (skuGroups_.isEmpty()) {
skuGroups_ = other.skuGroups_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureSkuGroupsIsMutable();
skuGroups_.addAll(other.skuGroups_);
}
onChanged();
}
} else {
if (!other.skuGroups_.isEmpty()) {
if (skuGroupsBuilder_.isEmpty()) {
skuGroupsBuilder_.dispose();
skuGroupsBuilder_ = null;
skuGroups_ = other.skuGroups_;
bitField0_ = (bitField0_ & ~0x00000001);
skuGroupsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getSkuGroupsFieldBuilder()
: null;
} else {
skuGroupsBuilder_.addAllMessages(other.skuGroups_);
}
}
}
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.channel.v1.SkuGroup m =
input.readMessage(
com.google.cloud.channel.v1.SkuGroup.parser(), extensionRegistry);
if (skuGroupsBuilder_ == null) {
ensureSkuGroupsIsMutable();
skuGroups_.add(m);
} else {
skuGroupsBuilder_.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.channel.v1.SkuGroup> skuGroups_ =
java.util.Collections.emptyList();
private void ensureSkuGroupsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
skuGroups_ = new java.util.ArrayList<com.google.cloud.channel.v1.SkuGroup>(skuGroups_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.channel.v1.SkuGroup,
com.google.cloud.channel.v1.SkuGroup.Builder,
com.google.cloud.channel.v1.SkuGroupOrBuilder>
skuGroupsBuilder_;
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public java.util.List<com.google.cloud.channel.v1.SkuGroup> getSkuGroupsList() {
if (skuGroupsBuilder_ == null) {
return java.util.Collections.unmodifiableList(skuGroups_);
} else {
return skuGroupsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public int getSkuGroupsCount() {
if (skuGroupsBuilder_ == null) {
return skuGroups_.size();
} else {
return skuGroupsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public com.google.cloud.channel.v1.SkuGroup getSkuGroups(int index) {
if (skuGroupsBuilder_ == null) {
return skuGroups_.get(index);
} else {
return skuGroupsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public Builder setSkuGroups(int index, com.google.cloud.channel.v1.SkuGroup value) {
if (skuGroupsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSkuGroupsIsMutable();
skuGroups_.set(index, value);
onChanged();
} else {
skuGroupsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public Builder setSkuGroups(
int index, com.google.cloud.channel.v1.SkuGroup.Builder builderForValue) {
if (skuGroupsBuilder_ == null) {
ensureSkuGroupsIsMutable();
skuGroups_.set(index, builderForValue.build());
onChanged();
} else {
skuGroupsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public Builder addSkuGroups(com.google.cloud.channel.v1.SkuGroup value) {
if (skuGroupsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSkuGroupsIsMutable();
skuGroups_.add(value);
onChanged();
} else {
skuGroupsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public Builder addSkuGroups(int index, com.google.cloud.channel.v1.SkuGroup value) {
if (skuGroupsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureSkuGroupsIsMutable();
skuGroups_.add(index, value);
onChanged();
} else {
skuGroupsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public Builder addSkuGroups(com.google.cloud.channel.v1.SkuGroup.Builder builderForValue) {
if (skuGroupsBuilder_ == null) {
ensureSkuGroupsIsMutable();
skuGroups_.add(builderForValue.build());
onChanged();
} else {
skuGroupsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public Builder addSkuGroups(
int index, com.google.cloud.channel.v1.SkuGroup.Builder builderForValue) {
if (skuGroupsBuilder_ == null) {
ensureSkuGroupsIsMutable();
skuGroups_.add(index, builderForValue.build());
onChanged();
} else {
skuGroupsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public Builder addAllSkuGroups(
java.lang.Iterable<? extends com.google.cloud.channel.v1.SkuGroup> values) {
if (skuGroupsBuilder_ == null) {
ensureSkuGroupsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, skuGroups_);
onChanged();
} else {
skuGroupsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public Builder clearSkuGroups() {
if (skuGroupsBuilder_ == null) {
skuGroups_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
skuGroupsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public Builder removeSkuGroups(int index) {
if (skuGroupsBuilder_ == null) {
ensureSkuGroupsIsMutable();
skuGroups_.remove(index);
onChanged();
} else {
skuGroupsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public com.google.cloud.channel.v1.SkuGroup.Builder getSkuGroupsBuilder(int index) {
return getSkuGroupsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public com.google.cloud.channel.v1.SkuGroupOrBuilder getSkuGroupsOrBuilder(int index) {
if (skuGroupsBuilder_ == null) {
return skuGroups_.get(index);
} else {
return skuGroupsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public java.util.List<? extends com.google.cloud.channel.v1.SkuGroupOrBuilder>
getSkuGroupsOrBuilderList() {
if (skuGroupsBuilder_ != null) {
return skuGroupsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(skuGroups_);
}
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public com.google.cloud.channel.v1.SkuGroup.Builder addSkuGroupsBuilder() {
return getSkuGroupsFieldBuilder()
.addBuilder(com.google.cloud.channel.v1.SkuGroup.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public com.google.cloud.channel.v1.SkuGroup.Builder addSkuGroupsBuilder(int index) {
return getSkuGroupsFieldBuilder()
.addBuilder(index, com.google.cloud.channel.v1.SkuGroup.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of SKU groups requested.
* </pre>
*
* <code>repeated .google.cloud.channel.v1.SkuGroup sku_groups = 1;</code>
*/
public java.util.List<com.google.cloud.channel.v1.SkuGroup.Builder> getSkuGroupsBuilderList() {
return getSkuGroupsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.channel.v1.SkuGroup,
com.google.cloud.channel.v1.SkuGroup.Builder,
com.google.cloud.channel.v1.SkuGroupOrBuilder>
getSkuGroupsFieldBuilder() {
if (skuGroupsBuilder_ == null) {
skuGroupsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.channel.v1.SkuGroup,
com.google.cloud.channel.v1.SkuGroup.Builder,
com.google.cloud.channel.v1.SkuGroupOrBuilder>(
skuGroups_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
skuGroups_ = null;
}
return skuGroupsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to retrieve the next page of results.
* Pass to [ListSkuGroups.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 the next page of results.
* Pass to [ListSkuGroups.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 the next page of results.
* Pass to [ListSkuGroups.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 the next page of results.
* Pass to [ListSkuGroups.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 the next page of results.
* Pass to [ListSkuGroups.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.channel.v1.ListSkuGroupsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.channel.v1.ListSkuGroupsResponse)
private static final com.google.cloud.channel.v1.ListSkuGroupsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.channel.v1.ListSkuGroupsResponse();
}
public static com.google.cloud.channel.v1.ListSkuGroupsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListSkuGroupsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListSkuGroupsResponse>() {
@java.lang.Override
public ListSkuGroupsResponse 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<ListSkuGroupsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListSkuGroupsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.channel.v1.ListSkuGroupsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,631 | java-language/proto-google-cloud-language-v1beta2/src/main/java/com/google/cloud/language/v1beta2/ClassifyTextRequest.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/language/v1beta2/language_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.language.v1beta2;
/**
*
*
* <pre>
* The document classification request message.
* </pre>
*
* Protobuf type {@code google.cloud.language.v1beta2.ClassifyTextRequest}
*/
public final class ClassifyTextRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.language.v1beta2.ClassifyTextRequest)
ClassifyTextRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ClassifyTextRequest.newBuilder() to construct.
private ClassifyTextRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ClassifyTextRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ClassifyTextRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.language.v1beta2.LanguageServiceProto
.internal_static_google_cloud_language_v1beta2_ClassifyTextRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.language.v1beta2.LanguageServiceProto
.internal_static_google_cloud_language_v1beta2_ClassifyTextRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.language.v1beta2.ClassifyTextRequest.class,
com.google.cloud.language.v1beta2.ClassifyTextRequest.Builder.class);
}
private int bitField0_;
public static final int DOCUMENT_FIELD_NUMBER = 1;
private com.google.cloud.language.v1beta2.Document document_;
/**
*
*
* <pre>
* Required. Input document.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.Document document = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the document field is set.
*/
@java.lang.Override
public boolean hasDocument() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Input document.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.Document document = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The document.
*/
@java.lang.Override
public com.google.cloud.language.v1beta2.Document getDocument() {
return document_ == null
? com.google.cloud.language.v1beta2.Document.getDefaultInstance()
: document_;
}
/**
*
*
* <pre>
* Required. Input document.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.Document document = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.language.v1beta2.DocumentOrBuilder getDocumentOrBuilder() {
return document_ == null
? com.google.cloud.language.v1beta2.Document.getDefaultInstance()
: document_;
}
public static final int CLASSIFICATION_MODEL_OPTIONS_FIELD_NUMBER = 3;
private com.google.cloud.language.v1beta2.ClassificationModelOptions classificationModelOptions_;
/**
*
*
* <pre>
* Model options to use for classification. Defaults to v1 options if not
* specified.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.ClassificationModelOptions classification_model_options = 3;
* </code>
*
* @return Whether the classificationModelOptions field is set.
*/
@java.lang.Override
public boolean hasClassificationModelOptions() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Model options to use for classification. Defaults to v1 options if not
* specified.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.ClassificationModelOptions classification_model_options = 3;
* </code>
*
* @return The classificationModelOptions.
*/
@java.lang.Override
public com.google.cloud.language.v1beta2.ClassificationModelOptions
getClassificationModelOptions() {
return classificationModelOptions_ == null
? com.google.cloud.language.v1beta2.ClassificationModelOptions.getDefaultInstance()
: classificationModelOptions_;
}
/**
*
*
* <pre>
* Model options to use for classification. Defaults to v1 options if not
* specified.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.ClassificationModelOptions classification_model_options = 3;
* </code>
*/
@java.lang.Override
public com.google.cloud.language.v1beta2.ClassificationModelOptionsOrBuilder
getClassificationModelOptionsOrBuilder() {
return classificationModelOptions_ == null
? com.google.cloud.language.v1beta2.ClassificationModelOptions.getDefaultInstance()
: classificationModelOptions_;
}
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, getDocument());
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeMessage(3, getClassificationModelOptions());
}
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, getDocument());
}
if (((bitField0_ & 0x00000002) != 0)) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
3, getClassificationModelOptions());
}
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.language.v1beta2.ClassifyTextRequest)) {
return super.equals(obj);
}
com.google.cloud.language.v1beta2.ClassifyTextRequest other =
(com.google.cloud.language.v1beta2.ClassifyTextRequest) obj;
if (hasDocument() != other.hasDocument()) return false;
if (hasDocument()) {
if (!getDocument().equals(other.getDocument())) return false;
}
if (hasClassificationModelOptions() != other.hasClassificationModelOptions()) return false;
if (hasClassificationModelOptions()) {
if (!getClassificationModelOptions().equals(other.getClassificationModelOptions()))
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 (hasDocument()) {
hash = (37 * hash) + DOCUMENT_FIELD_NUMBER;
hash = (53 * hash) + getDocument().hashCode();
}
if (hasClassificationModelOptions()) {
hash = (37 * hash) + CLASSIFICATION_MODEL_OPTIONS_FIELD_NUMBER;
hash = (53 * hash) + getClassificationModelOptions().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.language.v1beta2.ClassifyTextRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.language.v1beta2.ClassifyTextRequest 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.language.v1beta2.ClassifyTextRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.language.v1beta2.ClassifyTextRequest 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.language.v1beta2.ClassifyTextRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.language.v1beta2.ClassifyTextRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.language.v1beta2.ClassifyTextRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.language.v1beta2.ClassifyTextRequest 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.language.v1beta2.ClassifyTextRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.language.v1beta2.ClassifyTextRequest 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.language.v1beta2.ClassifyTextRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.language.v1beta2.ClassifyTextRequest 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.language.v1beta2.ClassifyTextRequest 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 document classification request message.
* </pre>
*
* Protobuf type {@code google.cloud.language.v1beta2.ClassifyTextRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.language.v1beta2.ClassifyTextRequest)
com.google.cloud.language.v1beta2.ClassifyTextRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.language.v1beta2.LanguageServiceProto
.internal_static_google_cloud_language_v1beta2_ClassifyTextRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.language.v1beta2.LanguageServiceProto
.internal_static_google_cloud_language_v1beta2_ClassifyTextRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.language.v1beta2.ClassifyTextRequest.class,
com.google.cloud.language.v1beta2.ClassifyTextRequest.Builder.class);
}
// Construct using com.google.cloud.language.v1beta2.ClassifyTextRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getDocumentFieldBuilder();
getClassificationModelOptionsFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
document_ = null;
if (documentBuilder_ != null) {
documentBuilder_.dispose();
documentBuilder_ = null;
}
classificationModelOptions_ = null;
if (classificationModelOptionsBuilder_ != null) {
classificationModelOptionsBuilder_.dispose();
classificationModelOptionsBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.language.v1beta2.LanguageServiceProto
.internal_static_google_cloud_language_v1beta2_ClassifyTextRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.language.v1beta2.ClassifyTextRequest getDefaultInstanceForType() {
return com.google.cloud.language.v1beta2.ClassifyTextRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.language.v1beta2.ClassifyTextRequest build() {
com.google.cloud.language.v1beta2.ClassifyTextRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.language.v1beta2.ClassifyTextRequest buildPartial() {
com.google.cloud.language.v1beta2.ClassifyTextRequest result =
new com.google.cloud.language.v1beta2.ClassifyTextRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.language.v1beta2.ClassifyTextRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.document_ = documentBuilder_ == null ? document_ : documentBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.classificationModelOptions_ =
classificationModelOptionsBuilder_ == null
? classificationModelOptions_
: classificationModelOptionsBuilder_.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.language.v1beta2.ClassifyTextRequest) {
return mergeFrom((com.google.cloud.language.v1beta2.ClassifyTextRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.language.v1beta2.ClassifyTextRequest other) {
if (other == com.google.cloud.language.v1beta2.ClassifyTextRequest.getDefaultInstance())
return this;
if (other.hasDocument()) {
mergeDocument(other.getDocument());
}
if (other.hasClassificationModelOptions()) {
mergeClassificationModelOptions(other.getClassificationModelOptions());
}
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(getDocumentFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 10
case 26:
{
input.readMessage(
getClassificationModelOptionsFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
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 com.google.cloud.language.v1beta2.Document document_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.language.v1beta2.Document,
com.google.cloud.language.v1beta2.Document.Builder,
com.google.cloud.language.v1beta2.DocumentOrBuilder>
documentBuilder_;
/**
*
*
* <pre>
* Required. Input document.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.Document document = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the document field is set.
*/
public boolean hasDocument() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. Input document.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.Document document = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The document.
*/
public com.google.cloud.language.v1beta2.Document getDocument() {
if (documentBuilder_ == null) {
return document_ == null
? com.google.cloud.language.v1beta2.Document.getDefaultInstance()
: document_;
} else {
return documentBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. Input document.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.Document document = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setDocument(com.google.cloud.language.v1beta2.Document value) {
if (documentBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
document_ = value;
} else {
documentBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Input document.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.Document document = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setDocument(com.google.cloud.language.v1beta2.Document.Builder builderForValue) {
if (documentBuilder_ == null) {
document_ = builderForValue.build();
} else {
documentBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Input document.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.Document document = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeDocument(com.google.cloud.language.v1beta2.Document value) {
if (documentBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& document_ != null
&& document_ != com.google.cloud.language.v1beta2.Document.getDefaultInstance()) {
getDocumentBuilder().mergeFrom(value);
} else {
document_ = value;
}
} else {
documentBuilder_.mergeFrom(value);
}
if (document_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. Input document.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.Document document = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearDocument() {
bitField0_ = (bitField0_ & ~0x00000001);
document_ = null;
if (documentBuilder_ != null) {
documentBuilder_.dispose();
documentBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. Input document.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.Document document = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.language.v1beta2.Document.Builder getDocumentBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getDocumentFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. Input document.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.Document document = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.language.v1beta2.DocumentOrBuilder getDocumentOrBuilder() {
if (documentBuilder_ != null) {
return documentBuilder_.getMessageOrBuilder();
} else {
return document_ == null
? com.google.cloud.language.v1beta2.Document.getDefaultInstance()
: document_;
}
}
/**
*
*
* <pre>
* Required. Input document.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.Document document = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.language.v1beta2.Document,
com.google.cloud.language.v1beta2.Document.Builder,
com.google.cloud.language.v1beta2.DocumentOrBuilder>
getDocumentFieldBuilder() {
if (documentBuilder_ == null) {
documentBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.language.v1beta2.Document,
com.google.cloud.language.v1beta2.Document.Builder,
com.google.cloud.language.v1beta2.DocumentOrBuilder>(
getDocument(), getParentForChildren(), isClean());
document_ = null;
}
return documentBuilder_;
}
private com.google.cloud.language.v1beta2.ClassificationModelOptions
classificationModelOptions_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.language.v1beta2.ClassificationModelOptions,
com.google.cloud.language.v1beta2.ClassificationModelOptions.Builder,
com.google.cloud.language.v1beta2.ClassificationModelOptionsOrBuilder>
classificationModelOptionsBuilder_;
/**
*
*
* <pre>
* Model options to use for classification. Defaults to v1 options if not
* specified.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.ClassificationModelOptions classification_model_options = 3;
* </code>
*
* @return Whether the classificationModelOptions field is set.
*/
public boolean hasClassificationModelOptions() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Model options to use for classification. Defaults to v1 options if not
* specified.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.ClassificationModelOptions classification_model_options = 3;
* </code>
*
* @return The classificationModelOptions.
*/
public com.google.cloud.language.v1beta2.ClassificationModelOptions
getClassificationModelOptions() {
if (classificationModelOptionsBuilder_ == null) {
return classificationModelOptions_ == null
? com.google.cloud.language.v1beta2.ClassificationModelOptions.getDefaultInstance()
: classificationModelOptions_;
} else {
return classificationModelOptionsBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Model options to use for classification. Defaults to v1 options if not
* specified.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.ClassificationModelOptions classification_model_options = 3;
* </code>
*/
public Builder setClassificationModelOptions(
com.google.cloud.language.v1beta2.ClassificationModelOptions value) {
if (classificationModelOptionsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
classificationModelOptions_ = value;
} else {
classificationModelOptionsBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Model options to use for classification. Defaults to v1 options if not
* specified.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.ClassificationModelOptions classification_model_options = 3;
* </code>
*/
public Builder setClassificationModelOptions(
com.google.cloud.language.v1beta2.ClassificationModelOptions.Builder builderForValue) {
if (classificationModelOptionsBuilder_ == null) {
classificationModelOptions_ = builderForValue.build();
} else {
classificationModelOptionsBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Model options to use for classification. Defaults to v1 options if not
* specified.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.ClassificationModelOptions classification_model_options = 3;
* </code>
*/
public Builder mergeClassificationModelOptions(
com.google.cloud.language.v1beta2.ClassificationModelOptions value) {
if (classificationModelOptionsBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& classificationModelOptions_ != null
&& classificationModelOptions_
!= com.google.cloud.language.v1beta2.ClassificationModelOptions
.getDefaultInstance()) {
getClassificationModelOptionsBuilder().mergeFrom(value);
} else {
classificationModelOptions_ = value;
}
} else {
classificationModelOptionsBuilder_.mergeFrom(value);
}
if (classificationModelOptions_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Model options to use for classification. Defaults to v1 options if not
* specified.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.ClassificationModelOptions classification_model_options = 3;
* </code>
*/
public Builder clearClassificationModelOptions() {
bitField0_ = (bitField0_ & ~0x00000002);
classificationModelOptions_ = null;
if (classificationModelOptionsBuilder_ != null) {
classificationModelOptionsBuilder_.dispose();
classificationModelOptionsBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Model options to use for classification. Defaults to v1 options if not
* specified.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.ClassificationModelOptions classification_model_options = 3;
* </code>
*/
public com.google.cloud.language.v1beta2.ClassificationModelOptions.Builder
getClassificationModelOptionsBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getClassificationModelOptionsFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Model options to use for classification. Defaults to v1 options if not
* specified.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.ClassificationModelOptions classification_model_options = 3;
* </code>
*/
public com.google.cloud.language.v1beta2.ClassificationModelOptionsOrBuilder
getClassificationModelOptionsOrBuilder() {
if (classificationModelOptionsBuilder_ != null) {
return classificationModelOptionsBuilder_.getMessageOrBuilder();
} else {
return classificationModelOptions_ == null
? com.google.cloud.language.v1beta2.ClassificationModelOptions.getDefaultInstance()
: classificationModelOptions_;
}
}
/**
*
*
* <pre>
* Model options to use for classification. Defaults to v1 options if not
* specified.
* </pre>
*
* <code>
* .google.cloud.language.v1beta2.ClassificationModelOptions classification_model_options = 3;
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.language.v1beta2.ClassificationModelOptions,
com.google.cloud.language.v1beta2.ClassificationModelOptions.Builder,
com.google.cloud.language.v1beta2.ClassificationModelOptionsOrBuilder>
getClassificationModelOptionsFieldBuilder() {
if (classificationModelOptionsBuilder_ == null) {
classificationModelOptionsBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.language.v1beta2.ClassificationModelOptions,
com.google.cloud.language.v1beta2.ClassificationModelOptions.Builder,
com.google.cloud.language.v1beta2.ClassificationModelOptionsOrBuilder>(
getClassificationModelOptions(), getParentForChildren(), isClean());
classificationModelOptions_ = null;
}
return classificationModelOptionsBuilder_;
}
@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.language.v1beta2.ClassifyTextRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.language.v1beta2.ClassifyTextRequest)
private static final com.google.cloud.language.v1beta2.ClassifyTextRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.language.v1beta2.ClassifyTextRequest();
}
public static com.google.cloud.language.v1beta2.ClassifyTextRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ClassifyTextRequest> PARSER =
new com.google.protobuf.AbstractParser<ClassifyTextRequest>() {
@java.lang.Override
public ClassifyTextRequest 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<ClassifyTextRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ClassifyTextRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.language.v1beta2.ClassifyTextRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/iotdb | 34,878 | integration-test/src/test/java/org/apache/iotdb/db/it/alignbydevice/IoTDBAlignByDeviceWithTemplateIT.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.iotdb.db.it.alignbydevice;
import org.apache.iotdb.it.env.EnvFactory;
import org.apache.iotdb.it.framework.IoTDBTestRunner;
import org.apache.iotdb.itbase.category.ClusterIT;
import org.apache.iotdb.itbase.category.LocalStandaloneIT;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.sql.Connection;
import java.sql.Statement;
import static org.apache.iotdb.db.it.utils.TestUtils.assertTestFail;
import static org.apache.iotdb.db.it.utils.TestUtils.resultSetEqualTest;
@RunWith(IoTDBTestRunner.class)
@Category({LocalStandaloneIT.class, ClusterIT.class})
public class IoTDBAlignByDeviceWithTemplateIT {
private static final String[] sqls =
new String[] {
// non-aligned template
"CREATE database root.sg1;",
"CREATE schema template t1 (s1 FLOAT encoding=RLE, s2 BOOLEAN encoding=PLAIN compression=SNAPPY, s3 INT32);",
"SET SCHEMA TEMPLATE t1 to root.sg1;",
"INSERT INTO root.sg1.d1(timestamp,s1,s2,s3) values(1,1.1,false,1), (2,2.2,false,2);",
"INSERT INTO root.sg1.d2(timestamp,s1,s2,s3) values(1,11.1,false,11), (2,22.2,false,22);",
"INSERT INTO root.sg1.d3(timestamp,s1,s2,s3) values(1,111.1,true,null), (4,444.4,true,44);",
"INSERT INTO root.sg1.d4(timestamp,s1,s2,s3) values(1,1111.1,true,1111), (5,5555.5,false,5555);",
// aligned template
"CREATE database root.sg2;",
"CREATE schema template t2 aligned (s1 FLOAT encoding=RLE, s2 BOOLEAN encoding=PLAIN compression=SNAPPY, s3 INT32);",
"SET SCHEMA TEMPLATE t2 to root.sg2;",
"INSERT INTO root.sg2.d1(timestamp,s1,s2,s3) values(1,1.1,false,1), (2,2.2,false,2);",
"INSERT INTO root.sg2.d2(timestamp,s1,s2,s3) values(1,11.1,false,11), (2,22.2,false,22);",
"INSERT INTO root.sg2.d3(timestamp,s1,s2,s3) values(1,111.1,true,null), (4,444.4,true,44);",
"INSERT INTO root.sg2.d4(timestamp,s1,s2,s3) values(1,1111.1,true,1111), (5,5555.5,false,5555);",
};
String[] expectedHeader;
String[] retArray;
@BeforeClass
public static void setUp() throws Exception {
EnvFactory.getEnv().initClusterEnvironment();
insertData();
}
@AfterClass
public static void tearDown() throws Exception {
EnvFactory.getEnv().cleanClusterEnvironment();
}
@Test
public void singleDeviceTest() {
expectedHeader = new String[] {"Time,Device,s3,s1,s2"};
retArray =
new String[] {
"1,root.sg1.d1,1,1.1,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.d1 order by time desc offset 1 limit 1 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"1,root.sg2.d1,1,1.1,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.d1 order by time desc offset 1 limit 1 ALIGN BY DEVICE;",
expectedHeader,
retArray);
}
@Test
public void selectWildcardNoFilterTest() {
// 1. order by device
expectedHeader = new String[] {"Time,Device,s3,s1,s2"};
retArray =
new String[] {
"1,root.sg1.d1,1,1.1,false,",
"2,root.sg1.d1,2,2.2,false,",
"1,root.sg1.d2,11,11.1,false,",
"2,root.sg1.d2,22,22.2,false,",
"1,root.sg1.d3,null,111.1,true,",
"4,root.sg1.d3,44,444.4,true,",
"1,root.sg1.d4,1111,1111.1,true,",
"5,root.sg1.d4,5555,5555.5,false,",
};
resultSetEqualTest("SELECT * FROM root.sg1.** ALIGN BY DEVICE;", expectedHeader, retArray);
retArray =
new String[] {
"1,root.sg2.d1,1,1.1,false,",
"2,root.sg2.d1,2,2.2,false,",
"1,root.sg2.d2,11,11.1,false,",
"2,root.sg2.d2,22,22.2,false,",
"1,root.sg2.d3,null,111.1,true,",
"4,root.sg2.d3,44,444.4,true,",
"1,root.sg2.d4,1111,1111.1,true,",
"5,root.sg2.d4,5555,5555.5,false,",
};
resultSetEqualTest("SELECT * FROM root.sg2.** ALIGN BY DEVICE;", expectedHeader, retArray);
expectedHeader = new String[] {"Time,Device,s3,s1,s2,s1"};
retArray =
new String[] {
"1,root.sg1.d1,1,1.1,false,1.1,",
"2,root.sg1.d1,2,2.2,false,2.2,",
"1,root.sg1.d2,11,11.1,false,11.1,",
"2,root.sg1.d2,22,22.2,false,22.2,",
"1,root.sg1.d3,null,111.1,true,111.1,",
"4,root.sg1.d3,44,444.4,true,444.4,",
"1,root.sg1.d4,1111,1111.1,true,1111.1,",
"5,root.sg1.d4,5555,5555.5,false,5555.5,",
};
resultSetEqualTest("SELECT *, s1 FROM root.sg1.** ALIGN BY DEVICE;", expectedHeader, retArray);
retArray =
new String[] {
"1,root.sg2.d1,1,1.1,false,1.1,",
"2,root.sg2.d1,2,2.2,false,2.2,",
"1,root.sg2.d2,11,11.1,false,11.1,",
"2,root.sg2.d2,22,22.2,false,22.2,",
"1,root.sg2.d3,null,111.1,true,111.1,",
"4,root.sg2.d3,44,444.4,true,444.4,",
"1,root.sg2.d4,1111,1111.1,true,1111.1,",
"5,root.sg2.d4,5555,5555.5,false,5555.5,",
};
resultSetEqualTest("SELECT *, s1 FROM root.sg2.** ALIGN BY DEVICE;", expectedHeader, retArray);
expectedHeader = new String[] {"Time,Device,s3,s1,s2"};
retArray =
new String[] {
"1,root.sg1.d1,1,1.1,false,",
"2,root.sg1.d1,2,2.2,false,",
"1,root.sg1.d2,11,11.1,false,",
"2,root.sg1.d2,22,22.2,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.d1,root.sg1.d2,root.sg1.d6 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"1,root.sg2.d1,1,1.1,false,",
"2,root.sg2.d1,2,2.2,false,",
"1,root.sg2.d2,11,11.1,false,",
"2,root.sg2.d2,22,22.2,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.d1,root.sg2.d2,root.sg2.d6 ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 2. order by device + limit/offset
expectedHeader = new String[] {"Time,Device,s3,s1,s2"};
retArray =
new String[] {
"2,root.sg1.d1,2,2.2,false,", "1,root.sg1.d2,11,11.1,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.** OFFSET 1 LIMIT 2 ALIGN BY DEVICE;", expectedHeader, retArray);
retArray =
new String[] {
"2,root.sg2.d1,2,2.2,false,", "1,root.sg2.d2,11,11.1,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.** OFFSET 1 LIMIT 2 ALIGN BY DEVICE;", expectedHeader, retArray);
// 3. order by time
retArray =
new String[] {
"5,root.sg1.d4,5555,5555.5,false,",
"4,root.sg1.d3,44,444.4,true,",
"2,root.sg1.d1,2,2.2,false,",
"2,root.sg1.d2,22,22.2,false,",
"1,root.sg1.d1,1,1.1,false,",
"1,root.sg1.d2,11,11.1,false,",
"1,root.sg1.d3,null,111.1,true,",
"1,root.sg1.d4,1111,1111.1,true,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.** ORDER BY TIME DESC ALIGN BY DEVICE;", expectedHeader, retArray);
retArray =
new String[] {
"5,root.sg2.d4,5555,5555.5,false,",
"4,root.sg2.d3,44,444.4,true,",
"2,root.sg2.d1,2,2.2,false,",
"2,root.sg2.d2,22,22.2,false,",
"1,root.sg2.d1,1,1.1,false,",
"1,root.sg2.d2,11,11.1,false,",
"1,root.sg2.d3,null,111.1,true,",
"1,root.sg2.d4,1111,1111.1,true,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.** ORDER BY TIME DESC ALIGN BY DEVICE;", expectedHeader, retArray);
// 4. order by time + limit/offset
retArray =
new String[] {
"5,root.sg1.d4,5555,5555.5,false,", "4,root.sg1.d3,44,444.4,true,",
"2,root.sg1.d1,2,2.2,false,", "2,root.sg1.d2,22,22.2,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.** ORDER BY TIME DESC LIMIT 4 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"5,root.sg2.d4,5555,5555.5,false,", "4,root.sg2.d3,44,444.4,true,",
"2,root.sg2.d1,2,2.2,false,", "2,root.sg2.d2,22,22.2,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.** ORDER BY TIME DESC LIMIT 4 ALIGN BY DEVICE;",
expectedHeader,
retArray);
}
@Test
public void selectMeasurementNoFilterTest() {
// 1. order by device
String[] expectedHeader = new String[] {"Time,Device,s3,s1"};
String[] retArray =
new String[] {
"1,root.sg1.d1,1,1.1,",
"2,root.sg1.d1,2,2.2,",
"1,root.sg1.d2,11,11.1,",
"2,root.sg1.d2,22,22.2,",
"1,root.sg1.d3,null,111.1,",
"4,root.sg1.d3,44,444.4,",
"1,root.sg1.d4,1111,1111.1,",
"5,root.sg1.d4,5555,5555.5,",
};
resultSetEqualTest("SELECT s3,s1 FROM root.sg1.** ALIGN BY DEVICE;", expectedHeader, retArray);
resultSetEqualTest(
"SELECT s3,s1,s_null FROM root.sg1.** ALIGN BY DEVICE;", expectedHeader, retArray);
retArray =
new String[] {
"1,root.sg2.d1,1,1.1,",
"2,root.sg2.d1,2,2.2,",
"1,root.sg2.d2,11,11.1,",
"2,root.sg2.d2,22,22.2,",
"1,root.sg2.d3,null,111.1,",
"4,root.sg2.d3,44,444.4,",
"1,root.sg2.d4,1111,1111.1,",
"5,root.sg2.d4,5555,5555.5,",
};
resultSetEqualTest("SELECT s3,s1 FROM root.sg2.** ALIGN BY DEVICE;", expectedHeader, retArray);
resultSetEqualTest(
"SELECT s3,s1,s_null FROM root.sg2.** ALIGN BY DEVICE;", expectedHeader, retArray);
// 2. order by device + limit/offset
retArray =
new String[] {
"2,root.sg1.d1,2,2.2,", "1,root.sg1.d2,11,11.1,",
};
resultSetEqualTest(
"SELECT s3,s1 FROM root.sg1.** OFFSET 1 LIMIT 2 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"2,root.sg2.d1,2,2.2,", "1,root.sg2.d2,11,11.1,",
};
resultSetEqualTest(
"SELECT s3,s1 FROM root.sg2.** OFFSET 1 LIMIT 2 ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 3. order by time
retArray =
new String[] {
"5,root.sg1.d4,5555,5555.5,",
"4,root.sg1.d3,44,444.4,",
"2,root.sg1.d1,2,2.2,",
"2,root.sg1.d2,22,22.2,",
"1,root.sg1.d1,1,1.1,",
"1,root.sg1.d2,11,11.1,",
"1,root.sg1.d3,null,111.1,",
"1,root.sg1.d4,1111,1111.1,",
};
resultSetEqualTest(
"SELECT s3,s1 FROM root.sg1.** ORDER BY TIME DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"5,root.sg2.d4,5555,5555.5,",
"4,root.sg2.d3,44,444.4,",
"2,root.sg2.d1,2,2.2,",
"2,root.sg2.d2,22,22.2,",
"1,root.sg2.d1,1,1.1,",
"1,root.sg2.d2,11,11.1,",
"1,root.sg2.d3,null,111.1,",
"1,root.sg2.d4,1111,1111.1,",
};
resultSetEqualTest(
"SELECT s3,s1 FROM root.sg2.** ORDER BY TIME DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 4. order by time + limit/offset
retArray =
new String[] {
"5,root.sg1.d4,5555,5555.5,", "4,root.sg1.d3,44,444.4,",
"2,root.sg1.d1,2,2.2,", "2,root.sg1.d2,22,22.2,",
};
resultSetEqualTest(
"SELECT s3,s1 FROM root.sg1.** ORDER BY TIME DESC LIMIT 4 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"5,root.sg2.d4,5555,5555.5,", "4,root.sg2.d3,44,444.4,",
"2,root.sg2.d1,2,2.2,", "2,root.sg2.d2,22,22.2,",
};
resultSetEqualTest(
"SELECT s3,s1 FROM root.sg2.** ORDER BY TIME DESC LIMIT 4 ALIGN BY DEVICE;",
expectedHeader,
retArray);
}
@Test
public void selectWildcardWithFilterOrderByTimeTest() {
// 1. order by time + time filter
String[] expectedHeader = new String[] {"Time,Device,s3,s1,s2"};
String[] retArray =
new String[] {
"4,root.sg1.d3,44,444.4,true,",
"2,root.sg1.d1,2,2.2,false,",
"2,root.sg1.d2,22,22.2,false,",
"1,root.sg1.d1,1,1.1,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.** WHERE time < 5 ORDER BY TIME DESC LIMIT 4 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"4,root.sg2.d3,44,444.4,true,",
"2,root.sg2.d1,2,2.2,false,",
"2,root.sg2.d2,22,22.2,false,",
"1,root.sg2.d1,1,1.1,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.** WHERE time < 5 ORDER BY TIME DESC LIMIT 4 ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 2. order by time + time filter + value filter
retArray =
new String[] {
"4,root.sg1.d3,44,444.4,true,", "2,root.sg1.d2,22,22.2,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.** where time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1 "
+ "ORDER BY TIME DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"4,root.sg2.d3,44,444.4,true,", "2,root.sg2.d2,22,22.2,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.** where time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1 "
+ "ORDER BY TIME DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 3. order by time + value filter: s_null > 1
retArray = new String[] {};
resultSetEqualTest(
"SELECT * FROM root.sg1.** WHERE s_null > 1 ORDER BY TIME ALIGN BY DEVICE;",
expectedHeader,
retArray);
resultSetEqualTest(
"SELECT * FROM root.sg2.** WHERE s_null > 1 ORDER BY TIME ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"4,root.sg1.d3,44,444.4,true,", "2,root.sg1.d2,22,22.2,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.** WHERE s_null > 1 or "
+ "(time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1) ORDER BY TIME DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"4,root.sg2.d3,44,444.4,true,", "2,root.sg2.d2,22,22.2,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.** WHERE s_null > 1 or "
+ "(time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1) ORDER BY TIME DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
}
@Test
public void selectWildcardWithFilterOrderByDeviceTest() {
// 1. order by device + time filter
String[] expectedHeader = new String[] {"Time,Device,s3,s1,s2"};
String[] retArray =
new String[] {
"1,root.sg1.d4,1111,1111.1,true,",
"1,root.sg1.d3,null,111.1,true,",
"4,root.sg1.d3,44,444.4,true,",
"1,root.sg1.d2,11,11.1,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.** WHERE time < 5 ORDER BY DEVICE DESC LIMIT 4 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"1,root.sg2.d4,1111,1111.1,true,",
"1,root.sg2.d3,null,111.1,true,",
"4,root.sg2.d3,44,444.4,true,",
"1,root.sg2.d2,11,11.1,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.** WHERE time < 5 ORDER BY DEVICE DESC LIMIT 4 ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 2. order by device + time filter + value filter
retArray =
new String[] {
"4,root.sg1.d3,44,444.4,true,", "2,root.sg1.d2,22,22.2,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.** where time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1 "
+ "ORDER BY DEVICE DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"2,root.sg2.d2,22,22.2,false,", "4,root.sg2.d3,44,444.4,true,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.** where time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1 "
+ "ORDER BY DEVICE ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 3. order by device + value filter: s_null > 1
retArray = new String[] {};
resultSetEqualTest(
"SELECT * FROM root.sg1.** WHERE s_null > 1 ORDER BY DEVICE ALIGN BY DEVICE;",
expectedHeader,
retArray);
resultSetEqualTest(
"SELECT * FROM root.sg2.** WHERE s_null > 1 ORDER BY DEVICE ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"4,root.sg1.d3,44,444.4,true,", "2,root.sg1.d2,22,22.2,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.** WHERE s_null > 1 or "
+ "(time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1) ORDER BY DEVICE DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"4,root.sg2.d3,44,444.4,true,", "2,root.sg2.d2,22,22.2,false,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.** WHERE s_null > 1 or "
+ "(time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1) ORDER BY DEVICE DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
}
@Test
public void selectMeasurementWithFilterOrderByTimeTest() {
// 1. order by time + time filter
String[] expectedHeader = new String[] {"Time,Device,s3,s2"};
String[] retArray =
new String[] {
"4,root.sg1.d3,44,true,",
"2,root.sg1.d1,2,false,",
"2,root.sg1.d2,22,false,",
"1,root.sg1.d1,1,false,",
};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg1.** WHERE time < 5 ORDER BY TIME DESC LIMIT 4 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"4,root.sg2.d3,44,true,",
"2,root.sg2.d1,2,false,",
"2,root.sg2.d2,22,false,",
"1,root.sg2.d1,1,false,",
};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg2.** WHERE time < 5 ORDER BY TIME DESC LIMIT 4 ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 2. order by time + time filter + value filter
retArray =
new String[] {
"4,root.sg1.d3,44,true,", "2,root.sg1.d2,22,false,",
};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg1.** where time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1 "
+ "ORDER BY TIME DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"4,root.sg2.d3,44,true,", "2,root.sg2.d2,22,false,",
};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg2.** where time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1 "
+ "ORDER BY TIME DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 3. order by time + value filter: s_null > 1
retArray = new String[] {};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg1.** WHERE s_null > 1 ORDER BY TIME ALIGN BY DEVICE;",
expectedHeader,
retArray);
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg2.** WHERE s_null > 1 ORDER BY TIME ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"2,root.sg1.d2,22,false,",
};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg1.** where s_null > 1 or (time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1) "
+ "ORDER BY TIME DESC OFFSET 1 LIMIT 1 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"2,root.sg2.d2,22,false,",
};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg2.** where s_null > 1 or (time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1) "
+ "ORDER BY TIME DESC OFFSET 1 LIMIT 1 ALIGN BY DEVICE;",
expectedHeader,
retArray);
}
@Test
public void selectMeasurementWithFilterOrderByDeviceTest() {
// 1. order by device + time filter
String[] expectedHeader = new String[] {"Time,Device,s3,s2"};
String[] retArray =
new String[] {
"1,root.sg1.d4,1111,true,",
"1,root.sg1.d3,null,true,",
"4,root.sg1.d3,44,true,",
"1,root.sg1.d2,11,false,",
};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg1.** WHERE time < 5 ORDER BY DEVICE DESC LIMIT 4 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"1,root.sg2.d4,1111,true,",
"1,root.sg2.d3,null,true,",
"4,root.sg2.d3,44,true,",
"1,root.sg2.d2,11,false,",
};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg2.** WHERE time < 5 ORDER BY DEVICE DESC LIMIT 4 ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 2. order by device + time filter + value filter
retArray =
new String[] {
"4,root.sg1.d3,44,true,", "2,root.sg1.d2,22,false,",
};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg1.** where time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1 "
+ "ORDER BY DEVICE DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"4,root.sg2.d3,44,true,", "2,root.sg2.d2,22,false,",
};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg2.** where time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1 "
+ "ORDER BY DEVICE DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 3. order by device + value filter: s_null > 1
retArray = new String[] {};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg1.** WHERE s_null > 1 ORDER BY DEVICE ALIGN BY DEVICE;",
expectedHeader,
retArray);
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg2.** WHERE s_null > 1 ORDER BY DEVICE ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"2,root.sg1.d2,22,false,",
};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg1.** where s_null > 1 or (time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1) "
+ "ORDER BY DEVICE DESC OFFSET 1 LIMIT 1 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"2,root.sg2.d2,22,false,",
};
resultSetEqualTest(
"SELECT s3,s2 FROM root.sg2.** where s_null > 1 or (time > 1 and time < 5 and s3>=11 and s3<=1111 and s1 != 11.1) "
+ "ORDER BY DEVICE DESC OFFSET 1 LIMIT 1 ALIGN BY DEVICE;",
expectedHeader,
retArray);
}
@Test
public void aliasTest() {
String[] expectedHeader = new String[] {"Time,Device,aa,bb,s3,s2"};
String[] retArray =
new String[] {
"1,root.sg1.d1,1.1,false,1,false,",
"2,root.sg1.d1,2.2,false,2,false,",
"1,root.sg1.d2,11.1,false,11,false,",
"2,root.sg1.d2,22.2,false,22,false,",
"1,root.sg1.d3,111.1,true,null,true,",
"4,root.sg1.d3,444.4,true,44,true,",
"1,root.sg1.d4,1111.1,true,1111,true,",
"5,root.sg1.d4,5555.5,false,5555,false,",
};
resultSetEqualTest(
"SELECT s1 as aa, s2 as bb, s3, s2 FROM root.sg1.** ALIGN BY DEVICE;",
expectedHeader,
retArray);
expectedHeader = new String[] {"Time,Device,aa,bb,s3,s2"};
retArray =
new String[] {
"1,root.sg2.d1,1.1,false,1,false,",
"2,root.sg2.d1,2.2,false,2,false,",
"1,root.sg2.d2,11.1,false,11,false,",
"2,root.sg2.d2,22.2,false,22,false,",
"1,root.sg2.d3,111.1,true,null,true,",
"4,root.sg2.d3,444.4,true,44,true,",
"1,root.sg2.d4,1111.1,true,1111,true,",
"5,root.sg2.d4,5555.5,false,5555,false,",
};
resultSetEqualTest(
"SELECT s1 as aa, s2 as bb, s3, s2 FROM root.sg2.** ALIGN BY DEVICE;",
expectedHeader,
retArray);
expectedHeader = new String[] {"Time,Device,a,b"};
retArray =
new String[] {
"1,root.sg1.d1,1.1,1.1,",
"2,root.sg1.d1,2.2,2.2,",
"1,root.sg1.d2,11.1,11.1,",
"2,root.sg1.d2,22.2,22.2,",
"1,root.sg1.d3,111.1,111.1,",
"4,root.sg1.d3,444.4,444.4,",
"1,root.sg1.d4,1111.1,1111.1,",
"5,root.sg1.d4,5555.5,5555.5,",
};
resultSetEqualTest(
"SELECT s1 as a, s1 as b FROM root.sg1.** ALIGN BY DEVICE;", expectedHeader, retArray);
expectedHeader = new String[] {"Time,Device,a,b"};
retArray =
new String[] {
"1,root.sg2.d1,1.1,1.1,",
"2,root.sg2.d1,2.2,2.2,",
"1,root.sg2.d2,11.1,11.1,",
"2,root.sg2.d2,22.2,22.2,",
"1,root.sg2.d3,111.1,111.1,",
"4,root.sg2.d3,444.4,444.4,",
"1,root.sg2.d4,1111.1,1111.1,",
"5,root.sg2.d4,5555.5,5555.5,",
};
resultSetEqualTest(
"SELECT s1 as a, s1 as b FROM root.sg2.** ALIGN BY DEVICE;", expectedHeader, retArray);
}
@Test
public void orderByExpressionTest() {
// order by expression is not supported temporarily
// 1. order by basic measurement
String[] expectedHeader = new String[] {"Time,Device,s3,s1,s2"};
String[] retArray =
new String[] {
"5,root.sg1.d4,5555,5555.5,false,",
"2,root.sg1.d2,22,22.2,false,",
"1,root.sg1.d2,11,11.1,false,",
"2,root.sg1.d1,2,2.2,false,",
"1,root.sg1.d1,1,1.1,false,",
"1,root.sg1.d4,1111,1111.1,true,",
"4,root.sg1.d3,44,444.4,true,",
"1,root.sg1.d3,null,111.1,true,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.** order by s2 asc, s1 desc ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"5,root.sg2.d4,5555,5555.5,false,",
"2,root.sg2.d2,22,22.2,false,",
"1,root.sg2.d2,11,11.1,false,",
"2,root.sg2.d1,2,2.2,false,",
"1,root.sg2.d1,1,1.1,false,",
"1,root.sg2.d4,1111,1111.1,true,",
"4,root.sg2.d3,44,444.4,true,",
"1,root.sg2.d3,null,111.1,true,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.** order by s2 asc, s1 desc ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 2. select measurement is different with order by measurement
expectedHeader = new String[] {"Time,Device,s3"};
retArray =
new String[] {
"5,root.sg1.d4,5555,",
"2,root.sg1.d2,22,",
"1,root.sg1.d2,11,",
"2,root.sg1.d1,2,",
"1,root.sg1.d1,1,",
"1,root.sg1.d4,1111,",
"4,root.sg1.d3,44,",
"1,root.sg1.d3,null,",
};
resultSetEqualTest(
"SELECT s3 FROM root.sg1.** order by s2 asc, s1 desc ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"5,root.sg2.d4,5555,",
"2,root.sg2.d2,22,",
"1,root.sg2.d2,11,",
"2,root.sg2.d1,2,",
"1,root.sg2.d1,1,",
"1,root.sg2.d4,1111,",
"4,root.sg2.d3,44,",
"1,root.sg2.d3,null,",
};
resultSetEqualTest(
"SELECT s3 FROM root.sg2.** order by s2 asc, s1 desc ALIGN BY DEVICE;",
expectedHeader,
retArray);
// 3. order by expression
retArray =
new String[] {
"5,root.sg1.d4,5555,",
"1,root.sg1.d4,1111,",
"4,root.sg1.d3,44,",
"2,root.sg1.d2,22,",
"1,root.sg1.d2,11,",
"2,root.sg1.d1,2,",
"1,root.sg1.d1,1,",
"1,root.sg1.d3,null,",
};
resultSetEqualTest(
"SELECT s3 FROM root.sg1.** order by s1+s3 desc ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"5,root.sg2.d4,5555,",
"1,root.sg2.d4,1111,",
"4,root.sg2.d3,44,",
"2,root.sg2.d2,22,",
"1,root.sg2.d2,11,",
"2,root.sg2.d1,2,",
"1,root.sg2.d1,1,",
"1,root.sg2.d3,null,",
};
resultSetEqualTest(
"SELECT s3 FROM root.sg2.** order by s1+s3 desc ALIGN BY DEVICE;",
expectedHeader,
retArray);
}
@Test
public void templateInvalidTest() {
// 1. non align by device query
String[] expectedHeader = new String[] {"Time,root.sg1.d4.s3,root.sg1.d4.s1,root.sg1.d4.s2"};
String[] retArray =
new String[] {
"1,1111,1111.1,true,", "5,5555,5555.5,false,",
};
resultSetEqualTest("SELECT * FROM root.sg1.** slimit 3;", expectedHeader, retArray);
expectedHeader = new String[] {"Time,root.sg2.d4.s3,root.sg2.d4.s1,root.sg2.d4.s2"};
retArray =
new String[] {
"1,1111,1111.1,true,", "5,5555,5555.5,false,",
};
resultSetEqualTest("SELECT * FROM root.sg2.** slimit 3;", expectedHeader, retArray);
// 2. aggregation
expectedHeader = new String[] {"Device,count(s1 + 1)"};
retArray =
new String[] {
"root.sg1.d1,2,", "root.sg1.d2,2,", "root.sg1.d3,2,", "root.sg1.d4,2,",
};
resultSetEqualTest(
"select count(s1+1) from root.sg1.** align by device;", expectedHeader, retArray);
expectedHeader = new String[] {"Device,count(s1 + 1)"};
retArray =
new String[] {
"root.sg2.d1,2,", "root.sg2.d2,2,", "root.sg2.d3,2,", "root.sg2.d4,2,",
};
resultSetEqualTest(
"select count(s1+1) from root.sg2.** align by device;", expectedHeader, retArray);
assertTestFail(
"select s1 from root.sg1.** where s1 align by device;",
"The output type of the expression in WHERE clause should be BOOLEAN, actual data type: FLOAT.");
assertTestFail(
"select s1 from root.sg2.** where s1 align by device;",
"The output type of the expression in WHERE clause should be BOOLEAN, actual data type: FLOAT.");
}
@Test
public void sLimitOffsetTest() {
// 1. original
String[] expectedHeader = new String[] {"Time,Device,s1"};
String[] retArray =
new String[] {
"1,root.sg1.d1,1.1,",
"2,root.sg1.d1,2.2,",
"1,root.sg1.d2,11.1,",
"2,root.sg1.d2,22.2,",
"1,root.sg1.d3,111.1,",
"4,root.sg1.d3,444.4,",
"1,root.sg1.d4,1111.1,",
"5,root.sg1.d4,5555.5,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.** slimit 1 soffset 1 ALIGN BY DEVICE;", expectedHeader, retArray);
retArray =
new String[] {
"1,root.sg2.d1,1.1,",
"2,root.sg2.d1,2.2,",
"1,root.sg2.d2,11.1,",
"2,root.sg2.d2,22.2,",
"1,root.sg2.d3,111.1,",
"4,root.sg2.d3,444.4,",
"1,root.sg2.d4,1111.1,",
"5,root.sg2.d4,5555.5,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.** slimit 1 soffset 1 ALIGN BY DEVICE;", expectedHeader, retArray);
expectedHeader = new String[] {"Time,Device,s1,s2"};
retArray =
new String[] {
"1,root.sg1.d1,1.1,false,",
"2,root.sg1.d1,2.2,false,",
"1,root.sg1.d2,11.1,false,",
"2,root.sg1.d2,22.2,false,",
"1,root.sg1.d3,111.1,true,",
"4,root.sg1.d3,444.4,true,",
"1,root.sg1.d4,1111.1,true,",
"5,root.sg1.d4,5555.5,false,",
};
resultSetEqualTest(
"SELECT *, s1 FROM root.sg1.** slimit 2 soffset 1 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"1,root.sg2.d1,1.1,false,",
"2,root.sg2.d1,2.2,false,",
"1,root.sg2.d2,11.1,false,",
"2,root.sg2.d2,22.2,false,",
"1,root.sg2.d3,111.1,true,",
"4,root.sg2.d3,444.4,true,",
"1,root.sg2.d4,1111.1,true,",
"5,root.sg2.d4,5555.5,false,",
};
resultSetEqualTest(
"SELECT *, s1 FROM root.sg2.** slimit 2 soffset 1 ALIGN BY DEVICE;",
expectedHeader,
retArray);
expectedHeader = new String[] {"Time,Device,s1"};
retArray =
new String[] {
"1,root.sg1.d1,1.1,", "2,root.sg1.d1,2.2,", "1,root.sg1.d2,11.1,", "2,root.sg1.d2,22.2,",
};
resultSetEqualTest(
"SELECT * FROM root.sg1.d1,root.sg1.d2,root.sg1.d6 soffset 1 slimit 1 ALIGN BY DEVICE;",
expectedHeader,
retArray);
retArray =
new String[] {
"1,root.sg2.d1,1.1,", "2,root.sg2.d1,2.2,", "1,root.sg2.d2,11.1,", "2,root.sg2.d2,22.2,",
};
resultSetEqualTest(
"SELECT * FROM root.sg2.d1,root.sg2.d2,root.sg2.d6 soffset 1 slimit 1 ALIGN BY DEVICE;",
expectedHeader,
retArray);
}
@Test
public void emptyResultTest() {
String[] expectedHeader = new String[] {"Time,Device,s3,s1,s2"};
String[] retArray = new String[] {};
resultSetEqualTest(
"SELECT * FROM root.sg1.** where time>=now()-1d and time<=now() "
+ "ORDER BY TIME DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
resultSetEqualTest(
"SELECT * FROM root.sg2.** where time>=now()-1d and time<=now() "
+ "ORDER BY TIME DESC ALIGN BY DEVICE;",
expectedHeader,
retArray);
}
protected static void insertData() {
try (Connection connection = EnvFactory.getEnv().getConnection();
Statement statement = connection.createStatement()) {
for (String sql : sqls) {
statement.execute(sql);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
googleapis/google-cloud-java | 35,626 | java-securesourcemanager/proto-google-cloud-securesourcemanager-v1/src/main/java/com/google/cloud/securesourcemanager/v1/ResolvePullRequestCommentsResponse.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/securesourcemanager/v1/secure_source_manager.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.securesourcemanager.v1;
/**
*
*
* <pre>
* The response to resolve multiple pull request comments.
* </pre>
*
* Protobuf type {@code google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse}
*/
public final class ResolvePullRequestCommentsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse)
ResolvePullRequestCommentsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ResolvePullRequestCommentsResponse.newBuilder() to construct.
private ResolvePullRequestCommentsResponse(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ResolvePullRequestCommentsResponse() {
pullRequestComments_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ResolvePullRequestCommentsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto
.internal_static_google_cloud_securesourcemanager_v1_ResolvePullRequestCommentsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto
.internal_static_google_cloud_securesourcemanager_v1_ResolvePullRequestCommentsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse.class,
com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse.Builder
.class);
}
public static final int PULL_REQUEST_COMMENTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.securesourcemanager.v1.PullRequestComment>
pullRequestComments_;
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.securesourcemanager.v1.PullRequestComment>
getPullRequestCommentsList() {
return pullRequestComments_;
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
@java.lang.Override
public java.util.List<
? extends com.google.cloud.securesourcemanager.v1.PullRequestCommentOrBuilder>
getPullRequestCommentsOrBuilderList() {
return pullRequestComments_;
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
@java.lang.Override
public int getPullRequestCommentsCount() {
return pullRequestComments_.size();
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
@java.lang.Override
public com.google.cloud.securesourcemanager.v1.PullRequestComment getPullRequestComments(
int index) {
return pullRequestComments_.get(index);
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
@java.lang.Override
public com.google.cloud.securesourcemanager.v1.PullRequestCommentOrBuilder
getPullRequestCommentsOrBuilder(int index) {
return pullRequestComments_.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 < pullRequestComments_.size(); i++) {
output.writeMessage(1, pullRequestComments_.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 < pullRequestComments_.size(); i++) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(1, pullRequestComments_.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.securesourcemanager.v1.ResolvePullRequestCommentsResponse)) {
return super.equals(obj);
}
com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse other =
(com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse) obj;
if (!getPullRequestCommentsList().equals(other.getPullRequestCommentsList())) 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 (getPullRequestCommentsCount() > 0) {
hash = (37 * hash) + PULL_REQUEST_COMMENTS_FIELD_NUMBER;
hash = (53 * hash) + getPullRequestCommentsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
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.securesourcemanager.v1.ResolvePullRequestCommentsResponse
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
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.securesourcemanager.v1.ResolvePullRequestCommentsResponse
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
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.securesourcemanager.v1.ResolvePullRequestCommentsResponse
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
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.securesourcemanager.v1.ResolvePullRequestCommentsResponse
parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
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.securesourcemanager.v1.ResolvePullRequestCommentsResponse 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 to resolve multiple pull request comments.
* </pre>
*
* Protobuf type {@code google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse)
com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto
.internal_static_google_cloud_securesourcemanager_v1_ResolvePullRequestCommentsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto
.internal_static_google_cloud_securesourcemanager_v1_ResolvePullRequestCommentsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse.class,
com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse.Builder
.class);
}
// Construct using
// com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (pullRequestCommentsBuilder_ == null) {
pullRequestComments_ = java.util.Collections.emptyList();
} else {
pullRequestComments_ = null;
pullRequestCommentsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.securesourcemanager.v1.SecureSourceManagerProto
.internal_static_google_cloud_securesourcemanager_v1_ResolvePullRequestCommentsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
getDefaultInstanceForType() {
return com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse build() {
com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
buildPartial() {
com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse result =
new com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse result) {
if (pullRequestCommentsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
pullRequestComments_ = java.util.Collections.unmodifiableList(pullRequestComments_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.pullRequestComments_ = pullRequestComments_;
} else {
result.pullRequestComments_ = pullRequestCommentsBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse 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.securesourcemanager.v1.ResolvePullRequestCommentsResponse) {
return mergeFrom(
(com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse other) {
if (other
== com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
.getDefaultInstance()) return this;
if (pullRequestCommentsBuilder_ == null) {
if (!other.pullRequestComments_.isEmpty()) {
if (pullRequestComments_.isEmpty()) {
pullRequestComments_ = other.pullRequestComments_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensurePullRequestCommentsIsMutable();
pullRequestComments_.addAll(other.pullRequestComments_);
}
onChanged();
}
} else {
if (!other.pullRequestComments_.isEmpty()) {
if (pullRequestCommentsBuilder_.isEmpty()) {
pullRequestCommentsBuilder_.dispose();
pullRequestCommentsBuilder_ = null;
pullRequestComments_ = other.pullRequestComments_;
bitField0_ = (bitField0_ & ~0x00000001);
pullRequestCommentsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getPullRequestCommentsFieldBuilder()
: null;
} else {
pullRequestCommentsBuilder_.addAllMessages(other.pullRequestComments_);
}
}
}
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.securesourcemanager.v1.PullRequestComment m =
input.readMessage(
com.google.cloud.securesourcemanager.v1.PullRequestComment.parser(),
extensionRegistry);
if (pullRequestCommentsBuilder_ == null) {
ensurePullRequestCommentsIsMutable();
pullRequestComments_.add(m);
} else {
pullRequestCommentsBuilder_.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.securesourcemanager.v1.PullRequestComment>
pullRequestComments_ = java.util.Collections.emptyList();
private void ensurePullRequestCommentsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
pullRequestComments_ =
new java.util.ArrayList<com.google.cloud.securesourcemanager.v1.PullRequestComment>(
pullRequestComments_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.securesourcemanager.v1.PullRequestComment,
com.google.cloud.securesourcemanager.v1.PullRequestComment.Builder,
com.google.cloud.securesourcemanager.v1.PullRequestCommentOrBuilder>
pullRequestCommentsBuilder_;
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public java.util.List<com.google.cloud.securesourcemanager.v1.PullRequestComment>
getPullRequestCommentsList() {
if (pullRequestCommentsBuilder_ == null) {
return java.util.Collections.unmodifiableList(pullRequestComments_);
} else {
return pullRequestCommentsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public int getPullRequestCommentsCount() {
if (pullRequestCommentsBuilder_ == null) {
return pullRequestComments_.size();
} else {
return pullRequestCommentsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public com.google.cloud.securesourcemanager.v1.PullRequestComment getPullRequestComments(
int index) {
if (pullRequestCommentsBuilder_ == null) {
return pullRequestComments_.get(index);
} else {
return pullRequestCommentsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public Builder setPullRequestComments(
int index, com.google.cloud.securesourcemanager.v1.PullRequestComment value) {
if (pullRequestCommentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePullRequestCommentsIsMutable();
pullRequestComments_.set(index, value);
onChanged();
} else {
pullRequestCommentsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public Builder setPullRequestComments(
int index,
com.google.cloud.securesourcemanager.v1.PullRequestComment.Builder builderForValue) {
if (pullRequestCommentsBuilder_ == null) {
ensurePullRequestCommentsIsMutable();
pullRequestComments_.set(index, builderForValue.build());
onChanged();
} else {
pullRequestCommentsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public Builder addPullRequestComments(
com.google.cloud.securesourcemanager.v1.PullRequestComment value) {
if (pullRequestCommentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePullRequestCommentsIsMutable();
pullRequestComments_.add(value);
onChanged();
} else {
pullRequestCommentsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public Builder addPullRequestComments(
int index, com.google.cloud.securesourcemanager.v1.PullRequestComment value) {
if (pullRequestCommentsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensurePullRequestCommentsIsMutable();
pullRequestComments_.add(index, value);
onChanged();
} else {
pullRequestCommentsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public Builder addPullRequestComments(
com.google.cloud.securesourcemanager.v1.PullRequestComment.Builder builderForValue) {
if (pullRequestCommentsBuilder_ == null) {
ensurePullRequestCommentsIsMutable();
pullRequestComments_.add(builderForValue.build());
onChanged();
} else {
pullRequestCommentsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public Builder addPullRequestComments(
int index,
com.google.cloud.securesourcemanager.v1.PullRequestComment.Builder builderForValue) {
if (pullRequestCommentsBuilder_ == null) {
ensurePullRequestCommentsIsMutable();
pullRequestComments_.add(index, builderForValue.build());
onChanged();
} else {
pullRequestCommentsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public Builder addAllPullRequestComments(
java.lang.Iterable<? extends com.google.cloud.securesourcemanager.v1.PullRequestComment>
values) {
if (pullRequestCommentsBuilder_ == null) {
ensurePullRequestCommentsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, pullRequestComments_);
onChanged();
} else {
pullRequestCommentsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public Builder clearPullRequestComments() {
if (pullRequestCommentsBuilder_ == null) {
pullRequestComments_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
pullRequestCommentsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public Builder removePullRequestComments(int index) {
if (pullRequestCommentsBuilder_ == null) {
ensurePullRequestCommentsIsMutable();
pullRequestComments_.remove(index);
onChanged();
} else {
pullRequestCommentsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public com.google.cloud.securesourcemanager.v1.PullRequestComment.Builder
getPullRequestCommentsBuilder(int index) {
return getPullRequestCommentsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public com.google.cloud.securesourcemanager.v1.PullRequestCommentOrBuilder
getPullRequestCommentsOrBuilder(int index) {
if (pullRequestCommentsBuilder_ == null) {
return pullRequestComments_.get(index);
} else {
return pullRequestCommentsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public java.util.List<
? extends com.google.cloud.securesourcemanager.v1.PullRequestCommentOrBuilder>
getPullRequestCommentsOrBuilderList() {
if (pullRequestCommentsBuilder_ != null) {
return pullRequestCommentsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(pullRequestComments_);
}
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public com.google.cloud.securesourcemanager.v1.PullRequestComment.Builder
addPullRequestCommentsBuilder() {
return getPullRequestCommentsFieldBuilder()
.addBuilder(
com.google.cloud.securesourcemanager.v1.PullRequestComment.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public com.google.cloud.securesourcemanager.v1.PullRequestComment.Builder
addPullRequestCommentsBuilder(int index) {
return getPullRequestCommentsFieldBuilder()
.addBuilder(
index,
com.google.cloud.securesourcemanager.v1.PullRequestComment.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of pull request comments resolved.
* </pre>
*
* <code>
* repeated .google.cloud.securesourcemanager.v1.PullRequestComment pull_request_comments = 1;
* </code>
*/
public java.util.List<com.google.cloud.securesourcemanager.v1.PullRequestComment.Builder>
getPullRequestCommentsBuilderList() {
return getPullRequestCommentsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.securesourcemanager.v1.PullRequestComment,
com.google.cloud.securesourcemanager.v1.PullRequestComment.Builder,
com.google.cloud.securesourcemanager.v1.PullRequestCommentOrBuilder>
getPullRequestCommentsFieldBuilder() {
if (pullRequestCommentsBuilder_ == null) {
pullRequestCommentsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.securesourcemanager.v1.PullRequestComment,
com.google.cloud.securesourcemanager.v1.PullRequestComment.Builder,
com.google.cloud.securesourcemanager.v1.PullRequestCommentOrBuilder>(
pullRequestComments_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
pullRequestComments_ = null;
}
return pullRequestCommentsBuilder_;
}
@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.securesourcemanager.v1.ResolvePullRequestCommentsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse)
private static final com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse();
}
public static com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ResolvePullRequestCommentsResponse> PARSER =
new com.google.protobuf.AbstractParser<ResolvePullRequestCommentsResponse>() {
@java.lang.Override
public ResolvePullRequestCommentsResponse 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<ResolvePullRequestCommentsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ResolvePullRequestCommentsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.securesourcemanager.v1.ResolvePullRequestCommentsResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-api-java-client-services | 35,866 | clients/google-api-services-retail/v2beta/1.31.0/com/google/api/services/retail/v2beta/model/GoogleCloudRetailV2betaSearchRequest.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.retail.v2beta.model;
/**
* Request message for SearchService.Search method.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Retail API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudRetailV2betaSearchRequest extends com.google.api.client.json.GenericJson {
/**
* Boost specification to boost certain products. See more details at this [user
* guide](https://cloud.google.com/retail/docs/boosting). Notice that if both
* ServingConfig.boost_control_ids and SearchRequest.boost_spec are set, the boost conditions from
* both places are evaluated. If a search request matches multiple boost conditions, the final
* boost score is equal to the sum of the boost scores from all matched boost conditions.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2betaSearchRequestBoostSpec boostSpec;
/**
* The branch resource name, such as
* `projects/locations/global/catalogs/default_catalog/branches/0`. Use "default_branch" as the
* branch ID or leave this field empty, to search products under the default branch.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String branch;
/**
* The default filter that is applied when a user performs a search without checking any filters
* on the search page. The filter applied to every search request when quality improvement such as
* query expansion is needed. For example, if a query does not have enough results, an expanded
* query with SearchRequest.canonical_filter will be returned as a supplement of the original
* query. This field is strongly recommended to achieve high search quality. See
* SearchRequest.filter for more details about filter syntax.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String canonicalFilter;
/**
* Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic to enable dynamic
* facets. Do not set this field. The specification for dynamically generated facets. Notice that
* only textual facets can be dynamically generated.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2betaSearchRequestDynamicFacetSpec dynamicFacetSpec;
/**
* Facet specifications for faceted search. If empty, no facets are returned. A maximum of 100
* values are allowed. Otherwise, an INVALID_ARGUMENT error is returned.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudRetailV2betaSearchRequestFacetSpec> facetSpecs;
/**
* The filter syntax consists of an expression language for constructing a predicate from one or
* more fields of the products being filtered. Filter expression is case-sensitive. See more
* details at this [user guide](https://cloud.google.com/retail/docs/filter-and-order#filter). If
* this field is unrecognizable, an INVALID_ARGUMENT is returned.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String filter;
/**
* The labels applied to a resource must meet the following requirements: * Each resource can have
* multiple labels, up to a maximum of 64. * Each label must be a key-value pair. * Keys have a
* minimum length of 1 character and a maximum length of 63 characters and cannot be empty. Values
* can be empty and have a maximum length of 63 characters. * Keys and values can contain only
* lowercase letters, numeric characters, underscores, and dashes. All characters must use UTF-8
* encoding, and international characters are allowed. * The key portion of a label must be
* unique. However, you can use the same key with multiple resources. * Keys must start with a
* lowercase letter or international character. See [Google Cloud
* Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements)
* for more details.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> labels;
/**
* A 0-indexed integer that specifies the current offset (that is, starting result location,
* amongst the Products deemed by the API as relevant) in search results. This field is only
* considered if page_token is unset. If this field is negative, an INVALID_ARGUMENT is returned.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer offset;
/**
* The order in which products are returned. Products can be ordered by a field in an Product
* object. Leave it unset if ordered by relevance. OrderBy expression is case-sensitive. See more
* details at this [user guide](https://cloud.google.com/retail/docs/filter-and-order#order). If
* this field is unrecognizable, an INVALID_ARGUMENT is returned.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String orderBy;
/**
* The categories associated with a category page. Required for category navigation queries to
* achieve good search quality. The format should be the same as UserEvent.page_categories; To
* represent full path of category, use '>' sign to separate different hierarchies. If '>' is part
* of the category name, please replace it with other character(s). Category pages include special
* pages such as sales or promotions. For instance, a special sale page may have the category
* hierarchy: "pageCategories" : ["Sales > 2017 Black Friday Deals"].
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> pageCategories;
/**
* Maximum number of Products to return. If unspecified, defaults to a reasonable value. The
* maximum allowed value is 120. Values above 120 will be coerced to 120. If this field is
* negative, an INVALID_ARGUMENT is returned.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer pageSize;
/**
* A page token SearchResponse.next_page_token, received from a previous SearchService.Search
* call. Provide this to retrieve the subsequent page. When paginating, all other parameters
* provided to SearchService.Search must match the call that provided the page token. Otherwise,
* an INVALID_ARGUMENT error is returned.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String pageToken;
/**
* The specification for personalization.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2betaSearchRequestPersonalizationSpec personalizationSpec;
/**
* Raw search query. If this field is empty, the request is considered a category browsing request
* and returned results are based on filter and page_categories.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String query;
/**
* The query expansion specification that specifies the conditions under which query expansion
* will occur. See more details at this [user guide](https://cloud.google.com/retail/docs/result-
* size#query_expansion).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2betaSearchRequestQueryExpansionSpec queryExpansionSpec;
/**
* The search mode of the search request. If not specified, a single search request triggers both
* product search and faceted search.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String searchMode;
/**
* The spell correction specification that specifies the mode under which spell correction will
* take effect.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2betaSearchRequestSpellCorrectionSpec spellCorrectionSpec;
/**
* User information.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2betaUserInfo userInfo;
/**
* The keys to fetch and rollup the matching variant Products attributes, FulfillmentInfo or
* LocalInventorys attributes. The attributes from all the matching variant Products or
* LocalInventorys are merged and de-duplicated. Notice that rollup attributes will lead to extra
* query latency. Maximum number of keys is 30. For FulfillmentInfo, a fulfillment type and a
* fulfillment ID must be provided in the format of "fulfillmentType.fulfillmentId". E.g., in
* "pickupInStore.store123", "pickupInStore" is fulfillment type and "store123" is the store ID.
* Supported keys are: * colorFamilies * price * originalPrice * discount * variantId *
* inventory(place_id,price) * inventory(place_id,original_price) *
* inventory(place_id,attributes.key), where key is any key in the
* Product.local_inventories.attributes map. * attributes.key, where key is any key in the
* Product.attributes map. * pickupInStore.id, where id is any FulfillmentInfo.place_ids for
* FulfillmentInfo.type "pickup-in-store". * shipToStore.id, where id is any
* FulfillmentInfo.place_ids for FulfillmentInfo.type "ship-to-store". * sameDayDelivery.id, where
* id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "same-day-delivery". *
* nextDayDelivery.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "next-
* day-delivery". * customFulfillment1.id, where id is any FulfillmentInfo.place_ids for
* FulfillmentInfo.type "custom-type-1". * customFulfillment2.id, where id is any
* FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-2". * customFulfillment3.id,
* where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-3". *
* customFulfillment4.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type
* "custom-type-4". * customFulfillment5.id, where id is any FulfillmentInfo.place_ids for
* FulfillmentInfo.type "custom-type-5". If this field is set to an invalid value other than
* these, an INVALID_ARGUMENT error is returned.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> variantRollupKeys;
/**
* Required. A unique identifier for tracking visitors. For example, this could be implemented
* with an HTTP cookie, which should be able to uniquely identify a visitor on a single device.
* This unique identifier should not change if the visitor logs in or out of the website. This
* should be the same identifier as UserEvent.visitor_id. The field must be a UTF-8 encoded string
* with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String visitorId;
/**
* Boost specification to boost certain products. See more details at this [user
* guide](https://cloud.google.com/retail/docs/boosting). Notice that if both
* ServingConfig.boost_control_ids and SearchRequest.boost_spec are set, the boost conditions from
* both places are evaluated. If a search request matches multiple boost conditions, the final
* boost score is equal to the sum of the boost scores from all matched boost conditions.
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequestBoostSpec getBoostSpec() {
return boostSpec;
}
/**
* Boost specification to boost certain products. See more details at this [user
* guide](https://cloud.google.com/retail/docs/boosting). Notice that if both
* ServingConfig.boost_control_ids and SearchRequest.boost_spec are set, the boost conditions from
* both places are evaluated. If a search request matches multiple boost conditions, the final
* boost score is equal to the sum of the boost scores from all matched boost conditions.
* @param boostSpec boostSpec or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setBoostSpec(GoogleCloudRetailV2betaSearchRequestBoostSpec boostSpec) {
this.boostSpec = boostSpec;
return this;
}
/**
* The branch resource name, such as
* `projects/locations/global/catalogs/default_catalog/branches/0`. Use "default_branch" as the
* branch ID or leave this field empty, to search products under the default branch.
* @return value or {@code null} for none
*/
public java.lang.String getBranch() {
return branch;
}
/**
* The branch resource name, such as
* `projects/locations/global/catalogs/default_catalog/branches/0`. Use "default_branch" as the
* branch ID or leave this field empty, to search products under the default branch.
* @param branch branch or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setBranch(java.lang.String branch) {
this.branch = branch;
return this;
}
/**
* The default filter that is applied when a user performs a search without checking any filters
* on the search page. The filter applied to every search request when quality improvement such as
* query expansion is needed. For example, if a query does not have enough results, an expanded
* query with SearchRequest.canonical_filter will be returned as a supplement of the original
* query. This field is strongly recommended to achieve high search quality. See
* SearchRequest.filter for more details about filter syntax.
* @return value or {@code null} for none
*/
public java.lang.String getCanonicalFilter() {
return canonicalFilter;
}
/**
* The default filter that is applied when a user performs a search without checking any filters
* on the search page. The filter applied to every search request when quality improvement such as
* query expansion is needed. For example, if a query does not have enough results, an expanded
* query with SearchRequest.canonical_filter will be returned as a supplement of the original
* query. This field is strongly recommended to achieve high search quality. See
* SearchRequest.filter for more details about filter syntax.
* @param canonicalFilter canonicalFilter or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setCanonicalFilter(java.lang.String canonicalFilter) {
this.canonicalFilter = canonicalFilter;
return this;
}
/**
* Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic to enable dynamic
* facets. Do not set this field. The specification for dynamically generated facets. Notice that
* only textual facets can be dynamically generated.
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequestDynamicFacetSpec getDynamicFacetSpec() {
return dynamicFacetSpec;
}
/**
* Deprecated. Refer to https://cloud.google.com/retail/docs/configs#dynamic to enable dynamic
* facets. Do not set this field. The specification for dynamically generated facets. Notice that
* only textual facets can be dynamically generated.
* @param dynamicFacetSpec dynamicFacetSpec or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setDynamicFacetSpec(GoogleCloudRetailV2betaSearchRequestDynamicFacetSpec dynamicFacetSpec) {
this.dynamicFacetSpec = dynamicFacetSpec;
return this;
}
/**
* Facet specifications for faceted search. If empty, no facets are returned. A maximum of 100
* values are allowed. Otherwise, an INVALID_ARGUMENT error is returned.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudRetailV2betaSearchRequestFacetSpec> getFacetSpecs() {
return facetSpecs;
}
/**
* Facet specifications for faceted search. If empty, no facets are returned. A maximum of 100
* values are allowed. Otherwise, an INVALID_ARGUMENT error is returned.
* @param facetSpecs facetSpecs or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setFacetSpecs(java.util.List<GoogleCloudRetailV2betaSearchRequestFacetSpec> facetSpecs) {
this.facetSpecs = facetSpecs;
return this;
}
/**
* The filter syntax consists of an expression language for constructing a predicate from one or
* more fields of the products being filtered. Filter expression is case-sensitive. See more
* details at this [user guide](https://cloud.google.com/retail/docs/filter-and-order#filter). If
* this field is unrecognizable, an INVALID_ARGUMENT is returned.
* @return value or {@code null} for none
*/
public java.lang.String getFilter() {
return filter;
}
/**
* The filter syntax consists of an expression language for constructing a predicate from one or
* more fields of the products being filtered. Filter expression is case-sensitive. See more
* details at this [user guide](https://cloud.google.com/retail/docs/filter-and-order#filter). If
* this field is unrecognizable, an INVALID_ARGUMENT is returned.
* @param filter filter or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setFilter(java.lang.String filter) {
this.filter = filter;
return this;
}
/**
* The labels applied to a resource must meet the following requirements: * Each resource can have
* multiple labels, up to a maximum of 64. * Each label must be a key-value pair. * Keys have a
* minimum length of 1 character and a maximum length of 63 characters and cannot be empty. Values
* can be empty and have a maximum length of 63 characters. * Keys and values can contain only
* lowercase letters, numeric characters, underscores, and dashes. All characters must use UTF-8
* encoding, and international characters are allowed. * The key portion of a label must be
* unique. However, you can use the same key with multiple resources. * Keys must start with a
* lowercase letter or international character. See [Google Cloud
* Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements)
* for more details.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getLabels() {
return labels;
}
/**
* The labels applied to a resource must meet the following requirements: * Each resource can have
* multiple labels, up to a maximum of 64. * Each label must be a key-value pair. * Keys have a
* minimum length of 1 character and a maximum length of 63 characters and cannot be empty. Values
* can be empty and have a maximum length of 63 characters. * Keys and values can contain only
* lowercase letters, numeric characters, underscores, and dashes. All characters must use UTF-8
* encoding, and international characters are allowed. * The key portion of a label must be
* unique. However, you can use the same key with multiple resources. * Keys must start with a
* lowercase letter or international character. See [Google Cloud
* Document](https://cloud.google.com/resource-manager/docs/creating-managing-labels#requirements)
* for more details.
* @param labels labels or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setLabels(java.util.Map<String, java.lang.String> labels) {
this.labels = labels;
return this;
}
/**
* A 0-indexed integer that specifies the current offset (that is, starting result location,
* amongst the Products deemed by the API as relevant) in search results. This field is only
* considered if page_token is unset. If this field is negative, an INVALID_ARGUMENT is returned.
* @return value or {@code null} for none
*/
public java.lang.Integer getOffset() {
return offset;
}
/**
* A 0-indexed integer that specifies the current offset (that is, starting result location,
* amongst the Products deemed by the API as relevant) in search results. This field is only
* considered if page_token is unset. If this field is negative, an INVALID_ARGUMENT is returned.
* @param offset offset or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setOffset(java.lang.Integer offset) {
this.offset = offset;
return this;
}
/**
* The order in which products are returned. Products can be ordered by a field in an Product
* object. Leave it unset if ordered by relevance. OrderBy expression is case-sensitive. See more
* details at this [user guide](https://cloud.google.com/retail/docs/filter-and-order#order). If
* this field is unrecognizable, an INVALID_ARGUMENT is returned.
* @return value or {@code null} for none
*/
public java.lang.String getOrderBy() {
return orderBy;
}
/**
* The order in which products are returned. Products can be ordered by a field in an Product
* object. Leave it unset if ordered by relevance. OrderBy expression is case-sensitive. See more
* details at this [user guide](https://cloud.google.com/retail/docs/filter-and-order#order). If
* this field is unrecognizable, an INVALID_ARGUMENT is returned.
* @param orderBy orderBy or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setOrderBy(java.lang.String orderBy) {
this.orderBy = orderBy;
return this;
}
/**
* The categories associated with a category page. Required for category navigation queries to
* achieve good search quality. The format should be the same as UserEvent.page_categories; To
* represent full path of category, use '>' sign to separate different hierarchies. If '>' is part
* of the category name, please replace it with other character(s). Category pages include special
* pages such as sales or promotions. For instance, a special sale page may have the category
* hierarchy: "pageCategories" : ["Sales > 2017 Black Friday Deals"].
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPageCategories() {
return pageCategories;
}
/**
* The categories associated with a category page. Required for category navigation queries to
* achieve good search quality. The format should be the same as UserEvent.page_categories; To
* represent full path of category, use '>' sign to separate different hierarchies. If '>' is part
* of the category name, please replace it with other character(s). Category pages include special
* pages such as sales or promotions. For instance, a special sale page may have the category
* hierarchy: "pageCategories" : ["Sales > 2017 Black Friday Deals"].
* @param pageCategories pageCategories or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setPageCategories(java.util.List<java.lang.String> pageCategories) {
this.pageCategories = pageCategories;
return this;
}
/**
* Maximum number of Products to return. If unspecified, defaults to a reasonable value. The
* maximum allowed value is 120. Values above 120 will be coerced to 120. If this field is
* negative, an INVALID_ARGUMENT is returned.
* @return value or {@code null} for none
*/
public java.lang.Integer getPageSize() {
return pageSize;
}
/**
* Maximum number of Products to return. If unspecified, defaults to a reasonable value. The
* maximum allowed value is 120. Values above 120 will be coerced to 120. If this field is
* negative, an INVALID_ARGUMENT is returned.
* @param pageSize pageSize or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setPageSize(java.lang.Integer pageSize) {
this.pageSize = pageSize;
return this;
}
/**
* A page token SearchResponse.next_page_token, received from a previous SearchService.Search
* call. Provide this to retrieve the subsequent page. When paginating, all other parameters
* provided to SearchService.Search must match the call that provided the page token. Otherwise,
* an INVALID_ARGUMENT error is returned.
* @return value or {@code null} for none
*/
public java.lang.String getPageToken() {
return pageToken;
}
/**
* A page token SearchResponse.next_page_token, received from a previous SearchService.Search
* call. Provide this to retrieve the subsequent page. When paginating, all other parameters
* provided to SearchService.Search must match the call that provided the page token. Otherwise,
* an INVALID_ARGUMENT error is returned.
* @param pageToken pageToken or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setPageToken(java.lang.String pageToken) {
this.pageToken = pageToken;
return this;
}
/**
* The specification for personalization.
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequestPersonalizationSpec getPersonalizationSpec() {
return personalizationSpec;
}
/**
* The specification for personalization.
* @param personalizationSpec personalizationSpec or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setPersonalizationSpec(GoogleCloudRetailV2betaSearchRequestPersonalizationSpec personalizationSpec) {
this.personalizationSpec = personalizationSpec;
return this;
}
/**
* Raw search query. If this field is empty, the request is considered a category browsing request
* and returned results are based on filter and page_categories.
* @return value or {@code null} for none
*/
public java.lang.String getQuery() {
return query;
}
/**
* Raw search query. If this field is empty, the request is considered a category browsing request
* and returned results are based on filter and page_categories.
* @param query query or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setQuery(java.lang.String query) {
this.query = query;
return this;
}
/**
* The query expansion specification that specifies the conditions under which query expansion
* will occur. See more details at this [user guide](https://cloud.google.com/retail/docs/result-
* size#query_expansion).
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequestQueryExpansionSpec getQueryExpansionSpec() {
return queryExpansionSpec;
}
/**
* The query expansion specification that specifies the conditions under which query expansion
* will occur. See more details at this [user guide](https://cloud.google.com/retail/docs/result-
* size#query_expansion).
* @param queryExpansionSpec queryExpansionSpec or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setQueryExpansionSpec(GoogleCloudRetailV2betaSearchRequestQueryExpansionSpec queryExpansionSpec) {
this.queryExpansionSpec = queryExpansionSpec;
return this;
}
/**
* The search mode of the search request. If not specified, a single search request triggers both
* product search and faceted search.
* @return value or {@code null} for none
*/
public java.lang.String getSearchMode() {
return searchMode;
}
/**
* The search mode of the search request. If not specified, a single search request triggers both
* product search and faceted search.
* @param searchMode searchMode or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setSearchMode(java.lang.String searchMode) {
this.searchMode = searchMode;
return this;
}
/**
* The spell correction specification that specifies the mode under which spell correction will
* take effect.
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequestSpellCorrectionSpec getSpellCorrectionSpec() {
return spellCorrectionSpec;
}
/**
* The spell correction specification that specifies the mode under which spell correction will
* take effect.
* @param spellCorrectionSpec spellCorrectionSpec or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setSpellCorrectionSpec(GoogleCloudRetailV2betaSearchRequestSpellCorrectionSpec spellCorrectionSpec) {
this.spellCorrectionSpec = spellCorrectionSpec;
return this;
}
/**
* User information.
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2betaUserInfo getUserInfo() {
return userInfo;
}
/**
* User information.
* @param userInfo userInfo or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setUserInfo(GoogleCloudRetailV2betaUserInfo userInfo) {
this.userInfo = userInfo;
return this;
}
/**
* The keys to fetch and rollup the matching variant Products attributes, FulfillmentInfo or
* LocalInventorys attributes. The attributes from all the matching variant Products or
* LocalInventorys are merged and de-duplicated. Notice that rollup attributes will lead to extra
* query latency. Maximum number of keys is 30. For FulfillmentInfo, a fulfillment type and a
* fulfillment ID must be provided in the format of "fulfillmentType.fulfillmentId". E.g., in
* "pickupInStore.store123", "pickupInStore" is fulfillment type and "store123" is the store ID.
* Supported keys are: * colorFamilies * price * originalPrice * discount * variantId *
* inventory(place_id,price) * inventory(place_id,original_price) *
* inventory(place_id,attributes.key), where key is any key in the
* Product.local_inventories.attributes map. * attributes.key, where key is any key in the
* Product.attributes map. * pickupInStore.id, where id is any FulfillmentInfo.place_ids for
* FulfillmentInfo.type "pickup-in-store". * shipToStore.id, where id is any
* FulfillmentInfo.place_ids for FulfillmentInfo.type "ship-to-store". * sameDayDelivery.id, where
* id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "same-day-delivery". *
* nextDayDelivery.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "next-
* day-delivery". * customFulfillment1.id, where id is any FulfillmentInfo.place_ids for
* FulfillmentInfo.type "custom-type-1". * customFulfillment2.id, where id is any
* FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-2". * customFulfillment3.id,
* where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-3". *
* customFulfillment4.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type
* "custom-type-4". * customFulfillment5.id, where id is any FulfillmentInfo.place_ids for
* FulfillmentInfo.type "custom-type-5". If this field is set to an invalid value other than
* these, an INVALID_ARGUMENT error is returned.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getVariantRollupKeys() {
return variantRollupKeys;
}
/**
* The keys to fetch and rollup the matching variant Products attributes, FulfillmentInfo or
* LocalInventorys attributes. The attributes from all the matching variant Products or
* LocalInventorys are merged and de-duplicated. Notice that rollup attributes will lead to extra
* query latency. Maximum number of keys is 30. For FulfillmentInfo, a fulfillment type and a
* fulfillment ID must be provided in the format of "fulfillmentType.fulfillmentId". E.g., in
* "pickupInStore.store123", "pickupInStore" is fulfillment type and "store123" is the store ID.
* Supported keys are: * colorFamilies * price * originalPrice * discount * variantId *
* inventory(place_id,price) * inventory(place_id,original_price) *
* inventory(place_id,attributes.key), where key is any key in the
* Product.local_inventories.attributes map. * attributes.key, where key is any key in the
* Product.attributes map. * pickupInStore.id, where id is any FulfillmentInfo.place_ids for
* FulfillmentInfo.type "pickup-in-store". * shipToStore.id, where id is any
* FulfillmentInfo.place_ids for FulfillmentInfo.type "ship-to-store". * sameDayDelivery.id, where
* id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "same-day-delivery". *
* nextDayDelivery.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "next-
* day-delivery". * customFulfillment1.id, where id is any FulfillmentInfo.place_ids for
* FulfillmentInfo.type "custom-type-1". * customFulfillment2.id, where id is any
* FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-2". * customFulfillment3.id,
* where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type "custom-type-3". *
* customFulfillment4.id, where id is any FulfillmentInfo.place_ids for FulfillmentInfo.type
* "custom-type-4". * customFulfillment5.id, where id is any FulfillmentInfo.place_ids for
* FulfillmentInfo.type "custom-type-5". If this field is set to an invalid value other than
* these, an INVALID_ARGUMENT error is returned.
* @param variantRollupKeys variantRollupKeys or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setVariantRollupKeys(java.util.List<java.lang.String> variantRollupKeys) {
this.variantRollupKeys = variantRollupKeys;
return this;
}
/**
* Required. A unique identifier for tracking visitors. For example, this could be implemented
* with an HTTP cookie, which should be able to uniquely identify a visitor on a single device.
* This unique identifier should not change if the visitor logs in or out of the website. This
* should be the same identifier as UserEvent.visitor_id. The field must be a UTF-8 encoded string
* with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned.
* @return value or {@code null} for none
*/
public java.lang.String getVisitorId() {
return visitorId;
}
/**
* Required. A unique identifier for tracking visitors. For example, this could be implemented
* with an HTTP cookie, which should be able to uniquely identify a visitor on a single device.
* This unique identifier should not change if the visitor logs in or out of the website. This
* should be the same identifier as UserEvent.visitor_id. The field must be a UTF-8 encoded string
* with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned.
* @param visitorId visitorId or {@code null} for none
*/
public GoogleCloudRetailV2betaSearchRequest setVisitorId(java.lang.String visitorId) {
this.visitorId = visitorId;
return this;
}
@Override
public GoogleCloudRetailV2betaSearchRequest set(String fieldName, Object value) {
return (GoogleCloudRetailV2betaSearchRequest) super.set(fieldName, value);
}
@Override
public GoogleCloudRetailV2betaSearchRequest clone() {
return (GoogleCloudRetailV2betaSearchRequest) super.clone();
}
}
|
apache/tomcat | 35,529 | java/org/apache/catalina/connector/Connector.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.catalina.connector;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashSet;
import javax.management.ObjectName;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleState;
import org.apache.catalina.Service;
import org.apache.catalina.core.AprStatus;
import org.apache.catalina.util.LifecycleMBeanBase;
import org.apache.coyote.AbstractProtocol;
import org.apache.coyote.Adapter;
import org.apache.coyote.ProtocolHandler;
import org.apache.coyote.UpgradeProtocol;
import org.apache.coyote.http11.AbstractHttp11Protocol;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.buf.B2CConverter;
import org.apache.tomcat.util.buf.CharsetUtil;
import org.apache.tomcat.util.buf.EncodedSolidusHandling;
import org.apache.tomcat.util.buf.StringUtils;
import org.apache.tomcat.util.compat.JreCompat;
import org.apache.tomcat.util.http.Method;
import org.apache.tomcat.util.net.SSLHostConfig;
import org.apache.tomcat.util.net.openssl.OpenSSLImplementation;
import org.apache.tomcat.util.net.openssl.OpenSSLStatus;
import org.apache.tomcat.util.res.StringManager;
/**
* Implementation of a Coyote connector.
*/
public class Connector extends LifecycleMBeanBase {
private static final Log log = LogFactory.getLog(Connector.class);
public static final String INTERNAL_EXECUTOR_NAME = "Internal";
// ------------------------------------------------------------ Constructor
/**
* Defaults to using HTTP/1.1 NIO implementation.
*/
public Connector() {
this("HTTP/1.1");
}
public Connector(String protocol) {
configuredProtocol = protocol;
ProtocolHandler p = null;
try {
p = ProtocolHandler.create(protocol);
} catch (Exception e) {
log.error(sm.getString("coyoteConnector.protocolHandlerInstantiationFailed"), e);
}
if (p != null) {
protocolHandler = p;
protocolHandlerClassName = protocolHandler.getClass().getName();
} else {
protocolHandler = null;
protocolHandlerClassName = protocol;
}
// Default for Connector depends on this system property
setThrowOnFailure(Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE"));
}
public Connector(ProtocolHandler protocolHandler) {
protocolHandlerClassName = protocolHandler.getClass().getName();
configuredProtocol = protocolHandlerClassName;
this.protocolHandler = protocolHandler;
// Default for Connector depends on this system property
setThrowOnFailure(Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE"));
}
// ----------------------------------------------------- Instance Variables
/**
* The <code>Service</code> we are associated with (if any).
*/
protected Service service = null;
/**
* If this is <code>true</code> the '\' character will be permitted as a path delimiter. If not specified, the
* default value of <code>false</code> will be used.
*/
protected boolean allowBackslash = false;
/**
* Do we allow TRACE ?
*/
protected boolean allowTrace = false;
/**
* Default timeout for asynchronous requests (ms).
*/
protected long asyncTimeout = 30000;
/**
* The "enable DNS lookups" flag for this Connector.
*/
protected boolean enableLookups = false;
/**
* If this is <code>true</code> then a call to <code>Response.getWriter()</code> if no character encoding has been
* specified will result in subsequent calls to <code>Response.getCharacterEncoding()</code> returning
* <code>ISO-8859-1</code> and the <code>Content-Type</code> response header will include a
* <code>charset=ISO-8859-1</code> component. (SRV.15.2.22.1) If not specified, the default specification compliant
* value of <code>true</code> will be used.
*/
protected boolean enforceEncodingInGetWriter = true;
/**
* Is generation of X-Powered-By response header enabled/disabled?
*/
protected boolean xpoweredBy = false;
/**
* The server name to which we should pretend requests to this Connector were directed. This is useful when
* operating Tomcat behind a proxy server, so that redirects get constructed accurately. If not specified, the
* server name included in the <code>Host</code> header is used.
*/
protected String proxyName = null;
/**
* The server port to which we should pretend requests to this Connector were directed. This is useful when
* operating Tomcat behind a proxy server, so that redirects get constructed accurately. If not specified, the port
* number specified by the <code>port</code> property is used.
*/
protected int proxyPort = 0;
/**
* The flag that controls recycling of the facades of the request processing objects. If set to <code>true</code>
* the object facades will be discarded when the request is recycled. If the security manager is enabled, this
* setting is ignored and object facades are always discarded.
*/
protected boolean discardFacades = true;
/**
* The redirect port for non-SSL to SSL redirects.
*/
protected int redirectPort = 443;
/**
* The request scheme that will be set on all requests received through this connector.
*/
protected String scheme = "http";
/**
* The secure connection flag that will be set on all requests received through this connector.
*/
protected boolean secure = false;
/**
* The string manager for this package.
*/
protected static final StringManager sm = StringManager.getManager(Connector.class);
/**
* The maximum number of cookies permitted for a request. Use a value less than zero for no limit. Defaults to 200.
*/
private int maxCookieCount = 200;
/**
* The maximum number of parameters (GET plus POST) which will be automatically parsed by the container. 1000 by
* default. A value of less than 0 means no limit.
*/
protected int maxParameterCount = 1000;
private int maxPartCount = 50;
private int maxPartHeaderSize = 512;
/**
* Maximum size of a POST which will be automatically parsed by the container. 2 MiB by default.
*/
protected int maxPostSize = 2 * 1024 * 1024;
/**
* Maximum size of a POST which will be saved by the container during authentication. 4 KiB by default
*/
protected int maxSavePostSize = 4 * 1024;
/**
* Comma-separated list of HTTP methods that will be parsed according to POST-style rules for
* application/x-www-form-urlencoded request bodies.
*/
protected String parseBodyMethods = Method.POST;
/**
* A Set of methods determined by {@link #parseBodyMethods}.
*/
protected HashSet<String> parseBodyMethodsSet;
/**
* Flag to use IP-based virtual hosting.
*/
protected boolean useIPVHosts = false;
/**
* Coyote Protocol handler class name. See {@link #Connector()} for current default.
*/
protected final String protocolHandlerClassName;
/**
* Name of the protocol that was configured.
*/
protected final String configuredProtocol;
/**
* Coyote protocol handler.
*/
protected final ProtocolHandler protocolHandler;
/**
* Coyote adapter.
*/
protected Adapter adapter = null;
/**
* The URI encoding in use.
*/
private Charset uriCharset = StandardCharsets.UTF_8;
/**
* The behavior when an encoded reverse solidus (backslash - \) is submitted.
*/
private EncodedSolidusHandling encodedReverseSolidusHandling = EncodedSolidusHandling.DECODE;
/**
* The behavior when an encoded solidus (slash - /) is submitted.
*/
private EncodedSolidusHandling encodedSolidusHandling = EncodedSolidusHandling.REJECT;
/**
* URI encoding as body.
*/
protected boolean useBodyEncodingForURI = false;
private boolean rejectSuspiciousURIs;
// ------------------------------------------------------------- Properties
/**
* Return a property from the protocol handler.
*
* @param name the property name
*
* @return the property value
*/
public Object getProperty(String name) {
if (protocolHandler == null) {
return null;
}
return IntrospectionUtils.getProperty(protocolHandler, name);
}
/**
* Set a property on the protocol handler.
*
* @param name the property name
* @param value the property value
*
* @return <code>true</code> if the property was successfully set
*/
public boolean setProperty(String name, String value) {
if (protocolHandler == null) {
return false;
}
return IntrospectionUtils.setProperty(protocolHandler, name, value);
}
/**
* @return the <code>Service</code> with which we are associated (if any).
*/
public Service getService() {
return this.service;
}
/**
* Set the <code>Service</code> with which we are associated (if any).
*
* @param service The service that owns this Engine
*/
public void setService(Service service) {
this.service = service;
}
/**
* @return <code>true</code> if backslash characters are allowed in URLs. Default value is <code>false</code>.
*/
public boolean getAllowBackslash() {
return allowBackslash;
}
/**
* Set the allowBackslash flag.
*
* @param allowBackslash the new flag value
*/
public void setAllowBackslash(boolean allowBackslash) {
this.allowBackslash = allowBackslash;
}
/**
* @return <code>true</code> if the TRACE method is allowed. Default value is <code>false</code>.
*/
public boolean getAllowTrace() {
return this.allowTrace;
}
/**
* Set the allowTrace flag, to disable or enable the TRACE HTTP method.
*
* @param allowTrace The new allowTrace flag
*/
public void setAllowTrace(boolean allowTrace) {
this.allowTrace = allowTrace;
}
/**
* @return the default timeout for async requests in ms.
*/
public long getAsyncTimeout() {
return asyncTimeout;
}
/**
* Set the default timeout for async requests.
*
* @param asyncTimeout The new timeout in ms.
*/
public void setAsyncTimeout(long asyncTimeout) {
this.asyncTimeout = asyncTimeout;
}
/**
* @return <code>true</code> if the object facades are discarded.
*/
public boolean getDiscardFacades() {
return discardFacades;
}
/**
* Set the recycling strategy for the object facades.
*
* @param discardFacades the new value of the flag
*/
public void setDiscardFacades(boolean discardFacades) {
this.discardFacades = discardFacades;
}
/**
* @return the "enable DNS lookups" flag.
*/
public boolean getEnableLookups() {
return this.enableLookups;
}
/**
* Set the "enable DNS lookups" flag.
*
* @param enableLookups The new "enable DNS lookups" flag value
*/
public void setEnableLookups(boolean enableLookups) {
this.enableLookups = enableLookups;
}
/**
* @return <code>true</code> if a default character encoding will be set when calling Response.getWriter()
*/
public boolean getEnforceEncodingInGetWriter() {
return enforceEncodingInGetWriter;
}
/**
* Set the enforceEncodingInGetWriter flag.
*
* @param enforceEncodingInGetWriter the new flag value
*/
public void setEnforceEncodingInGetWriter(boolean enforceEncodingInGetWriter) {
this.enforceEncodingInGetWriter = enforceEncodingInGetWriter;
}
public int getMaxCookieCount() {
return maxCookieCount;
}
public void setMaxCookieCount(int maxCookieCount) {
this.maxCookieCount = maxCookieCount;
}
/**
* @return the maximum number of parameters (GET plus POST) that will be automatically parsed by the container. A
* value of less than 0 means no limit.
*/
public int getMaxParameterCount() {
return maxParameterCount;
}
/**
* Set the maximum number of parameters (GET plus POST) that will be automatically parsed by the container. A value
* of less than 0 means no limit.
*
* @param maxParameterCount The new setting
*/
public void setMaxParameterCount(int maxParameterCount) {
this.maxParameterCount = maxParameterCount;
}
public int getMaxPartCount() {
return maxPartCount;
}
public void setMaxPartCount(int maxPartCount) {
this.maxPartCount = maxPartCount;
}
public int getMaxPartHeaderSize() {
return maxPartHeaderSize;
}
public void setMaxPartHeaderSize(int maxPartHeaderSize) {
this.maxPartHeaderSize = maxPartHeaderSize;
}
/**
* @return the maximum size of a POST which will be automatically parsed by the container.
*/
public int getMaxPostSize() {
return maxPostSize;
}
/**
* Set the maximum size of a POST which will be automatically parsed by the container.
*
* @param maxPostSize The new maximum size in bytes of a POST which will be automatically parsed by the container
*/
public void setMaxPostSize(int maxPostSize) {
this.maxPostSize = maxPostSize;
}
/**
* @return the maximum size of a POST which will be saved by the container during authentication.
*/
public int getMaxSavePostSize() {
return maxSavePostSize;
}
/**
* Set the maximum size of a POST which will be saved by the container during authentication.
*
* @param maxSavePostSize The new maximum size in bytes of a POST which will be saved by the container during
* authentication.
*/
public void setMaxSavePostSize(int maxSavePostSize) {
this.maxSavePostSize = maxSavePostSize;
setProperty("maxSavePostSize", String.valueOf(maxSavePostSize));
}
/**
* @return the HTTP methods which will support body parameters parsing
*/
public String getParseBodyMethods() {
return this.parseBodyMethods;
}
/**
* Set list of HTTP methods which should allow body parameter parsing. This defaults to <code>POST</code>.
*
* @param methods Comma separated list of HTTP method names
*/
public void setParseBodyMethods(String methods) {
HashSet<String> methodSet = new HashSet<>();
if (null != methods) {
methodSet.addAll(Arrays.asList(StringUtils.splitCommaSeparated(methods)));
}
if (methodSet.contains(Method.TRACE)) {
throw new IllegalArgumentException(sm.getString("coyoteConnector.parseBodyMethodNoTrace"));
}
this.parseBodyMethods = methods;
this.parseBodyMethodsSet = methodSet;
}
protected boolean isParseBodyMethod(String method) {
return parseBodyMethodsSet.contains(method);
}
/**
* @return the port number on which this connector is configured to listen for requests. The special value of 0
* means select a random free port when the socket is bound.
*/
public int getPort() {
// Try shortcut that should work for nearly all uses first as it does
// not use reflection and is therefore faster.
if (protocolHandler instanceof AbstractProtocol<?>) {
return ((AbstractProtocol<?>) protocolHandler).getPort();
}
// Fall back for custom protocol handlers not based on AbstractProtocol
Object port = getProperty("port");
if (port instanceof Integer) {
return ((Integer) port).intValue();
}
// Usually means an invalid protocol has been configured
return -1;
}
/**
* Set the port number on which we listen for requests.
*
* @param port The new port number
*/
public void setPort(int port) {
setProperty("port", String.valueOf(port));
}
public int getPortOffset() {
// Try shortcut that should work for nearly all uses first as it does
// not use reflection and is therefore faster.
if (protocolHandler instanceof AbstractProtocol<?>) {
return ((AbstractProtocol<?>) protocolHandler).getPortOffset();
}
// Fall back for custom protocol handlers not based on AbstractProtocol
Object port = getProperty("portOffset");
if (port instanceof Integer) {
return ((Integer) port).intValue();
}
// Usually means an invalid protocol has been configured.
return 0;
}
public void setPortOffset(int portOffset) {
setProperty("portOffset", String.valueOf(portOffset));
}
public int getPortWithOffset() {
int port = getPort();
// Zero is a special case and negative values are invalid
if (port > 0) {
return port + getPortOffset();
}
return port;
}
/**
* @return the port number on which this connector is listening to requests. If the special value for
* {@link #getPort} of zero is used then this method will report the actual port bound.
*/
public int getLocalPort() {
return ((Integer) getProperty("localPort")).intValue();
}
/**
* @return the Coyote protocol handler in use.
*/
public String getProtocol() {
return configuredProtocol;
}
/**
* @return the class name of the Coyote protocol handler in use.
*/
public String getProtocolHandlerClassName() {
return this.protocolHandlerClassName;
}
/**
* @return the protocol handler associated with the connector.
*/
public ProtocolHandler getProtocolHandler() {
return this.protocolHandler;
}
/**
* @return the proxy server name for this Connector.
*/
public String getProxyName() {
return this.proxyName;
}
/**
* Set the proxy server name for this Connector.
*
* @param proxyName The new proxy server name
*/
public void setProxyName(String proxyName) {
if (proxyName != null && !proxyName.isEmpty()) {
this.proxyName = proxyName;
} else {
this.proxyName = null;
}
}
/**
* @return the proxy server port for this Connector.
*/
public int getProxyPort() {
return this.proxyPort;
}
/**
* Set the proxy server port for this Connector.
*
* @param proxyPort The new proxy server port
*/
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
}
/**
* @return the port number to which a request should be redirected if it comes in on a non-SSL port and is subject
* to a security constraint with a transport guarantee that requires SSL.
*/
public int getRedirectPort() {
return this.redirectPort;
}
/**
* Set the redirect port number.
*
* @param redirectPort The redirect port number (non-SSL to SSL)
*/
public void setRedirectPort(int redirectPort) {
this.redirectPort = redirectPort;
}
public int getRedirectPortWithOffset() {
return getRedirectPort() + getPortOffset();
}
/**
* @return the scheme that will be assigned to requests received through this connector. Default value is "http".
*/
public String getScheme() {
return this.scheme;
}
/**
* Set the scheme that will be assigned to requests received through this connector.
*
* @param scheme The new scheme
*/
public void setScheme(String scheme) {
this.scheme = scheme;
}
/**
* @return the secure connection flag that will be assigned to requests received through this connector. Default
* value is "false".
*/
public boolean getSecure() {
return this.secure;
}
/**
* Set the secure connection flag that will be assigned to requests received through this connector.
*
* @param secure The new secure connection flag
*/
public void setSecure(boolean secure) {
this.secure = secure;
setProperty("secure", Boolean.toString(secure));
}
/**
* @return the name of character encoding to be used for the URI using the original case.
*/
public String getURIEncoding() {
return uriCharset.name();
}
/**
* @return The Charset to use to convert raw URI bytes (after %nn decoding) to characters. This will never be null
*/
public Charset getURICharset() {
return uriCharset;
}
/**
* Set the URI encoding to be used for the URI.
*
* @param URIEncoding The new URI character encoding.
*/
public void setURIEncoding(String URIEncoding) {
try {
Charset charset = B2CConverter.getCharset(URIEncoding);
if (!CharsetUtil.isAsciiSuperset(charset)) {
log.error(sm.getString("coyoteConnector.notAsciiSuperset", URIEncoding, uriCharset.name()));
return;
}
uriCharset = charset;
} catch (UnsupportedEncodingException e) {
log.error(sm.getString("coyoteConnector.invalidEncoding", URIEncoding, uriCharset.name()), e);
}
}
/**
* @return the true if the entity body encoding should be used for the URI.
*/
public boolean getUseBodyEncodingForURI() {
return this.useBodyEncodingForURI;
}
/**
* Set if the entity body encoding should be used for the URI.
*
* @param useBodyEncodingForURI The new value for the flag.
*/
public void setUseBodyEncodingForURI(boolean useBodyEncodingForURI) {
this.useBodyEncodingForURI = useBodyEncodingForURI;
}
/**
* Indicates whether the generation of an X-Powered-By response header for Servlet-generated responses is enabled or
* disabled for this Connector.
*
* @return <code>true</code> if generation of X-Powered-By response header is enabled, false otherwise
*/
public boolean getXpoweredBy() {
return xpoweredBy;
}
/**
* Enables or disables the generation of an X-Powered-By header (with value Servlet/2.5) for all servlet-generated
* responses returned by this Connector.
*
* @param xpoweredBy true if generation of X-Powered-By response header is to be enabled, false otherwise
*/
public void setXpoweredBy(boolean xpoweredBy) {
this.xpoweredBy = xpoweredBy;
}
/**
* Enable the use of IP-based virtual hosting.
*
* @param useIPVHosts <code>true</code> if Hosts are identified by IP, <code>false</code> if Hosts are identified by
* name.
*/
public void setUseIPVHosts(boolean useIPVHosts) {
this.useIPVHosts = useIPVHosts;
}
/**
* Test if IP-based virtual hosting is enabled.
*
* @return <code>true</code> if IP vhosts are enabled
*/
public boolean getUseIPVHosts() {
return useIPVHosts;
}
public String getExecutorName() {
Object obj = protocolHandler.getExecutor();
if (obj instanceof org.apache.catalina.Executor) {
return ((org.apache.catalina.Executor) obj).getName();
}
return INTERNAL_EXECUTOR_NAME;
}
public void addSslHostConfig(SSLHostConfig sslHostConfig) {
protocolHandler.addSslHostConfig(sslHostConfig);
}
public SSLHostConfig[] findSslHostConfigs() {
return protocolHandler.findSslHostConfigs();
}
public void addUpgradeProtocol(UpgradeProtocol upgradeProtocol) {
protocolHandler.addUpgradeProtocol(upgradeProtocol);
}
public UpgradeProtocol[] findUpgradeProtocols() {
return protocolHandler.findUpgradeProtocols();
}
public String getEncodedReverseSolidusHandling() {
return encodedReverseSolidusHandling.getValue();
}
public void setEncodedReverseSolidusHandling(String encodedReverseSolidusHandling) {
this.encodedReverseSolidusHandling = EncodedSolidusHandling.fromString(encodedReverseSolidusHandling);
}
public EncodedSolidusHandling getEncodedReverseSolidusHandlingInternal() {
return encodedReverseSolidusHandling;
}
public String getEncodedSolidusHandling() {
return encodedSolidusHandling.getValue();
}
public void setEncodedSolidusHandling(String encodedSolidusHandling) {
this.encodedSolidusHandling = EncodedSolidusHandling.fromString(encodedSolidusHandling);
}
public EncodedSolidusHandling getEncodedSolidusHandlingInternal() {
return encodedSolidusHandling;
}
public boolean getRejectSuspiciousURIs() {
return rejectSuspiciousURIs;
}
public void setRejectSuspiciousURIs(boolean rejectSuspiciousURIs) {
this.rejectSuspiciousURIs = rejectSuspiciousURIs;
}
// --------------------------------------------------------- Public Methods
/**
* Create (or allocate) and return a Request object suitable for specifying the contents of a Request to the
* responsible Container.
*
* @param coyoteRequest The Coyote request with which the Request object will always be associated. In normal usage
* this must be non-null. In some test scenarios, it may be possible to use a null request
* without triggering an NPE.
*
* @return a new Servlet request object
*/
public Request createRequest(org.apache.coyote.Request coyoteRequest) {
return new Request(this, coyoteRequest);
}
/**
* Create and return a Response object suitable for receiving the contents of a Response from the responsible
* Container.
*
* @param coyoteResponse The Coyote request with which the Response object will always be associated. In normal
* usage this must be non-null. In some test scenarios, it may be possible to use a null
* response without triggering an NPE.
*
* @return a new Servlet response object
*/
public Response createResponse(org.apache.coyote.Response coyoteResponse) {
int size = protocolHandler.getDesiredBufferSize();
if (size > 0) {
return new Response(coyoteResponse, size);
} else {
return new Response(coyoteResponse);
}
}
protected String createObjectNameKeyProperties(String type) {
Object addressObj = getProperty("address");
StringBuilder sb = new StringBuilder("type=");
sb.append(type);
String id = (protocolHandler != null) ? protocolHandler.getId() : null;
if (id != null) {
// Maintain MBean name compatibility, even if not accurate
sb.append(",port=0,address=");
sb.append(ObjectName.quote(id));
} else {
sb.append(",port=");
int port = getPortWithOffset();
if (port > 0) {
sb.append(port);
} else {
sb.append("auto-");
sb.append(getProperty("nameIndex"));
}
String address = "";
if (addressObj instanceof InetAddress) {
address = ((InetAddress) addressObj).getHostAddress();
} else if (addressObj != null) {
address = addressObj.toString();
}
if (!address.isEmpty()) {
sb.append(",address=");
sb.append(ObjectName.quote(address));
}
}
return sb.toString();
}
/**
* Pause the connector.
*/
public void pause() {
try {
if (protocolHandler != null) {
protocolHandler.pause();
}
} catch (Exception e) {
log.error(sm.getString("coyoteConnector.protocolHandlerPauseFailed"), e);
}
}
/**
* Resume the connector.
*/
public void resume() {
try {
if (protocolHandler != null) {
protocolHandler.resume();
}
} catch (Exception e) {
log.error(sm.getString("coyoteConnector.protocolHandlerResumeFailed"), e);
}
}
@Override
protected void initInternal() throws LifecycleException {
super.initInternal();
if (protocolHandler == null) {
throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerInstantiationFailed"));
}
// Initialize adapter
adapter = new CoyoteAdapter(this);
protocolHandler.setAdapter(adapter);
// Make sure parseBodyMethodsSet has a default
if (null == parseBodyMethodsSet) {
setParseBodyMethods(getParseBodyMethods());
}
if (JreCompat.isJre22Available() && OpenSSLStatus.getUseOpenSSL() && OpenSSLStatus.isAvailable() &&
protocolHandler instanceof AbstractHttp11Protocol<?> jsseProtocolHandler) {
// Use FFM and OpenSSL if available
if (jsseProtocolHandler.isSSLEnabled() && jsseProtocolHandler.getSslImplementationName() == null) {
// OpenSSL is compatible with the JSSE configuration, so use it if it is available
jsseProtocolHandler
.setSslImplementationName("org.apache.tomcat.util.net.openssl.panama.OpenSSLImplementation");
}
} else if (AprStatus.isAprAvailable() && AprStatus.getUseOpenSSL() &&
protocolHandler instanceof AbstractHttp11Protocol<?> jsseProtocolHandler) {
// Use tomcat-native and OpenSSL otherwise, if available
if (jsseProtocolHandler.isSSLEnabled() && jsseProtocolHandler.getSslImplementationName() == null) {
// OpenSSL is compatible with the JSSE configuration, so use it if APR is available
jsseProtocolHandler.setSslImplementationName(OpenSSLImplementation.class.getName());
}
}
// Otherwise the default JSSE will be used
try {
protocolHandler.init();
} catch (Exception e) {
throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerInitializationFailed"), e);
}
}
/**
* Begin processing requests via this Connector.
*
* @exception LifecycleException if a fatal startup error occurs
*/
@Override
protected void startInternal() throws LifecycleException {
// Validate settings before starting
String id = (protocolHandler != null) ? protocolHandler.getId() : null;
if (id == null && getPortWithOffset() < 0) {
throw new LifecycleException(
sm.getString("coyoteConnector.invalidPort", Integer.valueOf(getPortWithOffset())));
}
setState(LifecycleState.STARTING);
// Configure the utility executor before starting the protocol handler
if (protocolHandler != null && service != null) {
protocolHandler.setUtilityExecutor(service.getServer().getUtilityExecutor());
}
try {
protocolHandler.start();
} catch (Exception e) {
// Includes NPE - protocolHandler will be null for invalid protocol if throwOnFailure is false
throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerStartFailed"), e);
}
}
/**
* Terminate processing requests via this Connector.
*
* @exception LifecycleException if a fatal shutdown error occurs
*/
@Override
protected void stopInternal() throws LifecycleException {
setState(LifecycleState.STOPPING);
try {
if (protocolHandler != null) {
protocolHandler.stop();
}
} catch (Exception e) {
throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerStopFailed"), e);
}
// Remove the utility executor once the protocol handler has been stopped
if (protocolHandler != null) {
protocolHandler.setUtilityExecutor(null);
}
}
@Override
protected void destroyInternal() throws LifecycleException {
try {
if (protocolHandler != null) {
protocolHandler.destroy();
}
} catch (Exception e) {
throw new LifecycleException(sm.getString("coyoteConnector.protocolHandlerDestroyFailed"), e);
}
if (getService() != null) {
getService().removeConnector(this);
}
super.destroyInternal();
}
@Override
public String toString() {
// Not worth caching this right now
StringBuilder sb = new StringBuilder("Connector[");
String name = (String) getProperty("name");
if (name == null) {
sb.append(getProtocol());
sb.append('-');
String id = (protocolHandler != null) ? protocolHandler.getId() : null;
if (id != null) {
sb.append(id);
} else {
int port = getPortWithOffset();
if (port > 0) {
sb.append(port);
} else {
sb.append("auto-");
sb.append(getProperty("nameIndex"));
}
}
} else {
sb.append(name);
}
sb.append(']');
return sb.toString();
}
// -------------------- JMX registration --------------------
@Override
protected String getDomainInternal() {
Service s = getService();
if (s == null) {
return null;
} else {
return service.getDomain();
}
}
@Override
protected String getObjectNameKeyProperties() {
return createObjectNameKeyProperties("Connector");
}
}
|
openjdk/nashorn | 35,924 | src/org.openjdk.nashorn/share/classes/org/openjdk/nashorn/internal/objects/NativeJava.java | /*
* Copyright (c) 2010, 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 org.openjdk.nashorn.internal.objects;
import static org.openjdk.nashorn.internal.runtime.ECMAErrors.typeError;
import static org.openjdk.nashorn.internal.runtime.ScriptRuntime.UNDEFINED;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import jdk.dynalink.SecureLookupSupplier;
import jdk.dynalink.beans.BeansLinker;
import jdk.dynalink.beans.StaticClass;
import jdk.dynalink.linker.support.TypeUtilities;
import org.openjdk.nashorn.api.scripting.JSObject;
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
import org.openjdk.nashorn.api.scripting.ScriptUtils;
import org.openjdk.nashorn.internal.objects.annotations.Attribute;
import org.openjdk.nashorn.internal.objects.annotations.Function;
import org.openjdk.nashorn.internal.objects.annotations.ScriptClass;
import org.openjdk.nashorn.internal.objects.annotations.Where;
import org.openjdk.nashorn.internal.runtime.Context;
import org.openjdk.nashorn.internal.runtime.JSType;
import org.openjdk.nashorn.internal.runtime.ListAdapter;
import org.openjdk.nashorn.internal.runtime.PropertyMap;
import org.openjdk.nashorn.internal.runtime.ScriptFunction;
import org.openjdk.nashorn.internal.runtime.ScriptObject;
import org.openjdk.nashorn.internal.runtime.ScriptRuntime;
import org.openjdk.nashorn.internal.runtime.linker.Bootstrap;
import org.openjdk.nashorn.internal.runtime.linker.JavaAdapterFactory;
/**
* This class is the implementation for the {@code Java} global object exposed to programs running under Nashorn. This
* object acts as the API entry point to Java platform specific functionality, dealing with creating new instances of
* Java classes, subclassing Java classes, implementing Java interfaces, converting between Java arrays and ECMAScript
* arrays, and so forth.
*/
@ScriptClass("Java")
public final class NativeJava {
// initialized by nasgen
@SuppressWarnings("unused")
private static PropertyMap $nasgenmap$;
private NativeJava() {
// don't create me
throw new UnsupportedOperationException();
}
/**
* Returns true if the specified object is a Java type object, that is an instance of {@link StaticClass}.
* @param self not used
* @param type the object that is checked if it is a type object or not
* @return tells whether given object is a Java type object or not.
* @see #type(Object, Object)
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static boolean isType(final Object self, final Object type) {
return type instanceof StaticClass;
}
/**
* Returns synchronized wrapper version of the given ECMAScript function.
* @param self not used
* @param func the ECMAScript function whose synchronized version is returned.
* @param obj the object (i.e, lock) on which the function synchronizes.
* @return synchronized wrapper version of the given ECMAScript function.
*/
@Function(name="synchronized", attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object synchronizedFunc(final Object self, final Object func, final Object obj) {
if (func instanceof ScriptFunction) {
return ((ScriptFunction)func).createSynchronized(obj);
}
throw typeError("not.a.function", ScriptRuntime.safeToString(func));
}
/**
* Returns true if the specified object is a Java method.
* @param self not used
* @param obj the object that is checked if it is a Java method object or not
* @return tells whether given object is a Java method object or not.
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static boolean isJavaMethod(final Object self, final Object obj) {
return Bootstrap.isDynamicMethod(obj);
}
/**
* Returns true if the specified object is a java function (but not script function)
* @param self not used
* @param obj the object that is checked if it is a Java function or not
* @return tells whether given object is a Java function or not
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static boolean isJavaFunction(final Object self, final Object obj) {
return Bootstrap.isCallable(obj) && !(obj instanceof ScriptFunction);
}
/**
* Returns true if the specified object is a Java object but not a script object
* @param self not used
* @param obj the object that is checked
* @return tells whether given object is a Java object but not a script object
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static boolean isJavaObject(final Object self, final Object obj) {
return obj != null && !(obj instanceof ScriptObject);
}
/**
* Returns true if the specified object is a ECMAScript object, that is an instance of {@link ScriptObject}.
* @param self not used
* @param obj the object that is checked if it is a ECMAScript object or not
* @return tells whether given object is a ECMAScript object or not.
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static boolean isScriptObject(final Object self, final Object obj) {
return obj instanceof ScriptObject;
}
/**
* Returns true if the specified object is a ECMAScript function, that is an instance of {@link ScriptFunction}.
* @param self not used
* @param obj the object that is checked if it is a ECMAScript function or not
* @return tells whether given object is a ECMAScript function or not.
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static boolean isScriptFunction(final Object self, final Object obj) {
return obj instanceof ScriptFunction;
}
/**
* <p>
* Given a name of a Java type, returns an object representing that type in Nashorn. The Java class of the objects
* used to represent Java types in Nashorn is not {@link java.lang.Class} but rather {@link StaticClass}. They are
* the objects that you can use with the {@code new} operator to create new instances of the class as well as to
* access static members of the class. In Nashorn, {@code Class} objects are just regular Java objects that aren't
* treated specially. Instead of them, {@link StaticClass} instances - which we sometimes refer to as "Java type
* objects" are used as constructors with the {@code new} operator, and they expose static fields, properties, and
* methods. While this might seem confusing at first, it actually closely matches the Java language: you use a
* different expression (e.g. {@code java.io.File}) as an argument in "new" and to address statics, and it is
* distinct from the {@code Class} object (e.g. {@code java.io.File.class}). Below we cover in details the
* properties of the type objects.
* </p>
* <p><b>Constructing Java objects</b></p>
* Examples:
* <pre>
* var arrayListType = Java.type("java.util.ArrayList")
* var intType = Java.type("int")
* var stringArrayType = Java.type("java.lang.String[]")
* var int2DArrayType = Java.type("int[][]")
* </pre>
* Note that the name of the type is always a string for a fully qualified name. You can use any of these types to
* create new instances, e.g.:
* <pre>
* var anArrayList = new Java.type("java.util.ArrayList")
* </pre>
* or
* <pre>
* var ArrayList = Java.type("java.util.ArrayList")
* var anArrayList = new ArrayList
* var anArrayListWithSize = new ArrayList(16)
* </pre>
* In the special case of inner classes, you can either use the JVM fully qualified name, meaning using {@code $}
* sign in the class name, or you can use the dot:
* <pre>
* var ftype = Java.type("java.awt.geom.Arc2D$Float")
* </pre>
* and
* <pre>
* var ftype = Java.type("java.awt.geom.Arc2D.Float")
* </pre>
* both work. Note however that using the dollar sign is faster, as Java.type first tries to resolve the class name
* as it is originally specified, and the internal JVM names for inner classes use the dollar sign. If you use the
* dot, Java.type will internally get a ClassNotFoundException and subsequently retry by changing the last dot to
* dollar sign. As a matter of fact, it'll keep replacing dots with dollar signs until it either successfully loads
* the class or runs out of all dots in the name. This way it can correctly resolve and load even multiply nested
* inner classes with the dot notation. Again, this will be slower than using the dollar signs in the name. An
* alternative way to access the inner class is as a property of the outer class:
* <pre>
* var arctype = Java.type("java.awt.geom.Arc2D")
* var ftype = arctype.Float
* </pre>
* <p>
* You can access both static and non-static inner classes. If you want to create an instance of a non-static
* inner class, remember to pass an instance of its outer class as the first argument to the constructor.
* </p>
* <p>
* If the type is abstract, you can instantiate an anonymous subclass of it using an argument list that is
* applicable to any of its public or protected constructors, but inserting a JavaScript object with functions
* properties that provide JavaScript implementations of the abstract methods. If method names are overloaded, the
* JavaScript function will provide implementation for all overloads. E.g.:
* </p>
* <pre>
* var TimerTask = Java.type("java.util.TimerTask")
* var task = new TimerTask({ run: function() { print("Hello World!") } })
* </pre>
* <p>
* Nashorn supports a syntactic extension where a "new" expression followed by an argument is identical to
* invoking the constructor and passing the argument to it, so you can write the above example also as:
* </p>
* <pre>
* var task = new TimerTask {
* run: function() {
* print("Hello World!")
* }
* }
* </pre>
* <p>
* which is very similar to Java anonymous inner class definition. On the other hand, if the type is an abstract
* type with a single abstract method (commonly referred to as a "SAM type") or all abstract methods it has share
* the same overloaded name), then instead of an object, you can just pass a function, so the above example can
* become even more simplified to:
* </p>
* <pre>
* var task = new TimerTask(function() { print("Hello World!") })
* </pre>
* <p>
* Note that in every one of these cases if you are trying to instantiate an abstract class that has constructors
* that take some arguments, you can invoke those simply by specifying the arguments after the initial
* implementation object or function.
* </p>
* <p>The use of functions can be taken even further; if you are invoking a Java method that takes a SAM type,
* you can just pass in a function object, and Nashorn will know what you meant:
* </p>
* <pre>
* var timer = new Java.type("java.util.Timer")
* timer.schedule(function() { print("Hello World!") })
* </pre>
* <p>
* Here, {@code Timer.schedule()} expects a {@code TimerTask} as its argument, so Nashorn creates an instance of a
* {@code TimerTask} subclass and uses the passed function to implement its only abstract method, {@code run()}. In
* this usage though, you can't use non-default constructors; the type must be either an interface, or must have a
* protected or public no-arg constructor.
* </p>
* <p>
* You can also subclass non-abstract classes; for that you will need to use the {@link #extend(Object, Object...)}
* method.
* </p>
* <p><b>Accessing static members</b></p>
* Examples:
* <pre>
* var File = Java.type("java.io.File")
* var pathSep = File.pathSeparator
* var tmpFile1 = File.createTempFile("abcdefg", ".tmp")
* var tmpFile2 = File.createTempFile("abcdefg", ".tmp", new File("/tmp"))
* </pre>
* Actually, you can even assign static methods to variables, so the above example can be rewritten as:
* <pre>
* var File = Java.type("java.io.File")
* var createTempFile = File.createTempFile
* var tmpFile1 = createTempFile("abcdefg", ".tmp")
* var tmpFile2 = createTempFile("abcdefg", ".tmp", new File("/tmp"))
* </pre>
* If you need to access the actual {@code java.lang.Class} object for the type, you can use the {@code class}
* property on the object representing the type:
* <pre>
* var File = Java.type("java.io.File")
* var someFile = new File("blah")
* print(File.class === someFile.getClass()) // prints true
* </pre>
* Of course, you can also use the {@code getClass()} method or its equivalent {@code class} property on any
* instance of the class. Other way round, you can use the synthetic {@code static} property on any
* {@code java.lang.Class} object to retrieve its type-representing object:
* <pre>
* var File = Java.type("java.io.File")
* print(File.class.static === File) // prints true
* </pre>
* <p><b>{@code instanceof} operator</b></p>
* The standard ECMAScript {@code instanceof} operator is extended to recognize Java objects and their type objects:
* <pre>
* var File = Java.type("java.io.File")
* var aFile = new File("foo")
* print(aFile instanceof File) // prints true
* print(aFile instanceof File.class) // prints false - Class objects aren't type objects.
* </pre>
* @param self not used
* @param objTypeName the object whose JS string value represents the type name. You can use names of primitive Java
* types to obtain representations of them, and you can use trailing square brackets to represent Java array types.
* @return the object representing the named type
* @throws ClassNotFoundException if the class is not found
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object type(final Object self, final Object objTypeName) throws ClassNotFoundException {
return type(objTypeName);
}
private static StaticClass type(final Object objTypeName) throws ClassNotFoundException {
return StaticClass.forClass(type(JSType.toString(objTypeName)));
}
private static Class<?> type(final String typeName) throws ClassNotFoundException {
if (typeName.endsWith("[]")) {
return arrayType(typeName);
}
return simpleType(typeName);
}
/**
* Returns name of a java type {@link StaticClass}.
* @param self not used
* @param type the type whose name is returned
* @return name of the given type
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object typeName(final Object self, final Object type) {
if (type instanceof StaticClass) {
return ((StaticClass)type).getRepresentedClass().getName();
} else if (type instanceof Class) {
return ((Class<?>)type).getName();
} else {
return UNDEFINED;
}
}
/**
* Given a script object and a Java type, converts the script object into the desired Java type. Currently it
* performs shallow creation of Java arrays, as well as wrapping of objects in Lists, Dequeues, Queues,
* and Collections. If conversion is not possible or fails for some reason, TypeError is thrown.
* Example:
* <pre>
* var anArray = [1, "13", false]
* var javaIntArray = Java.to(anArray, "int[]")
* print(javaIntArray[0]) // prints 1
* print(javaIntArray[1]) // prints 13, as string "13" was converted to number 13 as per ECMAScript ToNumber conversion
* print(javaIntArray[2]) // prints 0, as boolean false was converted to number 0 as per ECMAScript ToNumber conversion
* </pre>
* @param self not used
* @param obj the script object. Can be null.
* @param objType either a {@link #type(Object, Object) type object} or a String describing the type of the Java
* object to create. Can not be null. If undefined, a "default" conversion is presumed (allowing the argument to be
* omitted).
* @return a Java object whose value corresponds to the original script object's value. Specifically, for array
* target types, returns a Java array of the same type with contents converted to the array's component type.
* Converts recursively when the target type is multidimensional array. For {@link List}, {@link Deque},
* {@link Queue}, or {@link Collection}, returns a live wrapper around the object, see {@link ListAdapter} for
* details. Returns null if obj is null.
* @throws ClassNotFoundException if the class described by objType is not found
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object to(final Object self, final Object obj, final Object objType) throws ClassNotFoundException {
if (obj == null) {
return null;
}
if (!(obj instanceof ScriptObject) && !(obj instanceof JSObject)) {
throw typeError("not.an.object", ScriptRuntime.safeToString(obj));
}
final Class<?> targetClass;
if(objType == UNDEFINED) {
targetClass = Object[].class;
} else {
final StaticClass targetType;
if(objType instanceof StaticClass) {
targetType = (StaticClass)objType;
} else {
targetType = type(objType);
}
targetClass = targetType.getRepresentedClass();
}
if(targetClass.isArray()) {
try {
if (self instanceof SecureLookupSupplier) {
return JSType.toJavaArrayWithLookup(obj, targetClass.getComponentType(), (SecureLookupSupplier)self);
}
return JSType.toJavaArray(obj, targetClass.getComponentType());
} catch (final Exception exp) {
throw typeError(exp, "java.array.conversion.failed", targetClass.getName());
}
}
if (targetClass == List.class || targetClass == Deque.class || targetClass == Queue.class || targetClass == Collection.class) {
return ListAdapter.create(obj);
}
throw typeError("unsupported.java.to.type", targetClass.getName());
}
/**
* Given a Java array or {@link Collection}, returns a JavaScript array with a shallow copy of its contents. Note
* that in most cases, you can use Java arrays and lists natively in Nashorn; in cases where for some reason you
* need to have an actual JavaScript native array (e.g. to work with the array comprehensions functions), you will
* want to use this method. Example:
* <pre>
* var File = Java.type("java.io.File")
* var listHomeDir = new File("~").listFiles()
* var jsListHome = Java.from(listHomeDir)
* var jpegModifiedDates = jsListHome
* .filter(function(val) { return val.getName().endsWith(".jpg") })
* .map(function(val) { return val.lastModified() })
* </pre>
* @param self not used
* @param objArray the java array or collection. Can be null.
* @return a JavaScript array with the copy of Java array's or collection's contents. Returns null if objArray is
* null.
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static NativeArray from(final Object self, final Object objArray) {
if (objArray == null) {
return null;
} else if (objArray instanceof Collection) {
return new NativeArray(ScriptUtils.unwrapArray(((Collection<?>)objArray).toArray()));
} else if (objArray instanceof Object[]) {
return new NativeArray(ScriptUtils.unwrapArray(((Object[])objArray).clone()));
} else if (objArray instanceof int[]) {
return new NativeArray(((int[])objArray).clone());
} else if (objArray instanceof double[]) {
return new NativeArray(((double[])objArray).clone());
} else if (objArray instanceof long[]) {
return new NativeArray(((long[])objArray).clone());
} else if (objArray instanceof byte[]) {
return new NativeArray(copyArray((byte[])objArray));
} else if (objArray instanceof short[]) {
return new NativeArray(copyArray((short[])objArray));
} else if (objArray instanceof char[]) {
return new NativeArray(copyArray((char[])objArray));
} else if (objArray instanceof float[]) {
return new NativeArray(copyArray((float[])objArray));
} else if (objArray instanceof boolean[]) {
return new NativeArray(copyArray((boolean[])objArray));
}
throw typeError("cant.convert.to.javascript.array", objArray.getClass().getName());
}
/**
* Return properties of the given object. Properties also include "method names".
* This is meant for source code completion in interactive shells or editors.
*
* @param object the object whose properties are returned.
* @return list of properties
*/
public static List<String> getProperties(final Object object) {
if (object instanceof StaticClass) {
// static properties of the given class
final Class<?> clazz = ((StaticClass)object).getRepresentedClass();
final ArrayList<String> props = new ArrayList<>();
try {
Bootstrap.checkReflectionAccess(clazz, true);
// Usually writable properties are a subset as 'write-only' properties are rare
props.addAll(BeansLinker.getReadableStaticPropertyNames(clazz));
props.addAll(BeansLinker.getStaticMethodNames(clazz));
} catch (final Exception ignored) {}
return props;
} else if (object instanceof JSObject) {
final JSObject jsObj = ((JSObject)object);
return new ArrayList<>(jsObj.keySet());
} else if (object != null && object != UNDEFINED) {
// instance properties of the given object
final Class<?> clazz = object.getClass();
final ArrayList<String> props = new ArrayList<>();
try {
Bootstrap.checkReflectionAccess(clazz, false);
// Usually writable properties are a subset as 'write-only' properties are rare
props.addAll(BeansLinker.getReadableInstancePropertyNames(clazz));
props.addAll(BeansLinker.getInstanceMethodNames(clazz));
} catch (final Exception ignored) {}
return props;
}
// don't know about that object
return Collections.emptyList();
}
private static int[] copyArray(final byte[] in) {
final int[] out = new int[in.length];
for(int i = 0; i < in.length; ++i) {
out[i] = in[i];
}
return out;
}
private static int[] copyArray(final short[] in) {
final int[] out = new int[in.length];
for(int i = 0; i < in.length; ++i) {
out[i] = in[i];
}
return out;
}
private static int[] copyArray(final char[] in) {
final int[] out = new int[in.length];
for(int i = 0; i < in.length; ++i) {
out[i] = in[i];
}
return out;
}
private static double[] copyArray(final float[] in) {
final double[] out = new double[in.length];
for(int i = 0; i < in.length; ++i) {
out[i] = in[i];
}
return out;
}
private static Object[] copyArray(final boolean[] in) {
final Object[] out = new Object[in.length];
for(int i = 0; i < in.length; ++i) {
out[i] = in[i];
}
return out;
}
private static Class<?> simpleType(final String typeName) throws ClassNotFoundException {
final Class<?> primClass = TypeUtilities.getPrimitiveTypeByName(typeName);
if(primClass != null) {
return primClass;
}
final Context ctx = Global.getThisContext();
try {
return ctx.findClass(typeName);
} catch(final ClassNotFoundException e) {
// The logic below compensates for a frequent user error - when people use dot notation to separate inner
// class names, i.e. "java.lang.Character.UnicodeBlock" vs."java.lang.Character$UnicodeBlock". The logic
// below will try alternative class names, replacing dots at the end of the name with dollar signs.
final StringBuilder nextName = new StringBuilder(typeName);
int lastDot = nextName.length();
for(;;) {
lastDot = nextName.lastIndexOf(".", lastDot - 1);
if(lastDot == -1) {
// Exhausted the search space, class not found - rethrow the original exception.
throw e;
}
nextName.setCharAt(lastDot, '$');
try {
return ctx.findClass(nextName.toString());
} catch(final ClassNotFoundException cnfe) {
// Intentionally ignored, so the loop retries with the next name
}
}
}
}
private static Class<?> arrayType(final String typeName) throws ClassNotFoundException {
return Array.newInstance(type(typeName.substring(0, typeName.length() - 2)), 0).getClass();
}
/**
* Returns a type object for a subclass of the specified Java class (or implementation of the specified interface)
* that acts as a script-to-Java adapter for it. See {@link #type(Object, Object)} for a discussion of type objects,
* and see {@link JavaAdapterFactory} for details on script-to-Java adapters. Note that you can also implement
* interfaces and subclass abstract classes using {@code new} operator on a type object for an interface or abstract
* class. However, to extend a non-abstract class, you will have to use this method. Example:
* <pre>
* var ArrayList = Java.type("java.util.ArrayList")
* var ArrayListExtender = Java.extend(ArrayList)
* var printSizeInvokedArrayList = new ArrayListExtender() {
* size: function() { print("size invoked!"); }
* }
* var printAddInvokedArrayList = new ArrayListExtender() {
* add: function(x, y) {
* if(typeof(y) === "undefined") {
* print("add(e) invoked!");
* } else {
* print("add(i, e) invoked!");
* }
* }
* </pre>
* We can see several important concepts in the above example:
* <ul>
* <li>Every specified list of Java types will have one extender subclass in Nashorn -
* repeated invocations of {@code extend} for the same list of types will yield
* the same extender type. It's a generic adapter that delegates to whatever JavaScript functions its implementation
* object has on a per-instance basis.</li>
* <li>If the Java method is overloaded (as in the above example {@code List.add()}), then your JavaScript adapter
* must be prepared to deal with all overloads.</li>
* <li>To invoke super methods from adapters, call them on the adapter instance prefixing them with {@code super$},
* or use the special {@link #_super(Object, Object) super-adapter}.</li>
* <li>It is also possible to specify an ordinary JavaScript object as the last argument to {@code extend}. In that
* case, it is treated as a class-level override. {@code extend} will return an extender class where all instances
* will have the methods implemented by functions on that object, just as if that object were passed as the last
* argument to their constructor. Example:
* <pre>
* var Runnable = Java.type("java.lang.Runnable")
* var R1 = Java.extend(Runnable, {
* run: function() {
* print("R1.run() invoked!")
* }
* })
* var r1 = new R1
* var t = new java.lang.Thread(r1)
* t.start()
* t.join()
* </pre>
* As you can see, you don't have to pass any object when you create a new instance of {@code R1} as its
* {@code run()} function was defined already when extending the class. If you also want to add instance-level
* overrides on these objects, you will have to repeatedly use {@code extend()} to subclass the class-level adapter.
* For such adapters, the order of precedence is instance-level method, class-level method, superclass method, or
* {@code UnsupportedOperationException} if the superclass method is abstract. If we continue our previous example:
* <pre>
* var R2 = Java.extend(R1);
* var r2 = new R2(function() { print("r2.run() invoked!") })
* r2.run()
* </pre>
* We'll see it'll print {@code "r2.run() invoked!"}, thus overriding on instance-level the class-level behavior.
* Note that you must use {@code Java.extend} to explicitly create an instance-override adapter class from a
* class-override adapter class, as the class-override adapter class is no longer abstract.
* </li>
* </ul>
* @param self not used
* @param types the original types. The caller must pass at least one Java type object of class {@link StaticClass}
* representing either a public interface or a non-final public class with at least one public or protected
* constructor. If more than one type is specified, at most one can be a class and the rest have to be interfaces.
* Invoking the method twice with exactly the same types in the same order - in absence of class-level overrides -
* will return the same adapter class, any reordering of types or even addition or removal of redundant types (i.e.
* interfaces that other types in the list already implement/extend, or {@code java.lang.Object} in a list of types
* consisting purely of interfaces) will result in a different adapter class, even though those adapter classes are
* functionally identical; we deliberately don't want to incur the additional processing cost of canonicalizing type
* lists. As a special case, the last argument can be a {@code ScriptObject} instead of a type. In this case, a
* separate adapter class is generated - new one for each invocation - that will use the passed script object as its
* implementation for all instances. Instances of such adapter classes can then be created without passing another
* script object in the constructor, as the class has a class-level behavior defined by the script object. However,
* you can still pass a script object (or if it's a SAM type, a function) to the constructor to provide further
* instance-level overrides.
*
* @return a new {@link StaticClass} that represents the adapter for the original types.
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object extend(final Object self, final Object... types) {
if(types == null || types.length == 0) {
throw typeError("extend.expects.at.least.one.argument");
}
final int l = types.length;
final int typesLen;
final ScriptObject classOverrides;
if(types[l - 1] instanceof ScriptObject) {
classOverrides = (ScriptObject)types[l - 1];
typesLen = l - 1;
if(typesLen == 0) {
throw typeError("extend.expects.at.least.one.type.argument");
}
} else {
classOverrides = null;
typesLen = l;
}
final Class<?>[] stypes = new Class<?>[typesLen];
try {
for(int i = 0; i < typesLen; ++i) {
stypes[i] = ((StaticClass)types[i]).getRepresentedClass();
}
} catch(final ClassCastException e) {
throw typeError("extend.expects.java.types");
}
return JavaAdapterFactory.getAdapterClassFor(stypes, classOverrides);
}
/**
* When given an object created using {@code Java.extend()} or equivalent mechanism (that is, any JavaScript-to-Java
* adapter), returns an object that can be used to invoke superclass methods on that object. E.g.:
* <pre>
* var cw = new FilterWriterAdapter(sw) {
* write: function(s, off, len) {
* s = capitalize(s, off, len)
* cw_super.write(s, 0, s.length())
* }
* }
* var cw_super = Java.super(cw)
* </pre>
* @param self the {@code Java} object itself - not used.
* @param adapter the original Java adapter instance for which the super adapter is created.
* @return a super adapter for the original adapter
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR, name="super")
public static Object _super(final Object self, final Object adapter) {
return Bootstrap.createSuperAdapter(adapter);
}
/**
* Returns an object that is compatible with Java JSON libraries expectations; namely, that if it itself, or any
* object transitively reachable through it is a JavaScript array, then such objects will be exposed as
* {@link JSObject} that also implements the {@link List} interface for exposing the array elements. An explicit
* API is required as otherwise Nashorn exposes all objects externally as {@link JSObject}s that also implement the
* {@link Map} interface instead. By using this method, arrays will be exposed as {@link List}s and all other
* objects as {@link Map}s.
* @param self not used
* @param obj the object to be exposed in a Java JSON library compatible manner.
* @return a wrapper around the object that will enforce Java JSON library compatible exposure.
*/
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object asJSONCompatible(final Object self, final Object obj) {
return ScriptObjectMirror.wrapAsJSONCompatible(obj, Context.getGlobal());
}
}
|
apache/fineract | 35,830 | integration-tests/src/test/java/org/apache/fineract/integrationtests/common/organisation/EntityDatatableChecksIntegrationTest.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.integrationtests.common.organisation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import com.google.gson.Gson;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.fineract.client.models.PostClientsResponse;
import org.apache.fineract.client.models.PostEntityDatatableChecksTemplateResponse;
import org.apache.fineract.integrationtests.common.ClientHelper;
import org.apache.fineract.integrationtests.common.CollateralManagementHelper;
import org.apache.fineract.integrationtests.common.CommonConstants;
import org.apache.fineract.integrationtests.common.GroupHelper;
import org.apache.fineract.integrationtests.common.Utils;
import org.apache.fineract.integrationtests.common.loans.LoanApplicationTestBuilder;
import org.apache.fineract.integrationtests.common.loans.LoanProductTestBuilder;
import org.apache.fineract.integrationtests.common.loans.LoanTestLifecycleExtension;
import org.apache.fineract.integrationtests.common.loans.LoanTransactionHelper;
import org.apache.fineract.integrationtests.common.savings.SavingsAccountHelper;
import org.apache.fineract.integrationtests.common.savings.SavingsProductHelper;
import org.apache.fineract.integrationtests.common.system.DatatableHelper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Entity Datatable Checks Integration Test for checking Creation, Deletion and Retrieval of Entity-Datatable Check
*/
@ExtendWith(LoanTestLifecycleExtension.class)
public class EntityDatatableChecksIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(EntityDatatableChecksIntegrationTest.class);
private RequestSpecification requestSpec;
private ResponseSpecification responseSpec;
private EntityDatatableChecksHelper entityDatatableChecksHelper;
private DatatableHelper datatableHelper;
private SavingsAccountHelper savingsAccountHelper;
private LoanTransactionHelper loanTransactionHelper;
private LoanTransactionHelper validationErrorHelper;
private static final String CLIENT_APP_TABLE_NAME = "m_client";
private static final String GROUP_APP_TABLE_NAME = "m_group";
private static final String SAVINGS_APP_TABLE_NAME = "m_savings_account";
private static final String LOAN_APP_TABLE_NAME = "m_loan";
public static final String MINIMUM_OPENING_BALANCE = "1000.0";
public static final String ACCOUNT_TYPE_INDIVIDUAL = "INDIVIDUAL";
public static final String DATE_TIME_FORMAT = "dd MMMM yyyy HH:mm";
@BeforeEach
public void setup() {
Utils.initializeRESTAssured();
this.requestSpec = new RequestSpecBuilder().setContentType(ContentType.JSON).build();
this.requestSpec.header("Authorization", "Basic " + Utils.loginIntoServerAndGetBase64EncodedAuthenticationKey());
this.responseSpec = new ResponseSpecBuilder().expectStatusCode(200).build();
this.entityDatatableChecksHelper = new EntityDatatableChecksHelper(this.requestSpec, this.responseSpec);
this.datatableHelper = new DatatableHelper(this.requestSpec, this.responseSpec);
}
@Test
public void validateCreateDeleteDatatableCheck() {
// creating datatable
String datatableName = this.datatableHelper.createDatatable(CLIENT_APP_TABLE_NAME, false);
DatatableHelper.verifyDatatableCreatedOnServer(this.requestSpec, this.responseSpec, datatableName);
// creating new entity datatable check
Integer entityDatatableCheckId = this.entityDatatableChecksHelper.createEntityDatatableCheck(CLIENT_APP_TABLE_NAME, datatableName,
100, null);
assertNotNull(entityDatatableCheckId, "ERROR IN CREATING THE ENTITY DATATABLE CHECK");
// deleting entity datatable check
entityDatatableCheckId = this.entityDatatableChecksHelper.deleteEntityDatatableCheck(entityDatatableCheckId);
assertNotNull(entityDatatableCheckId, "ERROR IN DELETING THE ENTITY DATATABLE CHECK");
// deleting the datatable
String deletedDataTableName = this.datatableHelper.deleteDatatable(datatableName);
assertEquals(datatableName, deletedDataTableName, "ERROR IN DELETING THE DATATABLE");
}
@Test
public void validateCreateDeleteEntityDatatableCheck() {
// creating datatable
String datatableName = this.datatableHelper.createDatatable(CLIENT_APP_TABLE_NAME, false);
DatatableHelper.verifyDatatableCreatedOnServer(this.requestSpec, this.responseSpec, datatableName);
// creating new entity datatable check
Integer entityDatatableCheckId = this.entityDatatableChecksHelper.createEntityDatatableCheck(CLIENT_APP_TABLE_NAME, datatableName,
100, null);
assertNotNull(entityDatatableCheckId, "ERROR IN CREATING THE ENTITY DATATABLE CHECK");
// deleting entity datatable check
entityDatatableCheckId = this.entityDatatableChecksHelper.deleteEntityDatatableCheck(entityDatatableCheckId);
assertNotNull(entityDatatableCheckId, "ERROR IN DELETING THE ENTITY DATATABLE CHECK");
// deleting the datatable
String deletedDataTableName = this.datatableHelper.deleteDatatable(datatableName);
assertEquals(datatableName, deletedDataTableName, "ERROR IN DELETING THE DATATABLE");
}
@Test
public void validateRetriveEntityDatatableChecksList() {
// retrieving entity datatable check
String entityDatatableChecksList = this.entityDatatableChecksHelper.retrieveEntityDatatableCheck();
assertNotNull("ERROR IN RETRIEVING THE ENTITY DATATABLE CHECKS", entityDatatableChecksList);
}
@Test
public void validateCreateClientWithEntityDatatableCheck() {
// creating datatable
String registeredTableName = this.datatableHelper.createDatatable(CLIENT_APP_TABLE_NAME, false);
DatatableHelper.verifyDatatableCreatedOnServer(this.requestSpec, this.responseSpec, registeredTableName);
// creating new entity datatable check
Integer entityDatatableCheckId = this.entityDatatableChecksHelper.createEntityDatatableCheck(CLIENT_APP_TABLE_NAME,
registeredTableName, 100, null);
assertNotNull(entityDatatableCheckId, "ERROR IN CREATING THE ENTITY DATATABLE CHECK");
// creating client with datatables
final Integer clientID = ClientHelper.createClientPendingWithDatatable(requestSpec, responseSpec, registeredTableName);
ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID);
// deleting entity datatable check
entityDatatableCheckId = this.entityDatatableChecksHelper.deleteEntityDatatableCheck(entityDatatableCheckId);
assertNotNull(entityDatatableCheckId, "ERROR IN DELETING THE ENTITY DATATABLE CHECK");
// deleting datatable entries
Integer appTableId = (Integer) this.datatableHelper.deleteDatatableEntries(registeredTableName, clientID, "clientId");
assertEquals(clientID, appTableId, "ERROR IN DELETING THE DATATABLE ENTRIES");
// deleting the datatable
String deletedDataTableName = this.datatableHelper.deleteDatatable(registeredTableName);
assertEquals(registeredTableName, deletedDataTableName, "ERROR IN DELETING THE DATATABLE");
}
@SuppressWarnings("unchecked")
@Test
public void validateCreateClientWithEntityDatatableCheckWithFailure() {
// building error response with status code 403
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build();
final ClientHelper validationErrorHelper = new ClientHelper(this.requestSpec, errorResponse);
// creating datatable
String registeredTableName = this.datatableHelper.createDatatable(CLIENT_APP_TABLE_NAME, false);
DatatableHelper.verifyDatatableCreatedOnServer(this.requestSpec, this.responseSpec, registeredTableName);
// creating new entity datatable check
Integer entityDatatableCheckId = this.entityDatatableChecksHelper.createEntityDatatableCheck(CLIENT_APP_TABLE_NAME,
registeredTableName, 100, null);
assertNotNull(entityDatatableCheckId, "ERROR IN CREATING THE ENTITY DATATABLE CHECK");
// creating client with datatables with error
ArrayList<HashMap<Object, Object>> clientErrorData = (ArrayList<HashMap<Object, Object>>) validationErrorHelper
.createClientPendingWithError(CommonConstants.RESPONSE_ERROR);
assertEquals("error.msg.entry.required.in.datatable.[" + registeredTableName + "]",
clientErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
// deleting entity datatable check
entityDatatableCheckId = this.entityDatatableChecksHelper.deleteEntityDatatableCheck(entityDatatableCheckId);
assertNotNull(entityDatatableCheckId, "ERROR IN DELETING THE ENTITY DATATABLE CHECK");
// deleting the datatable
String deletedDataTableName = this.datatableHelper.deleteDatatable(registeredTableName);
assertEquals(registeredTableName, deletedDataTableName, "ERROR IN DELETING THE DATATABLE");
}
@Test
public void validateCreateGroupWithEntityDatatableCheck() {
// creating datatable
String registeredTableName = this.datatableHelper.createDatatable(GROUP_APP_TABLE_NAME, false);
DatatableHelper.verifyDatatableCreatedOnServer(this.requestSpec, this.responseSpec, registeredTableName);
// creating new entity datatable check
Integer entityDatatableCheckId = this.entityDatatableChecksHelper.createEntityDatatableCheck(GROUP_APP_TABLE_NAME,
registeredTableName, 100, null);
assertNotNull(entityDatatableCheckId, "ERROR IN CREATING THE ENTITY DATATABLE CHECK");
// creating group with datatables
final Integer groupId = GroupHelper.createGroupPendingWithDatatable(this.requestSpec, this.responseSpec, registeredTableName);
GroupHelper.verifyGroupCreatedOnServer(this.requestSpec, this.responseSpec, groupId);
// deleting entity datatable check
entityDatatableCheckId = this.entityDatatableChecksHelper.deleteEntityDatatableCheck(entityDatatableCheckId);
assertNotNull(entityDatatableCheckId, "ERROR IN DELETING THE ENTITY DATATABLE CHECK");
// deleting datatable entries
Integer appTableId = (Integer) this.datatableHelper.deleteDatatableEntries(registeredTableName, groupId, "groupId");
assertEquals(groupId, appTableId, "ERROR IN DELETING THE DATATABLE ENTRIES");
// deleting the datatable
String deletedDataTableName = this.datatableHelper.deleteDatatable(registeredTableName);
assertEquals(registeredTableName, deletedDataTableName, "ERROR IN DELETING THE DATATABLE");
}
@SuppressWarnings("unchecked")
@Test
public void validateCreateGroupWithEntityDatatableCheckWithFailure() {
// building error response with status code 403
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build();
final GroupHelper validationErrorHelper = new GroupHelper(this.requestSpec, errorResponse);
// creating datatable
String registeredTableName = this.datatableHelper.createDatatable(GROUP_APP_TABLE_NAME, false);
DatatableHelper.verifyDatatableCreatedOnServer(this.requestSpec, this.responseSpec, registeredTableName);
// creating new entity datatable check
Integer entityDatatableCheckId = this.entityDatatableChecksHelper.createEntityDatatableCheck(GROUP_APP_TABLE_NAME,
registeredTableName, 100, null);
assertNotNull(entityDatatableCheckId, "ERROR IN CREATING THE ENTITY DATATABLE CHECK");
// creating group with datatables with error
ArrayList<HashMap<Object, Object>> groupErrorData = (ArrayList<HashMap<Object, Object>>) validationErrorHelper
.createGroupWithError(CommonConstants.RESPONSE_ERROR);
assertEquals("error.msg.entry.required.in.datatable.[" + registeredTableName + "]",
groupErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
// deleting entity datatable check
entityDatatableCheckId = this.entityDatatableChecksHelper.deleteEntityDatatableCheck(entityDatatableCheckId);
assertNotNull(entityDatatableCheckId, "ERROR IN DELETING THE ENTITY DATATABLE CHECK");
// deleting the datatable
String deletedDataTableName = this.datatableHelper.deleteDatatable(registeredTableName);
assertEquals(registeredTableName, deletedDataTableName, "ERROR IN DELETING THE DATATABLE");
}
@Test
public void validateCreateSavingsWithEntityDatatableCheck() {
this.savingsAccountHelper = new SavingsAccountHelper(this.requestSpec, this.responseSpec);
final String minBalanceForInterestCalculation = null;
final String minRequiredBalance = null;
final String enforceMinRequiredBalance = "false";
final boolean allowOverdraft = false;
// creating datatable
String registeredTableName = this.datatableHelper.createDatatable(SAVINGS_APP_TABLE_NAME, false);
DatatableHelper.verifyDatatableCreatedOnServer(this.requestSpec, this.responseSpec, registeredTableName);
// creating new entity datatable check
Integer entityDatatableCheckId = this.entityDatatableChecksHelper.createEntityDatatableCheck(SAVINGS_APP_TABLE_NAME,
registeredTableName, 100, null);
assertNotNull(entityDatatableCheckId, "ERROR IN CREATING THE ENTITY DATATABLE CHECK");
final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec);
ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID);
final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, MINIMUM_OPENING_BALANCE,
minBalanceForInterestCalculation, minRequiredBalance, enforceMinRequiredBalance, allowOverdraft);
Assertions.assertNotNull(savingsProductID);
// creating savings with datatables
final Integer savingsId = this.savingsAccountHelper.applyForSavingsApplicationWithDatatables(clientID, savingsProductID,
ACCOUNT_TYPE_INDIVIDUAL, "01 December 2016", registeredTableName);
Assertions.assertNotNull(savingsId);
// deleting entity datatable check
entityDatatableCheckId = this.entityDatatableChecksHelper.deleteEntityDatatableCheck(entityDatatableCheckId);
assertNotNull(entityDatatableCheckId, "ERROR IN DELETING THE ENTITY DATATABLE CHECK");
// deleting datatable entries
Integer appTableId = (Integer) this.datatableHelper.deleteDatatableEntries(registeredTableName, savingsId, "savingsId");
assertEquals(savingsId, appTableId, "ERROR IN DELETING THE DATATABLE ENTRIES");
// deleting the datatable
String deletedDataTableName = this.datatableHelper.deleteDatatable(registeredTableName);
assertEquals(registeredTableName, deletedDataTableName, "ERROR IN DELETING THE DATATABLE");
}
@SuppressWarnings("unchecked")
@Test
public void validateCreateSavingsWithEntityDatatableCheckWithFailure() {
// building error response with status code 403
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build();
final SavingsAccountHelper validationErrorHelper = new SavingsAccountHelper(this.requestSpec, errorResponse);
final String minBalanceForInterestCalculation = null;
final String minRequiredBalance = null;
final String enforceMinRequiredBalance = "false";
final boolean allowOverdraft = false;
// creating datatable
String registeredTableName = this.datatableHelper.createDatatable(SAVINGS_APP_TABLE_NAME, false);
DatatableHelper.verifyDatatableCreatedOnServer(this.requestSpec, this.responseSpec, registeredTableName);
// creating new entity datatable check
Integer entityDatatableCheckId = this.entityDatatableChecksHelper.createEntityDatatableCheck(SAVINGS_APP_TABLE_NAME,
registeredTableName, 100, null);
assertNotNull(entityDatatableCheckId, "ERROR IN CREATING THE ENTITY DATATABLE CHECK");
final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec);
ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID);
final Integer savingsProductID = createSavingsProduct(this.requestSpec, this.responseSpec, MINIMUM_OPENING_BALANCE,
minBalanceForInterestCalculation, minRequiredBalance, enforceMinRequiredBalance, allowOverdraft);
Assertions.assertNotNull(savingsProductID);
// creating savings with datatables with error
ArrayList<HashMap<Object, Object>> groupErrorData = (ArrayList<HashMap<Object, Object>>) validationErrorHelper
.applyForSavingsApplicationWithFailure(clientID, savingsProductID, ACCOUNT_TYPE_INDIVIDUAL, "01 December 2016",
CommonConstants.RESPONSE_ERROR);
assertEquals("error.msg.entry.required.in.datatable.[" + registeredTableName + "]",
groupErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
// deleting entity datatable check
entityDatatableCheckId = this.entityDatatableChecksHelper.deleteEntityDatatableCheck(entityDatatableCheckId);
assertNotNull(entityDatatableCheckId, "ERROR IN DELETING THE ENTITY DATATABLE CHECK");
// deleting the datatable
String deletedDataTableName = this.datatableHelper.deleteDatatable(registeredTableName);
assertEquals(registeredTableName, deletedDataTableName, "ERROR IN DELETING THE DATATABLE");
}
@Test
public void validateCreateLoanWithEntityDatatableCheck() {
this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec);
// creating client
final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec);
ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID);
// creating loan product
final Integer loanProductID = createLoanProduct("100", "0", LoanProductTestBuilder.DEFAULT_STRATEGY);
Assertions.assertNotNull(loanProductID);
// creating datatable
String registeredTableName = this.datatableHelper.createDatatable(LOAN_APP_TABLE_NAME, false);
DatatableHelper.verifyDatatableCreatedOnServer(this.requestSpec, this.responseSpec, registeredTableName);
// creating new entity datatable check
Integer entityDatatableCheckId = this.entityDatatableChecksHelper.createEntityDatatableCheck(LOAN_APP_TABLE_NAME,
registeredTableName, 100, loanProductID);
assertNotNull(entityDatatableCheckId, "ERROR IN CREATING THE ENTITY DATATABLE CHECK");
// creating new loan application
final Integer loanID = applyForLoanApplication(clientID, loanProductID, "5", registeredTableName);
Assertions.assertNotNull(loanID);
// deleting entity datatable check
entityDatatableCheckId = this.entityDatatableChecksHelper.deleteEntityDatatableCheck(entityDatatableCheckId);
assertNotNull(entityDatatableCheckId, "ERROR IN DELETING THE ENTITY DATATABLE CHECK");
// deleting datatable entries
Integer appTableId = (Integer) this.datatableHelper.deleteDatatableEntries(registeredTableName, loanID, "loanId");
assertEquals(loanID, appTableId, "ERROR IN DELETING THE DATATABLE ENTRIES");
// deleting the datatable
String deletedDataTableName = this.datatableHelper.deleteDatatable(registeredTableName);
assertEquals(registeredTableName, deletedDataTableName, "ERROR IN DELETING THE DATATABLE");
}
@SuppressWarnings("unchecked")
@Test
public void validateCreateLoanWithEntityDatatableCheckWithFailure() {
this.loanTransactionHelper = new LoanTransactionHelper(this.requestSpec, this.responseSpec);
// building error response with status code 403
final ResponseSpecification errorResponse = new ResponseSpecBuilder().expectStatusCode(403).build();
this.validationErrorHelper = new LoanTransactionHelper(this.requestSpec, errorResponse);
// creating client
final Integer clientID = ClientHelper.createClient(this.requestSpec, this.responseSpec);
ClientHelper.verifyClientCreatedOnServer(this.requestSpec, this.responseSpec, clientID);
// creating loan product
final Integer loanProductID = createLoanProduct("100", "0", LoanProductTestBuilder.DEFAULT_STRATEGY);
Assertions.assertNotNull(loanProductID);
// creating datatable
String registeredTableName = this.datatableHelper.createDatatable(LOAN_APP_TABLE_NAME, false);
DatatableHelper.verifyDatatableCreatedOnServer(this.requestSpec, this.responseSpec, registeredTableName);
// creating new entity datatable check
Integer entityDatatableCheckId = this.entityDatatableChecksHelper.createEntityDatatableCheck(LOAN_APP_TABLE_NAME,
registeredTableName, 100, loanProductID);
assertNotNull(entityDatatableCheckId, "ERROR IN CREATING THE ENTITY DATATABLE CHECK");
// creating new loan application with error
ArrayList<HashMap<Object, Object>> loanErrorData = (ArrayList<HashMap<Object, Object>>) applyForLoanApplicationWithError(clientID,
loanProductID, "5", CommonConstants.RESPONSE_ERROR);
assertEquals("error.msg.entry.required.in.datatable.[" + registeredTableName + "]",
loanErrorData.get(0).get(CommonConstants.RESPONSE_ERROR_MESSAGE_CODE));
// deleting entity datatable check
entityDatatableCheckId = this.entityDatatableChecksHelper.deleteEntityDatatableCheck(entityDatatableCheckId);
assertNotNull(entityDatatableCheckId, "ERROR IN DELETING THE ENTITY DATATABLE CHECK");
// deleting the datatable
String deletedDataTableName = this.datatableHelper.deleteDatatable(registeredTableName);
assertEquals(registeredTableName, deletedDataTableName, "ERROR IN DELETING THE DATATABLE");
}
private Integer createSavingsProduct(final RequestSpecification requestSpec, final ResponseSpecification responseSpec,
final String minOpenningBalance, String minBalanceForInterestCalculation, String minRequiredBalance,
String enforceMinRequiredBalance, final boolean allowOverdraft) {
final String taxGroupId = null;
return createSavingsProduct(requestSpec, responseSpec, minOpenningBalance, minBalanceForInterestCalculation, minRequiredBalance,
enforceMinRequiredBalance, allowOverdraft, taxGroupId, false);
}
private Integer createSavingsProduct(final RequestSpecification requestSpec, final ResponseSpecification responseSpec,
final String minOpenningBalance, String minBalanceForInterestCalculation, String minRequiredBalance,
String enforceMinRequiredBalance, final boolean allowOverdraft, final String taxGroupId, boolean withDormancy) {
LOG.info("------------------------------CREATING NEW SAVINGS PRODUCT ---------------------------------------");
SavingsProductHelper savingsProductHelper = new SavingsProductHelper();
if (allowOverdraft) {
final String overDraftLimit = "2000.0";
savingsProductHelper = savingsProductHelper.withOverDraft(overDraftLimit);
}
if (withDormancy) {
savingsProductHelper = savingsProductHelper.withDormancy();
}
final String savingsProductJSON = savingsProductHelper
//
.withInterestCompoundingPeriodTypeAsDaily()
//
.withInterestPostingPeriodTypeAsMonthly()
//
.withInterestCalculationPeriodTypeAsDailyBalance()
//
.withMinBalanceForInterestCalculation(minBalanceForInterestCalculation)
//
.withMinRequiredBalance(minRequiredBalance).withEnforceMinRequiredBalance(enforceMinRequiredBalance)
.withMinimumOpenningBalance(minOpenningBalance).withWithHoldTax(taxGroupId).build();
return SavingsProductHelper.createSavingsProduct(savingsProductJSON, requestSpec, responseSpec);
}
private Integer createLoanProduct(final String inMultiplesOf, final String digitsAfterDecimal, final String repaymentStrategy) {
LOG.info("------------------------------CREATING NEW LOAN PRODUCT ---------------------------------------");
final String loanProductJSON = new LoanProductTestBuilder() //
.withPrincipal("10000000.00") //
.withNumberOfRepayments("24") //
.withRepaymentAfterEvery("1") //
.withRepaymentTypeAsMonth() //
.withinterestRatePerPeriod("2") //
.withInterestRateFrequencyTypeAsMonths() //
.withRepaymentStrategy(repaymentStrategy) //
.withAmortizationTypeAsEqualPrincipalPayment() //
.withInterestTypeAsDecliningBalance() //
.currencyDetails(digitsAfterDecimal, inMultiplesOf).build(null);
return this.loanTransactionHelper.getLoanProductId(loanProductJSON);
}
private Integer applyForLoanApplication(final Integer clientID, final Integer loanProductID, String graceOnPrincipalPayment,
final String registeredTableName) {
LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------");
List<HashMap> collaterals = new ArrayList<>();
final Integer collateralId = CollateralManagementHelper.createCollateralProduct(this.requestSpec, this.responseSpec);
Assertions.assertNotNull(collateralId);
final Integer clientCollateralId = CollateralManagementHelper.createClientCollateral(this.requestSpec, this.responseSpec,
clientID.toString(), collateralId);
Assertions.assertNotNull(clientCollateralId);
addCollaterals(collaterals, clientCollateralId, BigDecimal.valueOf(1));
final String loanApplicationJSON = new LoanApplicationTestBuilder() //
.withPrincipal("10000000.00") //
.withLoanTermFrequency("24") //
.withLoanTermFrequencyAsMonths() //
.withNumberOfRepayments("24") //
.withRepaymentEveryAfter("1") //
.withRepaymentFrequencyTypeAsMonths() //
.withInterestRatePerPeriod("2") //
.withAmortizationTypeAsEqualPrincipalPayments() //
.withInterestTypeAsDecliningBalance() //
.withInterestCalculationPeriodTypeSameAsRepaymentPeriod() //
.withPrincipalGrace(graceOnPrincipalPayment).withExpectedDisbursementDate("02 June 2014") //
.withSubmittedOnDate("02 June 2014") //
.withDatatables(getTestDatatableAsJson(registeredTableName)) //
.withCollaterals(collaterals).build(clientID.toString(), loanProductID.toString(), null);
return this.loanTransactionHelper.getLoanId(loanApplicationJSON);
}
private Object applyForLoanApplicationWithError(final Integer clientID, final Integer loanProductID, String graceOnPrincipalPayment,
final String responseAttribute) {
LOG.info("--------------------------------APPLYING FOR LOAN APPLICATION--------------------------------");
List<HashMap> collaterals = new ArrayList<>();
final Integer collateralId = CollateralManagementHelper.createCollateralProduct(this.requestSpec, this.responseSpec);
Assertions.assertNotNull(collateralId);
final Integer clientCollateralId = CollateralManagementHelper.createClientCollateral(this.requestSpec, this.responseSpec,
clientID.toString(), collateralId);
Assertions.assertNotNull(clientCollateralId);
addCollaterals(collaterals, clientCollateralId, BigDecimal.valueOf(1));
final String loanApplicationJSON = new LoanApplicationTestBuilder() //
.withPrincipal("10000000.00") //
.withLoanTermFrequency("24") //
.withLoanTermFrequencyAsMonths() //
.withNumberOfRepayments("24") //
.withRepaymentEveryAfter("1") //
.withRepaymentFrequencyTypeAsMonths() //
.withInterestRatePerPeriod("2") //
.withAmortizationTypeAsEqualPrincipalPayments() //
.withInterestTypeAsDecliningBalance() //
.withInterestCalculationPeriodTypeSameAsRepaymentPeriod() //
.withPrincipalGrace(graceOnPrincipalPayment).withExpectedDisbursementDate("02 June 2014") //
.withSubmittedOnDate("02 June 2014") //
.withCollaterals(collaterals).build(clientID.toString(), loanProductID.toString(), null);
return this.validationErrorHelper.getLoanError(loanApplicationJSON, responseAttribute);
}
private HashMap<String, String> collaterals(Integer collateralId, BigDecimal quantity) {
HashMap<String, String> collateral = new HashMap<String, String>(1);
collateral.put("clientCollateralId", collateralId.toString());
collateral.put("quantity", quantity.toString());
return collateral;
}
private void addCollaterals(List<HashMap> collaterals, Integer collateralId, BigDecimal amount) {
collaterals.add(collaterals(collateralId, amount));
}
public static List<HashMap<String, Object>> getTestDatatableAsJson(final String registeredTableName) {
List<HashMap<String, Object>> datatablesListMap = new ArrayList<>();
HashMap<String, Object> datatableMap = new HashMap<>();
HashMap<String, Object> dataMap = new HashMap<>();
dataMap.put("locale", "en");
dataMap.put("Spouse Name", Utils.randomStringGenerator("Spouse_name", 4));
dataMap.put("Number of Dependents", 5);
dataMap.put("Time of Visit", "01 December 2016 04:03");
dataMap.put("dateFormat", DATE_TIME_FORMAT);
dataMap.put("Date of Approval", "02 December 2016 00:00");
datatableMap.put("registeredTableName", registeredTableName);
datatableMap.put("data", dataMap);
datatablesListMap.add(datatableMap);
return datatablesListMap;
}
@Test
public void createClientWithDatatableUsingEntitySubtype() {
// creating datatable for client entity person subentity
HashMap<String, Object> columnMap = new HashMap<>();
final List<HashMap<String, Object>> datatableColumnsList = new ArrayList<>();
final String datatableNamePerson = Utils.uniqueRandomStringGenerator(CLIENT_APP_TABLE_NAME + "_person_", 5).toLowerCase()
.toLowerCase();
final String datatableNameEntity = Utils.uniqueRandomStringGenerator(CLIENT_APP_TABLE_NAME + "_entity_", 5).toLowerCase()
.toLowerCase();
String itsAString = "itsastring";
DatatableHelper.addDatatableColumn(datatableColumnsList, itsAString, "String", true, 10, null);
// Person Subtype
columnMap.put("datatableName", datatableNamePerson);
columnMap.put("apptableName", CLIENT_APP_TABLE_NAME);
columnMap.put("entitySubType", "PERSON");
columnMap.put("multiRow", false);
String dateFormat = "dateFormat";
columnMap.put("columns", datatableColumnsList);
String datatabelRequestJsonString = new Gson().toJson(columnMap);
LOG.info("map : {}", datatabelRequestJsonString);
datatableHelper.createDatatable(datatabelRequestJsonString, "");
PostEntityDatatableChecksTemplateResponse entityDatatableChecksResponse = entityDatatableChecksHelper
.addEntityDatatableCheck(CLIENT_APP_TABLE_NAME, datatableNamePerson, 100, null);
assertNotNull(entityDatatableChecksResponse);
final Long personDatatableCheck = entityDatatableChecksResponse.getResourceId();
LOG.info("entityDatatableChecksResponse Person: {}", entityDatatableChecksResponse.getResourceId());
// Entity Subtype
columnMap = new HashMap<>();
columnMap.put("datatableName", datatableNameEntity);
columnMap.put("apptableName", CLIENT_APP_TABLE_NAME);
columnMap.put("entitySubType", "ENTITY");
columnMap.put("multiRow", false);
columnMap.put("columns", datatableColumnsList);
datatabelRequestJsonString = new Gson().toJson(columnMap);
LOG.info("map : {}", datatabelRequestJsonString);
datatableHelper.createDatatable(datatabelRequestJsonString, "");
entityDatatableChecksResponse = entityDatatableChecksHelper.addEntityDatatableCheck(CLIENT_APP_TABLE_NAME, datatableNameEntity, 100,
null);
assertNotNull(entityDatatableChecksResponse);
final Long entityDatatableCheck = entityDatatableChecksResponse.getResourceId();
LOG.info("entityDatatableChecksResponse Entity: {}", entityDatatableChecksResponse.getResourceId());
final HashMap<String, Object> datatableEntryMap = new HashMap<>();
datatableEntryMap.put(itsAString, Utils.randomStringGenerator("", 8));
datatableEntryMap.put("locale", "en");
final HashMap<String, Object> datatablesMap = new HashMap<>();
datatablesMap.put("registeredTableName", datatableNamePerson);
datatablesMap.put("data", datatableEntryMap);
String datatablesJsonString = new Gson().toJson(datatablesMap);
LOG.info("map : {}", datatablesJsonString);
PostClientsResponse postClientsResponse = ClientHelper.createClientAsPersonWithDatatable(requestSpec, responseSpec, "04 March 2011",
"1", datatablesMap);
assertNotNull(postClientsResponse);
assertNotNull(postClientsResponse.getResourceId());
// Remove the Entity Datatable checks for others tests
entityDatatableChecksHelper.deleteEntityDatatableCheck(personDatatableCheck.intValue());
entityDatatableChecksHelper.deleteEntityDatatableCheck(entityDatatableCheck.intValue());
}
}
|
google/j2objc | 35,963 | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/coll/CollationKeys.java | /* GENERATED SOURCE. DO NOT MODIFY. */
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
/*
*******************************************************************************
* Copyright (C) 2012-2015, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
* CollationKeys.java, ported from collationkeys.h/.cpp
*
* C++ version created on: 2012sep02
* created by: Markus W. Scherer
*/
package android.icu.impl.coll;
import android.icu.text.Collator;
/**
* @hide Only a subset of ICU is exposed in Android
*/
public final class CollationKeys /* all methods are static */ {
// Java porting note: C++ SortKeyByteSink class extends a common class ByteSink,
// which is not available in Java. We don't need a super class created for implementing
// collation features.
public static abstract class SortKeyByteSink {
protected byte[] buffer_;
// protected int capacity_; == buffer_.length
private int appended_ = 0;
// not used in Java -- private int ignore_ = 0;
public SortKeyByteSink(byte[] dest) {
buffer_ = dest;
}
/**
* Needed in Java for when we write to the buffer directly.
* In C++, the SortKeyByteSink is a subclass of ByteSink and lower-level code can write to that.
* TODO: Can we make Java SortKeyByteSink have-a ByteArrayWrapper and write through to it?
* Or maybe create interface ByteSink, have SortKeyByteSink implement it, and have BOCSU write to that??
*/
public void setBufferAndAppended(byte[] dest, int app) {
buffer_ = dest;
appended_ = app;
}
/* not used in Java -- public void IgnoreBytes(int numIgnore) {
ignore_ = numIgnore;
} */
/**
* @param bytes
* the array of byte
* @param n
* the length of bytes to be appended
*/
public void Append(byte[] bytes, int n) {
if (n <= 0 || bytes == null) {
return;
}
/* not used in Java -- if (ignore_ > 0) {
int ignoreRest = ignore_ - n;
if (ignoreRest >= 0) {
ignore_ = ignoreRest;
return;
} else {
start = ignore_;
n = -ignoreRest;
ignore_ = 0;
}
} */
int length = appended_;
appended_ += n;
int available = buffer_.length - length;
if (n <= available) {
System.arraycopy(bytes, 0, buffer_, length, n);
} else {
AppendBeyondCapacity(bytes, 0, n, length);
}
}
public void Append(int b) {
/* not used in Java -- if (ignore_ > 0) {
--ignore_;
} else */ {
if (appended_ < buffer_.length || Resize(1, appended_)) {
buffer_[appended_] = (byte) b;
}
++appended_;
}
}
// Java porting note: This method is not used by collator implementation.
//
// virtual char *GetAppendBuffer(int min_capacity,
// int desired_capacity_hint,
// char *scratch, int scratch_capacity,
// int *result_capacity);
public int NumberOfBytesAppended() {
return appended_;
}
public int GetRemainingCapacity() {
return /* not used in Java -- ignore_ + */ buffer_.length - appended_;
}
public boolean Overflowed() {
return appended_ > buffer_.length;
}
/* not used in Java -- public boolean IsOk() {
return true;
} */
/**
* @param bytes
* the array of byte
* @param start
* the start index within the array to be appended
* @param n
* the length of bytes to be appended
* @param length
* the length of buffer required to store the entire data (i.e. already appended
* bytes + bytes to be appended by this method)
*/
protected abstract void AppendBeyondCapacity(byte[] bytes, int start, int n, int length);
protected abstract boolean Resize(int appendCapacity, int length);
}
public static class LevelCallback {
/**
* @param level
* The next level about to be written to the ByteSink.
* @return true if the level is to be written (the base class implementation always returns
* true)
*/
boolean needToWrite(int level) {
return true;
}
}
public static final LevelCallback SIMPLE_LEVEL_FALLBACK = new LevelCallback();
private static final class SortKeyLevel {
private static final int INITIAL_CAPACITY = 40;
byte[] buffer = new byte[INITIAL_CAPACITY];
int len = 0;
// not used in Java -- private static final boolean ok = true; // In C++ "ok" is reset when memory allocations fail.
SortKeyLevel() {
}
/* not used in Java -- boolean isOk() {
return ok;
} */
boolean isEmpty() {
return len == 0;
}
int length() {
return len;
}
// Java porting note: Java uses this instead of C++ operator [] overload
// uint8_t operator[](int index)
byte getAt(int index) {
return buffer[index];
}
byte[] data() {
return buffer;
}
void appendByte(int b) {
if (len < buffer.length || ensureCapacity(1)) {
buffer[len++] = (byte) b;
}
}
void appendWeight16(int w) {
assert ((w & 0xffff) != 0);
byte b0 = (byte) (w >>> 8);
byte b1 = (byte) w;
int appendLength = (b1 == 0) ? 1 : 2;
if ((len + appendLength) <= buffer.length || ensureCapacity(appendLength)) {
buffer[len++] = b0;
if (b1 != 0) {
buffer[len++] = b1;
}
}
}
void appendWeight32(long w) {
assert (w != 0);
byte[] bytes = new byte[] { (byte) (w >>> 24), (byte) (w >>> 16), (byte) (w >>> 8),
(byte) w };
int appendLength = (bytes[1] == 0) ? 1 : (bytes[2] == 0) ? 2 : (bytes[3] == 0) ? 3 : 4;
if ((len + appendLength) <= buffer.length || ensureCapacity(appendLength)) {
buffer[len++] = bytes[0];
if (bytes[1] != 0) {
buffer[len++] = bytes[1];
if (bytes[2] != 0) {
buffer[len++] = bytes[2];
if (bytes[3] != 0) {
buffer[len++] = bytes[3];
}
}
}
}
}
void appendReverseWeight16(int w) {
assert ((w & 0xffff) != 0);
byte b0 = (byte) (w >>> 8);
byte b1 = (byte) w;
int appendLength = (b1 == 0) ? 1 : 2;
if ((len + appendLength) <= buffer.length || ensureCapacity(appendLength)) {
if (b1 == 0) {
buffer[len++] = b0;
} else {
buffer[len] = b1;
buffer[len + 1] = b0;
len += 2;
}
}
}
// Appends all but the last byte to the sink. The last byte should be the 01 terminator.
void appendTo(SortKeyByteSink sink) {
assert (len > 0 && buffer[len - 1] == 1);
sink.Append(buffer, len - 1);
}
private boolean ensureCapacity(int appendCapacity) {
/* not used in Java -- if (!ok) {
return false;
} */
int newCapacity = 2 * buffer.length;
int altCapacity = len + 2 * appendCapacity;
if (newCapacity < altCapacity) {
newCapacity = altCapacity;
}
if (newCapacity < 200) {
newCapacity = 200;
}
byte[] newbuf = new byte[newCapacity];
System.arraycopy(buffer, 0, newbuf, 0, len);
buffer = newbuf;
return true;
}
}
private static SortKeyLevel getSortKeyLevel(int levels, int level) {
return (levels & level) != 0 ? new SortKeyLevel() : null;
}
private CollationKeys() {
} // no instantiation
// Secondary level: Compress up to 33 common weights as 05..25 or 25..45.
private static final int SEC_COMMON_LOW = Collation.COMMON_BYTE;
private static final int SEC_COMMON_MIDDLE = SEC_COMMON_LOW + 0x20;
static final int SEC_COMMON_HIGH = SEC_COMMON_LOW + 0x40; // read by CollationDataReader
private static final int SEC_COMMON_MAX_COUNT = 0x21;
// Case level, lowerFirst: Compress up to 7 common weights as 1..7 or 7..13.
private static final int CASE_LOWER_FIRST_COMMON_LOW = 1;
private static final int CASE_LOWER_FIRST_COMMON_MIDDLE = 7;
private static final int CASE_LOWER_FIRST_COMMON_HIGH = 13;
private static final int CASE_LOWER_FIRST_COMMON_MAX_COUNT = 7;
// Case level, upperFirst: Compress up to 13 common weights as 3..15.
private static final int CASE_UPPER_FIRST_COMMON_LOW = 3;
@SuppressWarnings("unused")
private static final int CASE_UPPER_FIRST_COMMON_HIGH = 15;
private static final int CASE_UPPER_FIRST_COMMON_MAX_COUNT = 13;
// Tertiary level only (no case): Compress up to 97 common weights as 05..65 or 65..C5.
private static final int TER_ONLY_COMMON_LOW = Collation.COMMON_BYTE;
private static final int TER_ONLY_COMMON_MIDDLE = TER_ONLY_COMMON_LOW + 0x60;
private static final int TER_ONLY_COMMON_HIGH = TER_ONLY_COMMON_LOW + 0xc0;
private static final int TER_ONLY_COMMON_MAX_COUNT = 0x61;
// Tertiary with case, lowerFirst: Compress up to 33 common weights as 05..25 or 25..45.
private static final int TER_LOWER_FIRST_COMMON_LOW = Collation.COMMON_BYTE;
private static final int TER_LOWER_FIRST_COMMON_MIDDLE = TER_LOWER_FIRST_COMMON_LOW + 0x20;
private static final int TER_LOWER_FIRST_COMMON_HIGH = TER_LOWER_FIRST_COMMON_LOW + 0x40;
private static final int TER_LOWER_FIRST_COMMON_MAX_COUNT = 0x21;
// Tertiary with case, upperFirst: Compress up to 33 common weights as 85..A5 or A5..C5.
private static final int TER_UPPER_FIRST_COMMON_LOW = Collation.COMMON_BYTE + 0x80;
private static final int TER_UPPER_FIRST_COMMON_MIDDLE = TER_UPPER_FIRST_COMMON_LOW + 0x20;
private static final int TER_UPPER_FIRST_COMMON_HIGH = TER_UPPER_FIRST_COMMON_LOW + 0x40;
private static final int TER_UPPER_FIRST_COMMON_MAX_COUNT = 0x21;
// Quaternary level: Compress up to 113 common weights as 1C..8C or 8C..FC.
private static final int QUAT_COMMON_LOW = 0x1c;
private static final int QUAT_COMMON_MIDDLE = QUAT_COMMON_LOW + 0x70;
private static final int QUAT_COMMON_HIGH = QUAT_COMMON_LOW + 0xE0;
private static final int QUAT_COMMON_MAX_COUNT = 0x71;
// Primary weights shifted to quaternary level must be encoded with
// a lead byte below the common-weight compression range.
private static final int QUAT_SHIFTED_LIMIT_BYTE = QUAT_COMMON_LOW - 1; // 0x1b
/**
* Map from collation strength (UColAttributeValue) to a mask of Collation.Level bits up to that
* strength, excluding the CASE_LEVEL which is independent of the strength, and excluding
* IDENTICAL_LEVEL which this function does not write.
*/
private static final int levelMasks[] = new int[] {
2, // UCOL_PRIMARY -> PRIMARY_LEVEL
6, // UCOL_SECONDARY -> up to SECONDARY_LEVEL
0x16, // UCOL_TERTIARY -> up to TERTIARY_LEVEL
0x36, // UCOL_QUATERNARY -> up to QUATERNARY_LEVEL
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0,
0x36 // UCOL_IDENTICAL -> up to QUATERNARY_LEVEL
};
/**
* Writes the sort key bytes for minLevel up to the iterator data's strength. Optionally writes
* the case level. Stops writing levels when callback.needToWrite(level) returns false.
* Separates levels with the LEVEL_SEPARATOR_BYTE but does not write a TERMINATOR_BYTE.
*/
public static void writeSortKeyUpToQuaternary(CollationIterator iter, boolean[] compressibleBytes,
CollationSettings settings, SortKeyByteSink sink, int minLevel, LevelCallback callback,
boolean preflight) {
int options = settings.options;
// Set of levels to process and write.
int levels = levelMasks[CollationSettings.getStrength(options)];
if ((options & CollationSettings.CASE_LEVEL) != 0) {
levels |= Collation.CASE_LEVEL_FLAG;
}
// Minus the levels below minLevel.
levels &= ~((1 << minLevel) - 1);
if (levels == 0) {
return;
}
long variableTop;
if ((options & CollationSettings.ALTERNATE_MASK) == 0) {
variableTop = 0;
} else {
// +1 so that we can use "<" and primary ignorables test out early.
variableTop = settings.variableTop + 1;
}
int tertiaryMask = CollationSettings.getTertiaryMask(options);
byte[] p234 = new byte[3];
SortKeyLevel cases = getSortKeyLevel(levels, Collation.CASE_LEVEL_FLAG);
SortKeyLevel secondaries = getSortKeyLevel(levels, Collation.SECONDARY_LEVEL_FLAG);
SortKeyLevel tertiaries = getSortKeyLevel(levels, Collation.TERTIARY_LEVEL_FLAG);
SortKeyLevel quaternaries = getSortKeyLevel(levels, Collation.QUATERNARY_LEVEL_FLAG);
long prevReorderedPrimary = 0; // 0==no compression
int commonCases = 0;
int commonSecondaries = 0;
int commonTertiaries = 0;
int commonQuaternaries = 0;
int prevSecondary = 0;
int secSegmentStart = 0;
for (;;) {
// No need to keep all CEs in the buffer when we write a sort key.
iter.clearCEsIfNoneRemaining();
long ce = iter.nextCE();
long p = ce >>> 32;
if (p < variableTop && p > Collation.MERGE_SEPARATOR_PRIMARY) {
// Variable CE, shift it to quaternary level.
// Ignore all following primary ignorables, and shift further variable CEs.
if (commonQuaternaries != 0) {
--commonQuaternaries;
while (commonQuaternaries >= QUAT_COMMON_MAX_COUNT) {
quaternaries.appendByte(QUAT_COMMON_MIDDLE);
commonQuaternaries -= QUAT_COMMON_MAX_COUNT;
}
// Shifted primary weights are lower than the common weight.
quaternaries.appendByte(QUAT_COMMON_LOW + commonQuaternaries);
commonQuaternaries = 0;
}
do {
if ((levels & Collation.QUATERNARY_LEVEL_FLAG) != 0) {
if (settings.hasReordering()) {
p = settings.reorder(p);
}
if (((int) p >>> 24) >= QUAT_SHIFTED_LIMIT_BYTE) {
// Prevent shifted primary lead bytes from
// overlapping with the common compression range.
quaternaries.appendByte(QUAT_SHIFTED_LIMIT_BYTE);
}
quaternaries.appendWeight32(p);
}
do {
ce = iter.nextCE();
p = ce >>> 32;
} while (p == 0);
} while (p < variableTop && p > Collation.MERGE_SEPARATOR_PRIMARY);
}
// ce could be primary ignorable, or NO_CE, or the merge separator,
// or a regular primary CE, but it is not variable.
// If ce==NO_CE, then write nothing for the primary level but
// terminate compression on all levels and then exit the loop.
if (p > Collation.NO_CE_PRIMARY && (levels & Collation.PRIMARY_LEVEL_FLAG) != 0) {
// Test the un-reordered primary for compressibility.
boolean isCompressible = compressibleBytes[(int) p >>> 24];
if(settings.hasReordering()) {
p = settings.reorder(p);
}
int p1 = (int) p >>> 24;
if (!isCompressible || p1 != ((int) prevReorderedPrimary >>> 24)) {
if (prevReorderedPrimary != 0) {
if (p < prevReorderedPrimary) {
// No primary compression terminator
// at the end of the level or merged segment.
if (p1 > Collation.MERGE_SEPARATOR_BYTE) {
sink.Append(Collation.PRIMARY_COMPRESSION_LOW_BYTE);
}
} else {
sink.Append(Collation.PRIMARY_COMPRESSION_HIGH_BYTE);
}
}
sink.Append(p1);
if(isCompressible) {
prevReorderedPrimary = p;
} else {
prevReorderedPrimary = 0;
}
}
byte p2 = (byte) (p >>> 16);
if (p2 != 0) {
p234[0] = p2;
p234[1] = (byte) (p >>> 8);
p234[2] = (byte) p;
sink.Append(p234, (p234[1] == 0) ? 1 : (p234[2] == 0) ? 2 : 3);
}
// Optimization for internalNextSortKeyPart():
// When the primary level overflows we can stop because we need not
// calculate (preflight) the whole sort key length.
if (!preflight && sink.Overflowed()) {
// not used in Java -- if (!sink.IsOk()) {
// Java porting note: U_MEMORY_ALLOCATION_ERROR is set here in
// C implementation. IsOk() in Java always returns true, so this
// is a dead code.
return;
}
}
int lower32 = (int) ce;
if (lower32 == 0) {
continue;
} // completely ignorable, no secondary/case/tertiary/quaternary
if ((levels & Collation.SECONDARY_LEVEL_FLAG) != 0) {
int s = lower32 >>> 16; // 16 bits
if (s == 0) {
// secondary ignorable
} else if (s == Collation.COMMON_WEIGHT16 &&
((options & CollationSettings.BACKWARD_SECONDARY) == 0 ||
p != Collation.MERGE_SEPARATOR_PRIMARY)) {
// s is a common secondary weight, and
// backwards-secondary is off or the ce is not the merge separator.
++commonSecondaries;
} else if ((options & CollationSettings.BACKWARD_SECONDARY) == 0) {
if (commonSecondaries != 0) {
--commonSecondaries;
while (commonSecondaries >= SEC_COMMON_MAX_COUNT) {
secondaries.appendByte(SEC_COMMON_MIDDLE);
commonSecondaries -= SEC_COMMON_MAX_COUNT;
}
int b;
if (s < Collation.COMMON_WEIGHT16) {
b = SEC_COMMON_LOW + commonSecondaries;
} else {
b = SEC_COMMON_HIGH - commonSecondaries;
}
secondaries.appendByte(b);
commonSecondaries = 0;
}
secondaries.appendWeight16(s);
} else {
if (commonSecondaries != 0) {
--commonSecondaries;
// Append reverse weights. The level will be re-reversed later.
int remainder = commonSecondaries % SEC_COMMON_MAX_COUNT;
int b;
if (prevSecondary < Collation.COMMON_WEIGHT16) {
b = SEC_COMMON_LOW + remainder;
} else {
b = SEC_COMMON_HIGH - remainder;
}
secondaries.appendByte(b);
commonSecondaries -= remainder;
// commonSecondaries is now a multiple of SEC_COMMON_MAX_COUNT.
while (commonSecondaries > 0) { // same as >= SEC_COMMON_MAX_COUNT
secondaries.appendByte(SEC_COMMON_MIDDLE);
commonSecondaries -= SEC_COMMON_MAX_COUNT;
}
// commonSecondaries == 0
}
if (0 < p && p <= Collation.MERGE_SEPARATOR_PRIMARY) {
// The backwards secondary level compares secondary weights backwards
// within segments separated by the merge separator (U+FFFE).
byte[] secs = secondaries.data();
int last = secondaries.length() - 1;
while (secSegmentStart < last) {
byte b = secs[secSegmentStart];
secs[secSegmentStart++] = secs[last];
secs[last--] = b;
}
secondaries.appendByte(p == Collation.NO_CE_PRIMARY ?
Collation.LEVEL_SEPARATOR_BYTE : Collation.MERGE_SEPARATOR_BYTE);
prevSecondary = 0;
secSegmentStart = secondaries.length();
} else {
secondaries.appendReverseWeight16(s);
prevSecondary = s;
}
}
}
if ((levels & Collation.CASE_LEVEL_FLAG) != 0) {
if ((CollationSettings.getStrength(options) == Collator.PRIMARY) ? p == 0
: (lower32 >>> 16) == 0) {
// Primary+caseLevel: Ignore case level weights of primary ignorables.
// Otherwise: Ignore case level weights of secondary ignorables.
// For details see the comments in the CollationCompare class.
} else {
int c = (lower32 >>> 8) & 0xff; // case bits & tertiary lead byte
assert ((c & 0xc0) != 0xc0);
if ((c & 0xc0) == 0 && c > Collation.LEVEL_SEPARATOR_BYTE) {
++commonCases;
} else {
if ((options & CollationSettings.UPPER_FIRST) == 0) {
// lowerFirst: Compress common weights to nibbles 1..7..13, mixed=14,
// upper=15.
// If there are only common (=lowest) weights in the whole level,
// then we need not write anything.
// Level length differences are handled already on the next-higher level.
if (commonCases != 0 &&
(c > Collation.LEVEL_SEPARATOR_BYTE || !cases.isEmpty())) {
--commonCases;
while (commonCases >= CASE_LOWER_FIRST_COMMON_MAX_COUNT) {
cases.appendByte(CASE_LOWER_FIRST_COMMON_MIDDLE << 4);
commonCases -= CASE_LOWER_FIRST_COMMON_MAX_COUNT;
}
int b;
if (c <= Collation.LEVEL_SEPARATOR_BYTE) {
b = CASE_LOWER_FIRST_COMMON_LOW + commonCases;
} else {
b = CASE_LOWER_FIRST_COMMON_HIGH - commonCases;
}
cases.appendByte(b << 4);
commonCases = 0;
}
if (c > Collation.LEVEL_SEPARATOR_BYTE) {
c = (CASE_LOWER_FIRST_COMMON_HIGH + (c >>> 6)) << 4; // 14 or 15
}
} else {
// upperFirst: Compress common weights to nibbles 3..15, mixed=2,
// upper=1.
// The compressed common case weights only go up from the "low" value
// because with upperFirst the common weight is the highest one.
if (commonCases != 0) {
--commonCases;
while (commonCases >= CASE_UPPER_FIRST_COMMON_MAX_COUNT) {
cases.appendByte(CASE_UPPER_FIRST_COMMON_LOW << 4);
commonCases -= CASE_UPPER_FIRST_COMMON_MAX_COUNT;
}
cases.appendByte((CASE_UPPER_FIRST_COMMON_LOW + commonCases) << 4);
commonCases = 0;
}
if (c > Collation.LEVEL_SEPARATOR_BYTE) {
c = (CASE_UPPER_FIRST_COMMON_LOW - (c >>> 6)) << 4; // 2 or 1
}
}
// c is a separator byte 01,
// or a left-shifted nibble 0x10, 0x20, ... 0xf0.
cases.appendByte(c);
}
}
}
if ((levels & Collation.TERTIARY_LEVEL_FLAG) != 0) {
int t = lower32 & tertiaryMask;
assert ((lower32 & 0xc000) != 0xc000);
if (t == Collation.COMMON_WEIGHT16) {
++commonTertiaries;
} else if ((tertiaryMask & 0x8000) == 0) {
// Tertiary weights without case bits.
// Move lead bytes 06..3F to C6..FF for a large common-weight range.
if (commonTertiaries != 0) {
--commonTertiaries;
while (commonTertiaries >= TER_ONLY_COMMON_MAX_COUNT) {
tertiaries.appendByte(TER_ONLY_COMMON_MIDDLE);
commonTertiaries -= TER_ONLY_COMMON_MAX_COUNT;
}
int b;
if (t < Collation.COMMON_WEIGHT16) {
b = TER_ONLY_COMMON_LOW + commonTertiaries;
} else {
b = TER_ONLY_COMMON_HIGH - commonTertiaries;
}
tertiaries.appendByte(b);
commonTertiaries = 0;
}
if (t > Collation.COMMON_WEIGHT16) {
t += 0xc000;
}
tertiaries.appendWeight16(t);
} else if ((options & CollationSettings.UPPER_FIRST) == 0) {
// Tertiary weights with caseFirst=lowerFirst.
// Move lead bytes 06..BF to 46..FF for the common-weight range.
if (commonTertiaries != 0) {
--commonTertiaries;
while (commonTertiaries >= TER_LOWER_FIRST_COMMON_MAX_COUNT) {
tertiaries.appendByte(TER_LOWER_FIRST_COMMON_MIDDLE);
commonTertiaries -= TER_LOWER_FIRST_COMMON_MAX_COUNT;
}
int b;
if (t < Collation.COMMON_WEIGHT16) {
b = TER_LOWER_FIRST_COMMON_LOW + commonTertiaries;
} else {
b = TER_LOWER_FIRST_COMMON_HIGH - commonTertiaries;
}
tertiaries.appendByte(b);
commonTertiaries = 0;
}
if (t > Collation.COMMON_WEIGHT16) {
t += 0x4000;
}
tertiaries.appendWeight16(t);
} else {
// Tertiary weights with caseFirst=upperFirst.
// Do not change the artificial uppercase weight of a tertiary CE (0.0.ut),
// to keep tertiary CEs well-formed.
// Their case+tertiary weights must be greater than those of
// primary and secondary CEs.
//
// Separator 01 -> 01 (unchanged)
// Lowercase 02..04 -> 82..84 (includes uncased)
// Common weight 05 -> 85..C5 (common-weight compression range)
// Lowercase 06..3F -> C6..FF
// Mixed case 42..7F -> 42..7F
// Uppercase 82..BF -> 02..3F
// Tertiary CE 86..BF -> C6..FF
if (t <= Collation.NO_CE_WEIGHT16) {
// Keep separators unchanged.
} else if ((lower32 >>> 16) != 0) {
// Invert case bits of primary & secondary CEs.
t ^= 0xc000;
if (t < (TER_UPPER_FIRST_COMMON_HIGH << 8)) {
t -= 0x4000;
}
} else {
// Keep uppercase bits of tertiary CEs.
assert (0x8600 <= t && t <= 0xbfff);
t += 0x4000;
}
if (commonTertiaries != 0) {
--commonTertiaries;
while (commonTertiaries >= TER_UPPER_FIRST_COMMON_MAX_COUNT) {
tertiaries.appendByte(TER_UPPER_FIRST_COMMON_MIDDLE);
commonTertiaries -= TER_UPPER_FIRST_COMMON_MAX_COUNT;
}
int b;
if (t < (TER_UPPER_FIRST_COMMON_LOW << 8)) {
b = TER_UPPER_FIRST_COMMON_LOW + commonTertiaries;
} else {
b = TER_UPPER_FIRST_COMMON_HIGH - commonTertiaries;
}
tertiaries.appendByte(b);
commonTertiaries = 0;
}
tertiaries.appendWeight16(t);
}
}
if ((levels & Collation.QUATERNARY_LEVEL_FLAG) != 0) {
int q = lower32 & 0xffff;
if ((q & 0xc0) == 0 && q > Collation.NO_CE_WEIGHT16) {
++commonQuaternaries;
} else if (q == Collation.NO_CE_WEIGHT16
&& (options & CollationSettings.ALTERNATE_MASK) == 0
&& quaternaries.isEmpty()) {
// If alternate=non-ignorable and there are only common quaternary weights,
// then we need not write anything.
// The only weights greater than the merge separator and less than the common
// weight
// are shifted primary weights, which are not generated for
// alternate=non-ignorable.
// There are also exactly as many quaternary weights as tertiary weights,
// so level length differences are handled already on tertiary level.
// Any above-common quaternary weight will compare greater regardless.
quaternaries.appendByte(Collation.LEVEL_SEPARATOR_BYTE);
} else {
if (q == Collation.NO_CE_WEIGHT16) {
q = Collation.LEVEL_SEPARATOR_BYTE;
} else {
q = 0xfc + ((q >>> 6) & 3);
}
if (commonQuaternaries != 0) {
--commonQuaternaries;
while (commonQuaternaries >= QUAT_COMMON_MAX_COUNT) {
quaternaries.appendByte(QUAT_COMMON_MIDDLE);
commonQuaternaries -= QUAT_COMMON_MAX_COUNT;
}
int b;
if (q < QUAT_COMMON_LOW) {
b = QUAT_COMMON_LOW + commonQuaternaries;
} else {
b = QUAT_COMMON_HIGH - commonQuaternaries;
}
quaternaries.appendByte(b);
commonQuaternaries = 0;
}
quaternaries.appendByte(q);
}
}
if ((lower32 >>> 24) == Collation.LEVEL_SEPARATOR_BYTE) {
break;
} // ce == NO_CE
}
// Append the beyond-primary levels.
// not used in Java -- boolean ok = true;
if ((levels & Collation.SECONDARY_LEVEL_FLAG) != 0) {
if (!callback.needToWrite(Collation.SECONDARY_LEVEL)) {
return;
}
// not used in Java -- ok &= secondaries.isOk();
sink.Append(Collation.LEVEL_SEPARATOR_BYTE);
secondaries.appendTo(sink);
}
if ((levels & Collation.CASE_LEVEL_FLAG) != 0) {
if (!callback.needToWrite(Collation.CASE_LEVEL)) {
return;
}
// not used in Java -- ok &= cases.isOk();
sink.Append(Collation.LEVEL_SEPARATOR_BYTE);
// Write pairs of nibbles as bytes, except separator bytes as themselves.
int length = cases.length() - 1; // Ignore the trailing NO_CE.
byte b = 0;
for (int i = 0; i < length; ++i) {
byte c = cases.getAt(i);
assert ((c & 0xf) == 0 && c != 0);
if (b == 0) {
b = c;
} else {
sink.Append(b | ((c >> 4) & 0xf));
b = 0;
}
}
if (b != 0) {
sink.Append(b);
}
}
if ((levels & Collation.TERTIARY_LEVEL_FLAG) != 0) {
if (!callback.needToWrite(Collation.TERTIARY_LEVEL)) {
return;
}
// not used in Java -- ok &= tertiaries.isOk();
sink.Append(Collation.LEVEL_SEPARATOR_BYTE);
tertiaries.appendTo(sink);
}
if ((levels & Collation.QUATERNARY_LEVEL_FLAG) != 0) {
if (!callback.needToWrite(Collation.QUATERNARY_LEVEL)) {
return;
}
// not used in Java -- ok &= quaternaries.isOk();
sink.Append(Collation.LEVEL_SEPARATOR_BYTE);
quaternaries.appendTo(sink);
}
// not used in Java -- if (!ok || !sink.IsOk()) {
// Java porting note: U_MEMORY_ALLOCATION_ERROR is set here in
// C implementation. IsOk() in Java always returns true, so this
// is a dead code.
}
}
|
googleapis/google-cloud-java | 35,564 | java-translate/proto-google-cloud-translate-v3/src/main/java/com/google/cloud/translate/v3/ListExamplesResponse.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/translate/v3/automl_translation.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.translate.v3;
/**
*
*
* <pre>
* Response message for ListExamples.
* </pre>
*
* Protobuf type {@code google.cloud.translation.v3.ListExamplesResponse}
*/
public final class ListExamplesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.translation.v3.ListExamplesResponse)
ListExamplesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListExamplesResponse.newBuilder() to construct.
private ListExamplesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListExamplesResponse() {
examples_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListExamplesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_ListExamplesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_ListExamplesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.translate.v3.ListExamplesResponse.class,
com.google.cloud.translate.v3.ListExamplesResponse.Builder.class);
}
public static final int EXAMPLES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.translate.v3.Example> examples_;
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.translate.v3.Example> getExamplesList() {
return examples_;
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.translate.v3.ExampleOrBuilder>
getExamplesOrBuilderList() {
return examples_;
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
@java.lang.Override
public int getExamplesCount() {
return examples_.size();
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
@java.lang.Override
public com.google.cloud.translate.v3.Example getExamples(int index) {
return examples_.get(index);
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
@java.lang.Override
public com.google.cloud.translate.v3.ExampleOrBuilder getExamplesOrBuilder(int index) {
return examples_.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 this token to the page_token field in the ListExamplesRequest to
* obtain the corresponding 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 this token to the page_token field in the ListExamplesRequest to
* obtain the corresponding 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 < examples_.size(); i++) {
output.writeMessage(1, examples_.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 < examples_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, examples_.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.translate.v3.ListExamplesResponse)) {
return super.equals(obj);
}
com.google.cloud.translate.v3.ListExamplesResponse other =
(com.google.cloud.translate.v3.ListExamplesResponse) obj;
if (!getExamplesList().equals(other.getExamplesList())) 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 (getExamplesCount() > 0) {
hash = (37 * hash) + EXAMPLES_FIELD_NUMBER;
hash = (53 * hash) + getExamplesList().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.translate.v3.ListExamplesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3.ListExamplesResponse 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.translate.v3.ListExamplesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3.ListExamplesResponse 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.translate.v3.ListExamplesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.translate.v3.ListExamplesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.translate.v3.ListExamplesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3.ListExamplesResponse 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.translate.v3.ListExamplesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3.ListExamplesResponse 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.translate.v3.ListExamplesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.translate.v3.ListExamplesResponse 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.translate.v3.ListExamplesResponse 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 ListExamples.
* </pre>
*
* Protobuf type {@code google.cloud.translation.v3.ListExamplesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.translation.v3.ListExamplesResponse)
com.google.cloud.translate.v3.ListExamplesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_ListExamplesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_ListExamplesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.translate.v3.ListExamplesResponse.class,
com.google.cloud.translate.v3.ListExamplesResponse.Builder.class);
}
// Construct using com.google.cloud.translate.v3.ListExamplesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (examplesBuilder_ == null) {
examples_ = java.util.Collections.emptyList();
} else {
examples_ = null;
examplesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.translate.v3.AutoMLTranslationProto
.internal_static_google_cloud_translation_v3_ListExamplesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.translate.v3.ListExamplesResponse getDefaultInstanceForType() {
return com.google.cloud.translate.v3.ListExamplesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.translate.v3.ListExamplesResponse build() {
com.google.cloud.translate.v3.ListExamplesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.translate.v3.ListExamplesResponse buildPartial() {
com.google.cloud.translate.v3.ListExamplesResponse result =
new com.google.cloud.translate.v3.ListExamplesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.translate.v3.ListExamplesResponse result) {
if (examplesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
examples_ = java.util.Collections.unmodifiableList(examples_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.examples_ = examples_;
} else {
result.examples_ = examplesBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.translate.v3.ListExamplesResponse 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.translate.v3.ListExamplesResponse) {
return mergeFrom((com.google.cloud.translate.v3.ListExamplesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.translate.v3.ListExamplesResponse other) {
if (other == com.google.cloud.translate.v3.ListExamplesResponse.getDefaultInstance())
return this;
if (examplesBuilder_ == null) {
if (!other.examples_.isEmpty()) {
if (examples_.isEmpty()) {
examples_ = other.examples_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureExamplesIsMutable();
examples_.addAll(other.examples_);
}
onChanged();
}
} else {
if (!other.examples_.isEmpty()) {
if (examplesBuilder_.isEmpty()) {
examplesBuilder_.dispose();
examplesBuilder_ = null;
examples_ = other.examples_;
bitField0_ = (bitField0_ & ~0x00000001);
examplesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getExamplesFieldBuilder()
: null;
} else {
examplesBuilder_.addAllMessages(other.examples_);
}
}
}
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.translate.v3.Example m =
input.readMessage(
com.google.cloud.translate.v3.Example.parser(), extensionRegistry);
if (examplesBuilder_ == null) {
ensureExamplesIsMutable();
examples_.add(m);
} else {
examplesBuilder_.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.translate.v3.Example> examples_ =
java.util.Collections.emptyList();
private void ensureExamplesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
examples_ = new java.util.ArrayList<com.google.cloud.translate.v3.Example>(examples_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.translate.v3.Example,
com.google.cloud.translate.v3.Example.Builder,
com.google.cloud.translate.v3.ExampleOrBuilder>
examplesBuilder_;
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public java.util.List<com.google.cloud.translate.v3.Example> getExamplesList() {
if (examplesBuilder_ == null) {
return java.util.Collections.unmodifiableList(examples_);
} else {
return examplesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public int getExamplesCount() {
if (examplesBuilder_ == null) {
return examples_.size();
} else {
return examplesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public com.google.cloud.translate.v3.Example getExamples(int index) {
if (examplesBuilder_ == null) {
return examples_.get(index);
} else {
return examplesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public Builder setExamples(int index, com.google.cloud.translate.v3.Example value) {
if (examplesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureExamplesIsMutable();
examples_.set(index, value);
onChanged();
} else {
examplesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public Builder setExamples(
int index, com.google.cloud.translate.v3.Example.Builder builderForValue) {
if (examplesBuilder_ == null) {
ensureExamplesIsMutable();
examples_.set(index, builderForValue.build());
onChanged();
} else {
examplesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public Builder addExamples(com.google.cloud.translate.v3.Example value) {
if (examplesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureExamplesIsMutable();
examples_.add(value);
onChanged();
} else {
examplesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public Builder addExamples(int index, com.google.cloud.translate.v3.Example value) {
if (examplesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureExamplesIsMutable();
examples_.add(index, value);
onChanged();
} else {
examplesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public Builder addExamples(com.google.cloud.translate.v3.Example.Builder builderForValue) {
if (examplesBuilder_ == null) {
ensureExamplesIsMutable();
examples_.add(builderForValue.build());
onChanged();
} else {
examplesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public Builder addExamples(
int index, com.google.cloud.translate.v3.Example.Builder builderForValue) {
if (examplesBuilder_ == null) {
ensureExamplesIsMutable();
examples_.add(index, builderForValue.build());
onChanged();
} else {
examplesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public Builder addAllExamples(
java.lang.Iterable<? extends com.google.cloud.translate.v3.Example> values) {
if (examplesBuilder_ == null) {
ensureExamplesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, examples_);
onChanged();
} else {
examplesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public Builder clearExamples() {
if (examplesBuilder_ == null) {
examples_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
examplesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public Builder removeExamples(int index) {
if (examplesBuilder_ == null) {
ensureExamplesIsMutable();
examples_.remove(index);
onChanged();
} else {
examplesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public com.google.cloud.translate.v3.Example.Builder getExamplesBuilder(int index) {
return getExamplesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public com.google.cloud.translate.v3.ExampleOrBuilder getExamplesOrBuilder(int index) {
if (examplesBuilder_ == null) {
return examples_.get(index);
} else {
return examplesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public java.util.List<? extends com.google.cloud.translate.v3.ExampleOrBuilder>
getExamplesOrBuilderList() {
if (examplesBuilder_ != null) {
return examplesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(examples_);
}
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public com.google.cloud.translate.v3.Example.Builder addExamplesBuilder() {
return getExamplesFieldBuilder()
.addBuilder(com.google.cloud.translate.v3.Example.getDefaultInstance());
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public com.google.cloud.translate.v3.Example.Builder addExamplesBuilder(int index) {
return getExamplesFieldBuilder()
.addBuilder(index, com.google.cloud.translate.v3.Example.getDefaultInstance());
}
/**
*
*
* <pre>
* The sentence pairs.
* </pre>
*
* <code>repeated .google.cloud.translation.v3.Example examples = 1;</code>
*/
public java.util.List<com.google.cloud.translate.v3.Example.Builder> getExamplesBuilderList() {
return getExamplesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.translate.v3.Example,
com.google.cloud.translate.v3.Example.Builder,
com.google.cloud.translate.v3.ExampleOrBuilder>
getExamplesFieldBuilder() {
if (examplesBuilder_ == null) {
examplesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.translate.v3.Example,
com.google.cloud.translate.v3.Example.Builder,
com.google.cloud.translate.v3.ExampleOrBuilder>(
examples_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
examples_ = null;
}
return examplesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to retrieve next page of results.
* Pass this token to the page_token field in the ListExamplesRequest to
* obtain the corresponding 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 this token to the page_token field in the ListExamplesRequest to
* obtain the corresponding 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 this token to the page_token field in the ListExamplesRequest to
* obtain the corresponding 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 this token to the page_token field in the ListExamplesRequest to
* obtain the corresponding 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 this token to the page_token field in the ListExamplesRequest to
* obtain the corresponding 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.translation.v3.ListExamplesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.translation.v3.ListExamplesResponse)
private static final com.google.cloud.translate.v3.ListExamplesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.translate.v3.ListExamplesResponse();
}
public static com.google.cloud.translate.v3.ListExamplesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListExamplesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListExamplesResponse>() {
@java.lang.Override
public ListExamplesResponse 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<ListExamplesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListExamplesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.translate.v3.ListExamplesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 34,738 | java-os-config/proto-google-cloud-os-config-v1alpha/src/main/java/com/google/cloud/osconfig/v1alpha/OsPolicyProto.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/osconfig/v1alpha/os_policy.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.osconfig.v1alpha;
public final class OsPolicyProto {
private OsPolicyProto() {}
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_osconfig_v1alpha_OSPolicy_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_OSFilter_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_OSFilter_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_InventoryFilter_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_InventoryFilter_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_Remote_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_Remote_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_Gcs_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_Gcs_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_Deb_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_Deb_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_APT_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_APT_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_RPM_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_RPM_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_YUM_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_YUM_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_Zypper_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_Zypper_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_GooGet_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_GooGet_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_MSI_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_MSI_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_AptRepository_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_AptRepository_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_YumRepository_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_YumRepository_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_ZypperRepository_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_ZypperRepository_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_GooRepository_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_GooRepository_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_ExecResource_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_ExecResource_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_ExecResource_Exec_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_ExecResource_Exec_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_FileResource_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_FileResource_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_ResourceGroup_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_ResourceGroup_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/osconfig/v1alpha/os_polic"
+ "y.proto\022\035google.cloud.osconfig.v1alpha\032\037google/api/field_behavior.proto\"\204#\n"
+ "\010OSPolicy\022\017\n"
+ "\002id\030\001 \001(\tB\003\340A\002\022\023\n"
+ "\013description\030\002 \001(\t\022?\n"
+ "\004mode\030\003"
+ " \001(\0162,.google.cloud.osconfig.v1alpha.OSPolicy.ModeB\003\340A\002\022S\n"
+ "\017resource_groups\030\004"
+ " \003(\01325.google.cloud.osconfig.v1alpha.OSPolicy.ResourceGroupB\003\340A\002\022%\n"
+ "\035allow_no_resource_group_match\030\005 \001(\010\0325\n"
+ "\010OSFilter\022\025\n\r"
+ "os_short_name\030\001 \001(\t\022\022\n\n"
+ "os_version\030\002 \001(\t\032A\n"
+ "\017InventoryFilter\022\032\n\r"
+ "os_short_name\030\001 \001(\tB\003\340A\002\022\022\n\n"
+ "os_version\030\002 \001(\t\032\342\035\n"
+ "\010Resource\022\017\n"
+ "\002id\030\001 \001(\tB\003\340A\002\022O\n"
+ "\003pkg\030\002 \001(\0132@.g"
+ "oogle.cloud.osconfig.v1alpha.OSPolicy.Resource.PackageResourceH\000\022Y\n\n"
+ "repository\030\003"
+ " \001(\0132C.google.cloud.osconfig.v1alpha.OSPolicy.Resource.RepositoryResourceH\000\022M\n"
+ "\004exec\030\004"
+ " \001(\0132=.google.cloud.osconfig.v1alpha.OSPolicy.Resource.ExecResourceH\000\022M\n"
+ "\004file\030\005"
+ " \001(\0132=.google.cloud.osconfig.v1alpha.OSPolicy.Resource.FileResourceH\000\032\320\002\n"
+ "\004File\022N\n"
+ "\006remote\030\001 \001(\0132<.google.cloud.osconf"
+ "ig.v1alpha.OSPolicy.Resource.File.RemoteH\000\022H\n"
+ "\003gcs\030\002"
+ " \001(\01329.google.cloud.osconfig.v1alpha.OSPolicy.Resource.File.GcsH\000\022\024\n\n"
+ "local_path\030\003 \001(\tH\000\022\026\n"
+ "\016allow_insecure\030\004 \001(\010\0323\n"
+ "\006Remote\022\020\n"
+ "\003uri\030\001 \001(\tB\003\340A\002\022\027\n"
+ "\017sha256_checksum\030\002 \001(\t\032C\n"
+ "\003Gcs\022\023\n"
+ "\006bucket\030\001 \001(\tB\003\340A\002\022\023\n"
+ "\006object\030\002 \001(\tB\003\340A\002\022\022\n\n"
+ "generation\030\003 \001(\003B\006\n"
+ "\004type\032\331\t\n"
+ "\017PackageResource\022i\n\r"
+ "desired_state\030\001 \001(\0162M.google.cloud.osconfig."
+ "v1alpha.OSPolicy.Resource.PackageResource.DesiredStateB\003\340A\002\022S\n"
+ "\003apt\030\002 \001(\0132D.googl"
+ "e.cloud.osconfig.v1alpha.OSPolicy.Resource.PackageResource.APTH\000\022S\n"
+ "\003deb\030\003 \001(\0132D."
+ "google.cloud.osconfig.v1alpha.OSPolicy.Resource.PackageResource.DebH\000\022S\n"
+ "\003yum\030\004 \001"
+ "(\0132D.google.cloud.osconfig.v1alpha.OSPolicy.Resource.PackageResource.YUMH\000\022Y\n"
+ "\006zypper\030\005 \001(\0132G.google.cloud.osconfig.v1alp"
+ "ha.OSPolicy.Resource.PackageResource.ZypperH\000\022S\n"
+ "\003rpm\030\006 \001(\0132D.google.cloud.osconf"
+ "ig.v1alpha.OSPolicy.Resource.PackageResource.RPMH\000\022Y\n"
+ "\006googet\030\007 \001(\0132G.google.clou"
+ "d.osconfig.v1alpha.OSPolicy.Resource.PackageResource.GooGetH\000\022S\n"
+ "\003msi\030\010 \001(\0132D.goo"
+ "gle.cloud.osconfig.v1alpha.OSPolicy.Resource.PackageResource.MSIH\000\032d\n"
+ "\003Deb\022J\n"
+ "\006source\030\001"
+ " \001(\01325.google.cloud.osconfig.v1alpha.OSPolicy.Resource.FileB\003\340A\002\022\021\n"
+ "\tpull_deps\030\002 \001(\010\032\030\n"
+ "\003APT\022\021\n"
+ "\004name\030\001 \001(\tB\003\340A\002\032d\n"
+ "\003RPM\022J\n"
+ "\006source\030\001"
+ " \001(\01325.google.cloud.osconfig.v1alpha.OSPolicy.Resource.FileB\003\340A\002\022\021\n"
+ "\tpull_deps\030\002 \001(\010\032\030\n"
+ "\003YUM\022\021\n"
+ "\004name\030\001 \001(\tB\003\340A\002\032\033\n"
+ "\006Zypper\022\021\n"
+ "\004name\030\001 \001(\tB\003\340A\002\032\033\n"
+ "\006GooGet\022\021\n"
+ "\004name\030\001 \001(\tB\003\340A\002\032e\n"
+ "\003MSI\022J\n"
+ "\006source\030\001 "
+ "\001(\01325.google.cloud.osconfig.v1alpha.OSPolicy.Resource.FileB\003\340A\002\022\022\n\n"
+ "properties\030\002 \003(\t\"I\n"
+ "\014DesiredState\022\035\n"
+ "\031DESIRED_STATE_UNSPECIFIED\020\000\022\r\n"
+ "\tINSTALLED\020\001\022\013\n"
+ "\007REMOVED\020\002B\020\n"
+ "\016system_package\032\321\007\n"
+ "\022RepositoryResource\022`\n"
+ "\003apt\030\001 \001(\0132Q.google.cloud.osconfig.v1a"
+ "lpha.OSPolicy.Resource.RepositoryResource.AptRepositoryH\000\022`\n"
+ "\003yum\030\002 \001(\0132Q.google."
+ "cloud.osconfig.v1alpha.OSPolicy.Resource.RepositoryResource.YumRepositoryH\000\022f\n"
+ "\006zypper\030\003 \001(\0132T.google.cloud.osconfig.v1al"
+ "pha.OSPolicy.Resource.RepositoryResource.ZypperRepositoryH\000\022`\n"
+ "\003goo\030\004 \001(\0132Q.google.cloud.osconfig.v1alpha.OSPolicy.Resour"
+ "ce.RepositoryResource.GooRepositoryH\000\032\243\002\n\r"
+ "AptRepository\022x\n"
+ "\014archive_type\030\001 \001(\0162].google.cloud.osconfig.v1alpha.OSPolicy.R"
+ "esource.RepositoryResource.AptRepository.ArchiveTypeB\003\340A\002\022\020\n"
+ "\003uri\030\002 \001(\tB\003\340A\002\022\031\n"
+ "\014distribution\030\003 \001(\tB\003\340A\002\022\027\n\n"
+ "components\030\004 \003(\tB\003\340A\002\022\017\n"
+ "\007gpg_key\030\005 \001(\t\"A\n"
+ "\013ArchiveType\022\034\n"
+ "\030ARCHIVE_TYPE_UNSPECIFIED\020\000\022\007\n"
+ "\003DEB\020\001\022\013\n"
+ "\007DEB_SRC\020\002\032_\n\r"
+ "YumRepository\022\017\n"
+ "\002id\030\001 \001(\tB\003\340A\002\022\024\n"
+ "\014display_name\030\002 \001(\t\022\025\n"
+ "\010base_url\030\003 \001(\tB\003\340A\002\022\020\n"
+ "\010gpg_keys\030\004 \003(\t\032b\n"
+ "\020ZypperRepository\022\017\n"
+ "\002id\030\001 \001(\tB\003\340A\002\022\024\n"
+ "\014display_name\030\002 \001(\t\022\025\n"
+ "\010base_url\030\003 \001(\tB\003\340A\002\022\020\n"
+ "\010gpg_keys\030\004 \003(\t\0324\n\r"
+ "GooRepository\022\021\n"
+ "\004name\030\001 \001(\tB\003\340A\002\022\020\n"
+ "\003url\030\002 \001(\tB\003\340A\002B\014\n\n"
+ "repository\032\215\004\n"
+ "\014ExecResource\022Y\n"
+ "\010validate\030\001 \001(\0132B.google"
+ ".cloud.osconfig.v1alpha.OSPolicy.Resource.ExecResource.ExecB\003\340A\002\022S\n"
+ "\007enforce\030\002 \001("
+ "\0132B.google.cloud.osconfig.v1alpha.OSPolicy.Resource.ExecResource.Exec\032\314\002\n"
+ "\004Exec\022E\n"
+ "\004file\030\001"
+ " \001(\01325.google.cloud.osconfig.v1alpha.OSPolicy.Resource.FileH\000\022\020\n"
+ "\006script\030\002 \001(\tH\000\022\014\n"
+ "\004args\030\003 \003(\t\022h\n"
+ "\013interpreter\030\004 \001(\0162N.google.cloud.osconfig.v1alpha.OSPol"
+ "icy.Resource.ExecResource.Exec.InterpreterB\003\340A\002\022\030\n"
+ "\020output_file_path\030\005 \001(\t\"O\n"
+ "\013Interpreter\022\033\n"
+ "\027INTERPRETER_UNSPECIFIED\020\000\022\010\n"
+ "\004NONE\020\001\022\t\n"
+ "\005SHELL\020\002\022\016\n\n"
+ "POWERSHELL\020\003B\010\n"
+ "\006source\032\326\002\n"
+ "\014FileResource\022E\n"
+ "\004file\030\001 \001(\01325.go"
+ "ogle.cloud.osconfig.v1alpha.OSPolicy.Resource.FileH\000\022\021\n"
+ "\007content\030\002 \001(\tH\000\022\021\n"
+ "\004path\030\003 \001(\tB\003\340A\002\022^\n"
+ "\005state\030\004 \001(\0162J.google.cloud"
+ ".osconfig.v1alpha.OSPolicy.Resource.FileResource.DesiredStateB\003\340A\002\022\023\n"
+ "\013permissions\030\005 \001(\t\"Z\n"
+ "\014DesiredState\022\035\n"
+ "\031DESIRED_STATE_UNSPECIFIED\020\000\022\013\n"
+ "\007PRESENT\020\001\022\n\n"
+ "\006ABSENT\020\002\022\022\n"
+ "\016CONTENTS_MATCH\020\003B\010\n"
+ "\006sourceB\017\n\r"
+ "resource_type\032\366\001\n\r"
+ "ResourceGroup\022G\n"
+ "\tos_filter\030\001 "
+ "\001(\01320.google.cloud.osconfig.v1alpha.OSPolicy.OSFilterB\002\030\001\022R\n"
+ "\021inventory_filters\030\003"
+ " \003(\01327.google.cloud.osconfig.v1alpha.OSPolicy.InventoryFilter\022H\n"
+ "\tresources\030\002 \003(\013"
+ "20.google.cloud.osconfig.v1alpha.OSPolicy.ResourceB\003\340A\002\"=\n"
+ "\004Mode\022\024\n"
+ "\020MODE_UNSPECIFIED\020\000\022\016\n\n"
+ "VALIDATION\020\001\022\017\n"
+ "\013ENFORCEMENT\020\002B\326\001\n"
+ "!com.google.cloud.osconfig.v1alphaB\r"
+ "OsPolicyProtoP\001Z=cloud.google.com/go/oscon"
+ "fig/apiv1alpha/osconfigpb;osconfigpb\252\002\035G"
+ "oogle.Cloud.OsConfig.V1Alpha\312\002\035Google\\Cloud\\OsConfig\\V1alpha\352\002"
+ " Google::Cloud::OsConfig::V1alphab\006proto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.FieldBehaviorProto.getDescriptor(),
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_descriptor,
new java.lang.String[] {
"Id", "Description", "Mode", "ResourceGroups", "AllowNoResourceGroupMatch",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_OSFilter_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_descriptor.getNestedTypes().get(0);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_OSFilter_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_OSFilter_descriptor,
new java.lang.String[] {
"OsShortName", "OsVersion",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_InventoryFilter_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_descriptor.getNestedTypes().get(1);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_InventoryFilter_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_InventoryFilter_descriptor,
new java.lang.String[] {
"OsShortName", "OsVersion",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_descriptor.getNestedTypes().get(2);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_descriptor,
new java.lang.String[] {
"Id", "Pkg", "Repository", "Exec", "File", "ResourceType",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_descriptor,
new java.lang.String[] {
"Remote", "Gcs", "LocalPath", "AllowInsecure", "Type",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_Remote_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_Remote_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_Remote_descriptor,
new java.lang.String[] {
"Uri", "Sha256Checksum",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_Gcs_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_descriptor
.getNestedTypes()
.get(1);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_Gcs_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_File_Gcs_descriptor,
new java.lang.String[] {
"Bucket", "Object", "Generation",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_descriptor
.getNestedTypes()
.get(1);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_descriptor,
new java.lang.String[] {
"DesiredState",
"Apt",
"Deb",
"Yum",
"Zypper",
"Rpm",
"Googet",
"Msi",
"SystemPackage",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_Deb_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_Deb_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_Deb_descriptor,
new java.lang.String[] {
"Source", "PullDeps",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_APT_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_descriptor
.getNestedTypes()
.get(1);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_APT_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_APT_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_RPM_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_descriptor
.getNestedTypes()
.get(2);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_RPM_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_RPM_descriptor,
new java.lang.String[] {
"Source", "PullDeps",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_YUM_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_descriptor
.getNestedTypes()
.get(3);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_YUM_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_YUM_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_Zypper_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_descriptor
.getNestedTypes()
.get(4);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_Zypper_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_Zypper_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_GooGet_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_descriptor
.getNestedTypes()
.get(5);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_GooGet_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_GooGet_descriptor,
new java.lang.String[] {
"Name",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_MSI_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_descriptor
.getNestedTypes()
.get(6);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_MSI_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_PackageResource_MSI_descriptor,
new java.lang.String[] {
"Source", "Properties",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_descriptor
.getNestedTypes()
.get(2);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_descriptor,
new java.lang.String[] {
"Apt", "Yum", "Zypper", "Goo", "Repository",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_AptRepository_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_AptRepository_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_AptRepository_descriptor,
new java.lang.String[] {
"ArchiveType", "Uri", "Distribution", "Components", "GpgKey",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_YumRepository_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_descriptor
.getNestedTypes()
.get(1);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_YumRepository_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_YumRepository_descriptor,
new java.lang.String[] {
"Id", "DisplayName", "BaseUrl", "GpgKeys",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_ZypperRepository_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_descriptor
.getNestedTypes()
.get(2);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_ZypperRepository_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_ZypperRepository_descriptor,
new java.lang.String[] {
"Id", "DisplayName", "BaseUrl", "GpgKeys",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_GooRepository_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_descriptor
.getNestedTypes()
.get(3);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_GooRepository_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_RepositoryResource_GooRepository_descriptor,
new java.lang.String[] {
"Name", "Url",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_ExecResource_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_descriptor
.getNestedTypes()
.get(3);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_ExecResource_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_ExecResource_descriptor,
new java.lang.String[] {
"Validate", "Enforce",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_ExecResource_Exec_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_ExecResource_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_ExecResource_Exec_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_ExecResource_Exec_descriptor,
new java.lang.String[] {
"File", "Script", "Args", "Interpreter", "OutputFilePath", "Source",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_FileResource_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_descriptor
.getNestedTypes()
.get(4);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_FileResource_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_Resource_FileResource_descriptor,
new java.lang.String[] {
"File", "Content", "Path", "State", "Permissions", "Source",
});
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_ResourceGroup_descriptor =
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_descriptor.getNestedTypes().get(3);
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_ResourceGroup_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_osconfig_v1alpha_OSPolicy_ResourceGroup_descriptor,
new java.lang.String[] {
"OsFilter", "InventoryFilters", "Resources",
});
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor(
descriptor, registry);
com.google.api.FieldBehaviorProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
googleapis/google-cloud-java | 35,822 | java-dialogflow/grpc-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/PhoneNumbersGrpc.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.dialogflow.v2beta1;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
*
*
* <pre>
* Service for managing
* [PhoneNumbers][google.cloud.dialogflow.v2beta1.PhoneNumber].
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: google/cloud/dialogflow/v2beta1/phone_number.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class PhoneNumbersGrpc {
private PhoneNumbersGrpc() {}
public static final java.lang.String SERVICE_NAME =
"google.cloud.dialogflow.v2beta1.PhoneNumbers";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest,
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse>
getListPhoneNumbersMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "ListPhoneNumbers",
requestType = com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest.class,
responseType = com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest,
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse>
getListPhoneNumbersMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest,
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse>
getListPhoneNumbersMethod;
if ((getListPhoneNumbersMethod = PhoneNumbersGrpc.getListPhoneNumbersMethod) == null) {
synchronized (PhoneNumbersGrpc.class) {
if ((getListPhoneNumbersMethod = PhoneNumbersGrpc.getListPhoneNumbersMethod) == null) {
PhoneNumbersGrpc.getListPhoneNumbersMethod =
getListPhoneNumbersMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest,
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "ListPhoneNumbers"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse
.getDefaultInstance()))
.setSchemaDescriptor(
new PhoneNumbersMethodDescriptorSupplier("ListPhoneNumbers"))
.build();
}
}
}
return getListPhoneNumbersMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
getUpdatePhoneNumberMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "UpdatePhoneNumber",
requestType = com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest.class,
responseType = com.google.cloud.dialogflow.v2beta1.PhoneNumber.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
getUpdatePhoneNumberMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
getUpdatePhoneNumberMethod;
if ((getUpdatePhoneNumberMethod = PhoneNumbersGrpc.getUpdatePhoneNumberMethod) == null) {
synchronized (PhoneNumbersGrpc.class) {
if ((getUpdatePhoneNumberMethod = PhoneNumbersGrpc.getUpdatePhoneNumberMethod) == null) {
PhoneNumbersGrpc.getUpdatePhoneNumberMethod =
getUpdatePhoneNumberMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "UpdatePhoneNumber"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.PhoneNumber.getDefaultInstance()))
.setSchemaDescriptor(
new PhoneNumbersMethodDescriptorSupplier("UpdatePhoneNumber"))
.build();
}
}
}
return getUpdatePhoneNumberMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
getDeletePhoneNumberMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "DeletePhoneNumber",
requestType = com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest.class,
responseType = com.google.cloud.dialogflow.v2beta1.PhoneNumber.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
getDeletePhoneNumberMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
getDeletePhoneNumberMethod;
if ((getDeletePhoneNumberMethod = PhoneNumbersGrpc.getDeletePhoneNumberMethod) == null) {
synchronized (PhoneNumbersGrpc.class) {
if ((getDeletePhoneNumberMethod = PhoneNumbersGrpc.getDeletePhoneNumberMethod) == null) {
PhoneNumbersGrpc.getDeletePhoneNumberMethod =
getDeletePhoneNumberMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "DeletePhoneNumber"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.PhoneNumber.getDefaultInstance()))
.setSchemaDescriptor(
new PhoneNumbersMethodDescriptorSupplier("DeletePhoneNumber"))
.build();
}
}
}
return getDeletePhoneNumberMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
getUndeletePhoneNumberMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "UndeletePhoneNumber",
requestType = com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest.class,
responseType = com.google.cloud.dialogflow.v2beta1.PhoneNumber.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
getUndeletePhoneNumberMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
getUndeletePhoneNumberMethod;
if ((getUndeletePhoneNumberMethod = PhoneNumbersGrpc.getUndeletePhoneNumberMethod) == null) {
synchronized (PhoneNumbersGrpc.class) {
if ((getUndeletePhoneNumberMethod = PhoneNumbersGrpc.getUndeletePhoneNumberMethod)
== null) {
PhoneNumbersGrpc.getUndeletePhoneNumberMethod =
getUndeletePhoneNumberMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
generateFullMethodName(SERVICE_NAME, "UndeletePhoneNumber"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.dialogflow.v2beta1.PhoneNumber.getDefaultInstance()))
.setSchemaDescriptor(
new PhoneNumbersMethodDescriptorSupplier("UndeletePhoneNumber"))
.build();
}
}
}
return getUndeletePhoneNumberMethod;
}
/** Creates a new async stub that supports all call types for the service */
public static PhoneNumbersStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<PhoneNumbersStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<PhoneNumbersStub>() {
@java.lang.Override
public PhoneNumbersStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PhoneNumbersStub(channel, callOptions);
}
};
return PhoneNumbersStub.newStub(factory, channel);
}
/** Creates a new blocking-style stub that supports all types of calls on the service */
public static PhoneNumbersBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<PhoneNumbersBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<PhoneNumbersBlockingV2Stub>() {
@java.lang.Override
public PhoneNumbersBlockingV2Stub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PhoneNumbersBlockingV2Stub(channel, callOptions);
}
};
return PhoneNumbersBlockingV2Stub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static PhoneNumbersBlockingStub newBlockingStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<PhoneNumbersBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<PhoneNumbersBlockingStub>() {
@java.lang.Override
public PhoneNumbersBlockingStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PhoneNumbersBlockingStub(channel, callOptions);
}
};
return PhoneNumbersBlockingStub.newStub(factory, channel);
}
/** Creates a new ListenableFuture-style stub that supports unary calls on the service */
public static PhoneNumbersFutureStub newFutureStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<PhoneNumbersFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<PhoneNumbersFutureStub>() {
@java.lang.Override
public PhoneNumbersFutureStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PhoneNumbersFutureStub(channel, callOptions);
}
};
return PhoneNumbersFutureStub.newStub(factory, channel);
}
/**
*
*
* <pre>
* Service for managing
* [PhoneNumbers][google.cloud.dialogflow.v2beta1.PhoneNumber].
* </pre>
*/
public interface AsyncService {
/**
*
*
* <pre>
* Returns the list of all phone numbers in the specified project.
* </pre>
*/
default void listPhoneNumbers(
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getListPhoneNumbersMethod(), responseObserver);
}
/**
*
*
* <pre>
* Updates the specified `PhoneNumber`.
* </pre>
*/
default void updatePhoneNumber(
com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.PhoneNumber>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getUpdatePhoneNumberMethod(), responseObserver);
}
/**
*
*
* <pre>
* Requests deletion of a `PhoneNumber`. The `PhoneNumber` is moved into the
* [DELETE_REQUESTED][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.DELETE_REQUESTED]
* state immediately, and is deleted approximately 30 days later. This method
* may only be called on a `PhoneNumber` in the
* [ACTIVE][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.ACTIVE]
* state.
* </pre>
*/
default void deletePhoneNumber(
com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.PhoneNumber>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getDeletePhoneNumberMethod(), responseObserver);
}
/**
*
*
* <pre>
* Cancels the deletion request for a `PhoneNumber`. This method may only be
* called on a `PhoneNumber` in the
* [DELETE_REQUESTED][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.DELETE_REQUESTED]
* state.
* </pre>
*/
default void undeletePhoneNumber(
com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.PhoneNumber>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getUndeletePhoneNumberMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service PhoneNumbers.
*
* <pre>
* Service for managing
* [PhoneNumbers][google.cloud.dialogflow.v2beta1.PhoneNumber].
* </pre>
*/
public abstract static class PhoneNumbersImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override
public final io.grpc.ServerServiceDefinition bindService() {
return PhoneNumbersGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service PhoneNumbers.
*
* <pre>
* Service for managing
* [PhoneNumbers][google.cloud.dialogflow.v2beta1.PhoneNumber].
* </pre>
*/
public static final class PhoneNumbersStub
extends io.grpc.stub.AbstractAsyncStub<PhoneNumbersStub> {
private PhoneNumbersStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected PhoneNumbersStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PhoneNumbersStub(channel, callOptions);
}
/**
*
*
* <pre>
* Returns the list of all phone numbers in the specified project.
* </pre>
*/
public void listPhoneNumbers(
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getListPhoneNumbersMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Updates the specified `PhoneNumber`.
* </pre>
*/
public void updatePhoneNumber(
com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.PhoneNumber>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getUpdatePhoneNumberMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Requests deletion of a `PhoneNumber`. The `PhoneNumber` is moved into the
* [DELETE_REQUESTED][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.DELETE_REQUESTED]
* state immediately, and is deleted approximately 30 days later. This method
* may only be called on a `PhoneNumber` in the
* [ACTIVE][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.ACTIVE]
* state.
* </pre>
*/
public void deletePhoneNumber(
com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.PhoneNumber>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getDeletePhoneNumberMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Cancels the deletion request for a `PhoneNumber`. This method may only be
* called on a `PhoneNumber` in the
* [DELETE_REQUESTED][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.DELETE_REQUESTED]
* state.
* </pre>
*/
public void undeletePhoneNumber(
com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.PhoneNumber>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getUndeletePhoneNumberMethod(), getCallOptions()),
request,
responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service PhoneNumbers.
*
* <pre>
* Service for managing
* [PhoneNumbers][google.cloud.dialogflow.v2beta1.PhoneNumber].
* </pre>
*/
public static final class PhoneNumbersBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<PhoneNumbersBlockingV2Stub> {
private PhoneNumbersBlockingV2Stub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected PhoneNumbersBlockingV2Stub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PhoneNumbersBlockingV2Stub(channel, callOptions);
}
/**
*
*
* <pre>
* Returns the list of all phone numbers in the specified project.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse listPhoneNumbers(
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListPhoneNumbersMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Updates the specified `PhoneNumber`.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.PhoneNumber updatePhoneNumber(
com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUpdatePhoneNumberMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Requests deletion of a `PhoneNumber`. The `PhoneNumber` is moved into the
* [DELETE_REQUESTED][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.DELETE_REQUESTED]
* state immediately, and is deleted approximately 30 days later. This method
* may only be called on a `PhoneNumber` in the
* [ACTIVE][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.ACTIVE]
* state.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.PhoneNumber deletePhoneNumber(
com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeletePhoneNumberMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Cancels the deletion request for a `PhoneNumber`. This method may only be
* called on a `PhoneNumber` in the
* [DELETE_REQUESTED][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.DELETE_REQUESTED]
* state.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.PhoneNumber undeletePhoneNumber(
com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUndeletePhoneNumberMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do limited synchronous rpc calls to service PhoneNumbers.
*
* <pre>
* Service for managing
* [PhoneNumbers][google.cloud.dialogflow.v2beta1.PhoneNumber].
* </pre>
*/
public static final class PhoneNumbersBlockingStub
extends io.grpc.stub.AbstractBlockingStub<PhoneNumbersBlockingStub> {
private PhoneNumbersBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected PhoneNumbersBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PhoneNumbersBlockingStub(channel, callOptions);
}
/**
*
*
* <pre>
* Returns the list of all phone numbers in the specified project.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse listPhoneNumbers(
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListPhoneNumbersMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Updates the specified `PhoneNumber`.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.PhoneNumber updatePhoneNumber(
com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUpdatePhoneNumberMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Requests deletion of a `PhoneNumber`. The `PhoneNumber` is moved into the
* [DELETE_REQUESTED][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.DELETE_REQUESTED]
* state immediately, and is deleted approximately 30 days later. This method
* may only be called on a `PhoneNumber` in the
* [ACTIVE][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.ACTIVE]
* state.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.PhoneNumber deletePhoneNumber(
com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeletePhoneNumberMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Cancels the deletion request for a `PhoneNumber`. This method may only be
* called on a `PhoneNumber` in the
* [DELETE_REQUESTED][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.DELETE_REQUESTED]
* state.
* </pre>
*/
public com.google.cloud.dialogflow.v2beta1.PhoneNumber undeletePhoneNumber(
com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getUndeletePhoneNumberMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service PhoneNumbers.
*
* <pre>
* Service for managing
* [PhoneNumbers][google.cloud.dialogflow.v2beta1.PhoneNumber].
* </pre>
*/
public static final class PhoneNumbersFutureStub
extends io.grpc.stub.AbstractFutureStub<PhoneNumbersFutureStub> {
private PhoneNumbersFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected PhoneNumbersFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PhoneNumbersFutureStub(channel, callOptions);
}
/**
*
*
* <pre>
* Returns the list of all phone numbers in the specified project.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse>
listPhoneNumbers(com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getListPhoneNumbersMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Updates the specified `PhoneNumber`.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
updatePhoneNumber(com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUpdatePhoneNumberMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Requests deletion of a `PhoneNumber`. The `PhoneNumber` is moved into the
* [DELETE_REQUESTED][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.DELETE_REQUESTED]
* state immediately, and is deleted approximately 30 days later. This method
* may only be called on a `PhoneNumber` in the
* [ACTIVE][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.ACTIVE]
* state.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
deletePhoneNumber(com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getDeletePhoneNumberMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Cancels the deletion request for a `PhoneNumber`. This method may only be
* called on a `PhoneNumber` in the
* [DELETE_REQUESTED][google.cloud.dialogflow.v2beta1.PhoneNumber.LifecycleState.DELETE_REQUESTED]
* state.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.dialogflow.v2beta1.PhoneNumber>
undeletePhoneNumber(
com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getUndeletePhoneNumberMethod(), getCallOptions()), request);
}
}
private static final int METHODID_LIST_PHONE_NUMBERS = 0;
private static final int METHODID_UPDATE_PHONE_NUMBER = 1;
private static final int METHODID_DELETE_PHONE_NUMBER = 2;
private static final int METHODID_UNDELETE_PHONE_NUMBER = 3;
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_PHONE_NUMBERS:
serviceImpl.listPhoneNumbers(
(com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest) request,
(io.grpc.stub.StreamObserver<
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse>)
responseObserver);
break;
case METHODID_UPDATE_PHONE_NUMBER:
serviceImpl.updatePhoneNumber(
(com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.PhoneNumber>)
responseObserver);
break;
case METHODID_DELETE_PHONE_NUMBER:
serviceImpl.deletePhoneNumber(
(com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.PhoneNumber>)
responseObserver);
break;
case METHODID_UNDELETE_PHONE_NUMBER:
serviceImpl.undeletePhoneNumber(
(com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.dialogflow.v2beta1.PhoneNumber>)
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(
getListPhoneNumbersMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersRequest,
com.google.cloud.dialogflow.v2beta1.ListPhoneNumbersResponse>(
service, METHODID_LIST_PHONE_NUMBERS)))
.addMethod(
getUpdatePhoneNumberMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2beta1.UpdatePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>(
service, METHODID_UPDATE_PHONE_NUMBER)))
.addMethod(
getDeletePhoneNumberMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2beta1.DeletePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>(
service, METHODID_DELETE_PHONE_NUMBER)))
.addMethod(
getUndeletePhoneNumberMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.dialogflow.v2beta1.UndeletePhoneNumberRequest,
com.google.cloud.dialogflow.v2beta1.PhoneNumber>(
service, METHODID_UNDELETE_PHONE_NUMBER)))
.build();
}
private abstract static class PhoneNumbersBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier,
io.grpc.protobuf.ProtoServiceDescriptorSupplier {
PhoneNumbersBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.google.cloud.dialogflow.v2beta1.PhoneNumberProto.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("PhoneNumbers");
}
}
private static final class PhoneNumbersFileDescriptorSupplier
extends PhoneNumbersBaseDescriptorSupplier {
PhoneNumbersFileDescriptorSupplier() {}
}
private static final class PhoneNumbersMethodDescriptorSupplier
extends PhoneNumbersBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final java.lang.String methodName;
PhoneNumbersMethodDescriptorSupplier(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 (PhoneNumbersGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor =
result =
io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new PhoneNumbersFileDescriptorSupplier())
.addMethod(getListPhoneNumbersMethod())
.addMethod(getUpdatePhoneNumberMethod())
.addMethod(getDeletePhoneNumberMethod())
.addMethod(getUndeletePhoneNumberMethod())
.build();
}
}
}
return result;
}
}
|
googleapis/google-cloud-java | 35,529 | java-deploy/proto-google-cloud-deploy-v1/src/main/java/com/google/cloud/deploy/v1/DeployPolicyNotificationEvent.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/deploy/v1/deploypolicy_notification_payload.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.deploy.v1;
/**
*
*
* <pre>
* Payload proto for "clouddeploy.googleapis.com/deploypolicy_notification".
* Platform Log event that describes the failure to send a pub/sub notification
* when there is a DeployPolicy status change.
* </pre>
*
* Protobuf type {@code google.cloud.deploy.v1.DeployPolicyNotificationEvent}
*/
public final class DeployPolicyNotificationEvent extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.deploy.v1.DeployPolicyNotificationEvent)
DeployPolicyNotificationEventOrBuilder {
private static final long serialVersionUID = 0L;
// Use DeployPolicyNotificationEvent.newBuilder() to construct.
private DeployPolicyNotificationEvent(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private DeployPolicyNotificationEvent() {
message_ = "";
deployPolicy_ = "";
deployPolicyUid_ = "";
type_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new DeployPolicyNotificationEvent();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.deploy.v1.DeployPolicyNotificationPayloadProto
.internal_static_google_cloud_deploy_v1_DeployPolicyNotificationEvent_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.deploy.v1.DeployPolicyNotificationPayloadProto
.internal_static_google_cloud_deploy_v1_DeployPolicyNotificationEvent_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.deploy.v1.DeployPolicyNotificationEvent.class,
com.google.cloud.deploy.v1.DeployPolicyNotificationEvent.Builder.class);
}
public static final int MESSAGE_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object message_ = "";
/**
*
*
* <pre>
* Debug message for when a deploy policy fails to send a pub/sub
* notification.
* </pre>
*
* <code>string message = 1;</code>
*
* @return The message.
*/
@java.lang.Override
public java.lang.String getMessage() {
java.lang.Object ref = message_;
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();
message_ = s;
return s;
}
}
/**
*
*
* <pre>
* Debug message for when a deploy policy fails to send a pub/sub
* notification.
* </pre>
*
* <code>string message = 1;</code>
*
* @return The bytes for message.
*/
@java.lang.Override
public com.google.protobuf.ByteString getMessageBytes() {
java.lang.Object ref = message_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
message_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DEPLOY_POLICY_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object deployPolicy_ = "";
/**
*
*
* <pre>
* The name of the `DeployPolicy`.
* </pre>
*
* <code>string deploy_policy = 2;</code>
*
* @return The deployPolicy.
*/
@java.lang.Override
public java.lang.String getDeployPolicy() {
java.lang.Object ref = deployPolicy_;
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();
deployPolicy_ = s;
return s;
}
}
/**
*
*
* <pre>
* The name of the `DeployPolicy`.
* </pre>
*
* <code>string deploy_policy = 2;</code>
*
* @return The bytes for deployPolicy.
*/
@java.lang.Override
public com.google.protobuf.ByteString getDeployPolicyBytes() {
java.lang.Object ref = deployPolicy_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
deployPolicy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DEPLOY_POLICY_UID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object deployPolicyUid_ = "";
/**
*
*
* <pre>
* Unique identifier of the deploy policy.
* </pre>
*
* <code>string deploy_policy_uid = 3;</code>
*
* @return The deployPolicyUid.
*/
@java.lang.Override
public java.lang.String getDeployPolicyUid() {
java.lang.Object ref = deployPolicyUid_;
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();
deployPolicyUid_ = s;
return s;
}
}
/**
*
*
* <pre>
* Unique identifier of the deploy policy.
* </pre>
*
* <code>string deploy_policy_uid = 3;</code>
*
* @return The bytes for deployPolicyUid.
*/
@java.lang.Override
public com.google.protobuf.ByteString getDeployPolicyUidBytes() {
java.lang.Object ref = deployPolicyUid_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
deployPolicyUid_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TYPE_FIELD_NUMBER = 4;
private int type_ = 0;
/**
*
*
* <pre>
* Type of this notification, e.g. for a Pub/Sub failure.
* </pre>
*
* <code>.google.cloud.deploy.v1.Type type = 4;</code>
*
* @return The enum numeric value on the wire for type.
*/
@java.lang.Override
public int getTypeValue() {
return type_;
}
/**
*
*
* <pre>
* Type of this notification, e.g. for a Pub/Sub failure.
* </pre>
*
* <code>.google.cloud.deploy.v1.Type type = 4;</code>
*
* @return The type.
*/
@java.lang.Override
public com.google.cloud.deploy.v1.Type getType() {
com.google.cloud.deploy.v1.Type result = com.google.cloud.deploy.v1.Type.forNumber(type_);
return result == null ? com.google.cloud.deploy.v1.Type.UNRECOGNIZED : result;
}
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(message_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, message_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(deployPolicy_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, deployPolicy_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(deployPolicyUid_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, deployPolicyUid_);
}
if (type_ != com.google.cloud.deploy.v1.Type.TYPE_UNSPECIFIED.getNumber()) {
output.writeEnum(4, type_);
}
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(message_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, message_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(deployPolicy_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, deployPolicy_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(deployPolicyUid_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, deployPolicyUid_);
}
if (type_ != com.google.cloud.deploy.v1.Type.TYPE_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(4, type_);
}
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.deploy.v1.DeployPolicyNotificationEvent)) {
return super.equals(obj);
}
com.google.cloud.deploy.v1.DeployPolicyNotificationEvent other =
(com.google.cloud.deploy.v1.DeployPolicyNotificationEvent) obj;
if (!getMessage().equals(other.getMessage())) return false;
if (!getDeployPolicy().equals(other.getDeployPolicy())) return false;
if (!getDeployPolicyUid().equals(other.getDeployPolicyUid())) return false;
if (type_ != other.type_) 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) + MESSAGE_FIELD_NUMBER;
hash = (53 * hash) + getMessage().hashCode();
hash = (37 * hash) + DEPLOY_POLICY_FIELD_NUMBER;
hash = (53 * hash) + getDeployPolicy().hashCode();
hash = (37 * hash) + DEPLOY_POLICY_UID_FIELD_NUMBER;
hash = (53 * hash) + getDeployPolicyUid().hashCode();
hash = (37 * hash) + TYPE_FIELD_NUMBER;
hash = (53 * hash) + type_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.deploy.v1.DeployPolicyNotificationEvent parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.deploy.v1.DeployPolicyNotificationEvent 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.deploy.v1.DeployPolicyNotificationEvent parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.deploy.v1.DeployPolicyNotificationEvent 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.deploy.v1.DeployPolicyNotificationEvent parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.deploy.v1.DeployPolicyNotificationEvent parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.deploy.v1.DeployPolicyNotificationEvent parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.deploy.v1.DeployPolicyNotificationEvent 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.deploy.v1.DeployPolicyNotificationEvent parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.deploy.v1.DeployPolicyNotificationEvent 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.deploy.v1.DeployPolicyNotificationEvent parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.deploy.v1.DeployPolicyNotificationEvent 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.deploy.v1.DeployPolicyNotificationEvent 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>
* Payload proto for "clouddeploy.googleapis.com/deploypolicy_notification".
* Platform Log event that describes the failure to send a pub/sub notification
* when there is a DeployPolicy status change.
* </pre>
*
* Protobuf type {@code google.cloud.deploy.v1.DeployPolicyNotificationEvent}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.deploy.v1.DeployPolicyNotificationEvent)
com.google.cloud.deploy.v1.DeployPolicyNotificationEventOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.deploy.v1.DeployPolicyNotificationPayloadProto
.internal_static_google_cloud_deploy_v1_DeployPolicyNotificationEvent_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.deploy.v1.DeployPolicyNotificationPayloadProto
.internal_static_google_cloud_deploy_v1_DeployPolicyNotificationEvent_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.deploy.v1.DeployPolicyNotificationEvent.class,
com.google.cloud.deploy.v1.DeployPolicyNotificationEvent.Builder.class);
}
// Construct using com.google.cloud.deploy.v1.DeployPolicyNotificationEvent.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
message_ = "";
deployPolicy_ = "";
deployPolicyUid_ = "";
type_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.deploy.v1.DeployPolicyNotificationPayloadProto
.internal_static_google_cloud_deploy_v1_DeployPolicyNotificationEvent_descriptor;
}
@java.lang.Override
public com.google.cloud.deploy.v1.DeployPolicyNotificationEvent getDefaultInstanceForType() {
return com.google.cloud.deploy.v1.DeployPolicyNotificationEvent.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.deploy.v1.DeployPolicyNotificationEvent build() {
com.google.cloud.deploy.v1.DeployPolicyNotificationEvent result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.deploy.v1.DeployPolicyNotificationEvent buildPartial() {
com.google.cloud.deploy.v1.DeployPolicyNotificationEvent result =
new com.google.cloud.deploy.v1.DeployPolicyNotificationEvent(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.deploy.v1.DeployPolicyNotificationEvent result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.message_ = message_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.deployPolicy_ = deployPolicy_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.deployPolicyUid_ = deployPolicyUid_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.type_ = type_;
}
}
@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.deploy.v1.DeployPolicyNotificationEvent) {
return mergeFrom((com.google.cloud.deploy.v1.DeployPolicyNotificationEvent) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.deploy.v1.DeployPolicyNotificationEvent other) {
if (other == com.google.cloud.deploy.v1.DeployPolicyNotificationEvent.getDefaultInstance())
return this;
if (!other.getMessage().isEmpty()) {
message_ = other.message_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getDeployPolicy().isEmpty()) {
deployPolicy_ = other.deployPolicy_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getDeployPolicyUid().isEmpty()) {
deployPolicyUid_ = other.deployPolicyUid_;
bitField0_ |= 0x00000004;
onChanged();
}
if (other.type_ != 0) {
setTypeValue(other.getTypeValue());
}
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:
{
message_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
deployPolicy_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
deployPolicyUid_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 32:
{
type_ = input.readEnum();
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 java.lang.Object message_ = "";
/**
*
*
* <pre>
* Debug message for when a deploy policy fails to send a pub/sub
* notification.
* </pre>
*
* <code>string message = 1;</code>
*
* @return The message.
*/
public java.lang.String getMessage() {
java.lang.Object ref = message_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
message_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Debug message for when a deploy policy fails to send a pub/sub
* notification.
* </pre>
*
* <code>string message = 1;</code>
*
* @return The bytes for message.
*/
public com.google.protobuf.ByteString getMessageBytes() {
java.lang.Object ref = message_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
message_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Debug message for when a deploy policy fails to send a pub/sub
* notification.
* </pre>
*
* <code>string message = 1;</code>
*
* @param value The message to set.
* @return This builder for chaining.
*/
public Builder setMessage(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
message_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Debug message for when a deploy policy fails to send a pub/sub
* notification.
* </pre>
*
* <code>string message = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearMessage() {
message_ = getDefaultInstance().getMessage();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Debug message for when a deploy policy fails to send a pub/sub
* notification.
* </pre>
*
* <code>string message = 1;</code>
*
* @param value The bytes for message to set.
* @return This builder for chaining.
*/
public Builder setMessageBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
message_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object deployPolicy_ = "";
/**
*
*
* <pre>
* The name of the `DeployPolicy`.
* </pre>
*
* <code>string deploy_policy = 2;</code>
*
* @return The deployPolicy.
*/
public java.lang.String getDeployPolicy() {
java.lang.Object ref = deployPolicy_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
deployPolicy_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The name of the `DeployPolicy`.
* </pre>
*
* <code>string deploy_policy = 2;</code>
*
* @return The bytes for deployPolicy.
*/
public com.google.protobuf.ByteString getDeployPolicyBytes() {
java.lang.Object ref = deployPolicy_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
deployPolicy_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The name of the `DeployPolicy`.
* </pre>
*
* <code>string deploy_policy = 2;</code>
*
* @param value The deployPolicy to set.
* @return This builder for chaining.
*/
public Builder setDeployPolicy(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
deployPolicy_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the `DeployPolicy`.
* </pre>
*
* <code>string deploy_policy = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearDeployPolicy() {
deployPolicy_ = getDefaultInstance().getDeployPolicy();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the `DeployPolicy`.
* </pre>
*
* <code>string deploy_policy = 2;</code>
*
* @param value The bytes for deployPolicy to set.
* @return This builder for chaining.
*/
public Builder setDeployPolicyBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
deployPolicy_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object deployPolicyUid_ = "";
/**
*
*
* <pre>
* Unique identifier of the deploy policy.
* </pre>
*
* <code>string deploy_policy_uid = 3;</code>
*
* @return The deployPolicyUid.
*/
public java.lang.String getDeployPolicyUid() {
java.lang.Object ref = deployPolicyUid_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
deployPolicyUid_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Unique identifier of the deploy policy.
* </pre>
*
* <code>string deploy_policy_uid = 3;</code>
*
* @return The bytes for deployPolicyUid.
*/
public com.google.protobuf.ByteString getDeployPolicyUidBytes() {
java.lang.Object ref = deployPolicyUid_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
deployPolicyUid_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Unique identifier of the deploy policy.
* </pre>
*
* <code>string deploy_policy_uid = 3;</code>
*
* @param value The deployPolicyUid to set.
* @return This builder for chaining.
*/
public Builder setDeployPolicyUid(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
deployPolicyUid_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Unique identifier of the deploy policy.
* </pre>
*
* <code>string deploy_policy_uid = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearDeployPolicyUid() {
deployPolicyUid_ = getDefaultInstance().getDeployPolicyUid();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Unique identifier of the deploy policy.
* </pre>
*
* <code>string deploy_policy_uid = 3;</code>
*
* @param value The bytes for deployPolicyUid to set.
* @return This builder for chaining.
*/
public Builder setDeployPolicyUidBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
deployPolicyUid_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private int type_ = 0;
/**
*
*
* <pre>
* Type of this notification, e.g. for a Pub/Sub failure.
* </pre>
*
* <code>.google.cloud.deploy.v1.Type type = 4;</code>
*
* @return The enum numeric value on the wire for type.
*/
@java.lang.Override
public int getTypeValue() {
return type_;
}
/**
*
*
* <pre>
* Type of this notification, e.g. for a Pub/Sub failure.
* </pre>
*
* <code>.google.cloud.deploy.v1.Type type = 4;</code>
*
* @param value The enum numeric value on the wire for type to set.
* @return This builder for chaining.
*/
public Builder setTypeValue(int value) {
type_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Type of this notification, e.g. for a Pub/Sub failure.
* </pre>
*
* <code>.google.cloud.deploy.v1.Type type = 4;</code>
*
* @return The type.
*/
@java.lang.Override
public com.google.cloud.deploy.v1.Type getType() {
com.google.cloud.deploy.v1.Type result = com.google.cloud.deploy.v1.Type.forNumber(type_);
return result == null ? com.google.cloud.deploy.v1.Type.UNRECOGNIZED : result;
}
/**
*
*
* <pre>
* Type of this notification, e.g. for a Pub/Sub failure.
* </pre>
*
* <code>.google.cloud.deploy.v1.Type type = 4;</code>
*
* @param value The type to set.
* @return This builder for chaining.
*/
public Builder setType(com.google.cloud.deploy.v1.Type value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
type_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Type of this notification, e.g. for a Pub/Sub failure.
* </pre>
*
* <code>.google.cloud.deploy.v1.Type type = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearType() {
bitField0_ = (bitField0_ & ~0x00000008);
type_ = 0;
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.deploy.v1.DeployPolicyNotificationEvent)
}
// @@protoc_insertion_point(class_scope:google.cloud.deploy.v1.DeployPolicyNotificationEvent)
private static final com.google.cloud.deploy.v1.DeployPolicyNotificationEvent DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.deploy.v1.DeployPolicyNotificationEvent();
}
public static com.google.cloud.deploy.v1.DeployPolicyNotificationEvent getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<DeployPolicyNotificationEvent> PARSER =
new com.google.protobuf.AbstractParser<DeployPolicyNotificationEvent>() {
@java.lang.Override
public DeployPolicyNotificationEvent 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<DeployPolicyNotificationEvent> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<DeployPolicyNotificationEvent> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.deploy.v1.DeployPolicyNotificationEvent getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/pulsar | 35,988 | pulsar-functions/worker/src/main/java/org/apache/pulsar/functions/worker/FunctionActioner.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.functions.worker;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isEmpty;
import static org.apache.pulsar.common.functions.Utils.FILE;
import static org.apache.pulsar.common.functions.Utils.HTTP;
import static org.apache.pulsar.common.functions.Utils.hasPackageTypePrefix;
import static org.apache.pulsar.common.functions.Utils.isFunctionPackageUrlSupported;
import static org.apache.pulsar.functions.auth.FunctionAuthUtils.getFunctionAuthData;
import static org.apache.pulsar.functions.utils.FunctionCommon.getSinkType;
import static org.apache.pulsar.functions.utils.FunctionCommon.getSourceType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.io.MoreFiles;
import com.google.common.io.RecursiveDeleteOption;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.distributedlog.api.namespace.Namespace;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.client.api.MessageId;
import org.apache.pulsar.common.io.BatchSourceConfig;
import org.apache.pulsar.common.naming.TopicName;
import org.apache.pulsar.common.policies.data.SubscriptionStats;
import org.apache.pulsar.common.policies.data.TopicStats;
import org.apache.pulsar.common.util.ObjectMapperFactory;
import org.apache.pulsar.functions.instance.InstanceConfig;
import org.apache.pulsar.functions.instance.InstanceUtils;
import org.apache.pulsar.functions.proto.Function;
import org.apache.pulsar.functions.proto.Function.FunctionDetails;
import org.apache.pulsar.functions.proto.Function.FunctionMetaData;
import org.apache.pulsar.functions.proto.Function.SinkSpec;
import org.apache.pulsar.functions.proto.Function.SourceSpec;
import org.apache.pulsar.functions.runtime.RuntimeFactory;
import org.apache.pulsar.functions.runtime.RuntimeSpawner;
import org.apache.pulsar.functions.utils.Actions;
import org.apache.pulsar.functions.utils.FunctionCommon;
import org.apache.pulsar.functions.utils.SourceConfigUtils;
import org.apache.pulsar.functions.utils.ValidatableFunctionPackage;
import org.apache.pulsar.functions.utils.io.Connector;
@Data
@Slf4j
public class FunctionActioner {
private final WorkerConfig workerConfig;
private final RuntimeFactory runtimeFactory;
private final Namespace dlogNamespace;
private final ConnectorsManager connectorsManager;
private final FunctionsManager functionsManager;
private final PulsarAdmin pulsarAdmin;
private final PackageUrlValidator packageUrlValidator;
public FunctionActioner(WorkerConfig workerConfig,
RuntimeFactory runtimeFactory,
Namespace dlogNamespace,
ConnectorsManager connectorsManager,
FunctionsManager functionsManager, PulsarAdmin pulsarAdmin,
PackageUrlValidator packageUrlValidator) {
this.workerConfig = workerConfig;
this.runtimeFactory = runtimeFactory;
this.dlogNamespace = dlogNamespace;
this.connectorsManager = connectorsManager;
this.functionsManager = functionsManager;
this.pulsarAdmin = pulsarAdmin;
this.packageUrlValidator = packageUrlValidator;
}
public void startFunction(FunctionRuntimeInfo functionRuntimeInfo) {
try {
FunctionMetaData functionMetaData = functionRuntimeInfo.getFunctionInstance().getFunctionMetaData();
FunctionDetails functionDetails = functionMetaData.getFunctionDetails();
int instanceId = functionRuntimeInfo.getFunctionInstance().getInstanceId();
log.info("{}/{}/{}-{} Starting function ...", functionDetails.getTenant(), functionDetails.getNamespace(),
functionDetails.getName(), instanceId);
String packageFile;
String transformFunctionPackageFile = null;
Function.PackageLocationMetaData pkgLocation = functionMetaData.getPackageLocation();
Function.PackageLocationMetaData transformFunctionPkgLocation =
functionMetaData.getTransformFunctionPackageLocation();
if (runtimeFactory.externallyManaged()) {
packageFile = pkgLocation.getPackagePath();
transformFunctionPackageFile = transformFunctionPkgLocation.getPackagePath();
} else {
packageFile = getPackageFile(functionMetaData, functionDetails, instanceId, pkgLocation,
InstanceUtils.calculateSubjectType(functionDetails));
if (!isEmpty(transformFunctionPkgLocation.getPackagePath())) {
transformFunctionPackageFile =
getPackageFile(functionMetaData, functionDetails, instanceId, transformFunctionPkgLocation,
FunctionDetails.ComponentType.FUNCTION);
}
}
// Setup for batch sources if necessary
setupBatchSource(functionDetails);
RuntimeSpawner runtimeSpawner = getRuntimeSpawner(functionRuntimeInfo.getFunctionInstance(),
packageFile, transformFunctionPackageFile);
functionRuntimeInfo.setRuntimeSpawner(runtimeSpawner);
runtimeSpawner.start();
} catch (Exception ex) {
FunctionDetails details = functionRuntimeInfo.getFunctionInstance()
.getFunctionMetaData().getFunctionDetails();
log.error("{}/{}/{} Error starting function", details.getTenant(), details.getNamespace(),
details.getName(), ex);
functionRuntimeInfo.setStartupException(ex);
}
}
private String getPackageFile(FunctionMetaData functionMetaData, FunctionDetails functionDetails, int instanceId,
Function.PackageLocationMetaData pkgLocation,
FunctionDetails.ComponentType componentType)
throws URISyntaxException, IOException, ClassNotFoundException, PulsarAdminException {
String packagePath = pkgLocation.getPackagePath();
boolean isPkgUrlProvided = isFunctionPackageUrlSupported(packagePath);
String packageFile;
if (isPkgUrlProvided && packagePath.startsWith(FILE)) {
if (!packageUrlValidator.isValidPackageUrl(componentType, packagePath)) {
throw new IllegalArgumentException("Package URL " + packagePath + " is not valid");
}
URL url = new URL(packagePath);
File pkgFile = new File(url.toURI());
packageFile = pkgFile.getAbsolutePath();
} else if (FunctionCommon.isFunctionCodeBuiltin(functionDetails, componentType)) {
File pkgFile = getBuiltinArchive(
componentType,
FunctionDetails.newBuilder(functionMetaData.getFunctionDetails()));
packageFile = pkgFile.getAbsolutePath();
} else {
File pkgDir = new File(workerConfig.getDownloadDirectory(),
getDownloadPackagePath(functionMetaData, instanceId));
pkgDir.mkdirs();
File pkgFile = new File(
pkgDir,
new File(getDownloadFileName(functionMetaData.getFunctionDetails(),
pkgLocation)).getName());
downloadFile(pkgFile, isPkgUrlProvided, functionMetaData, instanceId, pkgLocation, componentType);
packageFile = pkgFile.getAbsolutePath();
}
return packageFile;
}
RuntimeSpawner getRuntimeSpawner(Function.Instance instance, String packageFile,
String transformFunctionPackageFile) {
FunctionMetaData functionMetaData = instance.getFunctionMetaData();
int instanceId = instance.getInstanceId();
FunctionDetails.Builder functionDetailsBuilder = FunctionDetails
.newBuilder(functionMetaData.getFunctionDetails());
// check to make sure functionAuthenticationSpec has any data and authentication is enabled.
// If not set to null, since for protobuf,
// even if the field is not set its not going to be null. Have to use the "has" method to check
Function.FunctionAuthenticationSpec functionAuthenticationSpec = null;
if (workerConfig.isAuthenticationEnabled() && instance.getFunctionMetaData().hasFunctionAuthSpec()) {
functionAuthenticationSpec = instance.getFunctionMetaData().getFunctionAuthSpec();
}
InstanceConfig instanceConfig = createInstanceConfig(functionDetailsBuilder.build(),
functionAuthenticationSpec,
instanceId, workerConfig.getPulsarFunctionsCluster());
RuntimeSpawner runtimeSpawner = new RuntimeSpawner(instanceConfig, packageFile,
functionMetaData.getPackageLocation().getOriginalFileName(),
transformFunctionPackageFile,
functionMetaData.getTransformFunctionPackageLocation().getOriginalFileName(),
runtimeFactory, workerConfig.getInstanceLivenessCheckFreqMs());
return runtimeSpawner;
}
InstanceConfig createInstanceConfig(FunctionDetails functionDetails, Function.FunctionAuthenticationSpec
functionAuthSpec, int instanceId, String clusterName) {
InstanceConfig instanceConfig = new InstanceConfig();
instanceConfig.setFunctionDetails(functionDetails);
// TODO: set correct function id and version when features implemented
instanceConfig.setFunctionId(UUID.randomUUID().toString());
instanceConfig.setTransformFunctionId(UUID.randomUUID().toString());
instanceConfig.setFunctionVersion(UUID.randomUUID().toString());
instanceConfig.setInstanceId(instanceId);
instanceConfig.setMaxBufferedTuples(1024);
instanceConfig.setPort(FunctionCommon.findAvailablePort());
instanceConfig.setMetricsPort(FunctionCommon.findAvailablePort());
instanceConfig.setClusterName(clusterName);
instanceConfig.setFunctionAuthenticationSpec(functionAuthSpec);
instanceConfig.setMaxPendingAsyncRequests(workerConfig.getMaxPendingAsyncRequests());
instanceConfig.setExposePulsarAdminClientEnabled(workerConfig.isExposeAdminClientEnabled());
if (workerConfig.getAdditionalJavaRuntimeArguments() != null) {
instanceConfig.setAdditionalJavaRuntimeArguments(workerConfig.getAdditionalJavaRuntimeArguments());
}
instanceConfig.setIgnoreUnknownConfigFields(workerConfig.isIgnoreUnknownConfigFields());
return instanceConfig;
}
private void downloadFile(File pkgFile, boolean isPkgUrlProvided, FunctionMetaData functionMetaData,
int instanceId, Function.PackageLocationMetaData pkgLocation,
FunctionDetails.ComponentType componentType)
throws IOException, PulsarAdminException {
FunctionDetails details = functionMetaData.getFunctionDetails();
File pkgDir = pkgFile.getParentFile();
if (pkgFile.exists()) {
log.warn("Function package exists already {} deleting it", pkgFile);
pkgFile.delete();
}
File tempPkgFile;
do {
tempPkgFile = new File(
pkgDir,
pkgFile.getName() + "." + instanceId + "." + UUID.randomUUID());
} while (tempPkgFile.exists() || !tempPkgFile.createNewFile());
String pkgLocationPath = pkgLocation.getPackagePath();
boolean downloadFromHttp = isPkgUrlProvided && pkgLocationPath.startsWith(HTTP);
boolean downloadFromPackageManagementService = isPkgUrlProvided && hasPackageTypePrefix(pkgLocationPath);
log.info("{}/{}/{} Function package file {} will be downloaded from {}", tempPkgFile, details.getTenant(),
details.getNamespace(), details.getName(),
downloadFromHttp ? pkgLocationPath : pkgLocation);
if (downloadFromHttp) {
if (!packageUrlValidator.isValidPackageUrl(componentType, pkgLocationPath)) {
throw new IllegalArgumentException("Package URL " + pkgLocationPath + " is not valid");
}
FunctionCommon.downloadFromHttpUrl(pkgLocationPath, tempPkgFile);
} else if (downloadFromPackageManagementService) {
getPulsarAdmin().packages().download(pkgLocationPath, tempPkgFile.getPath());
} else {
try (FileOutputStream tempPkgFos = new FileOutputStream(tempPkgFile)) {
WorkerUtils.downloadFromBookkeeper(
dlogNamespace,
tempPkgFos,
pkgLocationPath);
}
}
try {
// create a hardlink, if there are two concurrent createLink operations, one will fail.
// this ensures one instance will successfully download the package.
try {
Files.createLink(
Paths.get(pkgFile.toURI()),
Paths.get(tempPkgFile.toURI()));
log.info("Function package file is linked from {} to {}",
tempPkgFile, pkgFile);
} catch (FileAlreadyExistsException faee) {
// file already exists
log.warn("Function package has been downloaded from {} and saved at {}",
pkgLocation, pkgFile);
}
} finally {
tempPkgFile.delete();
}
if (details.getRuntime() == Function.FunctionDetails.Runtime.GO && !pkgFile.canExecute()) {
pkgFile.setExecutable(true);
log.info("Golang function package file {} is set to executable", pkgFile);
}
}
private void cleanupFunctionFiles(FunctionRuntimeInfo functionRuntimeInfo) {
Function.Instance instance = functionRuntimeInfo.getFunctionInstance();
FunctionMetaData functionMetaData = instance.getFunctionMetaData();
// clean up function package
File pkgDir = new File(
workerConfig.getDownloadDirectory(),
getDownloadPackagePath(functionMetaData, instance.getInstanceId()));
if (pkgDir.exists()) {
try {
MoreFiles.deleteRecursively(
Paths.get(pkgDir.toURI()), RecursiveDeleteOption.ALLOW_INSECURE);
} catch (IOException e) {
log.warn("Failed to delete package for function: {}",
FunctionCommon.getFullyQualifiedName(functionMetaData.getFunctionDetails()), e);
}
}
}
public void stopFunction(FunctionRuntimeInfo functionRuntimeInfo) {
Function.Instance instance = functionRuntimeInfo.getFunctionInstance();
FunctionMetaData functionMetaData = instance.getFunctionMetaData();
FunctionDetails details = functionMetaData.getFunctionDetails();
log.info("{}/{}/{}-{} Stopping function...", details.getTenant(), details.getNamespace(), details.getName(),
instance.getInstanceId());
if (functionRuntimeInfo.getRuntimeSpawner() != null) {
functionRuntimeInfo.getRuntimeSpawner().close();
functionRuntimeInfo.setRuntimeSpawner(null);
}
cleanupFunctionFiles(functionRuntimeInfo);
}
public void terminateFunction(FunctionRuntimeInfo functionRuntimeInfo) {
FunctionDetails details = functionRuntimeInfo.getFunctionInstance().getFunctionMetaData().getFunctionDetails();
String fqfn = FunctionCommon.getFullyQualifiedName(details);
log.info("{}-{} Terminating function...", fqfn, functionRuntimeInfo.getFunctionInstance().getInstanceId());
if (functionRuntimeInfo.getRuntimeSpawner() != null) {
functionRuntimeInfo.getRuntimeSpawner().close();
// cleanup any auth data cached
if (workerConfig.isAuthenticationEnabled()) {
functionRuntimeInfo.getRuntimeSpawner()
.getRuntimeFactory().getAuthProvider().ifPresent(functionAuthProvider -> {
try {
log.info("{}-{} Cleaning up authentication data for function...", fqfn,
functionRuntimeInfo.getFunctionInstance().getInstanceId());
functionAuthProvider
.cleanUpAuthData(
details,
Optional.ofNullable(getFunctionAuthData(
Optional.ofNullable(
functionRuntimeInfo.getRuntimeSpawner().getInstanceConfig()
.getFunctionAuthenticationSpec()))));
} catch (Exception e) {
log.error("Failed to cleanup auth data for function: {}", fqfn, e);
}
});
}
functionRuntimeInfo.setRuntimeSpawner(null);
}
cleanupFunctionFiles(functionRuntimeInfo);
//cleanup subscriptions
if (details.getSource().getCleanupSubscription()) {
Map<String, Function.ConsumerSpec> consumerSpecMap = details.getSource().getInputSpecsMap();
consumerSpecMap.entrySet().forEach(new Consumer<Map.Entry<String, Function.ConsumerSpec>>() {
@Override
public void accept(Map.Entry<String, Function.ConsumerSpec> stringConsumerSpecEntry) {
Function.ConsumerSpec consumerSpec = stringConsumerSpecEntry.getValue();
String topic = stringConsumerSpecEntry.getKey();
String subscriptionName = isBlank(functionRuntimeInfo.getFunctionInstance()
.getFunctionMetaData().getFunctionDetails().getSource().getSubscriptionName())
? InstanceUtils.getDefaultSubscriptionName(functionRuntimeInfo
.getFunctionInstance().getFunctionMetaData().getFunctionDetails())
: functionRuntimeInfo.getFunctionInstance().getFunctionMetaData()
.getFunctionDetails().getSource().getSubscriptionName();
deleteSubscription(topic, consumerSpec, subscriptionName,
String.format("Cleaning up subscriptions for function %s", fqfn));
}
});
}
// clean up done for batch sources if necessary
cleanupBatchSource(details);
}
private void deleteSubscription(String topic, Function.ConsumerSpec consumerSpec,
String subscriptionName, String msg) {
try {
Actions.newBuilder()
.addAction(
Actions.Action.builder()
.actionName(msg)
.numRetries(10)
.sleepBetweenInvocationsMs(1000)
.supplier(
getDeleteSubscriptionSupplier(topic,
consumerSpec.getIsRegexPattern(),
subscriptionName)
)
.build())
.run();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
private Supplier<Actions.ActionResult> getDeleteSubscriptionSupplier(
String topic, boolean isRegex, String subscriptionName) {
return () -> {
try {
if (isRegex) {
pulsarAdmin.namespaces().unsubscribeNamespace(TopicName
.get(topic).getNamespace(), subscriptionName);
} else {
pulsarAdmin.topics().deleteSubscription(topic,
subscriptionName);
}
} catch (PulsarAdminException e) {
if (e instanceof PulsarAdminException.NotFoundException) {
return Actions.ActionResult.builder()
.success(true)
.build();
} else {
// for debugging purposes
List<Map<String, String>> existingConsumers = Collections.emptyList();
SubscriptionStats sub = null;
try {
TopicStats stats = pulsarAdmin.topics().getStats(topic);
sub = stats.getSubscriptions().get(subscriptionName);
if (sub != null) {
existingConsumers = sub.getConsumers().stream()
.map(consumerStats -> consumerStats.getMetadata())
.collect(Collectors.toList());
}
} catch (PulsarAdminException e1) {
}
String errorMsg = e.getHttpError() != null ? e.getHttpError() : e.getMessage();
String finalErrorMsg;
if (sub != null) {
try {
finalErrorMsg = String.format("%s - existing consumers: %s",
errorMsg, ObjectMapperFactory.getMapper().writer().writeValueAsString(sub));
} catch (JsonProcessingException jsonProcessingException) {
finalErrorMsg = errorMsg;
}
} else {
finalErrorMsg = errorMsg;
}
return Actions.ActionResult.builder()
.success(false)
.errorMsg(finalErrorMsg)
.build();
}
}
return Actions.ActionResult.builder()
.success(true)
.build();
};
}
private Supplier<Actions.ActionResult> getDeleteTopicSupplier(String topic) {
return () -> {
try {
pulsarAdmin.topics().delete(topic, true);
} catch (PulsarAdminException e) {
if (e instanceof PulsarAdminException.NotFoundException) {
return Actions.ActionResult.builder()
.success(true)
.build();
} else {
// for debugging purposes
TopicStats stats = null;
try {
stats = pulsarAdmin.topics().getStats(topic);
} catch (PulsarAdminException e1) {
}
String errorMsg = e.getHttpError() != null ? e.getHttpError() : e.getMessage();
String finalErrorMsg;
if (stats != null) {
try {
finalErrorMsg = String.format("%s - topic stats: %s",
errorMsg, ObjectMapperFactory.getMapper().writer().writeValueAsString(stats));
} catch (JsonProcessingException jsonProcessingException) {
finalErrorMsg = errorMsg;
}
} else {
finalErrorMsg = errorMsg;
}
return Actions.ActionResult.builder()
.success(false)
.errorMsg(finalErrorMsg)
.build();
}
}
return Actions.ActionResult.builder()
.success(true)
.build();
};
}
private String getDownloadPackagePath(FunctionMetaData functionMetaData, int instanceId) {
return StringUtils.join(
new String[]{
functionMetaData.getFunctionDetails().getTenant(),
functionMetaData.getFunctionDetails().getNamespace(),
functionMetaData.getFunctionDetails().getName(),
Integer.toString(instanceId),
},
File.separatorChar);
}
private File getBuiltinArchive(FunctionDetails.ComponentType componentType, FunctionDetails.Builder functionDetails)
throws IOException, ClassNotFoundException {
if (componentType == FunctionDetails.ComponentType.SOURCE && functionDetails.hasSource()) {
SourceSpec sourceSpec = functionDetails.getSource();
if (!StringUtils.isEmpty(sourceSpec.getBuiltin())) {
Connector connector = connectorsManager.getConnector(sourceSpec.getBuiltin());
File archive = connector.getArchivePath().toFile();
String sourceClass = connector.getConnectorDefinition().getSourceClass();
SourceSpec.Builder builder = SourceSpec.newBuilder(functionDetails.getSource());
builder.setClassName(sourceClass);
functionDetails.setSource(builder);
fillSourceTypeClass(functionDetails, connector.getConnectorFunctionPackage(), sourceClass);
return archive;
}
}
if (componentType == FunctionDetails.ComponentType.SINK && functionDetails.hasSink()) {
SinkSpec sinkSpec = functionDetails.getSink();
if (!StringUtils.isEmpty(sinkSpec.getBuiltin())) {
Connector connector = connectorsManager.getConnector(sinkSpec.getBuiltin());
File archive = connector.getArchivePath().toFile();
String sinkClass = connector.getConnectorDefinition().getSinkClass();
SinkSpec.Builder builder = SinkSpec.newBuilder(functionDetails.getSink());
builder.setClassName(sinkClass);
functionDetails.setSink(builder);
fillSinkTypeClass(functionDetails, connector.getConnectorFunctionPackage(), sinkClass);
return archive;
}
}
if (componentType == FunctionDetails.ComponentType.FUNCTION
&& !StringUtils.isEmpty(functionDetails.getBuiltin())) {
return functionsManager.getFunctionArchive(functionDetails.getBuiltin()).toFile();
}
throw new IOException("Could not find built in archive definition");
}
private void fillSourceTypeClass(FunctionDetails.Builder functionDetails,
ValidatableFunctionPackage functionPackage, String className) {
String typeArg = getSourceType(className, functionPackage.getTypePool()).asErasure().getName();
SourceSpec.Builder sourceBuilder = SourceSpec.newBuilder(functionDetails.getSource());
sourceBuilder.setTypeClassName(typeArg);
functionDetails.setSource(sourceBuilder);
SinkSpec sinkSpec = functionDetails.getSink();
if (null == sinkSpec || StringUtils.isEmpty(sinkSpec.getTypeClassName())) {
SinkSpec.Builder sinkBuilder = SinkSpec.newBuilder(sinkSpec);
sinkBuilder.setTypeClassName(typeArg);
functionDetails.setSink(sinkBuilder);
}
}
private void fillSinkTypeClass(FunctionDetails.Builder functionDetails,
ValidatableFunctionPackage functionPackage, String className) {
String typeArg = getSinkType(className, functionPackage.getTypePool()).asErasure().getName();
SinkSpec.Builder sinkBuilder = SinkSpec.newBuilder(functionDetails.getSink());
sinkBuilder.setTypeClassName(typeArg);
functionDetails.setSink(sinkBuilder);
SourceSpec sourceSpec = functionDetails.getSource();
if (null == sourceSpec || StringUtils.isEmpty(sourceSpec.getTypeClassName())) {
SourceSpec.Builder sourceBuilder = SourceSpec.newBuilder(sourceSpec);
sourceBuilder.setTypeClassName(typeArg);
functionDetails.setSource(sourceBuilder);
}
}
private static String getDownloadFileName(FunctionDetails functionDetails,
Function.PackageLocationMetaData packageLocation) {
if (!org.apache.commons.lang3.StringUtils.isEmpty(packageLocation.getOriginalFileName())) {
return packageLocation.getOriginalFileName();
}
String[] hierarchy = functionDetails.getClassName().split("\\.");
String fileName;
if (hierarchy.length <= 0) {
fileName = functionDetails.getClassName();
} else if (hierarchy.length == 1) {
fileName = hierarchy[0];
} else {
fileName = hierarchy[hierarchy.length - 2];
}
switch (functionDetails.getRuntime()) {
case JAVA:
return fileName + ".jar";
case PYTHON:
return fileName + ".py";
case GO:
return fileName + ".go";
default:
throw new RuntimeException("Unknown runtime " + functionDetails.getRuntime());
}
}
private void setupBatchSource(Function.FunctionDetails functionDetails) {
if (isBatchSource(functionDetails)) {
String intermediateTopicName = SourceConfigUtils.computeBatchSourceIntermediateTopicName(
functionDetails.getTenant(), functionDetails.getNamespace(), functionDetails.getName()).toString();
String intermediateTopicSubscription = SourceConfigUtils.computeBatchSourceInstanceSubscriptionName(
functionDetails.getTenant(), functionDetails.getNamespace(), functionDetails.getName());
String fqfn = FunctionCommon.getFullyQualifiedName(
functionDetails.getTenant(), functionDetails.getNamespace(), functionDetails.getName());
try {
Actions.newBuilder()
.addAction(
Actions.Action.builder()
.actionName(String.format("Creating intermediate topic"
+ "%s with subscription %s for Batch Source %s",
intermediateTopicName, intermediateTopicSubscription, fqfn))
.numRetries(10)
.sleepBetweenInvocationsMs(1000)
.supplier(() -> {
try {
pulsarAdmin.topics().createSubscription(intermediateTopicName,
intermediateTopicSubscription, MessageId.latest);
return Actions.ActionResult.builder()
.success(true)
.build();
} catch (PulsarAdminException.ConflictException e) {
// topic and subscription already exists so just continue
return Actions.ActionResult.builder()
.success(true)
.build();
} catch (Exception e) {
return Actions.ActionResult.builder()
.errorMsg(e.getMessage())
.success(false)
.build();
}
})
.build())
.run();
} catch (InterruptedException e) {
log.error("Error setting up instance subscription for intermediate topic", e);
throw new RuntimeException(e);
}
}
}
private void cleanupBatchSource(Function.FunctionDetails functionDetails) {
if (isBatchSource(functionDetails)) {
// clean up intermediate topic
String intermediateTopicName = SourceConfigUtils
.computeBatchSourceIntermediateTopicName(functionDetails.getTenant(),
functionDetails.getNamespace(), functionDetails.getName()).toString();
String intermediateTopicSubscription = SourceConfigUtils.computeBatchSourceInstanceSubscriptionName(
functionDetails.getTenant(), functionDetails.getNamespace(), functionDetails.getName());
String fqfn = FunctionCommon.getFullyQualifiedName(functionDetails);
try {
Actions.newBuilder()
.addAction(
// Unsubscribe and allow time for consumers to close
Actions.Action.builder()
.actionName(String.format("Removing intermediate topic subscription %s for Batch Source %s",
intermediateTopicSubscription, fqfn))
.numRetries(10)
.sleepBetweenInvocationsMs(1000)
.supplier(
getDeleteSubscriptionSupplier(intermediateTopicName,
false,
intermediateTopicSubscription)
)
.build())
.addAction(
// Delete topic forcibly regardless whether unsubscribe succeeded or not
Actions.Action.builder()
.actionName(String.format("Deleting intermediate topic %s for Batch Source %s",
intermediateTopicName, fqfn))
.numRetries(10)
.sleepBetweenInvocationsMs(1000)
.supplier(getDeleteTopicSupplier(intermediateTopicName))
.build())
.run();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
private static boolean isBatchSource(Function.FunctionDetails functionDetails) {
if (InstanceUtils.calculateSubjectType(functionDetails) == FunctionDetails.ComponentType.SOURCE) {
String fqfn = FunctionCommon.getFullyQualifiedName(functionDetails);
Map<String, Object> configMap = SourceConfigUtils.extractSourceConfig(functionDetails.getSource(), fqfn);
if (configMap != null) {
BatchSourceConfig batchSourceConfig = SourceConfigUtils.extractBatchSourceConfig(configMap);
if (batchSourceConfig != null) {
return true;
}
}
}
return false;
}
}
|
apache/xmlgraphics-batik | 35,607 | batik-dom/src/main/java/org/apache/batik/dom/AbstractElement.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.batik.dom;
import java.io.Serializable;
import org.apache.batik.dom.events.DOMMutationEvent;
import org.apache.batik.dom.util.DOMUtilities;
import org.apache.batik.constants.XMLConstants;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.apache.batik.w3c.dom.ElementTraversal;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.TypeInfo;
import org.w3c.dom.events.MutationEvent;
/**
* This class implements the {@link org.w3c.dom.Element} interface.
*
* @author <a href="mailto:stephane@hillion.org">Stephane Hillion</a>
* @version $Id$
*/
public abstract class AbstractElement
extends AbstractParentChildNode
implements Element, ElementTraversal {
/**
* The attributes of this element.
*/
protected NamedNodeMap attributes;
/**
* The element type information.
*/
protected TypeInfo typeInfo;
/**
* Creates a new AbstractElement object.
*/
protected AbstractElement() {
}
/**
* Creates a new AbstractElement object.
* @param name The element name for validation purposes.
* @param owner The owner document.
* @exception DOMException
* INVALID_CHARACTER_ERR: if name contains invalid characters,
*/
protected AbstractElement(String name, AbstractDocument owner) {
ownerDocument = owner;
if (owner.getStrictErrorChecking() && !DOMUtilities.isValidName(name)) {
throw createDOMException(DOMException.INVALID_CHARACTER_ERR,
"xml.name",
new Object[] { name });
}
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.Node#getNodeType()}.
*
* @return {@link org.w3c.dom.Node#ELEMENT_NODE}
*/
public short getNodeType() {
return ELEMENT_NODE;
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.Node#hasAttributes()}.
*/
public boolean hasAttributes() {
return attributes != null && attributes.getLength() != 0;
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.Node#getAttributes()}.
*/
public NamedNodeMap getAttributes() {
return (attributes == null)
? attributes = createAttributes()
: attributes;
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.Element#getTagName()}.
*
* @return {@link #getNodeName()}.
*/
public String getTagName() {
return getNodeName();
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.Element#hasAttribute(String)}.
*/
public boolean hasAttribute( String name ) {
return attributes != null && attributes.getNamedItem( name ) != null;
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.Element#getAttribute(String)}.
*/
public String getAttribute(String name) {
if ( attributes == null ) {
return "";
}
Attr attr = (Attr)attributes.getNamedItem( name );
return ( attr == null ) ? "" : attr.getValue();
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.Element#setAttribute(String,String)}.
*/
public void setAttribute(String name, String value) throws DOMException {
if (attributes == null) {
attributes = createAttributes();
}
Attr attr = getAttributeNode(name);
if (attr == null) {
attr = getOwnerDocument().createAttribute(name);
attr.setValue(value);
attributes.setNamedItem(attr);
} else {
attr.setValue(value);
}
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.Element#removeAttribute(String)}.
*/
public void removeAttribute(String name) throws DOMException {
if (!hasAttribute(name)) {
return;
}
attributes.removeNamedItem(name);
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.Element#getAttributeNode(String)}.
*/
public Attr getAttributeNode(String name) {
if (attributes == null) {
return null;
}
return (Attr)attributes.getNamedItem(name);
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.Element#setAttributeNode(Attr)}.
*/
public Attr setAttributeNode(Attr newAttr) throws DOMException {
if (newAttr == null) {
return null;
}
if (attributes == null) {
attributes = createAttributes();
}
return (Attr)attributes.setNamedItemNS(newAttr);
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.Element#removeAttributeNode(Attr)}.
*/
public Attr removeAttributeNode(Attr oldAttr) throws DOMException {
if (oldAttr == null) {
return null;
}
if (attributes == null) {
throw createDOMException(DOMException.NOT_FOUND_ERR,
"attribute.missing",
new Object[] { oldAttr.getName() });
}
String nsURI = oldAttr.getNamespaceURI();
return (Attr)attributes.removeNamedItemNS(nsURI,
(nsURI==null
? oldAttr.getNodeName()
: oldAttr.getLocalName()));
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.Node#normalize()}.
*/
public void normalize() {
super.normalize();
if (attributes != null) {
NamedNodeMap map = getAttributes();
for (int i = map.getLength() - 1; i >= 0; i--) {
map.item(i).normalize();
}
}
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.Element#hasAttributeNS(String,String)}.
*/
public boolean hasAttributeNS( String namespaceURI, String localName ) {
if ( namespaceURI != null && namespaceURI.length() == 0 ) {
namespaceURI = null;
}
return attributes != null &&
attributes.getNamedItemNS( namespaceURI, localName ) != null;
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.Element#getAttributeNS(String,String)}.
*/
public String getAttributeNS( String namespaceURI, String localName ) {
if ( attributes == null ) {
return "";
}
if ( namespaceURI != null && namespaceURI.length() == 0 ) {
namespaceURI = null;
}
Attr attr = (Attr)attributes.getNamedItemNS( namespaceURI, localName );
return ( attr == null ) ? "" : attr.getValue();
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.Element#setAttributeNS(String,String,String)}.
*/
public void setAttributeNS(String namespaceURI,
String qualifiedName,
String value) throws DOMException {
if (attributes == null) {
attributes = createAttributes();
}
if (namespaceURI != null && namespaceURI.length() == 0) {
namespaceURI = null;
}
Attr attr = getAttributeNodeNS(namespaceURI, qualifiedName);
if (attr == null) {
attr = getOwnerDocument().createAttributeNS(namespaceURI,
qualifiedName);
attr.setValue(value);
attributes.setNamedItemNS(attr);
} else {
attr.setValue(value);
}
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.Element#removeAttributeNS(String,String)}.
*/
public void removeAttributeNS(String namespaceURI,
String localName) throws DOMException {
if (namespaceURI != null && namespaceURI.length() == 0) {
namespaceURI = null;
}
if (!hasAttributeNS(namespaceURI, localName)) {
return;
}
attributes.removeNamedItemNS(namespaceURI, localName);
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.Element#getAttributeNodeNS(String,String)}.
*/
public Attr getAttributeNodeNS(String namespaceURI,
String localName) {
if (namespaceURI != null && namespaceURI.length() == 0) {
namespaceURI = null;
}
if (attributes == null) {
return null;
}
return (Attr)attributes.getNamedItemNS(namespaceURI, localName);
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.Element#setAttributeNodeNS(Attr)}.
*/
public Attr setAttributeNodeNS(Attr newAttr) throws DOMException {
if (newAttr == null) {
return null;
}
if (attributes == null) {
attributes = createAttributes();
}
return (Attr)attributes.setNamedItemNS(newAttr);
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.Element#getSchemaTypeInfo()}.
*/
public TypeInfo getSchemaTypeInfo() {
if (typeInfo == null) {
typeInfo = new ElementTypeInfo();
}
return typeInfo;
}
/**
* <b>DOM</b>: Implements
* {@link org.w3c.dom.Element#setIdAttribute(String,boolean)}.
*/
public void setIdAttribute(String name, boolean isId) throws DOMException {
AbstractAttr a = (AbstractAttr) getAttributeNode(name);
if (a == null) {
throw createDOMException(DOMException.NOT_FOUND_ERR,
"attribute.missing",
new Object[] { name });
}
if (a.isReadonly()) {
throw createDOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
"readonly.node",
new Object[] { name });
}
updateIdEntry(a, isId);
a.isIdAttr = isId;
}
/**
* <b>DOM</b>: Implements
* {@link org.w3c.dom.Element#setIdAttributeNS(String,String,boolean)}.
*/
public void setIdAttributeNS( String ns, String ln, boolean isId )
throws DOMException {
if ( ns != null && ns.length() == 0 ) {
ns = null;
}
AbstractAttr a = (AbstractAttr)getAttributeNodeNS( ns, ln );
if (a == null) {
throw createDOMException(DOMException.NOT_FOUND_ERR,
"attribute.missing",
new Object[] { ns, ln });
}
if (a.isReadonly()) {
throw createDOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
"readonly.node",
new Object[] { a.getNodeName() });
}
updateIdEntry(a, isId);
a.isIdAttr = isId;
}
/**
* <b>DOM</b>: Implements
* {@link org.w3c.dom.Element#setIdAttributeNode(Attr,boolean)}.
*/
public void setIdAttributeNode( Attr attr, boolean isId )
throws DOMException {
AbstractAttr a = (AbstractAttr)attr;
if (a.isReadonly()) {
throw createDOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR,
"readonly.node",
new Object[] { a.getNodeName() });
}
updateIdEntry(a, isId);
a.isIdAttr = isId;
}
private void updateIdEntry(AbstractAttr a, boolean isId) {
if (a.isIdAttr) {
if (!isId) {
ownerDocument.removeIdEntry(this, a.getValue());
}
} else if (isId) {
ownerDocument.addIdEntry(this, a.getValue());
}
}
/**
* Get an ID attribute.
*/
protected Attr getIdAttribute() {
NamedNodeMap nnm = getAttributes();
if ( nnm == null ) {
return null;
}
int len = nnm.getLength();
for (int i = 0; i < len; i++) {
AbstractAttr a = (AbstractAttr)nnm.item(i);
if (a.isId()) {
return a;
}
}
return null;
}
/**
* Get the ID of this element.
*/
protected String getId() {
Attr a = getIdAttribute();
if (a != null) {
String id = a.getNodeValue();
if (id.length() > 0) {
return id;
}
}
return null;
}
/**
* Called when a child node has been added.
*/
protected void nodeAdded(Node node) {
invalidateElementsByTagName(node);
}
/**
* Called when a child node is going to be removed.
*/
protected void nodeToBeRemoved(Node node) {
invalidateElementsByTagName(node);
}
/**
* Invalidates the ElementsByTagName objects of this node and its parents.
*/
private void invalidateElementsByTagName(Node node) {
if (node.getNodeType() != ELEMENT_NODE) {
return;
}
AbstractDocument ad = getCurrentDocument();
String ns = node.getNamespaceURI();
String nm = node.getNodeName();
String ln = (ns == null) ? node.getNodeName() : node.getLocalName();
for (Node n = this; n != null; n = n.getParentNode()) {
switch (n.getNodeType()) {
case ELEMENT_NODE: // fall-through is intended
case DOCUMENT_NODE:
ElementsByTagName l = ad.getElementsByTagName(n, nm);
if (l != null) {
l.invalidate();
}
l = ad.getElementsByTagName(n, "*");
if (l != null) {
l.invalidate();
}
ElementsByTagNameNS lns = ad.getElementsByTagNameNS(n, ns, ln);
if (lns != null) {
lns.invalidate();
}
lns = ad.getElementsByTagNameNS(n, "*", ln);
if (lns != null) {
lns.invalidate();
}
lns = ad.getElementsByTagNameNS(n, ns, "*");
if (lns != null) {
lns.invalidate();
}
lns = ad.getElementsByTagNameNS(n, "*", "*");
if (lns != null) {
lns.invalidate();
}
}
}
//
// Invalidate children
//
Node c = node.getFirstChild();
while (c != null) {
invalidateElementsByTagName(c);
c = c.getNextSibling();
}
}
/**
* Creates the attribute list.
*/
protected NamedNodeMap createAttributes() {
return new NamedNodeHashMap();
}
/**
* Exports this node to the given document.
* @param n The clone node.
* @param d The destination document.
*/
protected Node export(Node n, AbstractDocument d) {
super.export(n, d);
AbstractElement ae = (AbstractElement)n;
if (attributes != null) {
NamedNodeMap map = attributes;
for (int i = map.getLength() - 1; i >= 0; i--) {
AbstractAttr aa = (AbstractAttr)map.item(i);
if (aa.getSpecified()) {
Attr attr = (Attr)aa.deepExport(aa.cloneNode(false), d);
if (aa instanceof AbstractAttrNS) {
ae.setAttributeNodeNS(attr);
} else {
ae.setAttributeNode(attr);
}
}
}
}
return n;
}
/**
* Deeply exports this node to the given document.
* @param n The clone node.
* @param d The destination document.
*/
protected Node deepExport(Node n, AbstractDocument d) {
super.deepExport(n, d);
AbstractElement ae = (AbstractElement)n;
if (attributes != null) {
NamedNodeMap map = attributes;
for (int i = map.getLength() - 1; i >= 0; i--) {
AbstractAttr aa = (AbstractAttr)map.item(i);
if (aa.getSpecified()) {
Attr attr = (Attr)aa.deepExport(aa.cloneNode(false), d);
if (aa instanceof AbstractAttrNS) {
ae.setAttributeNodeNS(attr);
} else {
ae.setAttributeNode(attr);
}
}
}
}
return n;
}
/**
* Copy the fields of the current node into the given node.
* @param n a node of the type of this.
*/
protected Node copyInto(Node n) {
super.copyInto(n);
AbstractElement ae = (AbstractElement)n;
if (attributes != null) {
NamedNodeMap map = attributes;
for (int i = map.getLength() - 1; i >= 0; i--) {
AbstractAttr aa = (AbstractAttr)map.item(i).cloneNode(true);
if (aa instanceof AbstractAttrNS) {
ae.setAttributeNodeNS(aa);
} else {
ae.setAttributeNode(aa);
}
}
}
return n;
}
/**
* Deeply copy the fields of the current node into the given node.
* @param n a node of the type of this.
*/
protected Node deepCopyInto(Node n) {
super.deepCopyInto(n);
AbstractElement ae = (AbstractElement)n;
if (attributes != null) {
NamedNodeMap map = attributes;
for (int i = map.getLength() - 1; i >= 0; i--) {
AbstractAttr aa = (AbstractAttr)map.item(i).cloneNode(true);
if (aa instanceof AbstractAttrNS) {
ae.setAttributeNodeNS(aa);
} else {
ae.setAttributeNode(aa);
}
}
}
return n;
}
/**
* Checks the validity of a node to be inserted.
* @param n The node to be inserted.
*/
protected void checkChildType(Node n, boolean replace) {
switch (n.getNodeType()) {
case ELEMENT_NODE: // fall-through is intended
case PROCESSING_INSTRUCTION_NODE:
case COMMENT_NODE:
case TEXT_NODE:
case CDATA_SECTION_NODE:
case ENTITY_REFERENCE_NODE:
case DOCUMENT_FRAGMENT_NODE:
break;
default:
throw createDOMException
(DOMException.HIERARCHY_REQUEST_ERR,
"child.type",
new Object[] {(int) getNodeType(),
getNodeName(),
(int) n.getNodeType(),
n.getNodeName() });
}
}
/**
* Fires a DOMAttrModified event.
* WARNING: public accessor because of compilation problems
* on Solaris. Do not change.
*
* @param name The attribute's name.
* @param node The attribute's node.
* @param oldv The old value of the attribute.
* @param newv The new value of the attribute.
* @param change The modification type.
*/
public void fireDOMAttrModifiedEvent(String name, Attr node, String oldv,
String newv, short change) {
switch (change) {
case MutationEvent.ADDITION:
if (node.isId())
ownerDocument.addIdEntry(this, newv);
attrAdded(node, newv);
break;
case MutationEvent.MODIFICATION:
if (node.isId())
ownerDocument.updateIdEntry(this, oldv, newv);
attrModified(node, oldv, newv);
break;
default: // MutationEvent.REMOVAL:
if (node.isId())
ownerDocument.removeIdEntry(this, oldv);
attrRemoved(node, oldv);
}
AbstractDocument doc = getCurrentDocument();
if (doc.getEventsEnabled() && !oldv.equals(newv)) {
DOMMutationEvent ev
= (DOMMutationEvent) doc.createEvent("MutationEvents");
ev.initMutationEventNS(XMLConstants.XML_EVENTS_NAMESPACE_URI,
"DOMAttrModified",
true, // canBubbleArg
false, // cancelableArg
node, // relatedNodeArg
oldv, // prevValueArg
newv, // newValueArg
name, // attrNameArg
change); // attrChange
dispatchEvent(ev);
}
}
/**
* Called when an attribute has been added.
*/
protected void attrAdded(Attr node, String newv) {
}
/**
* Called when an attribute has been modified.
*/
protected void attrModified(Attr node, String oldv, String newv) {
}
/**
* Called when an attribute has been removed.
*/
protected void attrRemoved(Attr node, String oldv) {
}
// ElementTraversal //////////////////////////////////////////////////////
/**
* <b>DOM</b>: Implements {@link ElementTraversal#getFirstElementChild()}.
*/
public Element getFirstElementChild() {
Node n = getFirstChild();
while (n != null) {
if (n.getNodeType() == Node.ELEMENT_NODE) {
return (Element) n;
}
n = n.getNextSibling();
}
return null;
}
/**
* <b>DOM</b>: Implements {@link ElementTraversal#getLastElementChild()}.
*/
public Element getLastElementChild() {
Node n = getLastChild();
while (n != null) {
if (n.getNodeType() == Node.ELEMENT_NODE) {
return (Element) n;
}
n = n.getPreviousSibling();
}
return null;
}
/**
* <b>DOM</b>: Implements {@link ElementTraversal#getNextElementSibling()}.
*/
public Element getNextElementSibling() {
Node n = getNextSibling();
while (n != null) {
if (n.getNodeType() == Node.ELEMENT_NODE) {
return (Element) n;
}
n = n.getNextSibling();
}
return null;
}
/**
* <b>DOM</b>: Implements {@link ElementTraversal#getPreviousElementSibling()}.
*/
public Element getPreviousElementSibling() {
Node n = getPreviousSibling();
while (n != null) {
if (n.getNodeType() == Node.ELEMENT_NODE) {
return (Element) n;
}
n = n.getPreviousSibling();
}
return (Element) n;
}
/**
* <b>DOM</b>: Implements {@link ElementTraversal#getChildElementCount()}.
*/
public int getChildElementCount() {
getChildNodes();
return childNodes.elementChildren;
}
/**
* An implementation of the {@link org.w3c.dom.NamedNodeMap}.
*
* <br>This Map is not Thread-safe, concurrent updates or reading while updating may give
* unexpected results.
*/
public class NamedNodeHashMap implements NamedNodeMap, Serializable {
/**
* The initial capacity
*/
protected static final int INITIAL_CAPACITY = 3;
/**
* The underlying array
*/
protected Entry[] table;
/**
* The number of entries
*/
protected int count;
/**
* Creates a new NamedNodeHashMap object.
*/
public NamedNodeHashMap() {
table = new Entry[INITIAL_CAPACITY];
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.NamedNodeMap#getNamedItem(String)}.
*/
public Node getNamedItem( String name ) {
if ( name == null ) {
return null;
}
return get( null, name );
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.NamedNodeMap#setNamedItem(Node)}.
*/
public Node setNamedItem( Node arg ) throws DOMException {
if ( arg == null ) {
return null;
}
checkNode( arg );
return setNamedItem( null, arg.getNodeName(), arg );
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.NamedNodeMap#removeNamedItem(String)}.
*/
public Node removeNamedItem( String name ) throws DOMException {
return removeNamedItemNS( null, name );
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.NamedNodeMap#item(int)}.
*/
public Node item( int index ) {
if ( index < 0 || index >= count ) {
return null;
}
int j = 0;
for (Entry aTable : table) {
Entry e = aTable;
if (e == null) {
continue;
}
do {
if (j++ == index) {
return e.value;
}
e = e.next;
} while (e != null);
}
return null;
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.NamedNodeMap#getLength()}.
*/
public int getLength() {
return count;
}
/**
* <b>DOM</b>: Implements {@link
* org.w3c.dom.NamedNodeMap#getNamedItemNS(String,String)}.
*/
public Node getNamedItemNS( String namespaceURI, String localName ) {
if ( namespaceURI != null && namespaceURI.length() == 0 ) {
namespaceURI = null;
}
return get( namespaceURI, localName );
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.NamedNodeMap#setNamedItemNS(Node)}.
*/
public Node setNamedItemNS( Node arg ) throws DOMException {
if ( arg == null ) {
return null;
}
String nsURI = arg.getNamespaceURI();
return setNamedItem( nsURI,
( nsURI == null )
? arg.getNodeName()
: arg.getLocalName(), arg );
}
/**
* <b>DOM</b>: Implements {@link org.w3c.dom.NamedNodeMap#removeNamedItemNS(String,String)}.
*/
public Node removeNamedItemNS( String namespaceURI, String localName )
throws DOMException {
if ( isReadonly() ) {
throw createDOMException
( DOMException.NO_MODIFICATION_ALLOWED_ERR,
"readonly.node.map",
new Object[]{} );
}
if ( localName == null ) {
throw createDOMException( DOMException.NOT_FOUND_ERR,
"attribute.missing",
new Object[]{""} );
}
if ( namespaceURI != null && namespaceURI.length() == 0 ) {
namespaceURI = null;
}
AbstractAttr n = (AbstractAttr)remove( namespaceURI, localName );
if ( n == null ) {
throw createDOMException( DOMException.NOT_FOUND_ERR,
"attribute.missing",
new Object[]{localName} );
}
n.setOwnerElement( null );
// Mutation event
fireDOMAttrModifiedEvent( n.getNodeName(), n, n.getNodeValue(), "",
MutationEvent.REMOVAL );
return n;
}
/**
* Adds a node to the map.
*/
public Node setNamedItem( String ns, String name, Node arg )
throws DOMException {
if ( ns != null && ns.length() == 0 ) {
ns = null;
}
( (AbstractAttr)arg ).setOwnerElement( AbstractElement.this );
AbstractAttr result = (AbstractAttr)put( ns, name, arg );
if ( result != null ) {
result.setOwnerElement( null );
fireDOMAttrModifiedEvent( name,
result,
result.getNodeValue(),
"",
MutationEvent.REMOVAL );
}
fireDOMAttrModifiedEvent( name,
(Attr)arg,
"",
arg.getNodeValue(),
MutationEvent.ADDITION );
return result;
}
/**
* Checks the validity of a node to add.
*/
protected void checkNode( Node arg ) {
if ( isReadonly() ) {
throw createDOMException
( DOMException.NO_MODIFICATION_ALLOWED_ERR,
"readonly.node.map",
new Object[]{} );
}
if ( getOwnerDocument() != arg.getOwnerDocument() ) {
throw createDOMException( DOMException.WRONG_DOCUMENT_ERR,
"node.from.wrong.document",
new Object[]{(int) arg.getNodeType(),
arg.getNodeName()} );
}
if ( arg.getNodeType() == ATTRIBUTE_NODE &&
( (Attr)arg ).getOwnerElement() != null ) {
throw createDOMException( DOMException.WRONG_DOCUMENT_ERR,
"inuse.attribute",
new Object[]{arg.getNodeName()} );
}
}
/**
* Gets the value of a variable
*
* @return the value or null
*/
protected Node get( String ns, String nm ) {
int hash = hashCode( ns, nm ) & 0x7FFFFFFF;
int index = hash % table.length;
for ( Entry e = table[ index ]; e != null; e = e.next ) {
if ( ( e.hash == hash ) && e.match( ns, nm ) ) {
return e.value;
}
}
return null;
}
/**
* Sets a new value for the given variable
*
* @return the old value or null
*/
protected Node put( String ns, String nm, Node value ) {
int hash = hashCode( ns, nm ) & 0x7FFFFFFF;
int index = hash % table.length;
for ( Entry e = table[ index ]; e != null; e = e.next ) {
if ( ( e.hash == hash ) && e.match( ns, nm ) ) {
Node old = e.value;
e.value = value;
return old;
}
}
// The key is not in the hash table
int len = table.length;
if ( count++ >= ( len - ( len >> 2 ) ) ) {
// more than 75% loaded: grow
rehash();
index = hash % table.length;
}
Entry e = new Entry( hash, ns, nm, value, table[ index ] );
table[ index ] = e;
return null;
}
/**
* Removes an entry from the table.
*
* @return the value or null.
*/
protected Node remove( String ns, String nm ) {
int hash = hashCode( ns, nm ) & 0x7FFFFFFF;
int index = hash % table.length;
Entry p = null;
for ( Entry e = table[ index ]; e != null; e = e.next ) {
if ( ( e.hash == hash ) && e.match( ns, nm ) ) {
Node result = e.value;
if ( p == null ) {
table[ index ] = e.next;
} else {
p.next = e.next;
}
count--;
return result;
}
p = e;
}
return null;
}
/**
* Rehash and grow the table.
*/
protected void rehash () {
Entry[] oldTable = table;
table = new Entry[oldTable.length * 2 + 1];
for (int i = oldTable.length-1; i >= 0; i--) {
for (Entry old = oldTable[i]; old != null;) {
Entry e = old;
old = old.next;
int index = e.hash % table.length;
e.next = table[index];
table[index] = e;
}
}
}
/**
* Computes a hash code corresponding to the given strings.
*/
protected int hashCode(String ns, String nm) {
int result = (ns == null) ? 0 : ns.hashCode();
return result ^ nm.hashCode();
}
}
/**
* To manage collisions in the attributes map.
* Implements a linked list of <code>Node</code>-objects.
*/
protected static class Entry implements Serializable {
/**
* The hash code, must not change after creation.
*/
public int hash; // should be final - would that break Serialization?
/**
* The namespace URI
*/
public String namespaceURI;
/**
* The node name.
*/
public String name;
/**
* The value
*/
public Node value;
/**
* The next entry
*/
public Entry next;
/**
* Creates a new entry
*/
public Entry(int hash, String ns, String nm, Node value, Entry next) {
this.hash = hash;
this.namespaceURI = ns;
this.name = nm;
this.value = value;
this.next = next;
}
/**
* Whether this entry match the given keys.
*/
public boolean match(String ns, String nm) {
if (namespaceURI != null) {
if (!namespaceURI.equals(ns)) {
return false;
}
} else if (ns != null) {
return false;
}
return name.equals(nm);
}
}
/**
* Inner class to hold type information about this element.
*/
public static class ElementTypeInfo implements TypeInfo {
/**
* Type namespace.
*/
public String getTypeNamespace() {
return null;
}
/**
* Type name.
*/
public String getTypeName() {
return null;
}
/**
* Returns whether this type derives from the given type.
*/
public boolean isDerivedFrom(String ns, String name, int method) {
return false;
}
}
}
|
googleapis/google-cloud-java | 35,498 | java-artifact-registry/proto-google-cloud-artifact-registry-v1beta2/src/main/java/com/google/devtools/artifactregistry/v1beta2/ListTagsRequest.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/tag.proto
// Protobuf Java Version: 3.25.8
package com.google.devtools.artifactregistry.v1beta2;
/**
*
*
* <pre>
* The request to list tags.
* </pre>
*
* Protobuf type {@code google.devtools.artifactregistry.v1beta2.ListTagsRequest}
*/
public final class ListTagsRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.devtools.artifactregistry.v1beta2.ListTagsRequest)
ListTagsRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListTagsRequest.newBuilder() to construct.
private ListTagsRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListTagsRequest() {
parent_ = "";
filter_ = "";
pageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListTagsRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.devtools.artifactregistry.v1beta2.TagProto
.internal_static_google_devtools_artifactregistry_v1beta2_ListTagsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.devtools.artifactregistry.v1beta2.TagProto
.internal_static_google_devtools_artifactregistry_v1beta2_ListTagsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.devtools.artifactregistry.v1beta2.ListTagsRequest.class,
com.google.devtools.artifactregistry.v1beta2.ListTagsRequest.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 tags 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 tags 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 FILTER_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object filter_ = "";
/**
*
*
* <pre>
* An expression for filtering the results of the request. Filter rules are
* case insensitive. The fields eligible for filtering are:
*
* * `version`
*
* An example of using a filter:
*
* * `version="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"`
* --> Tags that are applied to the version `1.0` in package `pkg1`.
* </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>
* An expression for filtering the results of the request. Filter rules are
* case insensitive. The fields eligible for filtering are:
*
* * `version`
*
* An example of using a filter:
*
* * `version="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"`
* --> Tags that are applied to the version `1.0` in package `pkg1`.
* </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 PAGE_SIZE_FIELD_NUMBER = 2;
private int pageSize_ = 0;
/**
*
*
* <pre>
* The maximum number of tags to return. Maximum page size is 10,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;
}
}
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_);
}
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_);
}
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.ListTagsRequest)) {
return super.equals(obj);
}
com.google.devtools.artifactregistry.v1beta2.ListTagsRequest other =
(com.google.devtools.artifactregistry.v1beta2.ListTagsRequest) 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.devtools.artifactregistry.v1beta2.ListTagsRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.artifactregistry.v1beta2.ListTagsRequest 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.ListTagsRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.artifactregistry.v1beta2.ListTagsRequest 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.ListTagsRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.devtools.artifactregistry.v1beta2.ListTagsRequest 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.ListTagsRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.devtools.artifactregistry.v1beta2.ListTagsRequest 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.ListTagsRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.devtools.artifactregistry.v1beta2.ListTagsRequest 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.ListTagsRequest 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.ListTagsRequest 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.ListTagsRequest 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 tags.
* </pre>
*
* Protobuf type {@code google.devtools.artifactregistry.v1beta2.ListTagsRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.devtools.artifactregistry.v1beta2.ListTagsRequest)
com.google.devtools.artifactregistry.v1beta2.ListTagsRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.devtools.artifactregistry.v1beta2.TagProto
.internal_static_google_devtools_artifactregistry_v1beta2_ListTagsRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.devtools.artifactregistry.v1beta2.TagProto
.internal_static_google_devtools_artifactregistry_v1beta2_ListTagsRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.devtools.artifactregistry.v1beta2.ListTagsRequest.class,
com.google.devtools.artifactregistry.v1beta2.ListTagsRequest.Builder.class);
}
// Construct using com.google.devtools.artifactregistry.v1beta2.ListTagsRequest.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.devtools.artifactregistry.v1beta2.TagProto
.internal_static_google_devtools_artifactregistry_v1beta2_ListTagsRequest_descriptor;
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1beta2.ListTagsRequest
getDefaultInstanceForType() {
return com.google.devtools.artifactregistry.v1beta2.ListTagsRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1beta2.ListTagsRequest build() {
com.google.devtools.artifactregistry.v1beta2.ListTagsRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1beta2.ListTagsRequest buildPartial() {
com.google.devtools.artifactregistry.v1beta2.ListTagsRequest result =
new com.google.devtools.artifactregistry.v1beta2.ListTagsRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.devtools.artifactregistry.v1beta2.ListTagsRequest 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.devtools.artifactregistry.v1beta2.ListTagsRequest) {
return mergeFrom((com.google.devtools.artifactregistry.v1beta2.ListTagsRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.devtools.artifactregistry.v1beta2.ListTagsRequest other) {
if (other
== com.google.devtools.artifactregistry.v1beta2.ListTagsRequest.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 16:
{
pageSize_ = input.readInt32();
bitField0_ |= 0x00000004;
break;
} // case 16
case 26:
{
pageToken_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 26
case 34:
{
filter_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
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 java.lang.Object parent_ = "";
/**
*
*
* <pre>
* The name of the parent resource whose tags 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 tags 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 tags 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 tags 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 tags 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 java.lang.Object filter_ = "";
/**
*
*
* <pre>
* An expression for filtering the results of the request. Filter rules are
* case insensitive. The fields eligible for filtering are:
*
* * `version`
*
* An example of using a filter:
*
* * `version="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"`
* --> Tags that are applied to the version `1.0` in package `pkg1`.
* </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>
* An expression for filtering the results of the request. Filter rules are
* case insensitive. The fields eligible for filtering are:
*
* * `version`
*
* An example of using a filter:
*
* * `version="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"`
* --> Tags that are applied to the version `1.0` in package `pkg1`.
* </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>
* An expression for filtering the results of the request. Filter rules are
* case insensitive. The fields eligible for filtering are:
*
* * `version`
*
* An example of using a filter:
*
* * `version="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"`
* --> Tags that are applied to the version `1.0` in package `pkg1`.
* </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_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* An expression for filtering the results of the request. Filter rules are
* case insensitive. The fields eligible for filtering are:
*
* * `version`
*
* An example of using a filter:
*
* * `version="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"`
* --> Tags that are applied to the version `1.0` in package `pkg1`.
* </pre>
*
* <code>string filter = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearFilter() {
filter_ = getDefaultInstance().getFilter();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* An expression for filtering the results of the request. Filter rules are
* case insensitive. The fields eligible for filtering are:
*
* * `version`
*
* An example of using a filter:
*
* * `version="projects/p1/locations/us-central1/repositories/repo1/packages/pkg1/versions/1.0"`
* --> Tags that are applied to the version `1.0` in package `pkg1`.
* </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_ |= 0x00000002;
onChanged();
return this;
}
private int pageSize_;
/**
*
*
* <pre>
* The maximum number of tags to return. Maximum page size is 10,000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return The pageSize.
*/
@java.lang.Override
public int getPageSize() {
return pageSize_;
}
/**
*
*
* <pre>
* The maximum number of tags to return. Maximum page size is 10,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_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The maximum number of tags to return. Maximum page size is 10,000.
* </pre>
*
* <code>int32 page_size = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearPageSize() {
bitField0_ = (bitField0_ & ~0x00000004);
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_ |= 0x00000008;
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_ & ~0x00000008);
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_ |= 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.devtools.artifactregistry.v1beta2.ListTagsRequest)
}
// @@protoc_insertion_point(class_scope:google.devtools.artifactregistry.v1beta2.ListTagsRequest)
private static final com.google.devtools.artifactregistry.v1beta2.ListTagsRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.devtools.artifactregistry.v1beta2.ListTagsRequest();
}
public static com.google.devtools.artifactregistry.v1beta2.ListTagsRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListTagsRequest> PARSER =
new com.google.protobuf.AbstractParser<ListTagsRequest>() {
@java.lang.Override
public ListTagsRequest 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<ListTagsRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListTagsRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.devtools.artifactregistry.v1beta2.ListTagsRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,561 | java-dialogflow-cx/proto-google-cloud-dialogflow-cx-v3beta1/src/main/java/com/google/cloud/dialogflow/cx/v3beta1/ToolCall.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/dialogflow/cx/v3beta1/tool_call.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dialogflow.cx.v3beta1;
/**
*
*
* <pre>
* Represents a call of a specific tool's action with the specified inputs.
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.ToolCall}
*/
public final class ToolCall extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.cx.v3beta1.ToolCall)
ToolCallOrBuilder {
private static final long serialVersionUID = 0L;
// Use ToolCall.newBuilder() to construct.
private ToolCall(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ToolCall() {
tool_ = "";
action_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ToolCall();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.cx.v3beta1.ToolCallProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_ToolCall_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.cx.v3beta1.ToolCallProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_ToolCall_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.cx.v3beta1.ToolCall.class,
com.google.cloud.dialogflow.cx.v3beta1.ToolCall.Builder.class);
}
private int bitField0_;
public static final int TOOL_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object tool_ = "";
/**
*
*
* <pre>
* The [tool][Tool] associated with this call.
* Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
* ID>/tools/<Tool ID>`.
* </pre>
*
* <code>
* string tool = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The tool.
*/
@java.lang.Override
public java.lang.String getTool() {
java.lang.Object ref = tool_;
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();
tool_ = s;
return s;
}
}
/**
*
*
* <pre>
* The [tool][Tool] associated with this call.
* Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
* ID>/tools/<Tool ID>`.
* </pre>
*
* <code>
* string tool = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for tool.
*/
@java.lang.Override
public com.google.protobuf.ByteString getToolBytes() {
java.lang.Object ref = tool_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
tool_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ACTION_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object action_ = "";
/**
*
*
* <pre>
* The name of the tool's action associated with this call.
* </pre>
*
* <code>string action = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The action.
*/
@java.lang.Override
public java.lang.String getAction() {
java.lang.Object ref = action_;
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();
action_ = s;
return s;
}
}
/**
*
*
* <pre>
* The name of the tool's action associated with this call.
* </pre>
*
* <code>string action = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for action.
*/
@java.lang.Override
public com.google.protobuf.ByteString getActionBytes() {
java.lang.Object ref = action_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
action_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int INPUT_PARAMETERS_FIELD_NUMBER = 3;
private com.google.protobuf.Struct inputParameters_;
/**
*
*
* <pre>
* The action's input parameters.
* </pre>
*
* <code>.google.protobuf.Struct input_parameters = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the inputParameters field is set.
*/
@java.lang.Override
public boolean hasInputParameters() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The action's input parameters.
* </pre>
*
* <code>.google.protobuf.Struct input_parameters = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The inputParameters.
*/
@java.lang.Override
public com.google.protobuf.Struct getInputParameters() {
return inputParameters_ == null
? com.google.protobuf.Struct.getDefaultInstance()
: inputParameters_;
}
/**
*
*
* <pre>
* The action's input parameters.
* </pre>
*
* <code>.google.protobuf.Struct input_parameters = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
@java.lang.Override
public com.google.protobuf.StructOrBuilder getInputParametersOrBuilder() {
return inputParameters_ == null
? com.google.protobuf.Struct.getDefaultInstance()
: inputParameters_;
}
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(tool_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, tool_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(action_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, action_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(3, getInputParameters());
}
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(tool_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, tool_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(action_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, action_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getInputParameters());
}
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.dialogflow.cx.v3beta1.ToolCall)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.cx.v3beta1.ToolCall other =
(com.google.cloud.dialogflow.cx.v3beta1.ToolCall) obj;
if (!getTool().equals(other.getTool())) return false;
if (!getAction().equals(other.getAction())) return false;
if (hasInputParameters() != other.hasInputParameters()) return false;
if (hasInputParameters()) {
if (!getInputParameters().equals(other.getInputParameters())) 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) + TOOL_FIELD_NUMBER;
hash = (53 * hash) + getTool().hashCode();
hash = (37 * hash) + ACTION_FIELD_NUMBER;
hash = (53 * hash) + getAction().hashCode();
if (hasInputParameters()) {
hash = (37 * hash) + INPUT_PARAMETERS_FIELD_NUMBER;
hash = (53 * hash) + getInputParameters().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.dialogflow.cx.v3beta1.ToolCall parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ToolCall 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.dialogflow.cx.v3beta1.ToolCall parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ToolCall 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.dialogflow.cx.v3beta1.ToolCall parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ToolCall parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ToolCall parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ToolCall 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.dialogflow.cx.v3beta1.ToolCall parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ToolCall 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.dialogflow.cx.v3beta1.ToolCall parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.cx.v3beta1.ToolCall 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.dialogflow.cx.v3beta1.ToolCall 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>
* Represents a call of a specific tool's action with the specified inputs.
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.cx.v3beta1.ToolCall}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.cx.v3beta1.ToolCall)
com.google.cloud.dialogflow.cx.v3beta1.ToolCallOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.cx.v3beta1.ToolCallProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_ToolCall_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.cx.v3beta1.ToolCallProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_ToolCall_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.cx.v3beta1.ToolCall.class,
com.google.cloud.dialogflow.cx.v3beta1.ToolCall.Builder.class);
}
// Construct using com.google.cloud.dialogflow.cx.v3beta1.ToolCall.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getInputParametersFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
tool_ = "";
action_ = "";
inputParameters_ = null;
if (inputParametersBuilder_ != null) {
inputParametersBuilder_.dispose();
inputParametersBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.dialogflow.cx.v3beta1.ToolCallProto
.internal_static_google_cloud_dialogflow_cx_v3beta1_ToolCall_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.ToolCall getDefaultInstanceForType() {
return com.google.cloud.dialogflow.cx.v3beta1.ToolCall.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.ToolCall build() {
com.google.cloud.dialogflow.cx.v3beta1.ToolCall result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.ToolCall buildPartial() {
com.google.cloud.dialogflow.cx.v3beta1.ToolCall result =
new com.google.cloud.dialogflow.cx.v3beta1.ToolCall(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.dialogflow.cx.v3beta1.ToolCall result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.tool_ = tool_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.action_ = action_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.inputParameters_ =
inputParametersBuilder_ == null ? inputParameters_ : inputParametersBuilder_.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.dialogflow.cx.v3beta1.ToolCall) {
return mergeFrom((com.google.cloud.dialogflow.cx.v3beta1.ToolCall) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.cx.v3beta1.ToolCall other) {
if (other == com.google.cloud.dialogflow.cx.v3beta1.ToolCall.getDefaultInstance())
return this;
if (!other.getTool().isEmpty()) {
tool_ = other.tool_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getAction().isEmpty()) {
action_ = other.action_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasInputParameters()) {
mergeInputParameters(other.getInputParameters());
}
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:
{
tool_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
action_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getInputParametersFieldBuilder().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 tool_ = "";
/**
*
*
* <pre>
* The [tool][Tool] associated with this call.
* Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
* ID>/tools/<Tool ID>`.
* </pre>
*
* <code>
* string tool = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The tool.
*/
public java.lang.String getTool() {
java.lang.Object ref = tool_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
tool_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The [tool][Tool] associated with this call.
* Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
* ID>/tools/<Tool ID>`.
* </pre>
*
* <code>
* string tool = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for tool.
*/
public com.google.protobuf.ByteString getToolBytes() {
java.lang.Object ref = tool_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
tool_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The [tool][Tool] associated with this call.
* Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
* ID>/tools/<Tool ID>`.
* </pre>
*
* <code>
* string tool = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The tool to set.
* @return This builder for chaining.
*/
public Builder setTool(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
tool_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The [tool][Tool] associated with this call.
* Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
* ID>/tools/<Tool ID>`.
* </pre>
*
* <code>
* string tool = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearTool() {
tool_ = getDefaultInstance().getTool();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The [tool][Tool] associated with this call.
* Format: `projects/<Project ID>/locations/<Location ID>/agents/<Agent
* ID>/tools/<Tool ID>`.
* </pre>
*
* <code>
* string tool = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for tool to set.
* @return This builder for chaining.
*/
public Builder setToolBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
tool_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object action_ = "";
/**
*
*
* <pre>
* The name of the tool's action associated with this call.
* </pre>
*
* <code>string action = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The action.
*/
public java.lang.String getAction() {
java.lang.Object ref = action_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
action_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The name of the tool's action associated with this call.
* </pre>
*
* <code>string action = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for action.
*/
public com.google.protobuf.ByteString getActionBytes() {
java.lang.Object ref = action_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
action_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The name of the tool's action associated with this call.
* </pre>
*
* <code>string action = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The action to set.
* @return This builder for chaining.
*/
public Builder setAction(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
action_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the tool's action associated with this call.
* </pre>
*
* <code>string action = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearAction() {
action_ = getDefaultInstance().getAction();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the tool's action associated with this call.
* </pre>
*
* <code>string action = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for action to set.
* @return This builder for chaining.
*/
public Builder setActionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
action_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.protobuf.Struct inputParameters_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Struct,
com.google.protobuf.Struct.Builder,
com.google.protobuf.StructOrBuilder>
inputParametersBuilder_;
/**
*
*
* <pre>
* The action's input parameters.
* </pre>
*
* <code>.google.protobuf.Struct input_parameters = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the inputParameters field is set.
*/
public boolean hasInputParameters() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* The action's input parameters.
* </pre>
*
* <code>.google.protobuf.Struct input_parameters = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The inputParameters.
*/
public com.google.protobuf.Struct getInputParameters() {
if (inputParametersBuilder_ == null) {
return inputParameters_ == null
? com.google.protobuf.Struct.getDefaultInstance()
: inputParameters_;
} else {
return inputParametersBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The action's input parameters.
* </pre>
*
* <code>.google.protobuf.Struct input_parameters = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setInputParameters(com.google.protobuf.Struct value) {
if (inputParametersBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
inputParameters_ = value;
} else {
inputParametersBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The action's input parameters.
* </pre>
*
* <code>.google.protobuf.Struct input_parameters = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder setInputParameters(com.google.protobuf.Struct.Builder builderForValue) {
if (inputParametersBuilder_ == null) {
inputParameters_ = builderForValue.build();
} else {
inputParametersBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The action's input parameters.
* </pre>
*
* <code>.google.protobuf.Struct input_parameters = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder mergeInputParameters(com.google.protobuf.Struct value) {
if (inputParametersBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& inputParameters_ != null
&& inputParameters_ != com.google.protobuf.Struct.getDefaultInstance()) {
getInputParametersBuilder().mergeFrom(value);
} else {
inputParameters_ = value;
}
} else {
inputParametersBuilder_.mergeFrom(value);
}
if (inputParameters_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The action's input parameters.
* </pre>
*
* <code>.google.protobuf.Struct input_parameters = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder clearInputParameters() {
bitField0_ = (bitField0_ & ~0x00000004);
inputParameters_ = null;
if (inputParametersBuilder_ != null) {
inputParametersBuilder_.dispose();
inputParametersBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The action's input parameters.
* </pre>
*
* <code>.google.protobuf.Struct input_parameters = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.protobuf.Struct.Builder getInputParametersBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getInputParametersFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The action's input parameters.
* </pre>
*
* <code>.google.protobuf.Struct input_parameters = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.protobuf.StructOrBuilder getInputParametersOrBuilder() {
if (inputParametersBuilder_ != null) {
return inputParametersBuilder_.getMessageOrBuilder();
} else {
return inputParameters_ == null
? com.google.protobuf.Struct.getDefaultInstance()
: inputParameters_;
}
}
/**
*
*
* <pre>
* The action's input parameters.
* </pre>
*
* <code>.google.protobuf.Struct input_parameters = 3 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Struct,
com.google.protobuf.Struct.Builder,
com.google.protobuf.StructOrBuilder>
getInputParametersFieldBuilder() {
if (inputParametersBuilder_ == null) {
inputParametersBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Struct,
com.google.protobuf.Struct.Builder,
com.google.protobuf.StructOrBuilder>(
getInputParameters(), getParentForChildren(), isClean());
inputParameters_ = null;
}
return inputParametersBuilder_;
}
@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.dialogflow.cx.v3beta1.ToolCall)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.cx.v3beta1.ToolCall)
private static final com.google.cloud.dialogflow.cx.v3beta1.ToolCall DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.cx.v3beta1.ToolCall();
}
public static com.google.cloud.dialogflow.cx.v3beta1.ToolCall getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ToolCall> PARSER =
new com.google.protobuf.AbstractParser<ToolCall>() {
@java.lang.Override
public ToolCall 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<ToolCall> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ToolCall> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.cx.v3beta1.ToolCall getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,687 | java-iap/proto-google-cloud-iap-v1/src/main/java/com/google/cloud/iap/v1/OAuthSettings.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/iap/v1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.iap.v1;
/**
*
*
* <pre>
* Configuration for OAuth login&consent flow behavior as well as for OAuth
* Credentials.
* </pre>
*
* Protobuf type {@code google.cloud.iap.v1.OAuthSettings}
*/
public final class OAuthSettings extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.iap.v1.OAuthSettings)
OAuthSettingsOrBuilder {
private static final long serialVersionUID = 0L;
// Use OAuthSettings.newBuilder() to construct.
private OAuthSettings(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private OAuthSettings() {
programmaticClients_ = com.google.protobuf.LazyStringArrayList.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new OAuthSettings();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_OAuthSettings_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_OAuthSettings_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iap.v1.OAuthSettings.class,
com.google.cloud.iap.v1.OAuthSettings.Builder.class);
}
private int bitField0_;
public static final int LOGIN_HINT_FIELD_NUMBER = 2;
private com.google.protobuf.StringValue loginHint_;
/**
*
*
* <pre>
* Domain hint to send as hd=? parameter in OAuth request flow. Enables
* redirect to primary IDP by skipping Google's login screen.
* https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
* Note: IAP does not verify that the id token's hd claim matches this value
* since access behavior is managed by IAM policies.
* </pre>
*
* <code>.google.protobuf.StringValue login_hint = 2;</code>
*
* @return Whether the loginHint field is set.
*/
@java.lang.Override
public boolean hasLoginHint() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Domain hint to send as hd=? parameter in OAuth request flow. Enables
* redirect to primary IDP by skipping Google's login screen.
* https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
* Note: IAP does not verify that the id token's hd claim matches this value
* since access behavior is managed by IAM policies.
* </pre>
*
* <code>.google.protobuf.StringValue login_hint = 2;</code>
*
* @return The loginHint.
*/
@java.lang.Override
public com.google.protobuf.StringValue getLoginHint() {
return loginHint_ == null ? com.google.protobuf.StringValue.getDefaultInstance() : loginHint_;
}
/**
*
*
* <pre>
* Domain hint to send as hd=? parameter in OAuth request flow. Enables
* redirect to primary IDP by skipping Google's login screen.
* https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
* Note: IAP does not verify that the id token's hd claim matches this value
* since access behavior is managed by IAM policies.
* </pre>
*
* <code>.google.protobuf.StringValue login_hint = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.StringValueOrBuilder getLoginHintOrBuilder() {
return loginHint_ == null ? com.google.protobuf.StringValue.getDefaultInstance() : loginHint_;
}
public static final int PROGRAMMATIC_CLIENTS_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private com.google.protobuf.LazyStringArrayList programmaticClients_ =
com.google.protobuf.LazyStringArrayList.emptyList();
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return A list containing the programmaticClients.
*/
public com.google.protobuf.ProtocolStringList getProgrammaticClientsList() {
return programmaticClients_;
}
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The count of programmaticClients.
*/
public int getProgrammaticClientsCount() {
return programmaticClients_.size();
}
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the element to return.
* @return The programmaticClients at the given index.
*/
public java.lang.String getProgrammaticClients(int index) {
return programmaticClients_.get(index);
}
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the programmaticClients at the given index.
*/
public com.google.protobuf.ByteString getProgrammaticClientsBytes(int index) {
return programmaticClients_.getByteString(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 (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getLoginHint());
}
for (int i = 0; i < programmaticClients_.size(); i++) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, programmaticClients_.getRaw(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(2, getLoginHint());
}
{
int dataSize = 0;
for (int i = 0; i < programmaticClients_.size(); i++) {
dataSize += computeStringSizeNoTag(programmaticClients_.getRaw(i));
}
size += dataSize;
size += 1 * getProgrammaticClientsList().size();
}
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.iap.v1.OAuthSettings)) {
return super.equals(obj);
}
com.google.cloud.iap.v1.OAuthSettings other = (com.google.cloud.iap.v1.OAuthSettings) obj;
if (hasLoginHint() != other.hasLoginHint()) return false;
if (hasLoginHint()) {
if (!getLoginHint().equals(other.getLoginHint())) return false;
}
if (!getProgrammaticClientsList().equals(other.getProgrammaticClientsList())) 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 (hasLoginHint()) {
hash = (37 * hash) + LOGIN_HINT_FIELD_NUMBER;
hash = (53 * hash) + getLoginHint().hashCode();
}
if (getProgrammaticClientsCount() > 0) {
hash = (37 * hash) + PROGRAMMATIC_CLIENTS_FIELD_NUMBER;
hash = (53 * hash) + getProgrammaticClientsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.iap.v1.OAuthSettings parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iap.v1.OAuthSettings 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.iap.v1.OAuthSettings parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iap.v1.OAuthSettings 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.iap.v1.OAuthSettings parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.iap.v1.OAuthSettings parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.iap.v1.OAuthSettings parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iap.v1.OAuthSettings 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.iap.v1.OAuthSettings parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.iap.v1.OAuthSettings 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.iap.v1.OAuthSettings parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.iap.v1.OAuthSettings 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.iap.v1.OAuthSettings 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>
* Configuration for OAuth login&consent flow behavior as well as for OAuth
* Credentials.
* </pre>
*
* Protobuf type {@code google.cloud.iap.v1.OAuthSettings}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.iap.v1.OAuthSettings)
com.google.cloud.iap.v1.OAuthSettingsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_OAuthSettings_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_OAuthSettings_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.iap.v1.OAuthSettings.class,
com.google.cloud.iap.v1.OAuthSettings.Builder.class);
}
// Construct using com.google.cloud.iap.v1.OAuthSettings.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getLoginHintFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
loginHint_ = null;
if (loginHintBuilder_ != null) {
loginHintBuilder_.dispose();
loginHintBuilder_ = null;
}
programmaticClients_ = com.google.protobuf.LazyStringArrayList.emptyList();
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.iap.v1.Service
.internal_static_google_cloud_iap_v1_OAuthSettings_descriptor;
}
@java.lang.Override
public com.google.cloud.iap.v1.OAuthSettings getDefaultInstanceForType() {
return com.google.cloud.iap.v1.OAuthSettings.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.iap.v1.OAuthSettings build() {
com.google.cloud.iap.v1.OAuthSettings result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.iap.v1.OAuthSettings buildPartial() {
com.google.cloud.iap.v1.OAuthSettings result =
new com.google.cloud.iap.v1.OAuthSettings(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.iap.v1.OAuthSettings result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.loginHint_ = loginHintBuilder_ == null ? loginHint_ : loginHintBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
programmaticClients_.makeImmutable();
result.programmaticClients_ = programmaticClients_;
}
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.iap.v1.OAuthSettings) {
return mergeFrom((com.google.cloud.iap.v1.OAuthSettings) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.iap.v1.OAuthSettings other) {
if (other == com.google.cloud.iap.v1.OAuthSettings.getDefaultInstance()) return this;
if (other.hasLoginHint()) {
mergeLoginHint(other.getLoginHint());
}
if (!other.programmaticClients_.isEmpty()) {
if (programmaticClients_.isEmpty()) {
programmaticClients_ = other.programmaticClients_;
bitField0_ |= 0x00000002;
} else {
ensureProgrammaticClientsIsMutable();
programmaticClients_.addAll(other.programmaticClients_);
}
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 18:
{
input.readMessage(getLoginHintFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000001;
break;
} // case 18
case 42:
{
java.lang.String s = input.readStringRequireUtf8();
ensureProgrammaticClientsIsMutable();
programmaticClients_.add(s);
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 com.google.protobuf.StringValue loginHint_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.StringValue,
com.google.protobuf.StringValue.Builder,
com.google.protobuf.StringValueOrBuilder>
loginHintBuilder_;
/**
*
*
* <pre>
* Domain hint to send as hd=? parameter in OAuth request flow. Enables
* redirect to primary IDP by skipping Google's login screen.
* https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
* Note: IAP does not verify that the id token's hd claim matches this value
* since access behavior is managed by IAM policies.
* </pre>
*
* <code>.google.protobuf.StringValue login_hint = 2;</code>
*
* @return Whether the loginHint field is set.
*/
public boolean hasLoginHint() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Domain hint to send as hd=? parameter in OAuth request flow. Enables
* redirect to primary IDP by skipping Google's login screen.
* https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
* Note: IAP does not verify that the id token's hd claim matches this value
* since access behavior is managed by IAM policies.
* </pre>
*
* <code>.google.protobuf.StringValue login_hint = 2;</code>
*
* @return The loginHint.
*/
public com.google.protobuf.StringValue getLoginHint() {
if (loginHintBuilder_ == null) {
return loginHint_ == null
? com.google.protobuf.StringValue.getDefaultInstance()
: loginHint_;
} else {
return loginHintBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Domain hint to send as hd=? parameter in OAuth request flow. Enables
* redirect to primary IDP by skipping Google's login screen.
* https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
* Note: IAP does not verify that the id token's hd claim matches this value
* since access behavior is managed by IAM policies.
* </pre>
*
* <code>.google.protobuf.StringValue login_hint = 2;</code>
*/
public Builder setLoginHint(com.google.protobuf.StringValue value) {
if (loginHintBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
loginHint_ = value;
} else {
loginHintBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Domain hint to send as hd=? parameter in OAuth request flow. Enables
* redirect to primary IDP by skipping Google's login screen.
* https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
* Note: IAP does not verify that the id token's hd claim matches this value
* since access behavior is managed by IAM policies.
* </pre>
*
* <code>.google.protobuf.StringValue login_hint = 2;</code>
*/
public Builder setLoginHint(com.google.protobuf.StringValue.Builder builderForValue) {
if (loginHintBuilder_ == null) {
loginHint_ = builderForValue.build();
} else {
loginHintBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Domain hint to send as hd=? parameter in OAuth request flow. Enables
* redirect to primary IDP by skipping Google's login screen.
* https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
* Note: IAP does not verify that the id token's hd claim matches this value
* since access behavior is managed by IAM policies.
* </pre>
*
* <code>.google.protobuf.StringValue login_hint = 2;</code>
*/
public Builder mergeLoginHint(com.google.protobuf.StringValue value) {
if (loginHintBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& loginHint_ != null
&& loginHint_ != com.google.protobuf.StringValue.getDefaultInstance()) {
getLoginHintBuilder().mergeFrom(value);
} else {
loginHint_ = value;
}
} else {
loginHintBuilder_.mergeFrom(value);
}
if (loginHint_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Domain hint to send as hd=? parameter in OAuth request flow. Enables
* redirect to primary IDP by skipping Google's login screen.
* https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
* Note: IAP does not verify that the id token's hd claim matches this value
* since access behavior is managed by IAM policies.
* </pre>
*
* <code>.google.protobuf.StringValue login_hint = 2;</code>
*/
public Builder clearLoginHint() {
bitField0_ = (bitField0_ & ~0x00000001);
loginHint_ = null;
if (loginHintBuilder_ != null) {
loginHintBuilder_.dispose();
loginHintBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Domain hint to send as hd=? parameter in OAuth request flow. Enables
* redirect to primary IDP by skipping Google's login screen.
* https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
* Note: IAP does not verify that the id token's hd claim matches this value
* since access behavior is managed by IAM policies.
* </pre>
*
* <code>.google.protobuf.StringValue login_hint = 2;</code>
*/
public com.google.protobuf.StringValue.Builder getLoginHintBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getLoginHintFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Domain hint to send as hd=? parameter in OAuth request flow. Enables
* redirect to primary IDP by skipping Google's login screen.
* https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
* Note: IAP does not verify that the id token's hd claim matches this value
* since access behavior is managed by IAM policies.
* </pre>
*
* <code>.google.protobuf.StringValue login_hint = 2;</code>
*/
public com.google.protobuf.StringValueOrBuilder getLoginHintOrBuilder() {
if (loginHintBuilder_ != null) {
return loginHintBuilder_.getMessageOrBuilder();
} else {
return loginHint_ == null
? com.google.protobuf.StringValue.getDefaultInstance()
: loginHint_;
}
}
/**
*
*
* <pre>
* Domain hint to send as hd=? parameter in OAuth request flow. Enables
* redirect to primary IDP by skipping Google's login screen.
* https://developers.google.com/identity/protocols/OpenIDConnect#hd-param
* Note: IAP does not verify that the id token's hd claim matches this value
* since access behavior is managed by IAM policies.
* </pre>
*
* <code>.google.protobuf.StringValue login_hint = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.StringValue,
com.google.protobuf.StringValue.Builder,
com.google.protobuf.StringValueOrBuilder>
getLoginHintFieldBuilder() {
if (loginHintBuilder_ == null) {
loginHintBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.StringValue,
com.google.protobuf.StringValue.Builder,
com.google.protobuf.StringValueOrBuilder>(
getLoginHint(), getParentForChildren(), isClean());
loginHint_ = null;
}
return loginHintBuilder_;
}
private com.google.protobuf.LazyStringArrayList programmaticClients_ =
com.google.protobuf.LazyStringArrayList.emptyList();
private void ensureProgrammaticClientsIsMutable() {
if (!programmaticClients_.isModifiable()) {
programmaticClients_ = new com.google.protobuf.LazyStringArrayList(programmaticClients_);
}
bitField0_ |= 0x00000002;
}
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return A list containing the programmaticClients.
*/
public com.google.protobuf.ProtocolStringList getProgrammaticClientsList() {
programmaticClients_.makeImmutable();
return programmaticClients_;
}
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The count of programmaticClients.
*/
public int getProgrammaticClientsCount() {
return programmaticClients_.size();
}
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the element to return.
* @return The programmaticClients at the given index.
*/
public java.lang.String getProgrammaticClients(int index) {
return programmaticClients_.get(index);
}
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index of the value to return.
* @return The bytes of the programmaticClients at the given index.
*/
public com.google.protobuf.ByteString getProgrammaticClientsBytes(int index) {
return programmaticClients_.getByteString(index);
}
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param index The index to set the value at.
* @param value The programmaticClients to set.
* @return This builder for chaining.
*/
public Builder setProgrammaticClients(int index, java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureProgrammaticClientsIsMutable();
programmaticClients_.set(index, value);
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The programmaticClients to add.
* @return This builder for chaining.
*/
public Builder addProgrammaticClients(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
ensureProgrammaticClientsIsMutable();
programmaticClients_.add(value);
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param values The programmaticClients to add.
* @return This builder for chaining.
*/
public Builder addAllProgrammaticClients(java.lang.Iterable<java.lang.String> values) {
ensureProgrammaticClientsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, programmaticClients_);
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearProgrammaticClients() {
programmaticClients_ = com.google.protobuf.LazyStringArrayList.emptyList();
bitField0_ = (bitField0_ & ~0x00000002);
;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. List of client ids allowed to use IAP programmatically.
* </pre>
*
* <code>repeated string programmatic_clients = 5 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The bytes of the programmaticClients to add.
* @return This builder for chaining.
*/
public Builder addProgrammaticClientsBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
ensureProgrammaticClientsIsMutable();
programmaticClients_.add(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.iap.v1.OAuthSettings)
}
// @@protoc_insertion_point(class_scope:google.cloud.iap.v1.OAuthSettings)
private static final com.google.cloud.iap.v1.OAuthSettings DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.iap.v1.OAuthSettings();
}
public static com.google.cloud.iap.v1.OAuthSettings getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<OAuthSettings> PARSER =
new com.google.protobuf.AbstractParser<OAuthSettings>() {
@java.lang.Override
public OAuthSettings 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<OAuthSettings> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<OAuthSettings> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.iap.v1.OAuthSettings getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/phoenix | 34,957 | phoenix-core/src/it/java/org/apache/phoenix/end2end/CostBasedDecisionIT.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.phoenix.end2end;
import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Map;
import java.util.Properties;
import org.apache.phoenix.compile.ExplainPlan;
import org.apache.phoenix.compile.ExplainPlanAttributes;
import org.apache.phoenix.jdbc.PhoenixPreparedStatement;
import org.apache.phoenix.query.BaseTest;
import org.apache.phoenix.query.QueryServices;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.QueryUtil;
import org.apache.phoenix.util.ReadOnlyProps;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.phoenix.thirdparty.com.google.common.collect.Maps;
@Category(NeedsOwnMiniClusterTest.class)
public class CostBasedDecisionIT extends BaseTest {
private final String testTable500;
private final String testTable990;
private final String testTable1000;
@BeforeClass
public static synchronized void doSetup() throws Exception {
Map<String, String> props = Maps.newHashMapWithExpectedSize(1);
props.put(QueryServices.STATS_GUIDEPOST_WIDTH_BYTES_ATTRIB, Long.toString(20));
props.put(QueryServices.STATS_UPDATE_FREQ_MS_ATTRIB, Long.toString(5));
props.put(QueryServices.USE_STATS_FOR_PARALLELIZATION, Boolean.toString(true));
props.put(QueryServices.COST_BASED_OPTIMIZER_ENABLED, Boolean.toString(true));
props.put(QueryServices.MAX_SERVER_CACHE_SIZE_ATTRIB, Long.toString(150000));
setUpTestDriver(new ReadOnlyProps(props.entrySet().iterator()));
}
public CostBasedDecisionIT() throws Exception {
testTable500 = initTestTableValues(500);
testTable990 = initTestTableValues(990);
testTable1000 = initTestTableValues(1000);
}
@Test
public void testCostOverridesStaticPlanOrdering1() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(true);
try {
String tableName = BaseTest.generateUniqueName();
conn.createStatement().execute("CREATE TABLE " + tableName + " (\n"
+ "rowkey VARCHAR PRIMARY KEY,\n" + "c1 VARCHAR,\n" + "c2 VARCHAR)");
conn.createStatement()
.execute("CREATE LOCAL INDEX " + tableName + "_idx ON " + tableName + " (c1)");
String query =
"SELECT rowkey, c1, c2 FROM " + tableName + " where c1 LIKE 'X0%' ORDER BY rowkey";
// Use the data table plan that opts out order-by when stats are not available.
verifyQueryPlan(query, "FULL SCAN");
PreparedStatement stmt =
conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
for (int i = 0; i < 10000; i++) {
int c1 = i % 16;
stmt.setString(1, "k" + i);
stmt.setString(2, "X" + Integer.toHexString(c1) + c1);
stmt.setString(3, "c");
stmt.execute();
}
conn.createStatement().execute("UPDATE STATISTICS " + tableName);
// Use the index table plan that has a lower cost when stats become available.
verifyQueryPlan(query, "RANGE SCAN");
} finally {
conn.close();
}
}
@Test
public void testCostOverridesStaticPlanOrdering2() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(true);
try {
String tableName = BaseTest.generateUniqueName();
String indexName = tableName + "_IDX";
conn.createStatement().execute("CREATE TABLE " + tableName + " (\n"
+ "rowkey VARCHAR PRIMARY KEY,\n" + "c1 VARCHAR,\n" + "c2 VARCHAR)");
conn.createStatement()
.execute("CREATE LOCAL INDEX " + indexName + " ON " + tableName + " (c1)");
String query =
"SELECT c1, max(rowkey), max(c2) FROM " + tableName + " where rowkey <= 'z' GROUP BY c1";
// Use the index table plan that opts out order-by when stats are not available.
ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
.optimizeQuery().getExplainPlan();
ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
assertEquals(tableName, explainPlanAttributes.getTableName());
assertEquals(" [*] - ['z']", explainPlanAttributes.getKeyRanges());
assertEquals("SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]",
explainPlanAttributes.getServerAggregate());
assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
PreparedStatement stmt =
conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
for (int i = 0; i < 10000; i++) {
int c1 = i % 16;
stmt.setString(1, "k" + i);
stmt.setString(2, "X" + Integer.toHexString(c1) + c1);
stmt.setString(3, "c");
stmt.execute();
}
conn.createStatement().execute("UPDATE STATISTICS " + tableName);
// Given that the range on C1 is meaningless and group-by becomes
// order-preserving if using the data table, the data table plan should
// come out as the best plan based on the costs.
plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
.getExplainPlan();
explainPlanAttributes = plan.getPlanStepsAsAttributes();
assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
assertEquals(indexName + "(" + tableName + ")", explainPlanAttributes.getTableName());
assertEquals(" [1]", explainPlanAttributes.getKeyRanges());
assertEquals("SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" <= 'z'",
explainPlanAttributes.getServerWhereFilter());
assertEquals("SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]",
explainPlanAttributes.getServerAggregate());
assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
} finally {
conn.close();
}
}
@Test
public void testCostOverridesStaticPlanOrdering3() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(true);
try {
String tableName = BaseTest.generateUniqueName();
String indexName1 = tableName + "_IDX1";
String indexName2 = tableName + "_IDX2";
conn.createStatement().execute("CREATE TABLE " + tableName + " (\n"
+ "rowkey VARCHAR PRIMARY KEY,\n" + "c1 INTEGER,\n" + "c2 INTEGER,\n" + "c3 INTEGER)");
conn.createStatement().execute(
"CREATE LOCAL INDEX " + indexName1 + " ON " + tableName + " (c1) INCLUDE (c2, c3)");
conn.createStatement().execute(
"CREATE LOCAL INDEX " + indexName2 + " ON " + tableName + " (c2, c3) INCLUDE (c1)");
String query =
"SELECT * FROM " + tableName + " where c1 BETWEEN 10 AND 20 AND c2 < 9000 AND C3 < 5000";
// Use the idx2 plan with a wider PK slot span when stats are not available.
ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
.optimizeQuery().getExplainPlan();
ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
assertEquals(indexName2 + "(" + tableName + ")", explainPlanAttributes.getTableName());
assertEquals(" [2,*] - [2,9,000]", explainPlanAttributes.getKeyRanges());
assertEquals(
"SERVER FILTER BY ((\"C1\" >= 10 AND \"C1\" <= 20) AND TO_INTEGER(\"C3\") < 5000)",
explainPlanAttributes.getServerWhereFilter());
assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
PreparedStatement stmt = conn
.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2, c3) VALUES (?, ?, ?, ?)");
for (int i = 0; i < 10000; i++) {
stmt.setString(1, "k" + i);
stmt.setInt(2, i);
stmt.setInt(3, i);
stmt.setInt(4, i);
stmt.execute();
}
conn.createStatement().execute("UPDATE STATISTICS " + tableName);
// Use the idx2 plan that scans less data when stats become available.
plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
.getExplainPlan();
explainPlanAttributes = plan.getPlanStepsAsAttributes();
assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
assertEquals("RANGE SCAN ", explainPlanAttributes.getExplainScanType());
assertEquals(indexName1 + "(" + tableName + ")", explainPlanAttributes.getTableName());
assertEquals(" [1,10] - [1,20]", explainPlanAttributes.getKeyRanges());
assertEquals("SERVER FILTER BY (\"C2\" < 9000 AND \"C3\" < 5000)",
explainPlanAttributes.getServerWhereFilter());
assertEquals("CLIENT MERGE SORT", explainPlanAttributes.getClientSortAlgo());
} finally {
conn.close();
}
}
@Test
public void testCostOverridesStaticPlanOrderingInUpsertQuery() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(true);
try {
String tableName = BaseTest.generateUniqueName();
String indexName1 = tableName + "_IDX1";
String indexName2 = tableName + "_IDX2";
conn.createStatement().execute("CREATE TABLE " + tableName + " (\n"
+ "rowkey VARCHAR PRIMARY KEY,\n" + "c1 INTEGER,\n" + "c2 INTEGER,\n" + "c3 INTEGER)");
conn.createStatement()
.execute("CREATE LOCAL INDEX " + indexName1 + " ON " + tableName + "(c1) INCLUDE (c2, c3)");
conn.createStatement().execute(
"CREATE LOCAL INDEX " + indexName2 + " ON " + tableName + " (c2, c3) INCLUDE (c1)");
String query = "UPSERT INTO " + tableName + " SELECT * FROM " + tableName
+ " where c1 BETWEEN 10 AND 20 AND c2 < 9000 AND C3 < 5000";
// Use the idx2 plan with a wider PK slot span when stats are not available.
verifyQueryPlan(query,
"UPSERT SELECT\n" + "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName2 + "(" + tableName
+ ")" + " [2,*] - [2,9,000]\n"
+ " SERVER FILTER BY ((\"C1\" >= 10 AND \"C1\" <= 20) AND TO_INTEGER(\"C3\") < 5000)\n"
+ "CLIENT MERGE SORT");
PreparedStatement stmt = conn
.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2, c3) VALUES (?, ?, ?, ?)");
for (int i = 0; i < 10000; i++) {
stmt.setString(1, "k" + i);
stmt.setInt(2, i);
stmt.setInt(3, i);
stmt.setInt(4, i);
stmt.execute();
}
conn.createStatement().execute("UPDATE STATISTICS " + tableName);
// Use the idx2 plan that scans less data when stats become available.
verifyQueryPlan(query,
"UPSERT SELECT\n" + "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName1 + "(" + tableName
+ ")" + " [1,10] - [1,20]\n" + " SERVER FILTER BY (\"C2\" < 9000 AND \"C3\" < 5000)\n"
+ "CLIENT MERGE SORT");
} finally {
conn.close();
}
}
@Test
public void testCostOverridesStaticPlanOrderingInDeleteQuery() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(true);
try {
String tableName = BaseTest.generateUniqueName();
String indexName1 = tableName + "_IDX1";
String indexName2 = tableName + "_IDX2";
conn.createStatement().execute("CREATE TABLE " + tableName + " (\n"
+ "rowkey VARCHAR PRIMARY KEY,\n" + "c1 INTEGER,\n" + "c2 INTEGER,\n" + "c3 INTEGER)");
conn.createStatement().execute(
"CREATE LOCAL INDEX " + indexName1 + " ON " + tableName + " (c1) INCLUDE (c2, c3)");
conn.createStatement().execute(
"CREATE LOCAL INDEX " + indexName2 + " ON " + tableName + " (c2, c3) INCLUDE (c1)");
String query =
"DELETE FROM " + tableName + " where c1 BETWEEN 10 AND 20 AND c2 < 9000 AND C3 < 5000";
// Use the idx2 plan with a wider PK slot span when stats are not available.
verifyQueryPlan(query,
"DELETE ROWS CLIENT SELECT\n" + "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName2 + "("
+ tableName + ")" + " [2,*] - [2,9,000]\n"
+ " SERVER FILTER BY ((\"C1\" >= 10 AND \"C1\" <= 20) AND TO_INTEGER(\"C3\") < 5000)\n"
+ "CLIENT MERGE SORT");
PreparedStatement stmt = conn
.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2, c3) VALUES (?, ?, ?, ?)");
for (int i = 0; i < 10000; i++) {
stmt.setString(1, "k" + i);
stmt.setInt(2, i);
stmt.setInt(3, i);
stmt.setInt(4, i);
stmt.execute();
}
conn.createStatement().execute("UPDATE STATISTICS " + tableName);
// Use the idx2 plan that scans less data when stats become available.
verifyQueryPlan(query,
"DELETE ROWS CLIENT SELECT\n" + "CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName1 + "("
+ tableName + ")" + " [1,10] - [1,20]\n"
+ " SERVER FILTER BY (\"C2\" < 9000 AND \"C3\" < 5000)\n" + "CLIENT MERGE SORT");
} finally {
conn.close();
}
}
@Test
public void testCostOverridesStaticPlanOrderingInUnionQuery() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(true);
try {
String tableName = BaseTest.generateUniqueName();
String indexName = tableName + "_IDX";
conn.createStatement().execute("CREATE TABLE " + tableName + " (\n"
+ "rowkey VARCHAR PRIMARY KEY,\n" + "c1 VARCHAR,\n" + "c2 VARCHAR)");
conn.createStatement()
.execute("CREATE LOCAL INDEX " + indexName + " ON " + tableName + " (c1)");
String query = "SELECT c1, max(rowkey), max(c2) FROM " + tableName
+ " where rowkey <= 'z' GROUP BY c1 " + "UNION ALL SELECT c1, max(rowkey), max(c2) FROM "
+ tableName + " where rowkey >= 'a' GROUP BY c1";
// Use the default plan when stats are not available.
verifyQueryPlan(query,
"UNION ALL OVER 2 QUERIES\n" + " CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName
+ " [*] - ['z']\n" + " SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]\n"
+ " CLIENT MERGE SORT\n" + " CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName
+ " ['a'] - [*]\n" + " SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]\n"
+ " CLIENT MERGE SORT");
PreparedStatement stmt =
conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
for (int i = 0; i < 10000; i++) {
int c1 = i % 16;
stmt.setString(1, "k" + i);
stmt.setString(2, "X" + Integer.toHexString(c1) + c1);
stmt.setString(3, "c");
stmt.execute();
}
conn.createStatement().execute("UPDATE STATISTICS " + tableName);
// Use the optimal plan based on cost when stats become available.
verifyQueryPlan(query,
"UNION ALL OVER 2 QUERIES\n" + " CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName
+ "(" + tableName + ") [1]\n" + " SERVER MERGE [0.C2]\n"
+ " SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" <= 'z'\n"
+ " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]\n"
+ " CLIENT MERGE SORT\n" + " CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName
+ "(" + tableName + ") [1]\n" + " SERVER MERGE [0.C2]\n"
+ " SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" >= 'a'\n"
+ " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]\n"
+ " CLIENT MERGE SORT");
} finally {
conn.close();
}
}
@Test
public void testCostOverridesStaticPlanOrderingInJoinQuery() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(true);
try {
String tableName = BaseTest.generateUniqueName();
String indexName = tableName + "_IDX";
conn.createStatement().execute("CREATE TABLE " + tableName + " (\n"
+ "rowkey VARCHAR PRIMARY KEY,\n" + "c1 VARCHAR,\n" + "c2 VARCHAR)");
conn.createStatement()
.execute("CREATE LOCAL INDEX " + tableName + "_idx ON " + tableName + " (c1)");
String query = "SELECT t1.rowkey, t1.c1, t1.c2, t2.c1, mc2 FROM " + tableName + " t1 "
+ "JOIN (SELECT c1, max(rowkey) mrk, max(c2) mc2 FROM " + tableName
+ " where rowkey <= 'z' GROUP BY c1) t2 "
+ "ON t1.rowkey = t2.mrk WHERE t1.c1 LIKE 'X0%' ORDER BY t1.rowkey";
// Use the default plan when stats are not available.
verifyQueryPlan(query,
"CLIENT PARALLEL 1-WAY FULL SCAN OVER " + tableName + "\n"
+ " SERVER FILTER BY C1 LIKE 'X0%'\n" + " PARALLEL INNER-JOIN TABLE 0\n"
+ " CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + tableName + " [*] - ['z']\n"
+ " SERVER AGGREGATE INTO DISTINCT ROWS BY [C1]\n"
+ " CLIENT MERGE SORT\n" + " DYNAMIC SERVER FILTER BY T1.ROWKEY IN (T2.MRK)");
PreparedStatement stmt =
conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
for (int i = 0; i < 10000; i++) {
int c1 = i % 16;
stmt.setString(1, "k" + i);
stmt.setString(2, "X" + Integer.toHexString(c1) + c1);
stmt.setString(3, "c");
stmt.execute();
}
conn.createStatement().execute("UPDATE STATISTICS " + tableName);
// Use the optimal plan based on cost when stats become available.
verifyQueryPlan(query,
"CLIENT PARALLEL 626-WAY RANGE SCAN OVER " + indexName + "(" + tableName
+ ") [1,'X0'] - [1,'X1']\n" + " SERVER MERGE [0.C2]\n"
+ " SERVER FILTER BY FIRST KEY ONLY\n" + " SERVER SORTED BY [\"T1.:ROWKEY\"]\n"
+ "CLIENT MERGE SORT\n" + " PARALLEL INNER-JOIN TABLE 0\n"
+ " CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + indexName + "(" + tableName
+ ") [1]\n" + " SERVER MERGE [0.C2]\n"
+ " SERVER FILTER BY FIRST KEY ONLY AND \"ROWKEY\" <= 'z'\n"
+ " SERVER AGGREGATE INTO ORDERED DISTINCT ROWS BY [\"C1\"]\n"
+ " CLIENT MERGE SORT\n"
+ " DYNAMIC SERVER FILTER BY \"T1.:ROWKEY\" IN (T2.MRK)");
} finally {
conn.close();
}
}
@Test
public void testHintOverridesCost() throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
conn.setAutoCommit(true);
try {
String tableName = BaseTest.generateUniqueName();
conn.createStatement().execute("CREATE TABLE " + tableName + " (\n"
+ "rowkey INTEGER PRIMARY KEY,\n" + "c1 VARCHAR,\n" + "c2 VARCHAR)");
conn.createStatement()
.execute("CREATE LOCAL INDEX " + tableName + "_idx ON " + tableName + " (c1)");
String query =
"SELECT rowkey, c1, c2 FROM " + tableName + " where rowkey between 1 and 10 ORDER BY c1";
String hintedQuery = query.replaceFirst("SELECT",
"SELECT /*+ INDEX(" + tableName + " " + tableName + "_idx) */");
String dataPlan = "[C1]";
String indexPlan =
"SERVER FILTER BY FIRST KEY ONLY AND (\"ROWKEY\" >= 1 AND \"ROWKEY\" <= 10)";
// Use the index table plan that opts out order-by when stats are not available.
ExplainPlan plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class)
.optimizeQuery().getExplainPlan();
ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
assertEquals(indexPlan, explainPlanAttributes.getServerWhereFilter());
PreparedStatement stmt =
conn.prepareStatement("UPSERT INTO " + tableName + " (rowkey, c1, c2) VALUES (?, ?, ?)");
for (int i = 0; i < 10000; i++) {
int c1 = i % 16;
stmt.setInt(1, i);
stmt.setString(2, "X" + Integer.toHexString(c1) + c1);
stmt.setString(3, "c");
stmt.execute();
}
conn.createStatement().execute("UPDATE STATISTICS " + tableName);
// Use the data table plan that has a lower cost when stats are available.
plan = conn.prepareStatement(query).unwrap(PhoenixPreparedStatement.class).optimizeQuery()
.getExplainPlan();
explainPlanAttributes = plan.getPlanStepsAsAttributes();
assertEquals(dataPlan, explainPlanAttributes.getServerSortedBy());
// Use the index table plan as has been hinted.
plan = conn.prepareStatement(hintedQuery).unwrap(PhoenixPreparedStatement.class)
.optimizeQuery().getExplainPlan();
explainPlanAttributes = plan.getPlanStepsAsAttributes();
assertEquals(indexPlan, explainPlanAttributes.getServerWhereFilter());
} finally {
conn.close();
}
}
/** Sort-merge-join w/ both children ordered wins over hash-join. */
@Test
public void testJoinStrategy() throws Exception {
String q = "SELECT *\n" + "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n"
+ "ON t1.ID = t2.ID";
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
ExplainPlan plan = conn.prepareStatement(q).unwrap(PhoenixPreparedStatement.class)
.optimizeQuery().getExplainPlan();
ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
assertEquals("SORT-MERGE-JOIN (INNER)", explainPlanAttributes.getAbstractExplainPlan());
assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
assertEquals(testTable500, explainPlanAttributes.getTableName());
ExplainPlanAttributes rhsTable = explainPlanAttributes.getRhsJoinQueryExplainPlan();
assertEquals("PARALLEL 1-WAY", rhsTable.getIteratorTypeAndScanSize());
assertEquals("FULL SCAN ", rhsTable.getExplainScanType());
assertEquals(testTable1000, rhsTable.getTableName());
}
}
/**
* Sort-merge-join w/ both children ordered wins over hash-join in an un-grouped aggregate query.
*/
@Test
public void testJoinStrategy2() throws Exception {
String q = "SELECT count(*)\n" + "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n"
+ "ON t1.ID = t2.ID\n" + "WHERE t1.COL1 < 200";
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
ExplainPlan plan = conn.prepareStatement(q).unwrap(PhoenixPreparedStatement.class)
.optimizeQuery().getExplainPlan();
ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
assertEquals("SORT-MERGE-JOIN (INNER)", explainPlanAttributes.getAbstractExplainPlan());
assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
assertEquals("SERVER FILTER BY COL1 < 200", explainPlanAttributes.getServerWhereFilter());
assertEquals(testTable500, explainPlanAttributes.getTableName());
assertEquals("CLIENT AGGREGATE INTO SINGLE ROW", explainPlanAttributes.getClientAggregate());
ExplainPlanAttributes rhsTable = explainPlanAttributes.getRhsJoinQueryExplainPlan();
assertEquals("PARALLEL 1-WAY", rhsTable.getIteratorTypeAndScanSize());
assertEquals("FULL SCAN ", rhsTable.getExplainScanType());
assertEquals("SERVER FILTER BY FIRST KEY ONLY", rhsTable.getServerWhereFilter());
assertEquals(testTable1000, rhsTable.getTableName());
}
}
/** Hash-join w/ PK/FK optimization wins over sort-merge-join w/ larger side ordered. */
@Test
public void testJoinStrategy3() throws Exception {
String q = "SELECT *\n" + "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n"
+ "ON t1.COL1 = t2.ID\n" + "WHERE t1.ID > 200";
String expected = "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n"
+ " PARALLEL INNER-JOIN TABLE 0\n" + " CLIENT PARALLEL 1-WAY RANGE SCAN OVER "
+ testTable500 + " [201] - [*]\n" + " DYNAMIC SERVER FILTER BY T2.ID IN (T1.COL1)";
verifyQueryPlan(q, expected);
}
/**
* Hash-join w/ PK/FK optimization wins over hash-join w/o PK/FK optimization when two sides are
* close in size.
*/
@Test
public void testJoinStrategy4() throws Exception {
String q = "SELECT *\n" + "FROM " + testTable990 + " t1 JOIN " + testTable1000 + " t2\n"
+ "ON t1.ID = t2.COL1";
String expected = "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable990 + "\n"
+ " PARALLEL INNER-JOIN TABLE 0\n" + " CLIENT PARALLEL 1-WAY FULL SCAN OVER "
+ testTable1000 + "\n" + " DYNAMIC SERVER FILTER BY T1.ID IN (T2.COL1)";
verifyQueryPlan(q, expected);
}
/** Hash-join wins over sort-merge-join w/ smaller side ordered. */
@Test
public void testJoinStrategy5() throws Exception {
String q = "SELECT *\n" + "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n"
+ "ON t1.ID = t2.COL1\n" + "WHERE t1.ID > 200";
String expected = "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n"
+ " PARALLEL INNER-JOIN TABLE 0\n" + " CLIENT PARALLEL 1-WAY RANGE SCAN OVER "
+ testTable500 + " [201] - [*]";
verifyQueryPlan(q, expected);
}
/** Hash-join wins over sort-merge-join w/o any side ordered. */
@Test
public void testJoinStrategy6() throws Exception {
String q = "SELECT *\n" + "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n"
+ "ON t1.COL1 = t2.COL1\n" + "WHERE t1.ID > 200";
String expected = "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n"
+ " PARALLEL INNER-JOIN TABLE 0\n" + " CLIENT PARALLEL 1-WAY RANGE SCAN OVER "
+ testTable500 + " [201] - [*]";
verifyQueryPlan(q, expected);
}
/**
* Hash-join wins over sort-merge-join w/ both sides ordered in an order-by query. This is because
* order-by can only be done on the client side after sort-merge-join and order-by w/o limit on
* the client side is very expensive.
*/
@Test
public void testJoinStrategy7() throws Exception {
String q = "SELECT *\n" + "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n"
+ "ON t1.ID = t2.ID\n" + "ORDER BY t1.COL1";
String expected = "CLIENT PARALLEL 1001-WAY FULL SCAN OVER " + testTable1000 + "\n"
+ " SERVER SORTED BY [T1.COL1]\n" + "CLIENT MERGE SORT\n"
+ " PARALLEL INNER-JOIN TABLE 0\n" + " CLIENT PARALLEL 1-WAY FULL SCAN OVER "
+ testTable500 + "\n" + " DYNAMIC SERVER FILTER BY T2.ID IN (T1.ID)";
verifyQueryPlan(q, expected);
}
/**
* Sort-merge-join w/ both sides ordered wins over hash-join in an order-by limit query. This is
* because order-by can only be done on the client side after sort-merge-join but order-by w/
* limit on the client side is less expensive.
*/
@Test
public void testJoinStrategy8() throws Exception {
String q = "SELECT *\n" + "FROM " + testTable500 + " t1 JOIN " + testTable1000 + " t2\n"
+ "ON t1.ID = t2.ID\n" + "ORDER BY t1.COL1 LIMIT 5";
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
ExplainPlan plan = conn.prepareStatement(q).unwrap(PhoenixPreparedStatement.class)
.optimizeQuery().getExplainPlan();
ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes();
assertEquals("SORT-MERGE-JOIN (INNER)", explainPlanAttributes.getAbstractExplainPlan());
assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize());
assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType());
assertEquals(testTable500, explainPlanAttributes.getTableName());
assertEquals("[T1.COL1]", explainPlanAttributes.getClientSortedBy());
assertEquals(new Integer(5), explainPlanAttributes.getClientRowLimit());
ExplainPlanAttributes rhsTable = explainPlanAttributes.getRhsJoinQueryExplainPlan();
assertEquals("PARALLEL 1-WAY", rhsTable.getIteratorTypeAndScanSize());
assertEquals("FULL SCAN ", rhsTable.getExplainScanType());
assertEquals(testTable1000, rhsTable.getTableName());
}
}
/**
* Multi-table join: sort-merge-join chosen since all join keys are PK.
*/
@Test
public void testJoinStrategy9() throws Exception {
String q = "SELECT *\n" + "FROM " + testTable1000 + " t1 LEFT JOIN " + testTable500 + " t2\n"
+ "ON t1.ID = t2.ID AND t2.ID > 200\n" + "LEFT JOIN " + testTable990 + " t3\n"
+ "ON t1.ID = t3.ID AND t3.ID < 100";
String expected = "SORT-MERGE-JOIN (LEFT) TABLES\n" + " SORT-MERGE-JOIN (LEFT) TABLES\n"
+ " CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n" + " AND\n"
+ " CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable500 + " [201] - [*]\n" + "AND\n"
+ " CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable990 + " [*] - [100]";
verifyQueryPlan(q, expected);
}
/**
* Multi-table join: a mix of join strategies chosen based on cost.
*/
@Test
public void testJoinStrategy10() throws Exception {
String q = "SELECT *\n" + "FROM " + testTable1000 + " t1 JOIN " + testTable500 + " t2\n"
+ "ON t1.ID = t2.COL1 AND t2.ID > 200\n" + "JOIN " + testTable990 + " t3\n"
+ "ON t1.ID = t3.ID AND t3.ID < 100";
String expected =
"SORT-MERGE-JOIN (INNER) TABLES\n" + " CLIENT PARALLEL 1-WAY FULL SCAN OVER "
+ testTable1000 + "\n" + " PARALLEL INNER-JOIN TABLE 0\n"
+ " CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable500 + " [201] - [*]\n"
+ " DYNAMIC SERVER FILTER BY T1.ID IN (T2.COL1)\n" + "AND\n"
+ " CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable990 + " [*] - [100]";
verifyQueryPlan(q, expected);
}
/**
* Multi-table join: hash-join two tables in parallel since two RHS tables are both small and can
* fit in memory at the same time.
*/
@Test
public void testJoinStrategy11() throws Exception {
String q = "SELECT *\n" + "FROM " + testTable1000 + " t1 JOIN " + testTable500 + " t2\n"
+ "ON t1.COL2 = t2.COL1 AND t2.ID > 200\n" + "JOIN " + testTable990 + " t3\n"
+ "ON t1.COL1 = t3.COL2 AND t3.ID < 100";
String expected = "CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable1000 + "\n"
+ " PARALLEL INNER-JOIN TABLE 0\n" + " CLIENT PARALLEL 1-WAY RANGE SCAN OVER "
+ testTable500 + " [201] - [*]\n" + " PARALLEL INNER-JOIN TABLE 1\n"
+ " CLIENT PARALLEL 1-WAY RANGE SCAN OVER " + testTable990 + " [*] - [100]";
verifyQueryPlan(q, expected);
}
/**
* Multi-table join: similar to {@link this#testJoinStrategy11()}, but the two RHS tables cannot
* fit in memory at the same time, and thus a mix of join strategies is chosen based on cost.
*/
@Test
public void testJoinStrategy12() throws Exception {
String q = "SELECT *\n" + "FROM " + testTable1000 + " t1 JOIN " + testTable990 + " t2\n"
+ "ON t1.COL2 = t2.COL1\n" + "JOIN " + testTable990 + " t3\n" + "ON t1.COL1 = t3.COL2";
String expected =
"SORT-MERGE-JOIN (INNER) TABLES\n" + " CLIENT PARALLEL 1001-WAY FULL SCAN OVER "
+ testTable1000 + "\n" + " SERVER SORTED BY [T1.COL1]\n" + " CLIENT MERGE SORT\n"
+ " PARALLEL INNER-JOIN TABLE 0\n"
+ " CLIENT PARALLEL 1-WAY FULL SCAN OVER " + testTable990 + "\n" + "AND\n"
+ " CLIENT PARALLEL 991-WAY FULL SCAN OVER " + testTable990 + "\n"
+ " SERVER SORTED BY [T3.COL2]\n" + " CLIENT MERGE SORT";
verifyQueryPlan(q, expected);
}
private static void verifyQueryPlan(String query, String expected) throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
Connection conn = DriverManager.getConnection(getUrl(), props);
ResultSet rs = conn.createStatement().executeQuery("explain " + query);
String plan = QueryUtil.getExplainPlan(rs);
assertTrue("Expected '" + expected + "' in the plan:\n" + plan + ".", plan.contains(expected));
}
private static String initTestTableValues(int rows) throws Exception {
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
String tableName = generateUniqueName();
conn.createStatement().execute("CREATE TABLE " + tableName + " (\n"
+ "ID INTEGER NOT NULL PRIMARY KEY,\n" + "COL1 INTEGER," + "COL2 INTEGER)");
PreparedStatement stmt =
conn.prepareStatement("UPSERT INTO " + tableName + " VALUES(?, ?, ?)");
for (int i = 0; i < rows; i++) {
stmt.setInt(1, i + 1);
stmt.setInt(2, rows - i);
stmt.setInt(3, rows + i);
stmt.execute();
}
conn.commit();
conn.createStatement().execute("UPDATE STATISTICS " + tableName);
return tableName;
}
}
}
|
googleapis/google-cloud-java | 35,835 | java-shopping-merchant-inventories/grpc-google-shopping-merchant-inventories-v1beta/src/main/java/com/google/shopping/merchant/inventories/v1beta/RegionalInventoryServiceGrpc.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.shopping.merchant.inventories.v1beta;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
*
*
* <pre>
* Service to manage regional inventory for products. There is also separate
* `regions` resource and API to manage regions definitions.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: google/shopping/merchant/inventories/v1beta/regionalinventory.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class RegionalInventoryServiceGrpc {
private RegionalInventoryServiceGrpc() {}
public static final java.lang.String SERVICE_NAME =
"google.shopping.merchant.inventories.v1beta.RegionalInventoryService";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesRequest,
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse>
getListRegionalInventoriesMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "ListRegionalInventories",
requestType =
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesRequest.class,
responseType =
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesRequest,
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse>
getListRegionalInventoriesMethod() {
io.grpc.MethodDescriptor<
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesRequest,
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse>
getListRegionalInventoriesMethod;
if ((getListRegionalInventoriesMethod =
RegionalInventoryServiceGrpc.getListRegionalInventoriesMethod)
== null) {
synchronized (RegionalInventoryServiceGrpc.class) {
if ((getListRegionalInventoriesMethod =
RegionalInventoryServiceGrpc.getListRegionalInventoriesMethod)
== null) {
RegionalInventoryServiceGrpc.getListRegionalInventoriesMethod =
getListRegionalInventoriesMethod =
io.grpc.MethodDescriptor
.<com.google.shopping.merchant.inventories.v1beta
.ListRegionalInventoriesRequest,
com.google.shopping.merchant.inventories.v1beta
.ListRegionalInventoriesResponse>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
generateFullMethodName(SERVICE_NAME, "ListRegionalInventories"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.shopping.merchant.inventories.v1beta
.ListRegionalInventoriesRequest.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.shopping.merchant.inventories.v1beta
.ListRegionalInventoriesResponse.getDefaultInstance()))
.setSchemaDescriptor(
new RegionalInventoryServiceMethodDescriptorSupplier(
"ListRegionalInventories"))
.build();
}
}
}
return getListRegionalInventoriesMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest,
com.google.shopping.merchant.inventories.v1beta.RegionalInventory>
getInsertRegionalInventoryMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "InsertRegionalInventory",
requestType =
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest.class,
responseType = com.google.shopping.merchant.inventories.v1beta.RegionalInventory.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest,
com.google.shopping.merchant.inventories.v1beta.RegionalInventory>
getInsertRegionalInventoryMethod() {
io.grpc.MethodDescriptor<
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest,
com.google.shopping.merchant.inventories.v1beta.RegionalInventory>
getInsertRegionalInventoryMethod;
if ((getInsertRegionalInventoryMethod =
RegionalInventoryServiceGrpc.getInsertRegionalInventoryMethod)
== null) {
synchronized (RegionalInventoryServiceGrpc.class) {
if ((getInsertRegionalInventoryMethod =
RegionalInventoryServiceGrpc.getInsertRegionalInventoryMethod)
== null) {
RegionalInventoryServiceGrpc.getInsertRegionalInventoryMethod =
getInsertRegionalInventoryMethod =
io.grpc.MethodDescriptor
.<com.google.shopping.merchant.inventories.v1beta
.InsertRegionalInventoryRequest,
com.google.shopping.merchant.inventories.v1beta.RegionalInventory>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
generateFullMethodName(SERVICE_NAME, "InsertRegionalInventory"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.shopping.merchant.inventories.v1beta
.InsertRegionalInventoryRequest.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.shopping.merchant.inventories.v1beta.RegionalInventory
.getDefaultInstance()))
.setSchemaDescriptor(
new RegionalInventoryServiceMethodDescriptorSupplier(
"InsertRegionalInventory"))
.build();
}
}
}
return getInsertRegionalInventoryMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.shopping.merchant.inventories.v1beta.DeleteRegionalInventoryRequest,
com.google.protobuf.Empty>
getDeleteRegionalInventoryMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "DeleteRegionalInventory",
requestType =
com.google.shopping.merchant.inventories.v1beta.DeleteRegionalInventoryRequest.class,
responseType = com.google.protobuf.Empty.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.shopping.merchant.inventories.v1beta.DeleteRegionalInventoryRequest,
com.google.protobuf.Empty>
getDeleteRegionalInventoryMethod() {
io.grpc.MethodDescriptor<
com.google.shopping.merchant.inventories.v1beta.DeleteRegionalInventoryRequest,
com.google.protobuf.Empty>
getDeleteRegionalInventoryMethod;
if ((getDeleteRegionalInventoryMethod =
RegionalInventoryServiceGrpc.getDeleteRegionalInventoryMethod)
== null) {
synchronized (RegionalInventoryServiceGrpc.class) {
if ((getDeleteRegionalInventoryMethod =
RegionalInventoryServiceGrpc.getDeleteRegionalInventoryMethod)
== null) {
RegionalInventoryServiceGrpc.getDeleteRegionalInventoryMethod =
getDeleteRegionalInventoryMethod =
io.grpc.MethodDescriptor
.<com.google.shopping.merchant.inventories.v1beta
.DeleteRegionalInventoryRequest,
com.google.protobuf.Empty>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
generateFullMethodName(SERVICE_NAME, "DeleteRegionalInventory"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.shopping.merchant.inventories.v1beta
.DeleteRegionalInventoryRequest.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.protobuf.Empty.getDefaultInstance()))
.setSchemaDescriptor(
new RegionalInventoryServiceMethodDescriptorSupplier(
"DeleteRegionalInventory"))
.build();
}
}
}
return getDeleteRegionalInventoryMethod;
}
/** Creates a new async stub that supports all call types for the service */
public static RegionalInventoryServiceStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<RegionalInventoryServiceStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<RegionalInventoryServiceStub>() {
@java.lang.Override
public RegionalInventoryServiceStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new RegionalInventoryServiceStub(channel, callOptions);
}
};
return RegionalInventoryServiceStub.newStub(factory, channel);
}
/** Creates a new blocking-style stub that supports all types of calls on the service */
public static RegionalInventoryServiceBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<RegionalInventoryServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<RegionalInventoryServiceBlockingV2Stub>() {
@java.lang.Override
public RegionalInventoryServiceBlockingV2Stub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new RegionalInventoryServiceBlockingV2Stub(channel, callOptions);
}
};
return RegionalInventoryServiceBlockingV2Stub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static RegionalInventoryServiceBlockingStub newBlockingStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<RegionalInventoryServiceBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<RegionalInventoryServiceBlockingStub>() {
@java.lang.Override
public RegionalInventoryServiceBlockingStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new RegionalInventoryServiceBlockingStub(channel, callOptions);
}
};
return RegionalInventoryServiceBlockingStub.newStub(factory, channel);
}
/** Creates a new ListenableFuture-style stub that supports unary calls on the service */
public static RegionalInventoryServiceFutureStub newFutureStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<RegionalInventoryServiceFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<RegionalInventoryServiceFutureStub>() {
@java.lang.Override
public RegionalInventoryServiceFutureStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new RegionalInventoryServiceFutureStub(channel, callOptions);
}
};
return RegionalInventoryServiceFutureStub.newStub(factory, channel);
}
/**
*
*
* <pre>
* Service to manage regional inventory for products. There is also separate
* `regions` resource and API to manage regions definitions.
* </pre>
*/
public interface AsyncService {
/**
*
*
* <pre>
* Lists the `RegionalInventory` resources for the given product in your
* merchant account. The response might contain fewer items than specified by
* `pageSize`. If `pageToken` was returned in previous request, it can be
* used to obtain additional results.
* `RegionalInventory` resources are listed per product for a given account.
* </pre>
*/
default void listRegionalInventories(
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesRequest request,
io.grpc.stub.StreamObserver<
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getListRegionalInventoriesMethod(), responseObserver);
}
/**
*
*
* <pre>
* Inserts a `RegionalInventory` to a given product in your
* merchant account.
* Replaces the full `RegionalInventory` resource if an entry with the same
* [`region`][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]
* already exists for the product.
* It might take up to 30 minutes for the new or updated `RegionalInventory`
* resource to appear in products.
* </pre>
*/
default void insertRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest request,
io.grpc.stub.StreamObserver<
com.google.shopping.merchant.inventories.v1beta.RegionalInventory>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getInsertRegionalInventoryMethod(), responseObserver);
}
/**
*
*
* <pre>
* Deletes the specified `RegionalInventory` resource from the given product
* in your merchant account. It might take up to an hour for the
* `RegionalInventory` to be deleted from the specific product.
* Once you have received a successful delete response, wait for that
* period before attempting a delete again.
* </pre>
*/
default void deleteRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.DeleteRegionalInventoryRequest request,
io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getDeleteRegionalInventoryMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service RegionalInventoryService.
*
* <pre>
* Service to manage regional inventory for products. There is also separate
* `regions` resource and API to manage regions definitions.
* </pre>
*/
public abstract static class RegionalInventoryServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override
public final io.grpc.ServerServiceDefinition bindService() {
return RegionalInventoryServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service RegionalInventoryService.
*
* <pre>
* Service to manage regional inventory for products. There is also separate
* `regions` resource and API to manage regions definitions.
* </pre>
*/
public static final class RegionalInventoryServiceStub
extends io.grpc.stub.AbstractAsyncStub<RegionalInventoryServiceStub> {
private RegionalInventoryServiceStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected RegionalInventoryServiceStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new RegionalInventoryServiceStub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists the `RegionalInventory` resources for the given product in your
* merchant account. The response might contain fewer items than specified by
* `pageSize`. If `pageToken` was returned in previous request, it can be
* used to obtain additional results.
* `RegionalInventory` resources are listed per product for a given account.
* </pre>
*/
public void listRegionalInventories(
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesRequest request,
io.grpc.stub.StreamObserver<
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getListRegionalInventoriesMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Inserts a `RegionalInventory` to a given product in your
* merchant account.
* Replaces the full `RegionalInventory` resource if an entry with the same
* [`region`][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]
* already exists for the product.
* It might take up to 30 minutes for the new or updated `RegionalInventory`
* resource to appear in products.
* </pre>
*/
public void insertRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest request,
io.grpc.stub.StreamObserver<
com.google.shopping.merchant.inventories.v1beta.RegionalInventory>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getInsertRegionalInventoryMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Deletes the specified `RegionalInventory` resource from the given product
* in your merchant account. It might take up to an hour for the
* `RegionalInventory` to be deleted from the specific product.
* Once you have received a successful delete response, wait for that
* period before attempting a delete again.
* </pre>
*/
public void deleteRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.DeleteRegionalInventoryRequest request,
io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getDeleteRegionalInventoryMethod(), getCallOptions()),
request,
responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service RegionalInventoryService.
*
* <pre>
* Service to manage regional inventory for products. There is also separate
* `regions` resource and API to manage regions definitions.
* </pre>
*/
public static final class RegionalInventoryServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<RegionalInventoryServiceBlockingV2Stub> {
private RegionalInventoryServiceBlockingV2Stub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected RegionalInventoryServiceBlockingV2Stub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new RegionalInventoryServiceBlockingV2Stub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists the `RegionalInventory` resources for the given product in your
* merchant account. The response might contain fewer items than specified by
* `pageSize`. If `pageToken` was returned in previous request, it can be
* used to obtain additional results.
* `RegionalInventory` resources are listed per product for a given account.
* </pre>
*/
public com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse
listRegionalInventories(
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesRequest
request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListRegionalInventoriesMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Inserts a `RegionalInventory` to a given product in your
* merchant account.
* Replaces the full `RegionalInventory` resource if an entry with the same
* [`region`][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]
* already exists for the product.
* It might take up to 30 minutes for the new or updated `RegionalInventory`
* resource to appear in products.
* </pre>
*/
public com.google.shopping.merchant.inventories.v1beta.RegionalInventory
insertRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getInsertRegionalInventoryMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Deletes the specified `RegionalInventory` resource from the given product
* in your merchant account. It might take up to an hour for the
* `RegionalInventory` to be deleted from the specific product.
* Once you have received a successful delete response, wait for that
* period before attempting a delete again.
* </pre>
*/
public com.google.protobuf.Empty deleteRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.DeleteRegionalInventoryRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeleteRegionalInventoryMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do limited synchronous rpc calls to service
* RegionalInventoryService.
*
* <pre>
* Service to manage regional inventory for products. There is also separate
* `regions` resource and API to manage regions definitions.
* </pre>
*/
public static final class RegionalInventoryServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<RegionalInventoryServiceBlockingStub> {
private RegionalInventoryServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected RegionalInventoryServiceBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new RegionalInventoryServiceBlockingStub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists the `RegionalInventory` resources for the given product in your
* merchant account. The response might contain fewer items than specified by
* `pageSize`. If `pageToken` was returned in previous request, it can be
* used to obtain additional results.
* `RegionalInventory` resources are listed per product for a given account.
* </pre>
*/
public com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse
listRegionalInventories(
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesRequest
request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListRegionalInventoriesMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Inserts a `RegionalInventory` to a given product in your
* merchant account.
* Replaces the full `RegionalInventory` resource if an entry with the same
* [`region`][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]
* already exists for the product.
* It might take up to 30 minutes for the new or updated `RegionalInventory`
* resource to appear in products.
* </pre>
*/
public com.google.shopping.merchant.inventories.v1beta.RegionalInventory
insertRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getInsertRegionalInventoryMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Deletes the specified `RegionalInventory` resource from the given product
* in your merchant account. It might take up to an hour for the
* `RegionalInventory` to be deleted from the specific product.
* Once you have received a successful delete response, wait for that
* period before attempting a delete again.
* </pre>
*/
public com.google.protobuf.Empty deleteRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.DeleteRegionalInventoryRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeleteRegionalInventoryMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service
* RegionalInventoryService.
*
* <pre>
* Service to manage regional inventory for products. There is also separate
* `regions` resource and API to manage regions definitions.
* </pre>
*/
public static final class RegionalInventoryServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<RegionalInventoryServiceFutureStub> {
private RegionalInventoryServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected RegionalInventoryServiceFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new RegionalInventoryServiceFutureStub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists the `RegionalInventory` resources for the given product in your
* merchant account. The response might contain fewer items than specified by
* `pageSize`. If `pageToken` was returned in previous request, it can be
* used to obtain additional results.
* `RegionalInventory` resources are listed per product for a given account.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesResponse>
listRegionalInventories(
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesRequest
request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getListRegionalInventoriesMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Inserts a `RegionalInventory` to a given product in your
* merchant account.
* Replaces the full `RegionalInventory` resource if an entry with the same
* [`region`][google.shopping.merchant.inventories.v1beta.RegionalInventory.region]
* already exists for the product.
* It might take up to 30 minutes for the new or updated `RegionalInventory`
* resource to appear in products.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.shopping.merchant.inventories.v1beta.RegionalInventory>
insertRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest
request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getInsertRegionalInventoryMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Deletes the specified `RegionalInventory` resource from the given product
* in your merchant account. It might take up to an hour for the
* `RegionalInventory` to be deleted from the specific product.
* Once you have received a successful delete response, wait for that
* period before attempting a delete again.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.protobuf.Empty>
deleteRegionalInventory(
com.google.shopping.merchant.inventories.v1beta.DeleteRegionalInventoryRequest
request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getDeleteRegionalInventoryMethod(), getCallOptions()), request);
}
}
private static final int METHODID_LIST_REGIONAL_INVENTORIES = 0;
private static final int METHODID_INSERT_REGIONAL_INVENTORY = 1;
private static final int METHODID_DELETE_REGIONAL_INVENTORY = 2;
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_REGIONAL_INVENTORIES:
serviceImpl.listRegionalInventories(
(com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesRequest)
request,
(io.grpc.stub.StreamObserver<
com.google.shopping.merchant.inventories.v1beta
.ListRegionalInventoriesResponse>)
responseObserver);
break;
case METHODID_INSERT_REGIONAL_INVENTORY:
serviceImpl.insertRegionalInventory(
(com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest)
request,
(io.grpc.stub.StreamObserver<
com.google.shopping.merchant.inventories.v1beta.RegionalInventory>)
responseObserver);
break;
case METHODID_DELETE_REGIONAL_INVENTORY:
serviceImpl.deleteRegionalInventory(
(com.google.shopping.merchant.inventories.v1beta.DeleteRegionalInventoryRequest)
request,
(io.grpc.stub.StreamObserver<com.google.protobuf.Empty>) 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(
getListRegionalInventoriesMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.shopping.merchant.inventories.v1beta.ListRegionalInventoriesRequest,
com.google.shopping.merchant.inventories.v1beta
.ListRegionalInventoriesResponse>(
service, METHODID_LIST_REGIONAL_INVENTORIES)))
.addMethod(
getInsertRegionalInventoryMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.shopping.merchant.inventories.v1beta.InsertRegionalInventoryRequest,
com.google.shopping.merchant.inventories.v1beta.RegionalInventory>(
service, METHODID_INSERT_REGIONAL_INVENTORY)))
.addMethod(
getDeleteRegionalInventoryMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.shopping.merchant.inventories.v1beta.DeleteRegionalInventoryRequest,
com.google.protobuf.Empty>(service, METHODID_DELETE_REGIONAL_INVENTORY)))
.build();
}
private abstract static class RegionalInventoryServiceBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier,
io.grpc.protobuf.ProtoServiceDescriptorSupplier {
RegionalInventoryServiceBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.google.shopping.merchant.inventories.v1beta.RegionalInventoryProto.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("RegionalInventoryService");
}
}
private static final class RegionalInventoryServiceFileDescriptorSupplier
extends RegionalInventoryServiceBaseDescriptorSupplier {
RegionalInventoryServiceFileDescriptorSupplier() {}
}
private static final class RegionalInventoryServiceMethodDescriptorSupplier
extends RegionalInventoryServiceBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final java.lang.String methodName;
RegionalInventoryServiceMethodDescriptorSupplier(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 (RegionalInventoryServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor =
result =
io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new RegionalInventoryServiceFileDescriptorSupplier())
.addMethod(getListRegionalInventoriesMethod())
.addMethod(getInsertRegionalInventoryMethod())
.addMethod(getDeleteRegionalInventoryMethod())
.build();
}
}
}
return result;
}
}
|
googleapis/google-cloud-java | 35,483 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams.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.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams}
*/
public final class SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams)
SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParamsOrBuilder {
private static final long serialVersionUID = 0L;
// Use SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams.newBuilder() to construct.
private SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams() {
op_ = "";
val_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
.class,
com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
.Builder.class);
}
/**
*
*
* <pre>
* The match operator for the field.
* </pre>
*
* Protobuf enum {@code
* google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams.Op}
*/
public enum Op implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* A value indicating that the enum field is not set.
* </pre>
*
* <code>UNDEFINED_OP = 0;</code>
*/
UNDEFINED_OP(0),
/**
*
*
* <pre>
* The operator matches if the field value contains the specified value.
* </pre>
*
* <code>CONTAINS = 215180831;</code>
*/
CONTAINS(215180831),
/**
*
*
* <pre>
* The operator matches if the field value ends with the specified value.
* </pre>
*
* <code>ENDS_WITH = 490402221;</code>
*/
ENDS_WITH(490402221),
/**
*
*
* <pre>
* The operator matches if the field value equals the specified value.
* </pre>
*
* <code>EQUALS = 442201023;</code>
*/
EQUALS(442201023),
/**
*
*
* <pre>
* The operator matches if the field value is any value.
* </pre>
*
* <code>EQUALS_ANY = 337226060;</code>
*/
EQUALS_ANY(337226060),
/**
*
*
* <pre>
* The operator matches if the field value starts with the specified value.
* </pre>
*
* <code>STARTS_WITH = 139505652;</code>
*/
STARTS_WITH(139505652),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* A value indicating that the enum field is not set.
* </pre>
*
* <code>UNDEFINED_OP = 0;</code>
*/
public static final int UNDEFINED_OP_VALUE = 0;
/**
*
*
* <pre>
* The operator matches if the field value contains the specified value.
* </pre>
*
* <code>CONTAINS = 215180831;</code>
*/
public static final int CONTAINS_VALUE = 215180831;
/**
*
*
* <pre>
* The operator matches if the field value ends with the specified value.
* </pre>
*
* <code>ENDS_WITH = 490402221;</code>
*/
public static final int ENDS_WITH_VALUE = 490402221;
/**
*
*
* <pre>
* The operator matches if the field value equals the specified value.
* </pre>
*
* <code>EQUALS = 442201023;</code>
*/
public static final int EQUALS_VALUE = 442201023;
/**
*
*
* <pre>
* The operator matches if the field value is any value.
* </pre>
*
* <code>EQUALS_ANY = 337226060;</code>
*/
public static final int EQUALS_ANY_VALUE = 337226060;
/**
*
*
* <pre>
* The operator matches if the field value starts with the specified value.
* </pre>
*
* <code>STARTS_WITH = 139505652;</code>
*/
public static final int STARTS_WITH_VALUE = 139505652;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static Op valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static Op forNumber(int value) {
switch (value) {
case 0:
return UNDEFINED_OP;
case 215180831:
return CONTAINS;
case 490402221:
return ENDS_WITH;
case 442201023:
return EQUALS;
case 337226060:
return EQUALS_ANY;
case 139505652:
return STARTS_WITH;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<Op> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<Op> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<Op>() {
public Op findValueByNumber(int number) {
return Op.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
return com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams.getDescriptor()
.getEnumTypes()
.get(0);
}
private static final Op[] VALUES = values();
public static Op valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private Op(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams.Op)
}
private int bitField0_;
public static final int OP_FIELD_NUMBER = 3553;
@SuppressWarnings("serial")
private volatile java.lang.Object op_ = "";
/**
*
*
* <pre>
* The match operator for the field.
* Check the Op enum for the list of possible values.
* </pre>
*
* <code>optional string op = 3553;</code>
*
* @return Whether the op field is set.
*/
@java.lang.Override
public boolean hasOp() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The match operator for the field.
* Check the Op enum for the list of possible values.
* </pre>
*
* <code>optional string op = 3553;</code>
*
* @return The op.
*/
@java.lang.Override
public java.lang.String getOp() {
java.lang.Object ref = op_;
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();
op_ = s;
return s;
}
}
/**
*
*
* <pre>
* The match operator for the field.
* Check the Op enum for the list of possible values.
* </pre>
*
* <code>optional string op = 3553;</code>
*
* @return The bytes for op.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOpBytes() {
java.lang.Object ref = op_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
op_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int VAL_FIELD_NUMBER = 116513;
@SuppressWarnings("serial")
private volatile java.lang.Object val_ = "";
/**
*
*
* <pre>
* The value of the field.
* </pre>
*
* <code>optional string val = 116513;</code>
*
* @return Whether the val field is set.
*/
@java.lang.Override
public boolean hasVal() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The value of the field.
* </pre>
*
* <code>optional string val = 116513;</code>
*
* @return The val.
*/
@java.lang.Override
public java.lang.String getVal() {
java.lang.Object ref = val_;
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();
val_ = s;
return s;
}
}
/**
*
*
* <pre>
* The value of the field.
* </pre>
*
* <code>optional string val = 116513;</code>
*
* @return The bytes for val.
*/
@java.lang.Override
public com.google.protobuf.ByteString getValBytes() {
java.lang.Object ref = val_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
val_ = 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, 3553, op_);
}
if (((bitField0_ & 0x00000002) != 0)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 116513, val_);
}
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(3553, op_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(116513, val_);
}
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.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams other =
(com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams)
obj;
if (hasOp() != other.hasOp()) return false;
if (hasOp()) {
if (!getOp().equals(other.getOp())) return false;
}
if (hasVal() != other.hasVal()) return false;
if (hasVal()) {
if (!getVal().equals(other.getVal())) 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 (hasOp()) {
hash = (37 * hash) + OP_FIELD_NUMBER;
hash = (53 * hash) + getOp().hashCode();
}
if (hasVal()) {
hash = (37 * hash) + VAL_FIELD_NUMBER;
hash = (53 * hash) + getVal().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
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
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
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
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
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
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
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
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
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
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
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
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
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.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
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.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams)
com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParamsOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams.class,
com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams.Builder.class);
}
// Construct using
// com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
op_ = "";
val_ = "";
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_SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
getDefaultInstanceForType() {
return com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
build() {
com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
buildPartial() {
com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
result =
new com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.op_ = op_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.val_ = val_;
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.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams) {
return mergeFrom(
(com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams)
other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
other) {
if (other
== com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams.getDefaultInstance())
return this;
if (other.hasOp()) {
op_ = other.op_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasVal()) {
val_ = other.val_;
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 28426:
{
op_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 28426
case 932106:
{
val_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 932106
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 op_ = "";
/**
*
*
* <pre>
* The match operator for the field.
* Check the Op enum for the list of possible values.
* </pre>
*
* <code>optional string op = 3553;</code>
*
* @return Whether the op field is set.
*/
public boolean hasOp() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The match operator for the field.
* Check the Op enum for the list of possible values.
* </pre>
*
* <code>optional string op = 3553;</code>
*
* @return The op.
*/
public java.lang.String getOp() {
java.lang.Object ref = op_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
op_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The match operator for the field.
* Check the Op enum for the list of possible values.
* </pre>
*
* <code>optional string op = 3553;</code>
*
* @return The bytes for op.
*/
public com.google.protobuf.ByteString getOpBytes() {
java.lang.Object ref = op_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
op_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The match operator for the field.
* Check the Op enum for the list of possible values.
* </pre>
*
* <code>optional string op = 3553;</code>
*
* @param value The op to set.
* @return This builder for chaining.
*/
public Builder setOp(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
op_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The match operator for the field.
* Check the Op enum for the list of possible values.
* </pre>
*
* <code>optional string op = 3553;</code>
*
* @return This builder for chaining.
*/
public Builder clearOp() {
op_ = getDefaultInstance().getOp();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The match operator for the field.
* Check the Op enum for the list of possible values.
* </pre>
*
* <code>optional string op = 3553;</code>
*
* @param value The bytes for op to set.
* @return This builder for chaining.
*/
public Builder setOpBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
op_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object val_ = "";
/**
*
*
* <pre>
* The value of the field.
* </pre>
*
* <code>optional string val = 116513;</code>
*
* @return Whether the val field is set.
*/
public boolean hasVal() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The value of the field.
* </pre>
*
* <code>optional string val = 116513;</code>
*
* @return The val.
*/
public java.lang.String getVal() {
java.lang.Object ref = val_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
val_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The value of the field.
* </pre>
*
* <code>optional string val = 116513;</code>
*
* @return The bytes for val.
*/
public com.google.protobuf.ByteString getValBytes() {
java.lang.Object ref = val_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
val_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The value of the field.
* </pre>
*
* <code>optional string val = 116513;</code>
*
* @param value The val to set.
* @return This builder for chaining.
*/
public Builder setVal(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
val_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The value of the field.
* </pre>
*
* <code>optional string val = 116513;</code>
*
* @return This builder for chaining.
*/
public Builder clearVal() {
val_ = getDefaultInstance().getVal();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The value of the field.
* </pre>
*
* <code>optional string val = 116513;</code>
*
* @param value The bytes for val to set.
* @return This builder for chaining.
*/
public Builder setValBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
val_ = 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.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams)
private static final com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE =
new com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams();
}
public static com.google.cloud.compute.v1
.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<
SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams>
PARSER =
new com.google.protobuf.AbstractParser<
SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams>() {
@java.lang.Override
public SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams 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<
SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams>
parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams>
getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.SecurityPolicyRulePreconfiguredWafConfigExclusionFieldParams
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,994 | java-aiplatform/google-cloud-aiplatform/src/main/java/com/google/cloud/aiplatform/v1/MetadataServiceSettings.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.aiplatform.v1;
import static com.google.cloud.aiplatform.v1.MetadataServiceClient.ListArtifactsPagedResponse;
import static com.google.cloud.aiplatform.v1.MetadataServiceClient.ListContextsPagedResponse;
import static com.google.cloud.aiplatform.v1.MetadataServiceClient.ListExecutionsPagedResponse;
import static com.google.cloud.aiplatform.v1.MetadataServiceClient.ListLocationsPagedResponse;
import static com.google.cloud.aiplatform.v1.MetadataServiceClient.ListMetadataSchemasPagedResponse;
import static com.google.cloud.aiplatform.v1.MetadataServiceClient.ListMetadataStoresPagedResponse;
import com.google.api.core.ApiFunction;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.ClientSettings;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.cloud.aiplatform.v1.stub.MetadataServiceStubSettings;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
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.longrunning.Operation;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link MetadataServiceClient}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (aiplatform.googleapis.com) and default port (443) are used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the
* [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings)
* of getMetadataStore:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* MetadataServiceSettings.Builder metadataServiceSettingsBuilder =
* MetadataServiceSettings.newBuilder();
* metadataServiceSettingsBuilder
* .getMetadataStoreSettings()
* .setRetrySettings(
* metadataServiceSettingsBuilder
* .getMetadataStoreSettings()
* .getRetrySettings()
* .toBuilder()
* .setInitialRetryDelayDuration(Duration.ofSeconds(1))
* .setInitialRpcTimeoutDuration(Duration.ofSeconds(5))
* .setMaxAttempts(5)
* .setMaxRetryDelayDuration(Duration.ofSeconds(30))
* .setMaxRpcTimeoutDuration(Duration.ofSeconds(60))
* .setRetryDelayMultiplier(1.3)
* .setRpcTimeoutMultiplier(1.5)
* .setTotalTimeoutDuration(Duration.ofSeconds(300))
* .build());
* MetadataServiceSettings metadataServiceSettings = metadataServiceSettingsBuilder.build();
* }</pre>
*
* Please refer to the [Client Side Retry
* Guide](https://github.com/googleapis/google-cloud-java/blob/main/docs/client_retries.md) for
* additional support in setting retries.
*
* <p>To configure the RetrySettings of a Long Running Operation method, create an
* OperationTimedPollAlgorithm object and update the RPC's polling algorithm. For example, to
* configure the RetrySettings for createMetadataStore:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* MetadataServiceSettings.Builder metadataServiceSettingsBuilder =
* MetadataServiceSettings.newBuilder();
* TimedRetryAlgorithm timedRetryAlgorithm =
* OperationalTimedPollAlgorithm.create(
* RetrySettings.newBuilder()
* .setInitialRetryDelayDuration(Duration.ofMillis(500))
* .setRetryDelayMultiplier(1.5)
* .setMaxRetryDelayDuration(Duration.ofMillis(5000))
* .setTotalTimeoutDuration(Duration.ofHours(24))
* .build());
* metadataServiceSettingsBuilder
* .createClusterOperationSettings()
* .setPollingAlgorithm(timedRetryAlgorithm)
* .build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class MetadataServiceSettings extends ClientSettings<MetadataServiceSettings> {
/** Returns the object with the settings used for calls to createMetadataStore. */
public UnaryCallSettings<CreateMetadataStoreRequest, Operation> createMetadataStoreSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).createMetadataStoreSettings();
}
/** Returns the object with the settings used for calls to createMetadataStore. */
public OperationCallSettings<
CreateMetadataStoreRequest, MetadataStore, CreateMetadataStoreOperationMetadata>
createMetadataStoreOperationSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).createMetadataStoreOperationSettings();
}
/** Returns the object with the settings used for calls to getMetadataStore. */
public UnaryCallSettings<GetMetadataStoreRequest, MetadataStore> getMetadataStoreSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).getMetadataStoreSettings();
}
/** Returns the object with the settings used for calls to listMetadataStores. */
public PagedCallSettings<
ListMetadataStoresRequest, ListMetadataStoresResponse, ListMetadataStoresPagedResponse>
listMetadataStoresSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).listMetadataStoresSettings();
}
/** Returns the object with the settings used for calls to deleteMetadataStore. */
public UnaryCallSettings<DeleteMetadataStoreRequest, Operation> deleteMetadataStoreSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).deleteMetadataStoreSettings();
}
/** Returns the object with the settings used for calls to deleteMetadataStore. */
public OperationCallSettings<
DeleteMetadataStoreRequest, Empty, DeleteMetadataStoreOperationMetadata>
deleteMetadataStoreOperationSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).deleteMetadataStoreOperationSettings();
}
/** Returns the object with the settings used for calls to createArtifact. */
public UnaryCallSettings<CreateArtifactRequest, Artifact> createArtifactSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).createArtifactSettings();
}
/** Returns the object with the settings used for calls to getArtifact. */
public UnaryCallSettings<GetArtifactRequest, Artifact> getArtifactSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).getArtifactSettings();
}
/** Returns the object with the settings used for calls to listArtifacts. */
public PagedCallSettings<ListArtifactsRequest, ListArtifactsResponse, ListArtifactsPagedResponse>
listArtifactsSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).listArtifactsSettings();
}
/** Returns the object with the settings used for calls to updateArtifact. */
public UnaryCallSettings<UpdateArtifactRequest, Artifact> updateArtifactSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).updateArtifactSettings();
}
/** Returns the object with the settings used for calls to deleteArtifact. */
public UnaryCallSettings<DeleteArtifactRequest, Operation> deleteArtifactSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).deleteArtifactSettings();
}
/** Returns the object with the settings used for calls to deleteArtifact. */
public OperationCallSettings<DeleteArtifactRequest, Empty, DeleteOperationMetadata>
deleteArtifactOperationSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).deleteArtifactOperationSettings();
}
/** Returns the object with the settings used for calls to purgeArtifacts. */
public UnaryCallSettings<PurgeArtifactsRequest, Operation> purgeArtifactsSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).purgeArtifactsSettings();
}
/** Returns the object with the settings used for calls to purgeArtifacts. */
public OperationCallSettings<
PurgeArtifactsRequest, PurgeArtifactsResponse, PurgeArtifactsMetadata>
purgeArtifactsOperationSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).purgeArtifactsOperationSettings();
}
/** Returns the object with the settings used for calls to createContext. */
public UnaryCallSettings<CreateContextRequest, Context> createContextSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).createContextSettings();
}
/** Returns the object with the settings used for calls to getContext. */
public UnaryCallSettings<GetContextRequest, Context> getContextSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).getContextSettings();
}
/** Returns the object with the settings used for calls to listContexts. */
public PagedCallSettings<ListContextsRequest, ListContextsResponse, ListContextsPagedResponse>
listContextsSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).listContextsSettings();
}
/** Returns the object with the settings used for calls to updateContext. */
public UnaryCallSettings<UpdateContextRequest, Context> updateContextSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).updateContextSettings();
}
/** Returns the object with the settings used for calls to deleteContext. */
public UnaryCallSettings<DeleteContextRequest, Operation> deleteContextSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).deleteContextSettings();
}
/** Returns the object with the settings used for calls to deleteContext. */
public OperationCallSettings<DeleteContextRequest, Empty, DeleteOperationMetadata>
deleteContextOperationSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).deleteContextOperationSettings();
}
/** Returns the object with the settings used for calls to purgeContexts. */
public UnaryCallSettings<PurgeContextsRequest, Operation> purgeContextsSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).purgeContextsSettings();
}
/** Returns the object with the settings used for calls to purgeContexts. */
public OperationCallSettings<PurgeContextsRequest, PurgeContextsResponse, PurgeContextsMetadata>
purgeContextsOperationSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).purgeContextsOperationSettings();
}
/** Returns the object with the settings used for calls to addContextArtifactsAndExecutions. */
public UnaryCallSettings<
AddContextArtifactsAndExecutionsRequest, AddContextArtifactsAndExecutionsResponse>
addContextArtifactsAndExecutionsSettings() {
return ((MetadataServiceStubSettings) getStubSettings())
.addContextArtifactsAndExecutionsSettings();
}
/** Returns the object with the settings used for calls to addContextChildren. */
public UnaryCallSettings<AddContextChildrenRequest, AddContextChildrenResponse>
addContextChildrenSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).addContextChildrenSettings();
}
/** Returns the object with the settings used for calls to removeContextChildren. */
public UnaryCallSettings<RemoveContextChildrenRequest, RemoveContextChildrenResponse>
removeContextChildrenSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).removeContextChildrenSettings();
}
/** Returns the object with the settings used for calls to queryContextLineageSubgraph. */
public UnaryCallSettings<QueryContextLineageSubgraphRequest, LineageSubgraph>
queryContextLineageSubgraphSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).queryContextLineageSubgraphSettings();
}
/** Returns the object with the settings used for calls to createExecution. */
public UnaryCallSettings<CreateExecutionRequest, Execution> createExecutionSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).createExecutionSettings();
}
/** Returns the object with the settings used for calls to getExecution. */
public UnaryCallSettings<GetExecutionRequest, Execution> getExecutionSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).getExecutionSettings();
}
/** Returns the object with the settings used for calls to listExecutions. */
public PagedCallSettings<
ListExecutionsRequest, ListExecutionsResponse, ListExecutionsPagedResponse>
listExecutionsSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).listExecutionsSettings();
}
/** Returns the object with the settings used for calls to updateExecution. */
public UnaryCallSettings<UpdateExecutionRequest, Execution> updateExecutionSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).updateExecutionSettings();
}
/** Returns the object with the settings used for calls to deleteExecution. */
public UnaryCallSettings<DeleteExecutionRequest, Operation> deleteExecutionSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).deleteExecutionSettings();
}
/** Returns the object with the settings used for calls to deleteExecution. */
public OperationCallSettings<DeleteExecutionRequest, Empty, DeleteOperationMetadata>
deleteExecutionOperationSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).deleteExecutionOperationSettings();
}
/** Returns the object with the settings used for calls to purgeExecutions. */
public UnaryCallSettings<PurgeExecutionsRequest, Operation> purgeExecutionsSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).purgeExecutionsSettings();
}
/** Returns the object with the settings used for calls to purgeExecutions. */
public OperationCallSettings<
PurgeExecutionsRequest, PurgeExecutionsResponse, PurgeExecutionsMetadata>
purgeExecutionsOperationSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).purgeExecutionsOperationSettings();
}
/** Returns the object with the settings used for calls to addExecutionEvents. */
public UnaryCallSettings<AddExecutionEventsRequest, AddExecutionEventsResponse>
addExecutionEventsSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).addExecutionEventsSettings();
}
/** Returns the object with the settings used for calls to queryExecutionInputsAndOutputs. */
public UnaryCallSettings<QueryExecutionInputsAndOutputsRequest, LineageSubgraph>
queryExecutionInputsAndOutputsSettings() {
return ((MetadataServiceStubSettings) getStubSettings())
.queryExecutionInputsAndOutputsSettings();
}
/** Returns the object with the settings used for calls to createMetadataSchema. */
public UnaryCallSettings<CreateMetadataSchemaRequest, MetadataSchema>
createMetadataSchemaSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).createMetadataSchemaSettings();
}
/** Returns the object with the settings used for calls to getMetadataSchema. */
public UnaryCallSettings<GetMetadataSchemaRequest, MetadataSchema> getMetadataSchemaSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).getMetadataSchemaSettings();
}
/** Returns the object with the settings used for calls to listMetadataSchemas. */
public PagedCallSettings<
ListMetadataSchemasRequest, ListMetadataSchemasResponse, ListMetadataSchemasPagedResponse>
listMetadataSchemasSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).listMetadataSchemasSettings();
}
/** Returns the object with the settings used for calls to queryArtifactLineageSubgraph. */
public UnaryCallSettings<QueryArtifactLineageSubgraphRequest, LineageSubgraph>
queryArtifactLineageSubgraphSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).queryArtifactLineageSubgraphSettings();
}
/** Returns the object with the settings used for calls to listLocations. */
public PagedCallSettings<ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>
listLocationsSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).listLocationsSettings();
}
/** Returns the object with the settings used for calls to getLocation. */
public UnaryCallSettings<GetLocationRequest, Location> getLocationSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).getLocationSettings();
}
/** Returns the object with the settings used for calls to setIamPolicy. */
public UnaryCallSettings<SetIamPolicyRequest, Policy> setIamPolicySettings() {
return ((MetadataServiceStubSettings) getStubSettings()).setIamPolicySettings();
}
/** Returns the object with the settings used for calls to getIamPolicy. */
public UnaryCallSettings<GetIamPolicyRequest, Policy> getIamPolicySettings() {
return ((MetadataServiceStubSettings) getStubSettings()).getIamPolicySettings();
}
/** Returns the object with the settings used for calls to testIamPermissions. */
public UnaryCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsSettings() {
return ((MetadataServiceStubSettings) getStubSettings()).testIamPermissionsSettings();
}
public static final MetadataServiceSettings create(MetadataServiceStubSettings stub)
throws IOException {
return new MetadataServiceSettings.Builder(stub.toBuilder()).build();
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return MetadataServiceStubSettings.defaultExecutorProviderBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return MetadataServiceStubSettings.getDefaultEndpoint();
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return MetadataServiceStubSettings.getDefaultServiceScopes();
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return MetadataServiceStubSettings.defaultCredentialsProviderBuilder();
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return MetadataServiceStubSettings.defaultGrpcTransportProviderBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return MetadataServiceStubSettings.defaultTransportChannelProvider();
}
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return MetadataServiceStubSettings.defaultApiClientHeaderProviderBuilder();
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected MetadataServiceSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
}
/** Builder for MetadataServiceSettings. */
public static class Builder extends ClientSettings.Builder<MetadataServiceSettings, Builder> {
protected Builder() throws IOException {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(MetadataServiceStubSettings.newBuilder(clientContext));
}
protected Builder(MetadataServiceSettings settings) {
super(settings.getStubSettings().toBuilder());
}
protected Builder(MetadataServiceStubSettings.Builder stubSettings) {
super(stubSettings);
}
private static Builder createDefault() {
return new Builder(MetadataServiceStubSettings.newBuilder());
}
public MetadataServiceStubSettings.Builder getStubSettingsBuilder() {
return ((MetadataServiceStubSettings.Builder) getStubSettings());
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(
getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater);
return this;
}
/** Returns the builder for the settings used for calls to createMetadataStore. */
public UnaryCallSettings.Builder<CreateMetadataStoreRequest, Operation>
createMetadataStoreSettings() {
return getStubSettingsBuilder().createMetadataStoreSettings();
}
/** Returns the builder for the settings used for calls to createMetadataStore. */
public OperationCallSettings.Builder<
CreateMetadataStoreRequest, MetadataStore, CreateMetadataStoreOperationMetadata>
createMetadataStoreOperationSettings() {
return getStubSettingsBuilder().createMetadataStoreOperationSettings();
}
/** Returns the builder for the settings used for calls to getMetadataStore. */
public UnaryCallSettings.Builder<GetMetadataStoreRequest, MetadataStore>
getMetadataStoreSettings() {
return getStubSettingsBuilder().getMetadataStoreSettings();
}
/** Returns the builder for the settings used for calls to listMetadataStores. */
public PagedCallSettings.Builder<
ListMetadataStoresRequest, ListMetadataStoresResponse, ListMetadataStoresPagedResponse>
listMetadataStoresSettings() {
return getStubSettingsBuilder().listMetadataStoresSettings();
}
/** Returns the builder for the settings used for calls to deleteMetadataStore. */
public UnaryCallSettings.Builder<DeleteMetadataStoreRequest, Operation>
deleteMetadataStoreSettings() {
return getStubSettingsBuilder().deleteMetadataStoreSettings();
}
/** Returns the builder for the settings used for calls to deleteMetadataStore. */
public OperationCallSettings.Builder<
DeleteMetadataStoreRequest, Empty, DeleteMetadataStoreOperationMetadata>
deleteMetadataStoreOperationSettings() {
return getStubSettingsBuilder().deleteMetadataStoreOperationSettings();
}
/** Returns the builder for the settings used for calls to createArtifact. */
public UnaryCallSettings.Builder<CreateArtifactRequest, Artifact> createArtifactSettings() {
return getStubSettingsBuilder().createArtifactSettings();
}
/** Returns the builder for the settings used for calls to getArtifact. */
public UnaryCallSettings.Builder<GetArtifactRequest, Artifact> getArtifactSettings() {
return getStubSettingsBuilder().getArtifactSettings();
}
/** Returns the builder for the settings used for calls to listArtifacts. */
public PagedCallSettings.Builder<
ListArtifactsRequest, ListArtifactsResponse, ListArtifactsPagedResponse>
listArtifactsSettings() {
return getStubSettingsBuilder().listArtifactsSettings();
}
/** Returns the builder for the settings used for calls to updateArtifact. */
public UnaryCallSettings.Builder<UpdateArtifactRequest, Artifact> updateArtifactSettings() {
return getStubSettingsBuilder().updateArtifactSettings();
}
/** Returns the builder for the settings used for calls to deleteArtifact. */
public UnaryCallSettings.Builder<DeleteArtifactRequest, Operation> deleteArtifactSettings() {
return getStubSettingsBuilder().deleteArtifactSettings();
}
/** Returns the builder for the settings used for calls to deleteArtifact. */
public OperationCallSettings.Builder<DeleteArtifactRequest, Empty, DeleteOperationMetadata>
deleteArtifactOperationSettings() {
return getStubSettingsBuilder().deleteArtifactOperationSettings();
}
/** Returns the builder for the settings used for calls to purgeArtifacts. */
public UnaryCallSettings.Builder<PurgeArtifactsRequest, Operation> purgeArtifactsSettings() {
return getStubSettingsBuilder().purgeArtifactsSettings();
}
/** Returns the builder for the settings used for calls to purgeArtifacts. */
public OperationCallSettings.Builder<
PurgeArtifactsRequest, PurgeArtifactsResponse, PurgeArtifactsMetadata>
purgeArtifactsOperationSettings() {
return getStubSettingsBuilder().purgeArtifactsOperationSettings();
}
/** Returns the builder for the settings used for calls to createContext. */
public UnaryCallSettings.Builder<CreateContextRequest, Context> createContextSettings() {
return getStubSettingsBuilder().createContextSettings();
}
/** Returns the builder for the settings used for calls to getContext. */
public UnaryCallSettings.Builder<GetContextRequest, Context> getContextSettings() {
return getStubSettingsBuilder().getContextSettings();
}
/** Returns the builder for the settings used for calls to listContexts. */
public PagedCallSettings.Builder<
ListContextsRequest, ListContextsResponse, ListContextsPagedResponse>
listContextsSettings() {
return getStubSettingsBuilder().listContextsSettings();
}
/** Returns the builder for the settings used for calls to updateContext. */
public UnaryCallSettings.Builder<UpdateContextRequest, Context> updateContextSettings() {
return getStubSettingsBuilder().updateContextSettings();
}
/** Returns the builder for the settings used for calls to deleteContext. */
public UnaryCallSettings.Builder<DeleteContextRequest, Operation> deleteContextSettings() {
return getStubSettingsBuilder().deleteContextSettings();
}
/** Returns the builder for the settings used for calls to deleteContext. */
public OperationCallSettings.Builder<DeleteContextRequest, Empty, DeleteOperationMetadata>
deleteContextOperationSettings() {
return getStubSettingsBuilder().deleteContextOperationSettings();
}
/** Returns the builder for the settings used for calls to purgeContexts. */
public UnaryCallSettings.Builder<PurgeContextsRequest, Operation> purgeContextsSettings() {
return getStubSettingsBuilder().purgeContextsSettings();
}
/** Returns the builder for the settings used for calls to purgeContexts. */
public OperationCallSettings.Builder<
PurgeContextsRequest, PurgeContextsResponse, PurgeContextsMetadata>
purgeContextsOperationSettings() {
return getStubSettingsBuilder().purgeContextsOperationSettings();
}
/** Returns the builder for the settings used for calls to addContextArtifactsAndExecutions. */
public UnaryCallSettings.Builder<
AddContextArtifactsAndExecutionsRequest, AddContextArtifactsAndExecutionsResponse>
addContextArtifactsAndExecutionsSettings() {
return getStubSettingsBuilder().addContextArtifactsAndExecutionsSettings();
}
/** Returns the builder for the settings used for calls to addContextChildren. */
public UnaryCallSettings.Builder<AddContextChildrenRequest, AddContextChildrenResponse>
addContextChildrenSettings() {
return getStubSettingsBuilder().addContextChildrenSettings();
}
/** Returns the builder for the settings used for calls to removeContextChildren. */
public UnaryCallSettings.Builder<RemoveContextChildrenRequest, RemoveContextChildrenResponse>
removeContextChildrenSettings() {
return getStubSettingsBuilder().removeContextChildrenSettings();
}
/** Returns the builder for the settings used for calls to queryContextLineageSubgraph. */
public UnaryCallSettings.Builder<QueryContextLineageSubgraphRequest, LineageSubgraph>
queryContextLineageSubgraphSettings() {
return getStubSettingsBuilder().queryContextLineageSubgraphSettings();
}
/** Returns the builder for the settings used for calls to createExecution. */
public UnaryCallSettings.Builder<CreateExecutionRequest, Execution> createExecutionSettings() {
return getStubSettingsBuilder().createExecutionSettings();
}
/** Returns the builder for the settings used for calls to getExecution. */
public UnaryCallSettings.Builder<GetExecutionRequest, Execution> getExecutionSettings() {
return getStubSettingsBuilder().getExecutionSettings();
}
/** Returns the builder for the settings used for calls to listExecutions. */
public PagedCallSettings.Builder<
ListExecutionsRequest, ListExecutionsResponse, ListExecutionsPagedResponse>
listExecutionsSettings() {
return getStubSettingsBuilder().listExecutionsSettings();
}
/** Returns the builder for the settings used for calls to updateExecution. */
public UnaryCallSettings.Builder<UpdateExecutionRequest, Execution> updateExecutionSettings() {
return getStubSettingsBuilder().updateExecutionSettings();
}
/** Returns the builder for the settings used for calls to deleteExecution. */
public UnaryCallSettings.Builder<DeleteExecutionRequest, Operation> deleteExecutionSettings() {
return getStubSettingsBuilder().deleteExecutionSettings();
}
/** Returns the builder for the settings used for calls to deleteExecution. */
public OperationCallSettings.Builder<DeleteExecutionRequest, Empty, DeleteOperationMetadata>
deleteExecutionOperationSettings() {
return getStubSettingsBuilder().deleteExecutionOperationSettings();
}
/** Returns the builder for the settings used for calls to purgeExecutions. */
public UnaryCallSettings.Builder<PurgeExecutionsRequest, Operation> purgeExecutionsSettings() {
return getStubSettingsBuilder().purgeExecutionsSettings();
}
/** Returns the builder for the settings used for calls to purgeExecutions. */
public OperationCallSettings.Builder<
PurgeExecutionsRequest, PurgeExecutionsResponse, PurgeExecutionsMetadata>
purgeExecutionsOperationSettings() {
return getStubSettingsBuilder().purgeExecutionsOperationSettings();
}
/** Returns the builder for the settings used for calls to addExecutionEvents. */
public UnaryCallSettings.Builder<AddExecutionEventsRequest, AddExecutionEventsResponse>
addExecutionEventsSettings() {
return getStubSettingsBuilder().addExecutionEventsSettings();
}
/** Returns the builder for the settings used for calls to queryExecutionInputsAndOutputs. */
public UnaryCallSettings.Builder<QueryExecutionInputsAndOutputsRequest, LineageSubgraph>
queryExecutionInputsAndOutputsSettings() {
return getStubSettingsBuilder().queryExecutionInputsAndOutputsSettings();
}
/** Returns the builder for the settings used for calls to createMetadataSchema. */
public UnaryCallSettings.Builder<CreateMetadataSchemaRequest, MetadataSchema>
createMetadataSchemaSettings() {
return getStubSettingsBuilder().createMetadataSchemaSettings();
}
/** Returns the builder for the settings used for calls to getMetadataSchema. */
public UnaryCallSettings.Builder<GetMetadataSchemaRequest, MetadataSchema>
getMetadataSchemaSettings() {
return getStubSettingsBuilder().getMetadataSchemaSettings();
}
/** Returns the builder for the settings used for calls to listMetadataSchemas. */
public PagedCallSettings.Builder<
ListMetadataSchemasRequest,
ListMetadataSchemasResponse,
ListMetadataSchemasPagedResponse>
listMetadataSchemasSettings() {
return getStubSettingsBuilder().listMetadataSchemasSettings();
}
/** Returns the builder for the settings used for calls to queryArtifactLineageSubgraph. */
public UnaryCallSettings.Builder<QueryArtifactLineageSubgraphRequest, LineageSubgraph>
queryArtifactLineageSubgraphSettings() {
return getStubSettingsBuilder().queryArtifactLineageSubgraphSettings();
}
/** Returns the builder for the settings used for calls to listLocations. */
public PagedCallSettings.Builder<
ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>
listLocationsSettings() {
return getStubSettingsBuilder().listLocationsSettings();
}
/** Returns the builder for the settings used for calls to getLocation. */
public UnaryCallSettings.Builder<GetLocationRequest, Location> getLocationSettings() {
return getStubSettingsBuilder().getLocationSettings();
}
/** Returns the builder for the settings used for calls to setIamPolicy. */
public UnaryCallSettings.Builder<SetIamPolicyRequest, Policy> setIamPolicySettings() {
return getStubSettingsBuilder().setIamPolicySettings();
}
/** Returns the builder for the settings used for calls to getIamPolicy. */
public UnaryCallSettings.Builder<GetIamPolicyRequest, Policy> getIamPolicySettings() {
return getStubSettingsBuilder().getIamPolicySettings();
}
/** Returns the builder for the settings used for calls to testIamPermissions. */
public UnaryCallSettings.Builder<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsSettings() {
return getStubSettingsBuilder().testIamPermissionsSettings();
}
@Override
public MetadataServiceSettings build() throws IOException {
return new MetadataServiceSettings(this);
}
}
}
|
googleapis/google-cloud-java | 35,561 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/GetIamPolicyRegionDiskRequest.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 RegionDisks.GetIamPolicy. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.GetIamPolicyRegionDiskRequest}
*/
public final class GetIamPolicyRegionDiskRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.GetIamPolicyRegionDiskRequest)
GetIamPolicyRegionDiskRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetIamPolicyRegionDiskRequest.newBuilder() to construct.
private GetIamPolicyRegionDiskRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetIamPolicyRegionDiskRequest() {
project_ = "";
region_ = "";
resource_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GetIamPolicyRegionDiskRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicyRegionDiskRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicyRegionDiskRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest.class,
com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest.Builder.class);
}
private int bitField0_;
public static final int OPTIONS_REQUESTED_POLICY_VERSION_FIELD_NUMBER = 499220029;
private int optionsRequestedPolicyVersion_ = 0;
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return Whether the optionsRequestedPolicyVersion field is set.
*/
@java.lang.Override
public boolean hasOptionsRequestedPolicyVersion() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return The optionsRequestedPolicyVersion.
*/
@java.lang.Override
public int getOptionsRequestedPolicyVersion() {
return optionsRequestedPolicyVersion_;
}
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];</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];</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 REGION_FIELD_NUMBER = 138946292;
@SuppressWarnings("serial")
private volatile java.lang.Object region_ = "";
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The region.
*/
@java.lang.Override
public java.lang.String getRegion() {
java.lang.Object ref = region_;
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();
region_ = s;
return s;
}
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for region.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRegionBytes() {
java.lang.Object ref = region_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
region_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int RESOURCE_FIELD_NUMBER = 195806222;
@SuppressWarnings("serial")
private volatile java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The resource.
*/
@java.lang.Override
public java.lang.String getResource() {
java.lang.Object ref = resource_;
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();
resource_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for resource.
*/
@java.lang.Override
public com.google.protobuf.ByteString getResourceBytes() {
java.lang.Object ref = resource_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resource_ = 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(region_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 138946292, region_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 195806222, resource_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeInt32(499220029, optionsRequestedPolicyVersion_);
}
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(region_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(138946292, region_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(195806222, resource_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size +=
com.google.protobuf.CodedOutputStream.computeInt32Size(
499220029, optionsRequestedPolicyVersion_);
}
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.GetIamPolicyRegionDiskRequest)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest other =
(com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest) obj;
if (hasOptionsRequestedPolicyVersion() != other.hasOptionsRequestedPolicyVersion())
return false;
if (hasOptionsRequestedPolicyVersion()) {
if (getOptionsRequestedPolicyVersion() != other.getOptionsRequestedPolicyVersion())
return false;
}
if (!getProject().equals(other.getProject())) return false;
if (!getRegion().equals(other.getRegion())) return false;
if (!getResource().equals(other.getResource())) 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 (hasOptionsRequestedPolicyVersion()) {
hash = (37 * hash) + OPTIONS_REQUESTED_POLICY_VERSION_FIELD_NUMBER;
hash = (53 * hash) + getOptionsRequestedPolicyVersion();
}
hash = (37 * hash) + PROJECT_FIELD_NUMBER;
hash = (53 * hash) + getProject().hashCode();
hash = (37 * hash) + REGION_FIELD_NUMBER;
hash = (53 * hash) + getRegion().hashCode();
hash = (37 * hash) + RESOURCE_FIELD_NUMBER;
hash = (53 * hash) + getResource().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest 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.GetIamPolicyRegionDiskRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest 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.GetIamPolicyRegionDiskRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest 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.GetIamPolicyRegionDiskRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest 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.GetIamPolicyRegionDiskRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest 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.GetIamPolicyRegionDiskRequest 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.GetIamPolicyRegionDiskRequest 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.GetIamPolicyRegionDiskRequest 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 RegionDisks.GetIamPolicy. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.GetIamPolicyRegionDiskRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.GetIamPolicyRegionDiskRequest)
com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicyRegionDiskRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicyRegionDiskRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest.class,
com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest.Builder.class);
}
// Construct using com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
optionsRequestedPolicyVersion_ = 0;
project_ = "";
region_ = "";
resource_ = "";
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_GetIamPolicyRegionDiskRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest getDefaultInstanceForType() {
return com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest build() {
com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest buildPartial() {
com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest result =
new com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.optionsRequestedPolicyVersion_ = optionsRequestedPolicyVersion_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.project_ = project_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.region_ = region_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.resource_ = resource_;
}
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.GetIamPolicyRegionDiskRequest) {
return mergeFrom((com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest other) {
if (other == com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest.getDefaultInstance())
return this;
if (other.hasOptionsRequestedPolicyVersion()) {
setOptionsRequestedPolicyVersion(other.getOptionsRequestedPolicyVersion());
}
if (!other.getProject().isEmpty()) {
project_ = other.project_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getRegion().isEmpty()) {
region_ = other.region_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getResource().isEmpty()) {
resource_ = other.resource_;
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 1111570338:
{
region_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 1111570338
case 1566449778:
{
resource_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 1566449778
case 1820481738:
{
project_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 1820481738
case -301207064:
{
optionsRequestedPolicyVersion_ = input.readInt32();
bitField0_ |= 0x00000001;
break;
} // case -301207064
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 int optionsRequestedPolicyVersion_;
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return Whether the optionsRequestedPolicyVersion field is set.
*/
@java.lang.Override
public boolean hasOptionsRequestedPolicyVersion() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return The optionsRequestedPolicyVersion.
*/
@java.lang.Override
public int getOptionsRequestedPolicyVersion() {
return optionsRequestedPolicyVersion_;
}
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @param value The optionsRequestedPolicyVersion to set.
* @return This builder for chaining.
*/
public Builder setOptionsRequestedPolicyVersion(int value) {
optionsRequestedPolicyVersion_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return This builder for chaining.
*/
public Builder clearOptionsRequestedPolicyVersion() {
bitField0_ = (bitField0_ & ~0x00000001);
optionsRequestedPolicyVersion_ = 0;
onChanged();
return this;
}
private java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</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];</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];</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];</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];</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 region_ = "";
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The region.
*/
public java.lang.String getRegion() {
java.lang.Object ref = region_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
region_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for region.
*/
public com.google.protobuf.ByteString getRegionBytes() {
java.lang.Object ref = region_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
region_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The region to set.
* @return This builder for chaining.
*/
public Builder setRegion(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
region_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearRegion() {
region_ = getDefaultInstance().getRegion();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for region to set.
* @return This builder for chaining.
*/
public Builder setRegionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
region_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The resource.
*/
public java.lang.String getResource() {
java.lang.Object ref = resource_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resource_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for resource.
*/
public com.google.protobuf.ByteString getResourceBytes() {
java.lang.Object ref = resource_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resource_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The resource to set.
* @return This builder for chaining.
*/
public Builder setResource(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
resource_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearResource() {
resource_ = getDefaultInstance().getResource();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for resource to set.
* @return This builder for chaining.
*/
public Builder setResourceBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
resource_ = 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.compute.v1.GetIamPolicyRegionDiskRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.GetIamPolicyRegionDiskRequest)
private static final com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest();
}
public static com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetIamPolicyRegionDiskRequest> PARSER =
new com.google.protobuf.AbstractParser<GetIamPolicyRegionDiskRequest>() {
@java.lang.Override
public GetIamPolicyRegionDiskRequest 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<GetIamPolicyRegionDiskRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetIamPolicyRegionDiskRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.GetIamPolicyRegionDiskRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,561 | java-compute/proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/GetIamPolicySubnetworkRequest.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 Subnetworks.GetIamPolicy. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.GetIamPolicySubnetworkRequest}
*/
public final class GetIamPolicySubnetworkRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.GetIamPolicySubnetworkRequest)
GetIamPolicySubnetworkRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetIamPolicySubnetworkRequest.newBuilder() to construct.
private GetIamPolicySubnetworkRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetIamPolicySubnetworkRequest() {
project_ = "";
region_ = "";
resource_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GetIamPolicySubnetworkRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicySubnetworkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicySubnetworkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest.class,
com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest.Builder.class);
}
private int bitField0_;
public static final int OPTIONS_REQUESTED_POLICY_VERSION_FIELD_NUMBER = 499220029;
private int optionsRequestedPolicyVersion_ = 0;
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return Whether the optionsRequestedPolicyVersion field is set.
*/
@java.lang.Override
public boolean hasOptionsRequestedPolicyVersion() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return The optionsRequestedPolicyVersion.
*/
@java.lang.Override
public int getOptionsRequestedPolicyVersion() {
return optionsRequestedPolicyVersion_;
}
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];</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];</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 REGION_FIELD_NUMBER = 138946292;
@SuppressWarnings("serial")
private volatile java.lang.Object region_ = "";
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The region.
*/
@java.lang.Override
public java.lang.String getRegion() {
java.lang.Object ref = region_;
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();
region_ = s;
return s;
}
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for region.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRegionBytes() {
java.lang.Object ref = region_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
region_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int RESOURCE_FIELD_NUMBER = 195806222;
@SuppressWarnings("serial")
private volatile java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The resource.
*/
@java.lang.Override
public java.lang.String getResource() {
java.lang.Object ref = resource_;
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();
resource_ = s;
return s;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for resource.
*/
@java.lang.Override
public com.google.protobuf.ByteString getResourceBytes() {
java.lang.Object ref = resource_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resource_ = 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(region_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 138946292, region_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 195806222, resource_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 227560217, project_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeInt32(499220029, optionsRequestedPolicyVersion_);
}
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(region_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(138946292, region_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(resource_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(195806222, resource_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(project_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(227560217, project_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size +=
com.google.protobuf.CodedOutputStream.computeInt32Size(
499220029, optionsRequestedPolicyVersion_);
}
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.GetIamPolicySubnetworkRequest)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest other =
(com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest) obj;
if (hasOptionsRequestedPolicyVersion() != other.hasOptionsRequestedPolicyVersion())
return false;
if (hasOptionsRequestedPolicyVersion()) {
if (getOptionsRequestedPolicyVersion() != other.getOptionsRequestedPolicyVersion())
return false;
}
if (!getProject().equals(other.getProject())) return false;
if (!getRegion().equals(other.getRegion())) return false;
if (!getResource().equals(other.getResource())) 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 (hasOptionsRequestedPolicyVersion()) {
hash = (37 * hash) + OPTIONS_REQUESTED_POLICY_VERSION_FIELD_NUMBER;
hash = (53 * hash) + getOptionsRequestedPolicyVersion();
}
hash = (37 * hash) + PROJECT_FIELD_NUMBER;
hash = (53 * hash) + getProject().hashCode();
hash = (37 * hash) + REGION_FIELD_NUMBER;
hash = (53 * hash) + getRegion().hashCode();
hash = (37 * hash) + RESOURCE_FIELD_NUMBER;
hash = (53 * hash) + getResource().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest 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.GetIamPolicySubnetworkRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest 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.GetIamPolicySubnetworkRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest 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.GetIamPolicySubnetworkRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest 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.GetIamPolicySubnetworkRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest 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.GetIamPolicySubnetworkRequest 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.GetIamPolicySubnetworkRequest 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.GetIamPolicySubnetworkRequest 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 Subnetworks.GetIamPolicy. See the method description for details.
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.GetIamPolicySubnetworkRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.GetIamPolicySubnetworkRequest)
com.google.cloud.compute.v1.GetIamPolicySubnetworkRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicySubnetworkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_GetIamPolicySubnetworkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest.class,
com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest.Builder.class);
}
// Construct using com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
optionsRequestedPolicyVersion_ = 0;
project_ = "";
region_ = "";
resource_ = "";
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_GetIamPolicySubnetworkRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest getDefaultInstanceForType() {
return com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest build() {
com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest buildPartial() {
com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest result =
new com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.optionsRequestedPolicyVersion_ = optionsRequestedPolicyVersion_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.project_ = project_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.region_ = region_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.resource_ = resource_;
}
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.GetIamPolicySubnetworkRequest) {
return mergeFrom((com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest other) {
if (other == com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest.getDefaultInstance())
return this;
if (other.hasOptionsRequestedPolicyVersion()) {
setOptionsRequestedPolicyVersion(other.getOptionsRequestedPolicyVersion());
}
if (!other.getProject().isEmpty()) {
project_ = other.project_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getRegion().isEmpty()) {
region_ = other.region_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getResource().isEmpty()) {
resource_ = other.resource_;
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 1111570338:
{
region_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 1111570338
case 1566449778:
{
resource_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 1566449778
case 1820481738:
{
project_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 1820481738
case -301207064:
{
optionsRequestedPolicyVersion_ = input.readInt32();
bitField0_ |= 0x00000001;
break;
} // case -301207064
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 int optionsRequestedPolicyVersion_;
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return Whether the optionsRequestedPolicyVersion field is set.
*/
@java.lang.Override
public boolean hasOptionsRequestedPolicyVersion() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return The optionsRequestedPolicyVersion.
*/
@java.lang.Override
public int getOptionsRequestedPolicyVersion() {
return optionsRequestedPolicyVersion_;
}
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @param value The optionsRequestedPolicyVersion to set.
* @return This builder for chaining.
*/
public Builder setOptionsRequestedPolicyVersion(int value) {
optionsRequestedPolicyVersion_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Requested IAM Policy version.
* </pre>
*
* <code>optional int32 options_requested_policy_version = 499220029;</code>
*
* @return This builder for chaining.
*/
public Builder clearOptionsRequestedPolicyVersion() {
bitField0_ = (bitField0_ & ~0x00000001);
optionsRequestedPolicyVersion_ = 0;
onChanged();
return this;
}
private java.lang.Object project_ = "";
/**
*
*
* <pre>
* Project ID for this request.
* </pre>
*
* <code>string project = 227560217 [(.google.api.field_behavior) = REQUIRED];</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];</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];</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];</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];</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 region_ = "";
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The region.
*/
public java.lang.String getRegion() {
java.lang.Object ref = region_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
region_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for region.
*/
public com.google.protobuf.ByteString getRegionBytes() {
java.lang.Object ref = region_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
region_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The region to set.
* @return This builder for chaining.
*/
public Builder setRegion(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
region_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearRegion() {
region_ = getDefaultInstance().getRegion();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* The name of the region for this request.
* </pre>
*
* <code>string region = 138946292 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for region to set.
* @return This builder for chaining.
*/
public Builder setRegionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
region_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The resource.
*/
public java.lang.String getResource() {
java.lang.Object ref = resource_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resource_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for resource.
*/
public com.google.protobuf.ByteString getResourceBytes() {
java.lang.Object ref = resource_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resource_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The resource to set.
* @return This builder for chaining.
*/
public Builder setResource(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
resource_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearResource() {
resource_ = getDefaultInstance().getResource();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* Name or id of the resource for this request.
* </pre>
*
* <code>string resource = 195806222 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for resource to set.
* @return This builder for chaining.
*/
public Builder setResourceBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
resource_ = 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.compute.v1.GetIamPolicySubnetworkRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.GetIamPolicySubnetworkRequest)
private static final com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest();
}
public static com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetIamPolicySubnetworkRequest> PARSER =
new com.google.protobuf.AbstractParser<GetIamPolicySubnetworkRequest>() {
@java.lang.Override
public GetIamPolicySubnetworkRequest 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<GetIamPolicySubnetworkRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetIamPolicySubnetworkRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.GetIamPolicySubnetworkRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,638 | java-dialogflow/proto-google-cloud-dialogflow-v2beta1/src/main/java/com/google/cloud/dialogflow/v2beta1/UpdateVersionRequest.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/dialogflow/v2beta1/version.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.dialogflow.v2beta1;
/**
*
*
* <pre>
* The request message for
* [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2beta1.UpdateVersionRequest}
*/
public final class UpdateVersionRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.dialogflow.v2beta1.UpdateVersionRequest)
UpdateVersionRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateVersionRequest.newBuilder() to construct.
private UpdateVersionRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateVersionRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateVersionRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2beta1.VersionProto
.internal_static_google_cloud_dialogflow_v2beta1_UpdateVersionRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2beta1.VersionProto
.internal_static_google_cloud_dialogflow_v2beta1_UpdateVersionRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest.class,
com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest.Builder.class);
}
private int bitField0_;
public static final int VERSION_FIELD_NUMBER = 1;
private com.google.cloud.dialogflow.v2beta1.Version version_;
/**
*
*
* <pre>
* Required. The version to update.
* Supported formats:
* - `projects/<Project ID>/agent/versions/<Version ID>`
* - `projects/<Project ID>/locations/<Location ID>/agent/versions/<Version
* ID>`
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.Version version = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the version field is set.
*/
@java.lang.Override
public boolean hasVersion() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The version to update.
* Supported formats:
* - `projects/<Project ID>/agent/versions/<Version ID>`
* - `projects/<Project ID>/locations/<Location ID>/agent/versions/<Version
* ID>`
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.Version version = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The version.
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.Version getVersion() {
return version_ == null
? com.google.cloud.dialogflow.v2beta1.Version.getDefaultInstance()
: version_;
}
/**
*
*
* <pre>
* Required. The version to update.
* Supported formats:
* - `projects/<Project ID>/agent/versions/<Version ID>`
* - `projects/<Project ID>/locations/<Location ID>/agent/versions/<Version
* ID>`
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.Version version = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.VersionOrBuilder getVersionOrBuilder() {
return version_ == null
? com.google.cloud.dialogflow.v2beta1.Version.getDefaultInstance()
: version_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Required. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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, getVersion());
}
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, getVersion());
}
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.dialogflow.v2beta1.UpdateVersionRequest)) {
return super.equals(obj);
}
com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest other =
(com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest) obj;
if (hasVersion() != other.hasVersion()) return false;
if (hasVersion()) {
if (!getVersion().equals(other.getVersion())) 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 (hasVersion()) {
hash = (37 * hash) + VERSION_FIELD_NUMBER;
hash = (53 * hash) + getVersion().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.dialogflow.v2beta1.UpdateVersionRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest 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.dialogflow.v2beta1.UpdateVersionRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest 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.dialogflow.v2beta1.UpdateVersionRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest 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.dialogflow.v2beta1.UpdateVersionRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest 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.dialogflow.v2beta1.UpdateVersionRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest 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.dialogflow.v2beta1.UpdateVersionRequest 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
* [Versions.UpdateVersion][google.cloud.dialogflow.v2beta1.Versions.UpdateVersion].
* </pre>
*
* Protobuf type {@code google.cloud.dialogflow.v2beta1.UpdateVersionRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.dialogflow.v2beta1.UpdateVersionRequest)
com.google.cloud.dialogflow.v2beta1.UpdateVersionRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.dialogflow.v2beta1.VersionProto
.internal_static_google_cloud_dialogflow_v2beta1_UpdateVersionRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.dialogflow.v2beta1.VersionProto
.internal_static_google_cloud_dialogflow_v2beta1_UpdateVersionRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest.class,
com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest.Builder.class);
}
// Construct using com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getVersionFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
version_ = null;
if (versionBuilder_ != null) {
versionBuilder_.dispose();
versionBuilder_ = 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.dialogflow.v2beta1.VersionProto
.internal_static_google_cloud_dialogflow_v2beta1_UpdateVersionRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest getDefaultInstanceForType() {
return com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest build() {
com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest buildPartial() {
com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest result =
new com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.version_ = versionBuilder_ == null ? version_ : versionBuilder_.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.dialogflow.v2beta1.UpdateVersionRequest) {
return mergeFrom((com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest other) {
if (other == com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest.getDefaultInstance())
return this;
if (other.hasVersion()) {
mergeVersion(other.getVersion());
}
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(getVersionFieldBuilder().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.dialogflow.v2beta1.Version version_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2beta1.Version,
com.google.cloud.dialogflow.v2beta1.Version.Builder,
com.google.cloud.dialogflow.v2beta1.VersionOrBuilder>
versionBuilder_;
/**
*
*
* <pre>
* Required. The version to update.
* Supported formats:
* - `projects/<Project ID>/agent/versions/<Version ID>`
* - `projects/<Project ID>/locations/<Location ID>/agent/versions/<Version
* ID>`
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.Version version = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the version field is set.
*/
public boolean hasVersion() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The version to update.
* Supported formats:
* - `projects/<Project ID>/agent/versions/<Version ID>`
* - `projects/<Project ID>/locations/<Location ID>/agent/versions/<Version
* ID>`
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.Version version = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The version.
*/
public com.google.cloud.dialogflow.v2beta1.Version getVersion() {
if (versionBuilder_ == null) {
return version_ == null
? com.google.cloud.dialogflow.v2beta1.Version.getDefaultInstance()
: version_;
} else {
return versionBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The version to update.
* Supported formats:
* - `projects/<Project ID>/agent/versions/<Version ID>`
* - `projects/<Project ID>/locations/<Location ID>/agent/versions/<Version
* ID>`
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.Version version = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setVersion(com.google.cloud.dialogflow.v2beta1.Version value) {
if (versionBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
version_ = value;
} else {
versionBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The version to update.
* Supported formats:
* - `projects/<Project ID>/agent/versions/<Version ID>`
* - `projects/<Project ID>/locations/<Location ID>/agent/versions/<Version
* ID>`
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.Version version = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setVersion(com.google.cloud.dialogflow.v2beta1.Version.Builder builderForValue) {
if (versionBuilder_ == null) {
version_ = builderForValue.build();
} else {
versionBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The version to update.
* Supported formats:
* - `projects/<Project ID>/agent/versions/<Version ID>`
* - `projects/<Project ID>/locations/<Location ID>/agent/versions/<Version
* ID>`
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.Version version = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeVersion(com.google.cloud.dialogflow.v2beta1.Version value) {
if (versionBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& version_ != null
&& version_ != com.google.cloud.dialogflow.v2beta1.Version.getDefaultInstance()) {
getVersionBuilder().mergeFrom(value);
} else {
version_ = value;
}
} else {
versionBuilder_.mergeFrom(value);
}
if (version_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The version to update.
* Supported formats:
* - `projects/<Project ID>/agent/versions/<Version ID>`
* - `projects/<Project ID>/locations/<Location ID>/agent/versions/<Version
* ID>`
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.Version version = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearVersion() {
bitField0_ = (bitField0_ & ~0x00000001);
version_ = null;
if (versionBuilder_ != null) {
versionBuilder_.dispose();
versionBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The version to update.
* Supported formats:
* - `projects/<Project ID>/agent/versions/<Version ID>`
* - `projects/<Project ID>/locations/<Location ID>/agent/versions/<Version
* ID>`
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.Version version = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.dialogflow.v2beta1.Version.Builder getVersionBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getVersionFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The version to update.
* Supported formats:
* - `projects/<Project ID>/agent/versions/<Version ID>`
* - `projects/<Project ID>/locations/<Location ID>/agent/versions/<Version
* ID>`
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.Version version = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.dialogflow.v2beta1.VersionOrBuilder getVersionOrBuilder() {
if (versionBuilder_ != null) {
return versionBuilder_.getMessageOrBuilder();
} else {
return version_ == null
? com.google.cloud.dialogflow.v2beta1.Version.getDefaultInstance()
: version_;
}
}
/**
*
*
* <pre>
* Required. The version to update.
* Supported formats:
* - `projects/<Project ID>/agent/versions/<Version ID>`
* - `projects/<Project ID>/locations/<Location ID>/agent/versions/<Version
* ID>`
* </pre>
*
* <code>
* .google.cloud.dialogflow.v2beta1.Version version = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2beta1.Version,
com.google.cloud.dialogflow.v2beta1.Version.Builder,
com.google.cloud.dialogflow.v2beta1.VersionOrBuilder>
getVersionFieldBuilder() {
if (versionBuilder_ == null) {
versionBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.dialogflow.v2beta1.Version,
com.google.cloud.dialogflow.v2beta1.Version.Builder,
com.google.cloud.dialogflow.v2beta1.VersionOrBuilder>(
getVersion(), getParentForChildren(), isClean());
version_ = null;
}
return versionBuilder_;
}
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>
* Required. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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>
* Required. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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>
* Required. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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>
* Required. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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>
* Required. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Required. The mask to control which fields get updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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.dialogflow.v2beta1.UpdateVersionRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.dialogflow.v2beta1.UpdateVersionRequest)
private static final com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest();
}
public static com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateVersionRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateVersionRequest>() {
@java.lang.Override
public UpdateVersionRequest 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<UpdateVersionRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateVersionRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.dialogflow.v2beta1.UpdateVersionRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
openjdk/jdk8 | 35,852 | jdk/src/share/classes/sun/rmi/rmic/RemoteClass.java | /*
* Copyright (c) 1997, 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 sun.rmi.rmic;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.security.MessageDigest;
import java.security.DigestOutputStream;
import java.security.NoSuchAlgorithmException;
import sun.tools.java.Type;
import sun.tools.java.ClassDefinition;
import sun.tools.java.ClassDeclaration;
import sun.tools.java.MemberDefinition;
import sun.tools.java.Identifier;
import sun.tools.java.ClassNotFound;
/**
* A RemoteClass object encapsulates RMI-specific information about
* a remote implementation class, i.e. a class that implements
* one or more remote interfaces.
*
* WARNING: The contents of this source file are not part of any
* supported API. Code that depends on them does so at its own risk:
* they are subject to change or removal without notice.
*
* @author Peter Jones
*/
public class RemoteClass implements sun.rmi.rmic.RMIConstants {
/**
* Create a RemoteClass object representing the remote meta-information
* of the given class.
*
* Returns true if successful. If the class is not a properly formed
* remote implementation class or if some other error occurs, the
* return value will be null, and errors will have been reported to
* the supplied BatchEnvironment.
*/
public static RemoteClass forClass(BatchEnvironment env,
ClassDefinition implClassDef)
{
RemoteClass rc = new RemoteClass(env, implClassDef);
if (rc.initialize()) {
return rc;
} else {
return null;
}
}
/**
* Return the ClassDefinition for this class.
*/
public ClassDefinition getClassDefinition() {
return implClassDef;
}
/**
* Return the name of the class represented by this object.
*/
public Identifier getName() {
return implClassDef.getName();
}
/**
* Return an array of ClassDefinitions representing all of the remote
* interfaces implemented by this class.
*
* A remote interface is any interface that extends Remote,
* directly or indirectly. The remote interfaces of a class
* are the interfaces directly listed in either the class's
* "implements" clause, or the "implements" clause of any
* of its superclasses, that are remote interfaces.
*
* The order of the array returned is arbitrary, and some elements
* may be superfluous (i.e., superinterfaces of other interfaces
* in the array).
*/
public ClassDefinition[] getRemoteInterfaces() {
return remoteInterfaces.clone();
}
/**
* Return an array of RemoteClass.Method objects representing all of
* the remote methods implemented by this class, i.e. all of the
* methods in the class's remote interfaces.
*
* The methods in the array are ordered according to the comparision
* of the strings consisting of their method name followed by their
* type signature, so each method's index in the array corresponds
* to its "operation number" in the JDK 1.1 version of the
* stub/skeleton protocol.
*/
public Method[] getRemoteMethods() {
return remoteMethods.clone();
}
/**
* Return the "interface hash" used to match a stub/skeleton pair for
* this class in the JDK 1.1 version of the stub/skeleton protocol.
*/
public long getInterfaceHash() {
return interfaceHash;
}
/**
* Return string representation of this object, consisting of
* the string "remote class " followed by the class name.
*/
public String toString() {
return "remote class " + implClassDef.getName().toString();
}
/** rmic environment for this object */
private BatchEnvironment env;
/** the remote implementation class this object corresponds to */
private ClassDefinition implClassDef;
/** remote interfaces implemented by this class */
private ClassDefinition[] remoteInterfaces;
/** all the remote methods of this class */
private Method[] remoteMethods;
/** stub/skeleton "interface hash" for this class */
private long interfaceHash;
/** cached definition for certain classes used in this environment */
private ClassDefinition defRemote;
private ClassDefinition defException;
private ClassDefinition defRemoteException;
/**
* Create a RemoteClass instance for the given class. The resulting
* object is not yet initialized.
*/
private RemoteClass(BatchEnvironment env, ClassDefinition implClassDef) {
this.env = env;
this.implClassDef = implClassDef;
}
/**
* Validate that the remote implementation class is properly formed
* and fill in the data structures required by the public interface.
*/
private boolean initialize() {
/*
* Verify that the "impl" is really a class, not an interface.
*/
if (implClassDef.isInterface()) {
env.error(0, "rmic.cant.make.stubs.for.interface",
implClassDef.getName());
return false;
}
/*
* Initialize cached definitions for the Remote interface and
* the RemoteException class.
*/
try {
defRemote =
env.getClassDeclaration(idRemote).getClassDefinition(env);
defException =
env.getClassDeclaration(idJavaLangException).
getClassDefinition(env);
defRemoteException =
env.getClassDeclaration(idRemoteException).
getClassDefinition(env);
} catch (ClassNotFound e) {
env.error(0, "rmic.class.not.found", e.name);
return false;
}
/*
* Here we find all of the remote interfaces of our remote
* implementation class. For each class up the superclass
* chain, add each directly-implemented interface that
* somehow extends Remote to a list.
*/
Vector<ClassDefinition> remotesImplemented = // list of remote interfaces found
new Vector<ClassDefinition>();
for (ClassDefinition classDef = implClassDef;
classDef != null;)
{
try {
ClassDeclaration[] interfaces = classDef.getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
ClassDefinition interfaceDef =
interfaces[i].getClassDefinition(env);
/*
* Add interface to the list if it extends Remote and
* it is not already there.
*/
if (!remotesImplemented.contains(interfaceDef) &&
defRemote.implementedBy(env, interfaces[i]))
{
remotesImplemented.addElement(interfaceDef);
/***** <DEBUG> */
if (env.verbose()) {
System.out.println("[found remote interface: " +
interfaceDef.getName() + "]");
/***** </DEBUG> */
}
}
}
/*
* Verify that the candidate remote implementation class
* implements at least one remote interface directly.
*/
if (classDef == implClassDef && remotesImplemented.isEmpty()) {
if (defRemote.implementedBy(env,
implClassDef.getClassDeclaration()))
{
/*
* This error message is used if the class does
* implement a remote interface through one of
* its superclasses, but not directly.
*/
env.error(0, "rmic.must.implement.remote.directly",
implClassDef.getName());
} else {
/*
* This error message is used if the class never
* implements a remote interface.
*/
env.error(0, "rmic.must.implement.remote",
implClassDef.getName());
}
return false;
}
/*
* Get definition for next superclass.
*/
classDef = (classDef.getSuperClass() != null ?
classDef.getSuperClass().getClassDefinition(env) :
null);
} catch (ClassNotFound e) {
env.error(0, "class.not.found", e.name, classDef.getName());
return false;
}
}
/*
* The "remotesImplemented" vector now contains all of the remote
* interfaces directly implemented by the remote class or by any
* of its superclasses.
*
* At this point, we could optimize the list by removing superfluous
* entries, i.e. any interfaces that are implemented by some other
* interface in the list anyway.
*
* This should be correct; would it be worthwhile?
*
* for (int i = 0; i < remotesImplemented.size();) {
* ClassDefinition interfaceDef =
* (ClassDefinition) remotesImplemented.elementAt(i);
* boolean isOtherwiseImplemented = false;
* for (int j = 0; j < remotesImplemented.size; j++) {
* if (j != i &&
* interfaceDef.implementedBy(env, (ClassDefinition)
* remotesImplemented.elementAt(j).
* getClassDeclaration()))
* {
* isOtherwiseImplemented = true;
* break;
* }
* }
* if (isOtherwiseImplemented) {
* remotesImplemented.removeElementAt(i);
* } else {
* ++i;
* }
* }
*/
/*
* Now we collect the methods from all of the remote interfaces
* into a hashtable.
*/
Hashtable<String, Method> methods = new Hashtable<String, Method>();
boolean errors = false;
for (Enumeration<ClassDefinition> enumeration
= remotesImplemented.elements();
enumeration.hasMoreElements();)
{
ClassDefinition interfaceDef = enumeration.nextElement();
if (!collectRemoteMethods(interfaceDef, methods))
errors = true;
}
if (errors)
return false;
/*
* Convert vector of remote interfaces to an array
* (order is not important for this array).
*/
remoteInterfaces = new ClassDefinition[remotesImplemented.size()];
remotesImplemented.copyInto(remoteInterfaces);
/*
* Sort table of remote methods into an array. The elements are
* sorted in ascending order of the string of the method's name
* and type signature, so that each elements index is equal to
* its operation number of the JDK 1.1 version of the stub/skeleton
* protocol.
*/
String[] orderedKeys = new String[methods.size()];
int count = 0;
for (Enumeration<Method> enumeration = methods.elements();
enumeration.hasMoreElements();)
{
Method m = enumeration.nextElement();
String key = m.getNameAndDescriptor();
int i;
for (i = count; i > 0; --i) {
if (key.compareTo(orderedKeys[i - 1]) >= 0) {
break;
}
orderedKeys[i] = orderedKeys[i - 1];
}
orderedKeys[i] = key;
++count;
}
remoteMethods = new Method[methods.size()];
for (int i = 0; i < remoteMethods.length; i++) {
remoteMethods[i] = methods.get(orderedKeys[i]);
/***** <DEBUG> */
if (env.verbose()) {
System.out.print("[found remote method <" + i + ">: " +
remoteMethods[i].getOperationString());
ClassDeclaration[] exceptions =
remoteMethods[i].getExceptions();
if (exceptions.length > 0)
System.out.print(" throws ");
for (int j = 0; j < exceptions.length; j++) {
if (j > 0)
System.out.print(", ");
System.out.print(exceptions[j].getName());
}
System.out.println("]");
}
/***** </DEBUG> */
}
/**
* Finally, pre-compute the interface hash to be used by
* stubs/skeletons for this remote class.
*/
interfaceHash = computeInterfaceHash();
return true;
}
/**
* Collect and validate all methods from given interface and all of
* its superinterfaces as remote methods. Remote methods are added
* to the supplied hashtable. Returns true if successful,
* or false if an error occurred.
*/
private boolean collectRemoteMethods(ClassDefinition interfaceDef,
Hashtable<String, Method> table)
{
if (!interfaceDef.isInterface()) {
throw new Error(
"expected interface, not class: " + interfaceDef.getName());
}
/*
* rmic used to enforce that a remote interface could not extend
* a non-remote interface, i.e. an interface that did not itself
* extend from Remote. The current version of rmic does not have
* this restriction, so the following code is now commented out.
*
* Verify that this interface extends Remote, since all interfaces
* extended by a remote interface must implement Remote.
*
* try {
* if (!defRemote.implementedBy(env,
* interfaceDef.getClassDeclaration()))
* {
* env.error(0, "rmic.can.mix.remote.nonremote",
* interfaceDef.getName());
* return false;
* }
* } catch (ClassNotFound e) {
* env.error(0, "class.not.found", e.name,
* interfaceDef.getName());
* return false;
* }
*/
boolean errors = false;
/*
* Search interface's members for methods.
*/
nextMember:
for (MemberDefinition member = interfaceDef.getFirstMember();
member != null;
member = member.getNextMember())
{
if (member.isMethod() &&
!member.isConstructor() && !member.isInitializer())
{
/*
* Verify that each method throws RemoteException.
*/
ClassDeclaration[] exceptions = member.getExceptions(env);
boolean hasRemoteException = false;
for (int i = 0; i < exceptions.length; i++) {
/*
* rmic used to enforce that a remote method had to
* explicitly list RemoteException in its "throws"
* clause; i.e., just throwing Exception was not
* acceptable. The current version of rmic does not
* have this restriction, so the following code is
* now commented out. Instead, the method is
* considered valid if RemoteException is a subclass
* of any of the methods declared exceptions.
*
* if (exceptions[i].getName().equals(
* idRemoteException))
* {
* hasRemoteException = true;
* break;
* }
*/
try {
if (defRemoteException.subClassOf(
env, exceptions[i]))
{
hasRemoteException = true;
break;
}
} catch (ClassNotFound e) {
env.error(0, "class.not.found", e.name,
interfaceDef.getName());
continue nextMember;
}
}
/*
* If this method did not throw RemoteException as required,
* generate the error but continue, so that multiple such
* errors can be reported.
*/
if (!hasRemoteException) {
env.error(0, "rmic.must.throw.remoteexception",
interfaceDef.getName(), member.toString());
errors = true;
continue nextMember;
}
/*
* Verify that the implementation of this method throws only
* java.lang.Exception or its subclasses (fix bugid 4092486).
* JRMP does not support remote methods throwing
* java.lang.Throwable or other subclasses.
*/
try {
MemberDefinition implMethod = implClassDef.findMethod(
env, member.getName(), member.getType());
if (implMethod != null) { // should not be null
exceptions = implMethod.getExceptions(env);
for (int i = 0; i < exceptions.length; i++) {
if (!defException.superClassOf(
env, exceptions[i]))
{
env.error(0, "rmic.must.only.throw.exception",
implMethod.toString(),
exceptions[i].getName());
errors = true;
continue nextMember;
}
}
}
} catch (ClassNotFound e) {
env.error(0, "class.not.found", e.name,
implClassDef.getName());
continue nextMember;
}
/*
* Create RemoteClass.Method object to represent this method
* found in a remote interface.
*/
Method newMethod = new Method(member);
/*
* Store remote method's representation in the table of
* remote methods found, keyed by its name and parameter
* signature.
*
* If the table already contains an entry with the same
* method name and parameter signature, then we must
* replace the old entry with a Method object that
* represents a legal combination of the old and the new
* methods; specifically, the combined method must have
* a throws list that contains (only) all of the checked
* exceptions that can be thrown by both the old or
* the new method (see bugid 4070653).
*/
String key = newMethod.getNameAndDescriptor();
Method oldMethod = table.get(key);
if (oldMethod != null) {
newMethod = newMethod.mergeWith(oldMethod);
if (newMethod == null) {
errors = true;
continue nextMember;
}
}
table.put(key, newMethod);
}
}
/*
* Recursively collect methods for all superinterfaces.
*/
try {
ClassDeclaration[] superDefs = interfaceDef.getInterfaces();
for (int i = 0; i < superDefs.length; i++) {
ClassDefinition superDef =
superDefs[i].getClassDefinition(env);
if (!collectRemoteMethods(superDef, table))
errors = true;
}
} catch (ClassNotFound e) {
env.error(0, "class.not.found", e.name, interfaceDef.getName());
return false;
}
return !errors;
}
/**
* Compute the "interface hash" of the stub/skeleton pair for this
* remote implementation class. This is the 64-bit value used to
* enforce compatibility between a stub and a skeleton using the
* JDK 1.1 version of the stub/skeleton protocol.
*
* It is calculated using the first 64 bits of a SHA digest. The
* digest is from a stream consisting of the following data:
* (int) stub version number, always 1
* for each remote method, in order of operation number:
* (UTF) method name
* (UTF) method type signature
* for each declared exception, in alphabetical name order:
* (UTF) name of exception class
*
*/
private long computeInterfaceHash() {
long hash = 0;
ByteArrayOutputStream sink = new ByteArrayOutputStream(512);
try {
MessageDigest md = MessageDigest.getInstance("SHA");
DataOutputStream out = new DataOutputStream(
new DigestOutputStream(sink, md));
out.writeInt(INTERFACE_HASH_STUB_VERSION);
for (int i = 0; i < remoteMethods.length; i++) {
MemberDefinition m = remoteMethods[i].getMemberDefinition();
Identifier name = m.getName();
Type type = m.getType();
out.writeUTF(name.toString());
// type signatures already use mangled class names
out.writeUTF(type.getTypeSignature());
ClassDeclaration exceptions[] = m.getExceptions(env);
sortClassDeclarations(exceptions);
for (int j = 0; j < exceptions.length; j++) {
out.writeUTF(Names.mangleClass(
exceptions[j].getName()).toString());
}
}
out.flush();
// use only the first 64 bits of the digest for the hash
byte hashArray[] = md.digest();
for (int i = 0; i < Math.min(8, hashArray.length); i++) {
hash += ((long) (hashArray[i] & 0xFF)) << (i * 8);
}
} catch (IOException e) {
throw new Error(
"unexpected exception computing intetrface hash: " + e);
} catch (NoSuchAlgorithmException e) {
throw new Error(
"unexpected exception computing intetrface hash: " + e);
}
return hash;
}
/**
* Sort array of class declarations alphabetically by their mangled
* fully-qualified class name. This is used to feed a method's exceptions
* in a canonical order into the digest stream for the interface hash
* computation.
*/
private void sortClassDeclarations(ClassDeclaration[] decl) {
for (int i = 1; i < decl.length; i++) {
ClassDeclaration curr = decl[i];
String name = Names.mangleClass(curr.getName()).toString();
int j;
for (j = i; j > 0; j--) {
if (name.compareTo(
Names.mangleClass(decl[j - 1].getName()).toString()) >= 0)
{
break;
}
decl[j] = decl[j - 1];
}
decl[j] = curr;
}
}
/**
* A RemoteClass.Method object encapsulates RMI-specific information
* about a particular remote method in the remote implementation class
* represented by the outer instance.
*/
public class Method implements Cloneable {
/**
* Return the definition of the actual class member corresponing
* to this method of a remote interface.
*
* REMIND: Can this method be removed?
*/
public MemberDefinition getMemberDefinition() {
return memberDef;
}
/**
* Return the name of this method.
*/
public Identifier getName() {
return memberDef.getName();
}
/**
* Return the type of this method.
*/
public Type getType() {
return memberDef.getType();
}
/**
* Return an array of the exception classes declared to be
* thrown by this remote method.
*
* For methods with the same name and type signature inherited
* from multiple remote interfaces, the array will contain
* the set of exceptions declared in all of the interfaces'
* methods that can be legally thrown in each of them.
*/
public ClassDeclaration[] getExceptions() {
return exceptions.clone();
}
/**
* Return the "method hash" used to identify this remote method
* in the JDK 1.2 version of the stub protocol.
*/
public long getMethodHash() {
return methodHash;
}
/**
* Return the string representation of this method.
*/
public String toString() {
return memberDef.toString();
}
/**
* Return the string representation of this method appropriate
* for the construction of a java.rmi.server.Operation object.
*/
public String getOperationString() {
return memberDef.toString();
}
/**
* Return a string consisting of this method's name followed by
* its method descriptor, using the Java VM's notation for
* method descriptors (see section 4.3.3 of The Java Virtual
* Machine Specification).
*/
public String getNameAndDescriptor() {
return memberDef.getName().toString() +
memberDef.getType().getTypeSignature();
}
/**
* Member definition for this method, from one of the remote
* interfaces that this method was found in.
*
* Note that this member definition may be only one of several
* member defintions that correspond to this remote method object,
* if several of this class's remote interfaces contain methods
* with the same name and type signature. Therefore, this member
* definition may declare more exceptions thrown that this remote
* method does.
*/
private MemberDefinition memberDef;
/** stub "method hash" to identify this method */
private long methodHash;
/**
* Exceptions declared to be thrown by this remote method.
*
* This list can include superfluous entries, such as
* unchecked exceptions and subclasses of other entries.
*/
private ClassDeclaration[] exceptions;
/**
* Create a new Method object corresponding to the given
* method definition.
*/
/*
* Temporarily comment out the private modifier until
* the VM allows outer class to access inner class's
* private constructor
*/
/* private */ Method(MemberDefinition memberDef) {
this.memberDef = memberDef;
exceptions = memberDef.getExceptions(env);
methodHash = computeMethodHash();
}
/**
* Cloning is supported by returning a shallow copy of this object.
*/
protected Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
throw new Error("clone failed");
}
}
/**
* Return a new Method object that is a legal combination of
* this method object and another one.
*
* This requires determining the exceptions declared by the
* combined method, which must be (only) all of the exceptions
* declared in both old Methods that may thrown in either of
* them.
*/
private Method mergeWith(Method other) {
if (!getName().equals(other.getName()) ||
!getType().equals(other.getType()))
{
throw new Error("attempt to merge method \"" +
other.getNameAndDescriptor() + "\" with \"" +
getNameAndDescriptor());
}
Vector<ClassDeclaration> legalExceptions
= new Vector<ClassDeclaration>();
try {
collectCompatibleExceptions(
other.exceptions, exceptions, legalExceptions);
collectCompatibleExceptions(
exceptions, other.exceptions, legalExceptions);
} catch (ClassNotFound e) {
env.error(0, "class.not.found", e.name,
getClassDefinition().getName());
return null;
}
Method merged = (Method) clone();
merged.exceptions = new ClassDeclaration[legalExceptions.size()];
legalExceptions.copyInto(merged.exceptions);
return merged;
}
/**
* Add to the supplied list all exceptions in the "from" array
* that are subclasses of an exception in the "with" array.
*/
private void collectCompatibleExceptions(ClassDeclaration[] from,
ClassDeclaration[] with,
Vector<ClassDeclaration> list)
throws ClassNotFound
{
for (int i = 0; i < from.length; i++) {
ClassDefinition exceptionDef = from[i].getClassDefinition(env);
if (!list.contains(from[i])) {
for (int j = 0; j < with.length; j++) {
if (exceptionDef.subClassOf(env, with[j])) {
list.addElement(from[i]);
break;
}
}
}
}
}
/**
* Compute the "method hash" of this remote method. The method
* hash is a long containing the first 64 bits of the SHA digest
* from the UTF encoded string of the method name and descriptor.
*
* REMIND: Should this method share implementation code with
* the outer class's computeInterfaceHash() method?
*/
private long computeMethodHash() {
long hash = 0;
ByteArrayOutputStream sink = new ByteArrayOutputStream(512);
try {
MessageDigest md = MessageDigest.getInstance("SHA");
DataOutputStream out = new DataOutputStream(
new DigestOutputStream(sink, md));
String methodString = getNameAndDescriptor();
/***** <DEBUG> */
if (env.verbose()) {
System.out.println("[string used for method hash: \"" +
methodString + "\"]");
}
/***** </DEBUG> */
out.writeUTF(methodString);
// use only the first 64 bits of the digest for the hash
out.flush();
byte hashArray[] = md.digest();
for (int i = 0; i < Math.min(8, hashArray.length); i++) {
hash += ((long) (hashArray[i] & 0xFF)) << (i * 8);
}
} catch (IOException e) {
throw new Error(
"unexpected exception computing intetrface hash: " + e);
} catch (NoSuchAlgorithmException e) {
throw new Error(
"unexpected exception computing intetrface hash: " + e);
}
return hash;
}
}
}
|
apache/giraph | 35,742 | giraph-core/src/main/java/org/apache/giraph/ooc/policy/MemoryEstimatorOracle.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.giraph.ooc.policy;
import com.sun.management.GarbageCollectionNotificationInfo;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import org.apache.commons.math.stat.regression.OLSMultipleLinearRegression;
import org.apache.giraph.comm.NetworkMetrics;
import org.apache.giraph.conf.FloatConfOption;
import org.apache.giraph.conf.ImmutableClassesGiraphConfiguration;
import org.apache.giraph.conf.LongConfOption;
import org.apache.giraph.edge.AbstractEdgeStore;
import org.apache.giraph.ooc.OutOfCoreEngine;
import org.apache.giraph.ooc.command.IOCommand;
import org.apache.giraph.ooc.command.LoadPartitionIOCommand;
import org.apache.giraph.ooc.command.WaitIOCommand;
import org.apache.giraph.utils.ThreadUtils;
import org.apache.giraph.worker.EdgeInputSplitsCallable;
import org.apache.giraph.worker.VertexInputSplitsCallable;
import org.apache.giraph.worker.WorkerProgress;
import org.apache.log4j.Logger;
import javax.annotation.Nullable;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static com.google.common.base.Preconditions.checkState;
/**
* Implementation of {@link OutOfCoreOracle} that uses a linear regression model
* to estimate actual memory usage based on the current state of computation.
* The model takes into consideration 5 parameters:
*
* y = c0 + c1*x1 + c2*x2 + c3*x3 + c4*x4 + c5*x5
*
* y: memory usage
* x1: edges loaded
* x2: vertices loaded
* x3: vertices processed
* x4: bytes received due to messages
* x5: bytes loaded/stored from/to disk due to OOC.
*
*/
public class MemoryEstimatorOracle implements OutOfCoreOracle {
/** Memory check interval in msec */
public static final LongConfOption CHECK_MEMORY_INTERVAL =
new LongConfOption("giraph.garbageEstimator.checkMemoryInterval", 1000,
"The interval where memory checker thread wakes up and " +
"monitors memory footprint (in milliseconds)");
/**
* If mem-usage is above this threshold and no Full GC has been called,
* we call it manually
*/
public static final FloatConfOption MANUAL_GC_MEMORY_PRESSURE =
new FloatConfOption("giraph.garbageEstimator.manualGCPressure", 0.95f,
"The threshold above which GC is called manually if Full GC has not " +
"happened in a while");
/** Used to detect a high memory pressure situation */
public static final FloatConfOption GC_MINIMUM_RECLAIM_FRACTION =
new FloatConfOption("giraph.garbageEstimator.gcReclaimFraction", 0.05f,
"Minimum percentage of memory we expect to be reclaimed after a Full " +
"GC. If less than this amount is reclaimed, it is sage to say " +
"we are in a high memory situation and the estimation mechanism " +
"has not recognized it yet!");
/** If mem-usage is above this threshold, active threads are set to 0 */
public static final FloatConfOption AM_HIGH_THRESHOLD =
new FloatConfOption("giraph.amHighThreshold", 0.95f,
"If mem-usage is above this threshold, all active threads " +
"(compute/input) are paused.");
/** If mem-usage is below this threshold, active threads are set to max */
public static final FloatConfOption AM_LOW_THRESHOLD =
new FloatConfOption("giraph.amLowThreshold", 0.90f,
"If mem-usage is below this threshold, all active threads " +
"(compute/input) are running.");
/** If mem-usage is above this threshold, credit is set to 0 */
public static final FloatConfOption CREDIT_HIGH_THRESHOLD =
new FloatConfOption("giraph.creditHighThreshold", 0.95f,
"If mem-usage is above this threshold, credit is set to 0");
/** If mem-usage is below this threshold, credit is set to max */
public static final FloatConfOption CREDIT_LOW_THRESHOLD =
new FloatConfOption("giraph.creditLowThreshold", 0.90f,
"If mem-usage is below this threshold, credit is set to max");
/** OOC starts if mem-usage is above this threshold */
public static final FloatConfOption OOC_THRESHOLD =
new FloatConfOption("giraph.oocThreshold", 0.90f,
"If mem-usage is above this threshold, out of core threads starts " +
"writing data to disk");
/** Logger */
private static final Logger LOG =
Logger.getLogger(MemoryEstimatorOracle.class);
/** Cached value for {@link #MANUAL_GC_MEMORY_PRESSURE} */
private final float manualGCMemoryPressure;
/** Cached value for {@link #GC_MINIMUM_RECLAIM_FRACTION} */
private final float gcReclaimFraction;
/** Cached value for {@link #AM_HIGH_THRESHOLD} */
private final float amHighThreshold;
/** Cached value for {@link #AM_LOW_THRESHOLD} */
private final float amLowThreshold;
/** Cached value for {@link #CREDIT_HIGH_THRESHOLD} */
private final float creditHighThreshold;
/** Cached value for {@link #CREDIT_LOW_THRESHOLD} */
private final float creditLowThreshold;
/** Cached value for {@link #OOC_THRESHOLD} */
private final float oocThreshold;
/** Reference to running OOC engine */
private final OutOfCoreEngine oocEngine;
/** Memory estimator instance */
private final MemoryEstimator memoryEstimator;
/** Keeps track of the number of bytes stored/loaded by OOC */
private final AtomicLong oocBytesInjected = new AtomicLong(0);
/** How many bytes to offload */
private final AtomicLong numBytesToOffload = new AtomicLong(0);
/** Current state of the OOC */
private volatile State state = State.STABLE;
/** Timestamp of the last major GC */
private volatile long lastMajorGCTime = 0;
/**
* Different states the OOC can be in.
*/
private enum State {
/** No offloading */
STABLE,
/** Current offloading */
OFFLOADING,
}
/**
* Constructor.
* @param conf Configuration
* @param oocEngine OOC engine.:w
*
*/
public MemoryEstimatorOracle(ImmutableClassesGiraphConfiguration conf,
final OutOfCoreEngine oocEngine) {
this.oocEngine = oocEngine;
this.memoryEstimator = new MemoryEstimator(this.oocBytesInjected,
oocEngine.getNetworkMetrics());
this.manualGCMemoryPressure = MANUAL_GC_MEMORY_PRESSURE.get(conf);
this.gcReclaimFraction = GC_MINIMUM_RECLAIM_FRACTION.get(conf);
this.amHighThreshold = AM_HIGH_THRESHOLD.get(conf);
this.amLowThreshold = AM_LOW_THRESHOLD.get(conf);
this.creditHighThreshold = CREDIT_HIGH_THRESHOLD.get(conf);
this.creditLowThreshold = CREDIT_LOW_THRESHOLD.get(conf);
this.oocThreshold = OOC_THRESHOLD.get(conf);
final long checkMemoryInterval = CHECK_MEMORY_INTERVAL.get(conf);
ThreadUtils.startThread(new Runnable() {
@Override
public void run() {
while (true) {
long oldGenUsageEstimate = memoryEstimator.getUsageEstimate();
MemoryUsage usage = getOldGenUsed();
if (oldGenUsageEstimate > 0) {
updateRates(oldGenUsageEstimate, usage.getMax());
} else {
long time = System.currentTimeMillis();
if (time - lastMajorGCTime >= 10000) {
double used = (double) usage.getUsed() / usage.getMax();
if (used > manualGCMemoryPressure) {
if (LOG.isInfoEnabled()) {
LOG.info(
"High memory pressure with no full GC from the JVM. " +
"Calling GC manually. Used fraction of old-gen is " +
String.format("%.2f", used) + ".");
}
System.gc();
time = System.currentTimeMillis() - time;
usage = getOldGenUsed();
used = (double) usage.getUsed() / usage.getMax();
if (LOG.isInfoEnabled()) {
LOG.info("Manual GC done. It took " +
String.format("%.2f", time / 1000.0) +
" seconds. Used fraction of old-gen is " +
String.format("%.2f", used) + ".");
}
}
}
}
try {
Thread.sleep(checkMemoryInterval);
} catch (InterruptedException e) {
LOG.warn("run: exception occurred!", e);
return;
}
}
}
}, "ooc-memory-checker", oocEngine.getServiceWorker().getGraphTaskManager()
.createUncaughtExceptionHandler());
}
/**
* Resets all the counters used in the memory estimation. This is called at
* the beginning of a new superstep.
* <p>
* The number of vertices to compute in the next superstep gets reset in
* {@link org.apache.giraph.graph.GraphTaskManager#processGraphPartitions}
* right before
* {@link org.apache.giraph.partition.PartitionStore#startIteration()} gets
* called.
*/
@Override
public void startIteration() {
AbstractEdgeStore.PROGRESS_COUNTER.reset();
oocBytesInjected.set(0);
memoryEstimator.clear();
memoryEstimator.setCurrentSuperstep(oocEngine.getSuperstep());
oocEngine.updateRequestsCreditFraction(1);
oocEngine.updateActiveThreadsFraction(1);
}
@Override
public IOAction[] getNextIOActions() {
if (state == State.OFFLOADING) {
return new IOAction[]{
IOAction.STORE_MESSAGES_AND_BUFFERS, IOAction.STORE_PARTITION};
}
long oldGenUsage = memoryEstimator.getUsageEstimate();
MemoryUsage usage = getOldGenUsed();
if (oldGenUsage > 0) {
double usageEstimate = (double) oldGenUsage / usage.getMax();
if (usageEstimate > oocThreshold) {
return new IOAction[]{
IOAction.STORE_MESSAGES_AND_BUFFERS,
IOAction.STORE_PARTITION};
} else {
return new IOAction[]{IOAction.LOAD_PARTITION};
}
} else {
return new IOAction[]{IOAction.LOAD_PARTITION};
}
}
@Override
public boolean approve(IOCommand command) {
return true;
}
@Override
public void commandCompleted(IOCommand command) {
if (command instanceof LoadPartitionIOCommand) {
oocBytesInjected.getAndAdd(command.bytesTransferred());
if (state == State.OFFLOADING) {
numBytesToOffload.getAndAdd(command.bytesTransferred());
}
} else if (!(command instanceof WaitIOCommand)) {
oocBytesInjected.getAndAdd(0 - command.bytesTransferred());
if (state == State.OFFLOADING) {
numBytesToOffload.getAndAdd(0 - command.bytesTransferred());
}
}
if (state == State.OFFLOADING && numBytesToOffload.get() <= 0) {
numBytesToOffload.set(0);
state = State.STABLE;
updateRates(-1, 1);
}
}
/**
* When a new GC has completed, we can get an accurate measurement of the
* memory usage. We use this to update the linear regression model.
*
* @param gcInfo GC information
*/
@Override
public synchronized void gcCompleted(
GarbageCollectionNotificationInfo gcInfo) {
String action = gcInfo.getGcAction().toLowerCase();
String cause = gcInfo.getGcCause().toLowerCase();
if (action.contains("major") &&
(cause.contains("ergo") || cause.contains("system"))) {
lastMajorGCTime = System.currentTimeMillis();
MemoryUsage before = null;
MemoryUsage after = null;
for (Map.Entry<String, MemoryUsage> entry :
gcInfo.getGcInfo().getMemoryUsageBeforeGc().entrySet()) {
String poolName = entry.getKey();
if (poolName.toLowerCase().contains("old")) {
before = entry.getValue();
after = gcInfo.getGcInfo().getMemoryUsageAfterGc().get(poolName);
break;
}
}
if (after == null) {
throw new IllegalStateException("Missing Memory Usage After GC info");
}
if (before == null) {
throw new IllegalStateException("Missing Memory Usage Before GC info");
}
// Compare the estimation with the actual value
long usedMemoryEstimate = memoryEstimator.getUsageEstimate();
long usedMemoryReal = after.getUsed();
if (usedMemoryEstimate >= 0) {
if (LOG.isInfoEnabled()) {
LOG.info("gcCompleted: estimate=" + usedMemoryEstimate + " real=" +
usedMemoryReal + " error=" +
((double) Math.abs(usedMemoryEstimate - usedMemoryReal) /
usedMemoryReal * 100));
}
}
// Number of edges loaded so far (if in input superstep)
long edgesLoaded = oocEngine.getSuperstep() >= 0 ? 0 :
EdgeInputSplitsCallable.getTotalEdgesLoadedMeter().count();
// Number of vertices loaded so far (if in input superstep)
long verticesLoaded = oocEngine.getSuperstep() >= 0 ? 0 :
VertexInputSplitsCallable.getTotalVerticesLoadedMeter().count();
// Number of vertices computed (if either in compute or store phase)
long verticesComputed = WorkerProgress.get().getVerticesComputed() +
WorkerProgress.get().getVerticesStored() +
AbstractEdgeStore.PROGRESS_COUNTER.getProgress();
// Number of bytes received
long receivedBytes =
oocEngine.getNetworkMetrics().getBytesReceivedPerSuperstep();
// Number of OOC bytes
long oocBytes = oocBytesInjected.get();
memoryEstimator.addRecord(getOldGenUsed().getUsed(), edgesLoaded,
verticesLoaded, verticesComputed, receivedBytes, oocBytes);
long garbage = before.getUsed() - after.getUsed();
long maxMem = after.getMax();
long memUsed = after.getUsed();
boolean isTight = (maxMem - memUsed) < 2 * gcReclaimFraction * maxMem &&
garbage < gcReclaimFraction * maxMem;
boolean predictionExist = memoryEstimator.getUsageEstimate() > 0;
if (isTight && !predictionExist) {
if (LOG.isInfoEnabled()) {
LOG.info("gcCompleted: garbage=" + garbage + " memUsed=" +
memUsed + " maxMem=" + maxMem);
}
numBytesToOffload.set((long) (2 * gcReclaimFraction * maxMem) -
(maxMem - memUsed));
if (LOG.isInfoEnabled()) {
LOG.info("gcCompleted: tight memory usage. Starting to offload " +
"until " + numBytesToOffload.get() + " bytes are offloaded");
}
state = State.OFFLOADING;
updateRates(1, 1);
}
}
}
/**
* Given an estimate for the current memory usage and the maximum available
* memory, it updates the active threads and flow control credit in the
* OOC engine.
*
* @param usageEstimateMem Estimate of memory usage.
* @param maxMemory Maximum memory.
*/
private void updateRates(long usageEstimateMem, long maxMemory) {
double usageEstimate = (double) usageEstimateMem / maxMemory;
if (usageEstimate > 0) {
if (usageEstimate >= amHighThreshold) {
oocEngine.updateActiveThreadsFraction(0);
} else if (usageEstimate < amLowThreshold) {
oocEngine.updateActiveThreadsFraction(1);
} else {
oocEngine.updateActiveThreadsFraction(1 -
(usageEstimate - amLowThreshold) /
(amHighThreshold - amLowThreshold));
}
if (usageEstimate >= creditHighThreshold) {
oocEngine.updateRequestsCreditFraction(0);
} else if (usageEstimate < creditLowThreshold) {
oocEngine.updateRequestsCreditFraction(1);
} else {
oocEngine.updateRequestsCreditFraction(1 -
(usageEstimate - creditLowThreshold) /
(creditHighThreshold - creditLowThreshold));
}
} else {
oocEngine.updateActiveThreadsFraction(1);
oocEngine.updateRequestsCreditFraction(1);
}
}
/**
* Returns statistics about the old gen pool.
* @return {@link MemoryUsage}.
*/
private MemoryUsage getOldGenUsed() {
List<MemoryPoolMXBean> memoryPoolList =
ManagementFactory.getMemoryPoolMXBeans();
for (MemoryPoolMXBean pool : memoryPoolList) {
String normalName = pool.getName().toLowerCase();
if (normalName.contains("old") || normalName.contains("tenured")) {
return pool.getUsage();
}
}
throw new IllegalStateException("Bad Memory Pool");
}
/**
* Maintains statistics about the current state and progress of the
* computation and produces estimates of memory usage using a technique
* based on linear regression.
*
* Upon a GC events, it gets updated with the most recent statistics through
* the {@link #addRecord} method.
*/
private static class MemoryEstimator {
/** Stores the (x1,x2,...,x5) arrays of data samples, one for each sample */
private List<double[]> dataSamples = new ArrayList<>();
/** Stores the y memory usage dataSamples, one for each sample */
private DoubleArrayList memorySamples = new DoubleArrayList();
/** Stores the coefficients computed by the linear regression model */
private double[] coefficient = new double[6];
/** Stores the column indices that can be used in the regression model */
private List<Integer> validColumnIndices = new ArrayList<>();
/** Potentially out-of-range coefficient values */
private double[] extreme = new double[6];
/** Indicates whether current coefficients can be used for estimation */
private boolean isValid = false;
/** Implementation of linear regression */
private OLSMultipleLinearRegression mlr = new OLSMultipleLinearRegression();
/** Used to synchronize access to the data samples */
private Lock lock = new ReentrantLock();
/** The estimation method depends on the current superstep. */
private long currentSuperstep = -1;
/** The estimation method depends on the bytes injected. */
private final AtomicLong oocBytesInjected;
/** Provides network statistics */
private final NetworkMetrics networkMetrics;
/**
* Constructor
* @param oocBytesInjected Reference to {@link AtomicLong} object
* maintaining the number of OOC bytes stored.
* @param networkMetrics Interface to get network stats.
*/
public MemoryEstimator(AtomicLong oocBytesInjected,
NetworkMetrics networkMetrics) {
this.oocBytesInjected = oocBytesInjected;
this.networkMetrics = networkMetrics;
}
/**
* Clear data structure (called from single threaded program).
*/
public void clear() {
dataSamples.clear();
memorySamples.clear();
isValid = false;
}
public void setCurrentSuperstep(long superstep) {
this.currentSuperstep = superstep;
}
/**
* Given the current state of computation (i.e. current edges loaded,
* vertices computed etc) and the current model (i.e. the regression
* coefficient), it returns a prediction about the memory usage in bytes.
*
* @return Memory estimate in bytes.
*/
public long getUsageEstimate() {
long usage = -1;
lock.lock();
try {
if (isValid) {
// Number of edges loaded so far (if in input superstep)
long edgesLoaded = currentSuperstep >= 0 ? 0 :
EdgeInputSplitsCallable.getTotalEdgesLoadedMeter().count();
// Number of vertices loaded so far (if in input superstep)
long verticesLoaded = currentSuperstep >= 0 ? 0 :
VertexInputSplitsCallable.getTotalVerticesLoadedMeter().count();
// Number of vertices computed (if either in compute or store phase)
long verticesComputed = WorkerProgress.get().getVerticesComputed() +
WorkerProgress.get().getVerticesStored() +
AbstractEdgeStore.PROGRESS_COUNTER.getProgress();
// Number of bytes received
long receivedBytes = networkMetrics.getBytesReceivedPerSuperstep();
// Number of OOC bytes
long oocBytes = this.oocBytesInjected.get();
usage = (long) (edgesLoaded * coefficient[0] +
verticesLoaded * coefficient[1] +
verticesComputed * coefficient[2] +
receivedBytes * coefficient[3] +
oocBytes * coefficient[4] +
coefficient[5]);
}
} finally {
lock.unlock();
}
return usage;
}
/**
* Updates the linear regression model with a new data point.
*
* @param memUsed Current real value of memory usage.
* @param edges Number of edges loaded.
* @param vertices Number of vertices loaded.
* @param verticesProcessed Number of vertices processed.
* @param bytesReceived Number of bytes received.
* @param oocBytesInjected Number of bytes stored/loaded due to OOC.
*/
public void addRecord(long memUsed, long edges, long vertices,
long verticesProcessed,
long bytesReceived, long oocBytesInjected) {
checkState(memUsed > 0, "Memory Usage cannot be negative");
if (dataSamples.size() > 0) {
double[] last = dataSamples.get(dataSamples.size() - 1);
if (edges == last[0] && vertices == last[1] &&
verticesProcessed == last[2] && bytesReceived == last[3] &&
oocBytesInjected == last[4]) {
if (LOG.isDebugEnabled()) {
LOG.debug(
"addRecord: avoiding to add the same entry as the last one!");
}
return;
}
}
dataSamples.add(new double[] {edges, vertices, verticesProcessed,
bytesReceived, oocBytesInjected});
memorySamples.add((double) memUsed);
// Weed out the columns that are all zero
validColumnIndices.clear();
for (int i = 0; i < 5; ++i) {
boolean validIndex = false;
// Check if there is a non-zero entry in the column
for (double[] value : dataSamples) {
if (value[i] != 0) {
validIndex = true;
break;
}
}
if (validIndex) {
// check if all entries are not equal to each other
double firstValue = -1;
boolean allEqual = true;
for (double[] value : dataSamples) {
if (firstValue == -1) {
firstValue = value[i];
} else {
if (Math.abs((value[i] - firstValue) / firstValue) > 0.01) {
allEqual = false;
break;
}
}
}
validIndex = !allEqual;
if (validIndex) {
// Check if the column has linear dependency with another column
for (int col = i + 1; col < 5; ++col) {
if (isLinearDependence(dataSamples, i, col)) {
validIndex = false;
break;
}
}
}
}
if (validIndex) {
validColumnIndices.add(i);
}
}
// If we filtered out columns in the previous step, we are going to run
// the regression without those columns.
// Create the coefficient table
boolean setIsValid = false;
lock.lock();
try {
if (validColumnIndices.size() >= 1 &&
dataSamples.size() >= validColumnIndices.size() + 1) {
double[][] xValues = new double[dataSamples.size()][];
fillXMatrix(dataSamples, validColumnIndices, xValues);
double[] yValues =
memorySamples.toDoubleArray(new double[memorySamples.size()]);
mlr.newSampleData(yValues, xValues);
boolean isRegressionValid =
calculateRegression(coefficient, validColumnIndices, mlr);
if (!isRegressionValid) { // invalid regression result
return; // The finally-block at the end will release any locks.
}
// After the computation of the regression, some coefficients may have
// values outside the valid value range. In this case, we set the
// coefficient to the minimum or maximum value allowed, and re-run the
// regression.
// We only care about coefficients of two of the variables:
// bytes received due to messages (receivedBytes -- index 3 in
// `coefficient` array) and bytes transferred due to OOC (oocBytes --
// index 4 in `coefficient` array).
//
// receivedByte's coefficient cannot be negative, meaning that it does
// not make sense that memory footprint decreases because of receipt
// of messages. We either have message combiner or we do not have
// combiner. If message combiner is used, the memory footprint
// will not change much due to messages leading to the coefficient for
// oocBytes to be close to 0. If message combiner is not used, the
// memory only increase with messages, and the coefficient should be
// positive. In this case, a message is usually deserialized and then
// written to the message store. We assume that the process of
// deserializing the message and putting it into the message store
// will not result in more than twice the size of the serialized form
// of the message (meaning that the memory footprint for message store
// will not be more than 2*receivedBytes). Based on this assumption
// the upper bound for coefficient of receivedBytes should be 2.
//
// "oocBytes" represents the size of the serialized form of data that
// has transferred to/from secondary storage. On the other hand, in
// our estimation mechanism, we are estimating the aggregate size of
// all live objects in memory, meaning that we are estimating the size
// of deserialized for of data in memory. Since we are not using any
// (de)compression for (de)serialization of data, we assume that
// size of serialized data <= size of deserialized data <=
// 2 * (size of serialized dat)
// This basically means that the coefficient for oocBytes should be
// between 1 and 2.
boolean changed;
extreme[3] = -1;
extreme[4] = -1;
do {
Boolean result = null;
result = refineCoefficient(4, 1, 2, xValues, yValues);
if (result == null) { // invalid regression result
return; // finally-block will release lock
}
changed = result;
result = refineCoefficient(3, 0, 2, xValues, yValues);
if (result == null) { // invalid regression result
return; // finally-block will release lock
}
changed |= result;
} while (changed);
if (extreme[3] != -1) {
coefficient[3] = extreme[3];
}
if (extreme[4] != -1) {
coefficient[4] = extreme[4];
}
setIsValid = true;
return; // the finally-block will execute before return
}
} finally {
// This inner try-finally block is necessary to ensure that the
// lock is always released.
try {
isValid = setIsValid;
printStats();
} finally {
lock.unlock();
}
}
}
/**
* Certain coefficients need to be within a specific range.
* If the coefficient is not in this range, we set it to the closest bound
* and re-run the linear regression. In this case, we keep the possible
* extremum coefficient in an intermediate array ("extreme"). Also, if
* we choose the extremum coefficient for an index, that index is removed
* from the regression calculation as well as the rest of the refinement
* process.
*
* Note that the regression calculation here is based on the method of
* least square for minimizing the error. The sum of squares of errors for
* all points is a convex function. This means if we solve the
* non-constrained linear regression and then refine the coefficient to
* apply their bounds, we will achieve a solution to our constrained
* linear regression problem.
*
* This method is called in a loop to refine certain coefficients. The loop
* should continue until all coefficients are refined and are within their
* range.
*
* @param coefIndex Coefficient index
* @param lowerBound Lower bound
* @param upperBound Upper bound
* @param xValues double[][] matrix with data samples
* @param yValues double[] matrix with y samples
* @return True if coefficients were out-of-range, false otherwise. A null
* value means the regression result was invalid and the result of
* this method is invalid too.
*/
@Nullable
private Boolean refineCoefficient(int coefIndex, double lowerBound,
double upperBound, double[][] xValues, double[] yValues) {
boolean result = false;
if (coefficient[coefIndex] < lowerBound ||
coefficient[coefIndex] > upperBound) {
double value;
if (coefficient[coefIndex] < lowerBound) {
value = lowerBound;
} else {
value = upperBound;
}
int ptr = -1;
// Finding the 'coefIndex' in the valid indices. Since this method is
// used only for the variables with higher indices, we use a reverse
// loop to lookup the 'coefIndex' for faster termination of the loop.
for (int i = validColumnIndices.size() - 1; i >= 0; --i) {
if (validColumnIndices.get(i) == coefIndex) {
ptr = i;
break;
}
}
if (ptr != -1) {
if (LOG.isDebugEnabled()) {
LOG.debug("addRecord: coefficient at index " + coefIndex +
" is wrong in the regression, setting it to " + value);
}
// remove from valid column
validColumnIndices.remove(ptr);
// re-create the X matrix
fillXMatrix(dataSamples, validColumnIndices, xValues);
// adjust Y values
for (int i = 0; i < memorySamples.size(); ++i) {
yValues[i] -= value * dataSamples.get(i)[coefIndex];
}
// save new coefficient value in intermediate array
extreme[coefIndex] = value;
// re-run regression
mlr.newSampleData(yValues, xValues);
result = calculateRegression(coefficient, validColumnIndices, mlr);
if (!result) { // invalid regression result
return null;
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug(
"addRecord: coefficient was not in the regression, " +
"setting it to the extreme of the bound");
}
result = false;
}
coefficient[coefIndex] = value;
}
return result;
}
/**
* Calculates the regression.
* @param coefficient Array of coefficients
* @param validColumnIndices List of valid columns
* @param mlr {@link OLSMultipleLinearRegression} instance.
* @return True if the result is valid, false otherwise.
*/
private static boolean calculateRegression(double[] coefficient,
List<Integer> validColumnIndices, OLSMultipleLinearRegression mlr) {
if (coefficient.length != validColumnIndices.size()) {
LOG.info("There are " + coefficient.length +
" coefficients, and " + validColumnIndices.size() +
" valid columns in the regression");
}
double[] beta = mlr.estimateRegressionParameters();
Arrays.fill(coefficient, 0);
for (int i = 0; i < validColumnIndices.size(); ++i) {
coefficient[validColumnIndices.get(i)] = beta[i];
}
coefficient[5] = beta[validColumnIndices.size()];
return true;
}
/**
* Copies values from a List of double[] to a double[][]. Takes into
* consideration the list of valid column indices.
* @param sourceValues Source List of double[]
* @param validColumnIndices Valid column indices
* @param xValues Target double[][] matrix.
*/
private static void fillXMatrix(List<double[]> sourceValues,
List<Integer> validColumnIndices,
double[][] xValues) {
for (int i = 0; i < sourceValues.size(); ++i) {
xValues[i] = new double[validColumnIndices.size() + 1];
for (int j = 0; j < validColumnIndices.size(); ++j) {
xValues[i][j] = sourceValues.get(i)[validColumnIndices.get(j)];
}
xValues[i][validColumnIndices.size()] = 1;
}
}
/**
* Utility function that checks whether two doubles are equals given an
* accuracy tolerance.
*
* @param val1 First value
* @param val2 Second value
* @return True if within a threshold
*/
private static boolean equal(double val1, double val2) {
return Math.abs(val1 - val2) < 0.01;
}
/**
* Utility function that checks if two columns have linear dependence.
*
* @param values Matrix in the form of a List of double[] values.
* @param col1 First column index
* @param col2 Second column index
* @return True if there is linear dependence.
*/
private static boolean isLinearDependence(List<double[]> values,
int col1, int col2) {
boolean firstValSeen = false;
double firstVal = 0;
for (double[] value : values) {
double val1 = value[col1];
double val2 = value[col2];
if (equal(val1, 0)) {
if (equal(val2, 0)) {
continue;
} else {
return false;
}
}
if (equal(val2, 0)) {
return false;
}
if (!firstValSeen) {
firstVal = val1 / val2;
firstValSeen = true;
} else {
if (!equal((val1 / val2 - firstVal) / firstVal, 0)) {
return false;
}
}
}
return true;
}
/**
* Prints statistics about the regression model.
*/
private void printStats() {
if (LOG.isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
sb.append(
"\nEDGES\t\tVERTICES\t\tV_PROC\t\tRECEIVED\t\tOOC\t\tMEM_USED\n");
for (int i = 0; i < dataSamples.size(); ++i) {
for (int j = 0; j < dataSamples.get(i).length; ++j) {
sb.append(String.format("%.2f\t\t", dataSamples.get(i)[j]));
}
sb.append(memorySamples.get(i));
sb.append("\n");
}
sb.append("COEFFICIENT:\n");
for (int i = 0; i < coefficient.length; ++i) {
sb.append(String.format("%.2f\t\t", coefficient[i]));
}
sb.append("\n");
LOG.debug("printStats: isValid=" + isValid + sb.toString());
}
}
}
}
|
apache/impala | 35,847 | fe/src/main/java/org/apache/impala/analysis/SetOperationStmt.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.impala.analysis;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.impala.catalog.Column;
import org.apache.impala.catalog.ColumnStats;
import org.apache.impala.catalog.FeView;
import org.apache.impala.common.AnalysisException;
import org.apache.impala.rewrite.ExprRewriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
/**
* Representation of a set operation with its list of operands, and optional order by and
* limit. A child class UnionStmt encapsulates instances that contain only Union operands.
* EXCEPT, INTERSECT, and any combination of the previous with UNION is rewritten in
* StmtRewriter to use joins in place of native operators.
*
* TODO: This class contains many methods and members that should be pushed down to
* UnionStmt.
*
* A union materializes its results, and its resultExprs are SlotRefs into a new
* materialized tuple. During analysis, the operands are normalized (separated into a
* single sequence of DISTINCT followed by a single sequence of ALL operands) and unnested
* to the extent possible. This also creates the AggregationInfo for UNION DISTINCT
* operands. EXCEPT and INTERSECT are unnested during analysis, then rewritten discarding
* the original instance of SetOperationStmt.
*
* Use of resultExprs vs. baseTblResultExprs: We consistently use/cast the resultExprs of
* union operands because the final expr substitution happens during planning. The only
* place where baseTblResultExprs are used is in materializeRequiredSlots() because that
* is called before plan generation and we need to mark the slots of resolved exprs as
* materialized.
*/
public class SetOperationStmt extends QueryStmt {
private final static Logger LOG = LoggerFactory.getLogger(SetOperationStmt.class);
public static enum Qualifier { ALL, DISTINCT }
public static enum SetOperator { EXCEPT, INTERSECT, UNION }
/**
* Represents an operand to a set operation. It consists of a query statement, the set
* operation to perform (except/intersect/union) and its left all/distinct qualifier
* (null for the first operand).
*/
public static class SetOperand {
// Effective qualifier. Should not be reset() to preserve changes made during
// distinct propagation and unnesting that are needed after rewriting Subqueries.
private Qualifier qualifier_;
private SetOperator operator_;
/////////////////////////////////////////
// BEGIN: Members that need to be reset()
private QueryStmt queryStmt_;
// Analyzer used for this operand. Set in analyze().
// We must preserve the conjuncts registered in the analyzer for partition pruning.
private Analyzer analyzer_;
// Map from SetOperationStmt's result slots to our resultExprs. Used during plan
// generation.
private final ExprSubstitutionMap smap_;
// END: Members that need to be reset()
/////////////////////////////////////////
public SetOperand(QueryStmt queryStmt, SetOperator operator, Qualifier qualifier) {
queryStmt_ = queryStmt;
operator_ = operator;
qualifier_ = qualifier;
smap_ = new ExprSubstitutionMap();
}
public void analyze(Analyzer parent) throws AnalysisException {
if (isAnalyzed()) return;
// Used to trigger a rewrite in StmtRewriter
if (operator_ == SetOperator.INTERSECT || operator_ == SetOperator.EXCEPT) {
parent.setSetOpNeedsRewrite();
}
analyzer_ = new Analyzer(parent);
queryStmt_.analyze(analyzer_);
}
public boolean isAnalyzed() { return analyzer_ != null; }
public QueryStmt getQueryStmt() { return queryStmt_; }
public Qualifier getQualifier() { return qualifier_; }
public SetOperator getSetOperator() { return operator_; }
// Used for propagating DISTINCT.
public void setQualifier(Qualifier qualifier) { qualifier_ = qualifier; }
public void setSetOperator(SetOperator operator) { operator_ = operator; }
public void setQueryStmt(QueryStmt stmt) { queryStmt_ = stmt; }
public Analyzer getAnalyzer() { return analyzer_; }
public ExprSubstitutionMap getSmap() { return smap_; }
public boolean hasAnalyticExprs() {
if (queryStmt_ instanceof SelectStmt) {
return ((SelectStmt) queryStmt_).hasAnalyticInfo();
} else {
Preconditions.checkState(queryStmt_ instanceof SetOperationStmt);
return ((SetOperationStmt) queryStmt_).hasAnalyticExprs();
}
}
/**
* C'tor for cloning.
*/
private SetOperand(SetOperand other) {
queryStmt_ = other.queryStmt_.clone();
qualifier_ = other.qualifier_;
operator_ = other.operator_;
analyzer_ = other.analyzer_;
smap_ = other.smap_.clone();
}
public void reset() {
queryStmt_.reset();
analyzer_ = null;
smap_.clear();
}
@Override
public SetOperand clone() {
return new SetOperand(this);
}
}
/////////////////////////////////////////
// BEGIN: Members that need to be reset()
// before analysis, this contains the list of operands derived verbatim from the query;
// after analysis, this contains all of distinctOperands followed by allOperands
protected final List<SetOperand> operands_;
// filled during analyze(); contains all operands that need to go through
// distinct aggregation
protected final List<SetOperand> unionDistinctOperands_ = new ArrayList<>();
// filled during analyze(); contains all operands that can be aggregated with
// a simple merge without duplicate elimination (also needs to merge the output
// of the DISTINCT operands)
protected final List<SetOperand> unionAllOperands_ = new ArrayList<>();
// filled during analyze(); contains all intersect distinct operands
protected final List<SetOperand> intersectDistinctOperands_ = new ArrayList<>();
// filled during analyze(); contains all except distinct operands
protected final List<SetOperand> exceptDistinctOperands_ = new ArrayList<>();
protected MultiAggregateInfo distinctAggInfo_; // only set if we have UNION DISTINCT ops
// Single tuple materialized by the union. Set in analyze().
protected TupleId tupleId_;
// set prior to unnesting
protected String toSqlString_ = null;
// true if any of the operands_ references an AnalyticExpr
private boolean hasAnalyticExprs_ = false;
// List of output expressions produced by the union without the ORDER BY portion
// (if any). Same as resultExprs_ if there is no ORDER BY.
protected List<Expr> setOperationResultExprs_ = new ArrayList<>();
// List of expressions produced by analyzer.castToSetOpCompatibleTypes().
// Contains a list of exprs such that for every i-th expr in that list, it is the first
// widest compatible expression encountered among all i-th exprs in every result expr
// list of the operands.
protected List<Expr> widestExprs_ = new ArrayList<>();
// Holds the SelectStmt as a result of rewriting EXCEPT and INTERSECT. For cases where
// all the operands are UNION this will remain null.
protected QueryStmt rewrittenStmt_ = null;
// END: Members that need to be reset()
/////////////////////////////////////////
public SetOperationStmt(List<SetOperand> operands, List<OrderByElement> orderByElements,
LimitElement limitElement) {
super(orderByElements, limitElement);
Preconditions.checkNotNull(operands);
Preconditions.checkState(operands.size() > 0);
operands_ = operands;
}
/**
* C'tor for cloning.
*/
protected SetOperationStmt(SetOperationStmt other) {
super(other.cloneOrderByElements(),
(other.limitElement_ == null) ? null : other.limitElement_.clone());
operands_ = new ArrayList<>();
if (analyzer_ != null) {
for (SetOperand o : other.unionDistinctOperands_) {
unionDistinctOperands_.add(o.clone());
}
for (SetOperand o : other.unionAllOperands_) {
unionAllOperands_.add(o.clone());
}
for (SetOperand o : other.exceptDistinctOperands_) {
exceptDistinctOperands_.add(o.clone());
}
for (SetOperand o : other.intersectDistinctOperands_) {
intersectDistinctOperands_.add(o.clone());
}
}
for (SetOperand operand : other.operands_) operands_.add(operand.clone());
analyzer_ = other.analyzer_;
distinctAggInfo_ =
(other.distinctAggInfo_ != null) ? other.distinctAggInfo_.clone() : null;
tupleId_ = other.tupleId_;
toSqlString_ = (other.toSqlString_ != null) ? new String(other.toSqlString_) : null;
hasAnalyticExprs_ = other.hasAnalyticExprs_;
withClause_ = (other.withClause_ != null) ? other.withClause_.clone() : null;
setOperationResultExprs_ = Expr.cloneList(other.setOperationResultExprs_);
widestExprs_ = other.widestExprs_;
rewrittenStmt_ = other.rewrittenStmt_;
}
public static QueryStmt createUnionOrSetOperation(List<SetOperand> operands,
List<OrderByElement> orderByElements, LimitElement limitElement) {
boolean unionOnly = true;
for (SetOperand op : operands) {
if (op.getSetOperator() != null && op.getSetOperator() != SetOperator.UNION) {
unionOnly = false;
break;
}
}
if (unionOnly) {
return new UnionStmt(operands, orderByElements, limitElement);
} else {
return new SetOperationStmt(operands, orderByElements, limitElement);
}
}
public List<SetOperand> getOperands() { return operands_; }
public List<SetOperand> getUnionDistinctOperands() { return unionDistinctOperands_; }
public boolean hasUnionDistinctOps() { return !unionDistinctOperands_.isEmpty(); }
public List<SetOperand> getUnionAllOperands() { return unionAllOperands_; }
public boolean hasUnionAllOps() { return !unionAllOperands_.isEmpty(); }
public List<SetOperand> getExceptDistinctOperands() { return exceptDistinctOperands_; }
public boolean hasExceptDistinctOps() { return !exceptDistinctOperands_.isEmpty(); }
public List<SetOperand> getIntersectDistinctOperands() {
return intersectDistinctOperands_;
}
public boolean hasIntersectDistinctOps() {
return !intersectDistinctOperands_.isEmpty();
}
public boolean hasOnlyUnionOps() {
return (hasUnionDistinctOps() || hasUnionAllOps()) && !hasIntersectDistinctOps()
&& !hasExceptDistinctOps();
}
public boolean hasOnlyUnionDistinctOps() {
return hasUnionDistinctOps() && !hasUnionAllOps() && !hasIntersectDistinctOps()
&& !hasExceptDistinctOps();
}
public boolean hasOnlyUnionAllOps() {
return hasUnionAllOps() && !hasUnionDistinctOps() && !hasIntersectDistinctOps()
&& !hasExceptDistinctOps();
}
public boolean hasOnlyIntersectDistinctOps() {
return hasIntersectDistinctOps() && !hasUnionDistinctOps() && !hasUnionAllOps()
&& !hasExceptDistinctOps();
}
public boolean hasOnlyExceptDistinctOps() {
return hasExceptDistinctOps() && !hasUnionDistinctOps() && !hasUnionAllOps()
&& !hasIntersectDistinctOps();
}
public MultiAggregateInfo getDistinctAggInfo() { return distinctAggInfo_; }
public boolean hasAnalyticExprs() { return hasAnalyticExprs_; }
public TupleId getTupleId() { return tupleId_; }
public boolean hasRewrittenStmt() { return rewrittenStmt_ != null; }
public QueryStmt getRewrittenStmt() { return rewrittenStmt_; }
public void removeUnionAllOperands() {
operands_.removeAll(unionAllOperands_);
unionAllOperands_.clear();
}
@Override
public boolean resolveTableMask(Analyzer analyzer) throws AnalysisException {
boolean hasChanges = false;
for (SetOperand op : operands_) {
hasChanges |= op.getQueryStmt().resolveTableMask(analyzer);
}
return hasChanges;
}
@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
if (isAnalyzed()) return;
super.analyze(analyzer);
final org.apache.impala.thrift.TQueryOptions query_options =
analyzer.getQueryCtx().client_request.query_options;
if (query_options.values_stmt_avoid_lossy_char_padding
&& query_options.allow_unsafe_casts) {
throw new AnalysisException("Query options ALLOW_UNSAFE_CASTS and " +
"VALUES_STMT_AVOID_LOSSY_CHAR_PADDING are not allowed to be set at the same " +
"time if the query contains set operation(s).");
}
// Propagates DISTINCT from right to left.
propagateDistinct();
analyzeOperands(analyzer);
// Remember the SQL string before unnesting operands.
toSqlString_ = toSql();
if (origSqlString_ == null) origSqlString_ = toSqlString_;
// Unnest the operands before casting the result exprs. Unnesting may add
// additional entries to operands_ and the result exprs of those unnested
// operands must also be cast properly.
unnestOperands(analyzer);
// Compute hasAnalyticExprs_
hasAnalyticExprs_ = false;
for (SetOperand op : operands_) {
if (op.hasAnalyticExprs()) {
hasAnalyticExprs_ = true;
break;
}
}
// Collect all result expr lists and cast the exprs as necessary.
List<List<Expr>> resultExprLists = new ArrayList<>();
for (SetOperand op : operands_) {
resultExprLists.add(op.getQueryStmt().getResultExprs());
}
widestExprs_ = analyzer.castToSetOpCompatibleTypes(resultExprLists,
shouldAvoidLossyCharPadding(analyzer));
// TODO (IMPALA-11018): Currently only UNION ALL is supported for collection types
// due to missing handling in BE.
if (!hasOnlyUnionAllOps()) {
for (Expr expr: widestExprs_) {
Preconditions.checkState(!expr.getType().isCollectionType(),
"UNION, EXCEPT and INTERSECT are not supported for collection types");
}
}
// Create tuple descriptor materialized by this UnionStmt, its resultExprs, and
// its sortInfo if necessary.
createMetadata(analyzer);
createSortInfo(analyzer);
// Create unnested operands' smaps.
for (SetOperand operand : operands_) setOperandSmap(operand, analyzer);
// Create distinctAggInfo, if necessary.
if (!unionDistinctOperands_.isEmpty()) {
// Aggregate produces exactly the same tuple as the original union stmt.
List<Expr> groupingExprs = Expr.cloneList(resultExprs_);
try {
distinctAggInfo_ = MultiAggregateInfo.createDistinct(
groupingExprs, analyzer.getTupleDesc(tupleId_), analyzer);
} catch (AnalysisException e) {
// Should never happen.
throw new IllegalStateException(
"Error creating agg info in SetOperationStmt.analyze()", e);
}
}
setOperationResultExprs_ = Expr.cloneList(resultExprs_);
if (evaluateOrderBy_) createSortTupleInfo(analyzer);
baseTblResultExprs_ = resultExprs_;
}
/**
* If all values in a column are CHARs but they have different lengths, the common type
* will normally be the CHAR type of the greatest length, in which case other CHAR
* values are padded; this function decides whether this should be avoided by using
* VARCHAR as the common type. See IMPALA-10753.
*
* The default behaviour is returning false, subclasses can override it.
*/
protected boolean shouldAvoidLossyCharPadding(Analyzer analyzer) {
return false;
}
/**
* Analyzes all operands and checks that they return an equal number of exprs.
* Throws an AnalysisException if that is not the case, or if analyzing
* an operand fails.
*/
protected void analyzeOperands(Analyzer analyzer) throws AnalysisException {
for (int i = 0; i < operands_.size(); ++i) {
operands_.get(i).analyze(analyzer);
QueryStmt firstQuery = operands_.get(0).getQueryStmt();
List<Expr> firstExprs = operands_.get(0).getQueryStmt().getResultExprs();
QueryStmt query = operands_.get(i).getQueryStmt();
List<Expr> exprs = query.getResultExprs();
if (firstExprs.size() != exprs.size()) {
throw new AnalysisException("Operands have unequal number of columns:\n" +
"'" + queryStmtToSql(firstQuery) + "' has " +
firstExprs.size() + " column(s)\n" +
"'" + queryStmtToSql(query) + "' has " + exprs.size() + " column(s)");
}
}
}
/**
* Marks the baseTblResultExprs of its operands as materialized, based on
* which of the output slots have been marked.
* Calls materializeRequiredSlots() on the operands themselves.
*/
@Override
public void materializeRequiredSlots(Analyzer analyzer) {
TupleDescriptor tupleDesc = analyzer.getDescTbl().getTupleDesc(tupleId_);
// to keep things simple we materialize all grouping exprs = output slots,
// regardless of what's being referenced externally
if (!unionDistinctOperands_.isEmpty()) tupleDesc.materializeSlots();
if (evaluateOrderBy_) sortInfo_.materializeRequiredSlots(analyzer, null);
// collect operands' result exprs
List<SlotDescriptor> outputSlots = tupleDesc.getSlots();
List<Expr> exprs = new ArrayList<>();
for (int i = 0; i < outputSlots.size(); ++i) {
SlotDescriptor slotDesc = outputSlots.get(i);
if (!slotDesc.isMaterialized()) continue;
for (SetOperand op : operands_) {
exprs.add(op.getQueryStmt().getBaseTblResultExprs().get(i));
}
}
if (distinctAggInfo_ != null) {
distinctAggInfo_.materializeRequiredSlots(analyzer, null);
}
materializeSlots(analyzer, exprs);
for (SetOperand op : operands_) {
op.getQueryStmt().materializeRequiredSlots(analyzer);
}
}
/**
* String representation of queryStmt used in reporting errors.
* Allow subclasses to override this.
*/
protected String queryStmtToSql(QueryStmt queryStmt) {
return queryStmt.toSql();
}
/**
* Propagates DISTINCT (if present) from right to left.
* Implied associativity:
* A UNION ALL B UNION DISTINCT C = (A UNION ALL B) UNION DISTINCT C
* = A UNION DISTINCT B UNION DISTINCT C
*/
protected void propagateDistinct() {
int lastDistinctPos = -1;
for (int i = operands_.size() - 1; i > 0; --i) {
SetOperand operand = operands_.get(i);
if (lastDistinctPos != -1) {
// There is a DISTINCT somewhere to the right.
operand.setQualifier(Qualifier.DISTINCT);
} else if (operand.getQualifier() == Qualifier.DISTINCT) {
lastDistinctPos = i;
}
}
}
@Override
public void rewriteExprs(ExprRewriter rewriter) throws AnalysisException {
// No rewrites are needed for distinctAggInfo_, resultExprs_, or baseTblResultExprs_
// as those Exprs are simply SlotRefs.
for (SetOperand op : operands_) op.getQueryStmt().rewriteExprs(rewriter);
if (orderByElements_ != null) {
for (OrderByElement orderByElem : orderByElements_) {
orderByElem.setExpr(rewriter.rewrite(orderByElem.getExpr(), analyzer_));
}
}
}
@Override
public void getMaterializedTupleIds(List<TupleId> tupleIdList) {
// Return the sort tuple if there is an evaluated order by.
if (evaluateOrderBy_) {
tupleIdList.add(sortInfo_.getSortTupleDescriptor().getId());
} else {
tupleIdList.add(tupleId_);
}
}
@Override
public void collectTableRefs(List<TableRef> tblRefs, boolean fromClauseOnly) {
super.collectTableRefs(tblRefs, fromClauseOnly);
for (SetOperand op : operands_) {
op.getQueryStmt().collectTableRefs(tblRefs, fromClauseOnly);
}
}
@Override
public void collectInlineViews(Set<FeView> inlineViews) {
super.collectInlineViews(inlineViews);
for (SetOperand operand : operands_) {
operand.getQueryStmt().collectInlineViews(inlineViews);
}
}
@Override
public String toSql(ToSqlOptions options) {
if (!options.showRewritten() && toSqlString_ != null) return toSqlString_;
StringBuilder strBuilder = new StringBuilder();
Preconditions.checkState(operands_.size() > 0);
if (withClause_ != null) {
strBuilder.append(withClause_.toSql(options));
strBuilder.append(" ");
}
operandsToSql(options, strBuilder);
// Order By clause
if (hasOrderByClause()) {
strBuilder.append(" ORDER BY ");
for (int i = 0; i < orderByElements_.size(); ++i) {
strBuilder.append(orderByElements_.get(i).toSql(options));
strBuilder.append((i + 1 != orderByElements_.size()) ? ", " : "");
}
}
// Limit clause.
strBuilder.append(limitElement_.toSql(options));
return strBuilder.toString();
}
private void operandsToSql(ToSqlOptions options, StringBuilder strBuilder) {
strBuilder.append(operands_.get(0).getQueryStmt().toSql(options));
// If there is only one operand we simply print it without any mention of a set
// operator. It is only possible in a 'ValuesStmt' - otherwise it is syntactically
// impossible in SQL.
if (operands_.size() == 1) return;
for (int i = 1; i < operands_.size() - 1; ++i) {
String opName = operands_.get(i).getSetOperator() != null ?
operands_.get(i).getSetOperator().name() :
"UNION";
strBuilder.append(" " + opName + " "
+ ((operands_.get(i).getQualifier() == Qualifier.ALL) ? "ALL " : ""));
if (operands_.get(i).getQueryStmt() instanceof SetOperationStmt) {
strBuilder.append("(");
}
strBuilder.append(operands_.get(i).getQueryStmt().toSql(options));
if (operands_.get(i).getQueryStmt() instanceof SetOperationStmt) {
strBuilder.append(")");
}
}
// Determine whether we need parentheses around the last union operand.
SetOperand lastOperand = operands_.get(operands_.size() - 1);
QueryStmt lastQueryStmt = lastOperand.getQueryStmt();
strBuilder.append(" " + lastOperand.getSetOperator().name() + " "
+ ((lastOperand.getQualifier() == Qualifier.ALL) ? "ALL " : ""));
if (lastQueryStmt instanceof SetOperationStmt
|| ((hasOrderByClause() || hasLimit() || hasOffset()) && !lastQueryStmt.hasLimit()
&& !lastQueryStmt.hasOffset() && !lastQueryStmt.hasOrderByClause())) {
strBuilder.append("(");
strBuilder.append(lastQueryStmt.toSql(options));
strBuilder.append(")");
} else {
strBuilder.append(lastQueryStmt.toSql(options));
}
}
@Override
public List<String> getColLabels() {
Preconditions.checkState(operands_.size() > 0);
return operands_.get(0).getQueryStmt().getColLabels();
}
public List<Expr> getSetOperationResultExprs() { return setOperationResultExprs_; }
public List<Expr> getWidestExprs() { return widestExprs_; }
@Override
public SetOperationStmt clone() { return new SetOperationStmt(this); }
/**
* Undoes all changes made by analyze() except distinct propagation and unnesting. After
* analysis, operands_ contains the list of unnested operands with qualifiers adjusted
* to reflect distinct propagation. Every operand in that list is reset(). The
* unionDistinctOperands_ and unionAllOperands_ are cleared because they are redundant
* with operands_.
*/
@Override
public void reset() {
super.reset();
for (SetOperand op : operands_) op.reset();
unionDistinctOperands_.clear();
unionAllOperands_.clear();
intersectDistinctOperands_.clear();
exceptDistinctOperands_.clear();
distinctAggInfo_ = null;
tupleId_ = null;
toSqlString_ = null;
hasAnalyticExprs_ = false;
setOperationResultExprs_.clear();
widestExprs_ = null;
rewrittenStmt_ = null;
}
/**
* Create a descriptor for the tuple materialized by the union.
* Set resultExprs to be slot refs into that tuple.
* Also fills the substitution map, such that "order by" can properly resolve
* column references from the result of the union.
*/
private void createMetadata(Analyzer analyzer) throws AnalysisException {
// Create tuple descriptor for materialized tuple created by the union.
TupleDescriptor tupleDesc = analyzer.getDescTbl().createTupleDescriptor("union");
tupleDesc.setIsMaterialized(true);
tupleId_ = tupleDesc.getId();
if (LOG.isTraceEnabled()) {
LOG.trace("SetOperationStmt.createMetadata: tupleId=" + tupleId_.toString());
}
// One slot per expr in the select blocks. Use first select block as representative.
List<Expr> firstSelectExprs = operands_.get(0).getQueryStmt().getResultExprs();
// Compute column stats for the materialized slots from the source exprs.
List<ColumnStats> columnStats = new ArrayList<>();
List<Set<Column>> sourceColumns = new ArrayList<>();
for (int i = 0; i < operands_.size(); ++i) {
List<Expr> selectExprs = operands_.get(i).getQueryStmt().getResultExprs();
for (int j = 0; j < selectExprs.size(); ++j) {
if (i == 0) {
ColumnStats statsToAdd = ColumnStats.fromExpr(selectExprs.get(j));
columnStats.add(statsToAdd);
sourceColumns.add(new HashSet<>());
} else {
ColumnStats statsToAdd = columnStats.get(j).hasNumDistinctValues() ?
ColumnStats.fromExpr(selectExprs.get(j), sourceColumns.get(j)) :
ColumnStats.fromExpr(selectExprs.get(j));
columnStats.get(j).add(statsToAdd);
}
if (columnStats.get(j).hasNumDistinctValues()) {
// Collect expr columns to keep ndv low in later stats addition.
SlotRef slotRef = selectExprs.get(j).unwrapSlotRef(false);
if (slotRef != null && slotRef.hasDesc()) {
slotRef.getDesc().collectColumns(sourceColumns.get(j));
}
}
}
}
// Create tuple descriptor and slots.
for (int i = 0; i < firstSelectExprs.size(); ++i) {
Expr expr = firstSelectExprs.get(i);
SlotDescriptor slotDesc = analyzer.addSlotDescriptor(tupleDesc);
slotDesc.setLabel(getColLabels().get(i));
slotDesc.setType(expr.getType());
if (expr.getType().isCollectionType()) {
slotDesc.setItemTupleDesc(((SlotRef)expr).getDesc().getItemTupleDesc());
}
slotDesc.setStats(columnStats.get(i));
SlotRef outputSlotRef = new SlotRef(slotDesc);
resultExprs_.add(outputSlotRef);
// Add to aliasSMap so that column refs in "order by" can be resolved.
if (orderByElements_ != null) {
SlotRef aliasRef = new SlotRef(getColLabels().get(i));
if (aliasSmap_.containsMappingFor(aliasRef)) {
ambiguousAliasList_.add(aliasRef);
} else {
aliasSmap_.put(aliasRef, outputSlotRef);
}
}
boolean isNullable = false;
// register single-directional value transfers from output slot
// to operands' result exprs (if those happen to be slotrefs);
// don't do that if the operand computes analytic exprs
// (see Planner.createInlineViewPlan() for the reasoning)
for (SetOperand op : operands_) {
Expr resultExpr = op.getQueryStmt().getResultExprs().get(i);
slotDesc.addSourceExpr(resultExpr);
SlotRef slotRef = resultExpr.unwrapSlotRef(false);
if (slotRef == null || slotRef.getDesc().getIsNullable()) isNullable = true;
if (op.hasAnalyticExprs()) continue;
slotRef = resultExpr.unwrapSlotRef(true);
if (slotRef == null) continue;
analyzer.registerValueTransfer(outputSlotRef.getSlotId(), slotRef.getSlotId());
}
// If all the child slots are not nullable, then the union output slot should not
// be nullable as well.
slotDesc.setIsNullable(isNullable);
}
baseTblResultExprs_ = resultExprs_;
}
/**
* Fill distinct-/all Operands and performs possible unnesting of SetOperationStmt
* operands in the process.
*/
private void unnestOperands(Analyzer analyzer) throws AnalysisException {
if (operands_.size() == 1) {
// ValuesStmt for a single row.
unionAllOperands_.add(operands_.get(0));
return;
}
// find index of first ALL operand
int firstUnionAllIdx = operands_.size();
for (int i = 1; i < operands_.size(); ++i) {
SetOperand operand = operands_.get(i);
if (operand.getQualifier() == Qualifier.ALL) {
firstUnionAllIdx = (i == 1 ? 0 : i);
break;
}
}
List<SetOperand> localOps = new ArrayList<>();
List<SetOperand> tempOps = new ArrayList<>();
// operands[0] is always implicitly ALL, so operands[1] can't be the
// first one
Preconditions.checkState(firstUnionAllIdx != 1);
// unnest DISTINCT operands
for (int i = 0; i < firstUnionAllIdx; ++i) {
tempOps.clear();
SetOperator op = operands_.get(i).getSetOperator();
if (op == null || op == SetOperator.UNION) {
// It is safe to handle the first operand here as we know the first ALL index
// isn't 1 therefore any union can be absorbed.
unnestOperand(tempOps, Qualifier.DISTINCT, operands_.get(i));
localOps.addAll(tempOps);
// If the first operand isn't unnested we treat it as distinct
unionDistinctOperands_.addAll(tempOps);
} else if (op == SetOperator.EXCEPT) {
unnestOperand(tempOps, Qualifier.DISTINCT, operands_.get(i));
localOps.addAll(tempOps);
exceptDistinctOperands_.addAll(tempOps);
} else if (op == SetOperator.INTERSECT) {
unnestOperand(tempOps, Qualifier.DISTINCT, operands_.get(i));
localOps.addAll(tempOps);
intersectDistinctOperands_.addAll(tempOps);
} else {
throw new AnalysisException("Invalid operand in SetOperationStmt: " +
queryStmtToSql(this)); }
}
// unnest ALL operands
for (int i = firstUnionAllIdx; i < operands_.size(); ++i) {
tempOps.clear();
unnestOperand(tempOps, Qualifier.ALL, operands_.get(i));
localOps.addAll(tempOps);
unionAllOperands_.addAll(tempOps);
}
for (SetOperand op : unionDistinctOperands_) {
op.setSetOperator(SetOperator.UNION);
op.setQualifier(Qualifier.DISTINCT);
}
for (SetOperand op : intersectDistinctOperands_) {
op.setSetOperator(SetOperator.INTERSECT);
op.setQualifier(Qualifier.DISTINCT);
}
for (SetOperand op : exceptDistinctOperands_) {
op.setSetOperator(SetOperator.EXCEPT);
op.setQualifier(Qualifier.DISTINCT);
}
for (SetOperand op : unionAllOperands_) {
op.setSetOperator(SetOperator.UNION);
op.setQualifier(Qualifier.ALL);
}
operands_.clear();
operands_.addAll(localOps);
}
/**
* Add a single operand to the target list; if the operand itself is a SetOperationStmt,
* apply unnesting to the extent possible (possibly modifying 'operand' in the process).
*
* Absorb means convert qualifier into target type, this applies to ALL -> DISTINCT,
* currently only done with UNIQUE propagateDistinct() ensures ALL operands are always
* the rightmost, therefore they can be pulled out and absorbed into DISTINCT or just
* added to the outer ALL.
*
* EXCEPT is never unnested.
* (E E) E -> (E E) E
* INTERSECT is unnested unless first
* (I) I I -> (I) I I
* I (I) I -> I I I
* I (I (I I)) -> I I I I
* UNION ALL plucks UNION ALL out
* (UD UD UA) UA UA -> (UD UD) UA UA UA
* UNION DISTINCT absorbs other unions.
* (UD UD UA) UD UA -> UD UD UD UD UA
* (UA UA UA) UA UA -> UA UA UA UA UA
* (UA UA UA) UD UD -> UD UD UD UD UD
*
*/
private void unnestOperand(
List<SetOperand> target, Qualifier targetQualifier, SetOperand operand) {
Preconditions.checkState(operand.isAnalyzed());
QueryStmt queryStmt = operand.getQueryStmt();
if (queryStmt instanceof SelectStmt) {
target.add(operand);
return;
}
Preconditions.checkState(queryStmt instanceof SetOperationStmt);
SetOperationStmt stmt = (SetOperationStmt) queryStmt;
if (stmt.hasLimit() || stmt.hasOffset()) {
// we must preserve the nested Set Operation
target.add(operand);
return;
}
// 1. Unnest INTERSECT only if the nested statement contains only INTERSECTs.
// 2. Union distinct will absorb UNION DISTNCT and UNION ALL if no INTERSECT / EXCEPT
// are present
// 3. Union ALL will always be to the right of any DISTINCT, so we can unnest ALL if
// the target is ALL
// 4. For the first operand with a distinct target, we unnest and absorb only when
// UNIONs are the only operator. All INTERSECT in the first operand aren't unnested,
// this doesn't affect correctness, it's just a simplification.
SetOperator targetOperator = operand.getSetOperator();
if (targetOperator == SetOperator.INTERSECT && stmt.hasOnlyIntersectDistinctOps()) {
target.addAll(stmt.getIntersectDistinctOperands());
} else if (targetOperator == SetOperator.EXCEPT && stmt.hasOnlyExceptDistinctOps()) {
// EXCEPT should not be unnested
target.add(operand);
} else if (targetOperator == SetOperator.UNION && stmt.hasOnlyUnionOps()) {
if (targetQualifier == Qualifier.DISTINCT || !stmt.hasUnionDistinctOps()) {
target.addAll(stmt.getUnionDistinctOperands());
target.addAll(stmt.getUnionAllOperands());
} else {
target.addAll(stmt.getUnionAllOperands());
stmt.removeUnionAllOperands();
target.add(operand);
}
// Special cases for the first operand.
} else if (targetOperator == null && targetQualifier == Qualifier.ALL) {
// Case 3
target.addAll(stmt.getUnionAllOperands());
if (stmt.hasUnionDistinctOps() || stmt.hasExceptDistinctOps()
|| stmt.hasIntersectDistinctOps()) {
stmt.removeUnionAllOperands();
target.add(operand);
}
} else if (targetOperator == null && targetQualifier == Qualifier.DISTINCT) {
// Case 4
if (stmt.hasOnlyUnionOps()) {
target.addAll(stmt.getUnionDistinctOperands());
target.addAll(stmt.getUnionAllOperands());
} else {
target.add(operand);
}
} else {
// Mixed operators are not safe to unnest
target.add(operand);
}
}
/**
* Sets the smap for the given operand. It maps from the output slots this union's
* tuple to the corresponding result exprs of the operand.
*/
private void setOperandSmap(SetOperand operand, Analyzer analyzer) {
TupleDescriptor tupleDesc = analyzer.getDescTbl().getTupleDesc(tupleId_);
// operands' smaps were already set in the operands' analyze()
operand.getSmap().clear();
List<Expr> resultExprs = operand.getQueryStmt().getResultExprs();
Preconditions.checkState(resultExprs.size() == tupleDesc.getSlots().size());
for (int i = 0; i < tupleDesc.getSlots().size(); ++i) {
SlotDescriptor outputSlot = tupleDesc.getSlots().get(i);
// Map to the original (uncast) result expr of the operand.
Expr origExpr = resultExprs.get(i).unwrapExpr(true).clone();
operand.getSmap().put(new SlotRef(outputSlot), origExpr);
}
}
}
|
googleapis/google-cloud-java | 35,473 | java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/AcquireLeaseRequest.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/streaming_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.visionai.v1;
/**
*
*
* <pre>
* Request message for acquiring a lease.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.AcquireLeaseRequest}
*/
public final class AcquireLeaseRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.AcquireLeaseRequest)
AcquireLeaseRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use AcquireLeaseRequest.newBuilder() to construct.
private AcquireLeaseRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private AcquireLeaseRequest() {
series_ = "";
owner_ = "";
leaseType_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new AcquireLeaseRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.StreamingServiceProto
.internal_static_google_cloud_visionai_v1_AcquireLeaseRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.StreamingServiceProto
.internal_static_google_cloud_visionai_v1_AcquireLeaseRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.AcquireLeaseRequest.class,
com.google.cloud.visionai.v1.AcquireLeaseRequest.Builder.class);
}
private int bitField0_;
public static final int SERIES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object series_ = "";
/**
*
*
* <pre>
* The series name.
* </pre>
*
* <code>string series = 1;</code>
*
* @return The series.
*/
@java.lang.Override
public java.lang.String getSeries() {
java.lang.Object ref = series_;
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();
series_ = s;
return s;
}
}
/**
*
*
* <pre>
* The series name.
* </pre>
*
* <code>string series = 1;</code>
*
* @return The bytes for series.
*/
@java.lang.Override
public com.google.protobuf.ByteString getSeriesBytes() {
java.lang.Object ref = series_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
series_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int OWNER_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object owner_ = "";
/**
*
*
* <pre>
* The owner name.
* </pre>
*
* <code>string owner = 2;</code>
*
* @return The owner.
*/
@java.lang.Override
public java.lang.String getOwner() {
java.lang.Object ref = owner_;
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();
owner_ = s;
return s;
}
}
/**
*
*
* <pre>
* The owner name.
* </pre>
*
* <code>string owner = 2;</code>
*
* @return The bytes for owner.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOwnerBytes() {
java.lang.Object ref = owner_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
owner_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TERM_FIELD_NUMBER = 3;
private com.google.protobuf.Duration term_;
/**
*
*
* <pre>
* The lease term.
* </pre>
*
* <code>.google.protobuf.Duration term = 3;</code>
*
* @return Whether the term field is set.
*/
@java.lang.Override
public boolean hasTerm() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The lease term.
* </pre>
*
* <code>.google.protobuf.Duration term = 3;</code>
*
* @return The term.
*/
@java.lang.Override
public com.google.protobuf.Duration getTerm() {
return term_ == null ? com.google.protobuf.Duration.getDefaultInstance() : term_;
}
/**
*
*
* <pre>
* The lease term.
* </pre>
*
* <code>.google.protobuf.Duration term = 3;</code>
*/
@java.lang.Override
public com.google.protobuf.DurationOrBuilder getTermOrBuilder() {
return term_ == null ? com.google.protobuf.Duration.getDefaultInstance() : term_;
}
public static final int LEASE_TYPE_FIELD_NUMBER = 4;
private int leaseType_ = 0;
/**
*
*
* <pre>
* The lease type.
* </pre>
*
* <code>.google.cloud.visionai.v1.LeaseType lease_type = 4;</code>
*
* @return The enum numeric value on the wire for leaseType.
*/
@java.lang.Override
public int getLeaseTypeValue() {
return leaseType_;
}
/**
*
*
* <pre>
* The lease type.
* </pre>
*
* <code>.google.cloud.visionai.v1.LeaseType lease_type = 4;</code>
*
* @return The leaseType.
*/
@java.lang.Override
public com.google.cloud.visionai.v1.LeaseType getLeaseType() {
com.google.cloud.visionai.v1.LeaseType result =
com.google.cloud.visionai.v1.LeaseType.forNumber(leaseType_);
return result == null ? com.google.cloud.visionai.v1.LeaseType.UNRECOGNIZED : result;
}
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(series_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, series_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(owner_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, owner_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(3, getTerm());
}
if (leaseType_ != com.google.cloud.visionai.v1.LeaseType.LEASE_TYPE_UNSPECIFIED.getNumber()) {
output.writeEnum(4, leaseType_);
}
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(series_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, series_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(owner_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, owner_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getTerm());
}
if (leaseType_ != com.google.cloud.visionai.v1.LeaseType.LEASE_TYPE_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(4, leaseType_);
}
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.AcquireLeaseRequest)) {
return super.equals(obj);
}
com.google.cloud.visionai.v1.AcquireLeaseRequest other =
(com.google.cloud.visionai.v1.AcquireLeaseRequest) obj;
if (!getSeries().equals(other.getSeries())) return false;
if (!getOwner().equals(other.getOwner())) return false;
if (hasTerm() != other.hasTerm()) return false;
if (hasTerm()) {
if (!getTerm().equals(other.getTerm())) return false;
}
if (leaseType_ != other.leaseType_) 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) + SERIES_FIELD_NUMBER;
hash = (53 * hash) + getSeries().hashCode();
hash = (37 * hash) + OWNER_FIELD_NUMBER;
hash = (53 * hash) + getOwner().hashCode();
if (hasTerm()) {
hash = (37 * hash) + TERM_FIELD_NUMBER;
hash = (53 * hash) + getTerm().hashCode();
}
hash = (37 * hash) + LEASE_TYPE_FIELD_NUMBER;
hash = (53 * hash) + leaseType_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.visionai.v1.AcquireLeaseRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.AcquireLeaseRequest 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.AcquireLeaseRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.AcquireLeaseRequest 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.AcquireLeaseRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.AcquireLeaseRequest 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.AcquireLeaseRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.AcquireLeaseRequest 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.AcquireLeaseRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.AcquireLeaseRequest 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.AcquireLeaseRequest 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.AcquireLeaseRequest 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.AcquireLeaseRequest 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 acquiring a lease.
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.AcquireLeaseRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.AcquireLeaseRequest)
com.google.cloud.visionai.v1.AcquireLeaseRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.StreamingServiceProto
.internal_static_google_cloud_visionai_v1_AcquireLeaseRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.StreamingServiceProto
.internal_static_google_cloud_visionai_v1_AcquireLeaseRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.AcquireLeaseRequest.class,
com.google.cloud.visionai.v1.AcquireLeaseRequest.Builder.class);
}
// Construct using com.google.cloud.visionai.v1.AcquireLeaseRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getTermFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
series_ = "";
owner_ = "";
term_ = null;
if (termBuilder_ != null) {
termBuilder_.dispose();
termBuilder_ = null;
}
leaseType_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.visionai.v1.StreamingServiceProto
.internal_static_google_cloud_visionai_v1_AcquireLeaseRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.visionai.v1.AcquireLeaseRequest getDefaultInstanceForType() {
return com.google.cloud.visionai.v1.AcquireLeaseRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.visionai.v1.AcquireLeaseRequest build() {
com.google.cloud.visionai.v1.AcquireLeaseRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.visionai.v1.AcquireLeaseRequest buildPartial() {
com.google.cloud.visionai.v1.AcquireLeaseRequest result =
new com.google.cloud.visionai.v1.AcquireLeaseRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.visionai.v1.AcquireLeaseRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.series_ = series_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.owner_ = owner_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.term_ = termBuilder_ == null ? term_ : termBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.leaseType_ = leaseType_;
}
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.AcquireLeaseRequest) {
return mergeFrom((com.google.cloud.visionai.v1.AcquireLeaseRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.visionai.v1.AcquireLeaseRequest other) {
if (other == com.google.cloud.visionai.v1.AcquireLeaseRequest.getDefaultInstance())
return this;
if (!other.getSeries().isEmpty()) {
series_ = other.series_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getOwner().isEmpty()) {
owner_ = other.owner_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasTerm()) {
mergeTerm(other.getTerm());
}
if (other.leaseType_ != 0) {
setLeaseTypeValue(other.getLeaseTypeValue());
}
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:
{
series_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
owner_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getTermFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 26
case 32:
{
leaseType_ = input.readEnum();
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 java.lang.Object series_ = "";
/**
*
*
* <pre>
* The series name.
* </pre>
*
* <code>string series = 1;</code>
*
* @return The series.
*/
public java.lang.String getSeries() {
java.lang.Object ref = series_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
series_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The series name.
* </pre>
*
* <code>string series = 1;</code>
*
* @return The bytes for series.
*/
public com.google.protobuf.ByteString getSeriesBytes() {
java.lang.Object ref = series_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
series_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The series name.
* </pre>
*
* <code>string series = 1;</code>
*
* @param value The series to set.
* @return This builder for chaining.
*/
public Builder setSeries(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
series_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* The series name.
* </pre>
*
* <code>string series = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearSeries() {
series_ = getDefaultInstance().getSeries();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* The series name.
* </pre>
*
* <code>string series = 1;</code>
*
* @param value The bytes for series to set.
* @return This builder for chaining.
*/
public Builder setSeriesBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
series_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private java.lang.Object owner_ = "";
/**
*
*
* <pre>
* The owner name.
* </pre>
*
* <code>string owner = 2;</code>
*
* @return The owner.
*/
public java.lang.String getOwner() {
java.lang.Object ref = owner_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
owner_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The owner name.
* </pre>
*
* <code>string owner = 2;</code>
*
* @return The bytes for owner.
*/
public com.google.protobuf.ByteString getOwnerBytes() {
java.lang.Object ref = owner_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
owner_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The owner name.
* </pre>
*
* <code>string owner = 2;</code>
*
* @param value The owner to set.
* @return This builder for chaining.
*/
public Builder setOwner(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
owner_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The owner name.
* </pre>
*
* <code>string owner = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearOwner() {
owner_ = getDefaultInstance().getOwner();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The owner name.
* </pre>
*
* <code>string owner = 2;</code>
*
* @param value The bytes for owner to set.
* @return This builder for chaining.
*/
public Builder setOwnerBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
owner_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.protobuf.Duration term_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Duration,
com.google.protobuf.Duration.Builder,
com.google.protobuf.DurationOrBuilder>
termBuilder_;
/**
*
*
* <pre>
* The lease term.
* </pre>
*
* <code>.google.protobuf.Duration term = 3;</code>
*
* @return Whether the term field is set.
*/
public boolean hasTerm() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* The lease term.
* </pre>
*
* <code>.google.protobuf.Duration term = 3;</code>
*
* @return The term.
*/
public com.google.protobuf.Duration getTerm() {
if (termBuilder_ == null) {
return term_ == null ? com.google.protobuf.Duration.getDefaultInstance() : term_;
} else {
return termBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The lease term.
* </pre>
*
* <code>.google.protobuf.Duration term = 3;</code>
*/
public Builder setTerm(com.google.protobuf.Duration value) {
if (termBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
term_ = value;
} else {
termBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The lease term.
* </pre>
*
* <code>.google.protobuf.Duration term = 3;</code>
*/
public Builder setTerm(com.google.protobuf.Duration.Builder builderForValue) {
if (termBuilder_ == null) {
term_ = builderForValue.build();
} else {
termBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The lease term.
* </pre>
*
* <code>.google.protobuf.Duration term = 3;</code>
*/
public Builder mergeTerm(com.google.protobuf.Duration value) {
if (termBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& term_ != null
&& term_ != com.google.protobuf.Duration.getDefaultInstance()) {
getTermBuilder().mergeFrom(value);
} else {
term_ = value;
}
} else {
termBuilder_.mergeFrom(value);
}
if (term_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The lease term.
* </pre>
*
* <code>.google.protobuf.Duration term = 3;</code>
*/
public Builder clearTerm() {
bitField0_ = (bitField0_ & ~0x00000004);
term_ = null;
if (termBuilder_ != null) {
termBuilder_.dispose();
termBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The lease term.
* </pre>
*
* <code>.google.protobuf.Duration term = 3;</code>
*/
public com.google.protobuf.Duration.Builder getTermBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getTermFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The lease term.
* </pre>
*
* <code>.google.protobuf.Duration term = 3;</code>
*/
public com.google.protobuf.DurationOrBuilder getTermOrBuilder() {
if (termBuilder_ != null) {
return termBuilder_.getMessageOrBuilder();
} else {
return term_ == null ? com.google.protobuf.Duration.getDefaultInstance() : term_;
}
}
/**
*
*
* <pre>
* The lease term.
* </pre>
*
* <code>.google.protobuf.Duration term = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Duration,
com.google.protobuf.Duration.Builder,
com.google.protobuf.DurationOrBuilder>
getTermFieldBuilder() {
if (termBuilder_ == null) {
termBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Duration,
com.google.protobuf.Duration.Builder,
com.google.protobuf.DurationOrBuilder>(
getTerm(), getParentForChildren(), isClean());
term_ = null;
}
return termBuilder_;
}
private int leaseType_ = 0;
/**
*
*
* <pre>
* The lease type.
* </pre>
*
* <code>.google.cloud.visionai.v1.LeaseType lease_type = 4;</code>
*
* @return The enum numeric value on the wire for leaseType.
*/
@java.lang.Override
public int getLeaseTypeValue() {
return leaseType_;
}
/**
*
*
* <pre>
* The lease type.
* </pre>
*
* <code>.google.cloud.visionai.v1.LeaseType lease_type = 4;</code>
*
* @param value The enum numeric value on the wire for leaseType to set.
* @return This builder for chaining.
*/
public Builder setLeaseTypeValue(int value) {
leaseType_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* The lease type.
* </pre>
*
* <code>.google.cloud.visionai.v1.LeaseType lease_type = 4;</code>
*
* @return The leaseType.
*/
@java.lang.Override
public com.google.cloud.visionai.v1.LeaseType getLeaseType() {
com.google.cloud.visionai.v1.LeaseType result =
com.google.cloud.visionai.v1.LeaseType.forNumber(leaseType_);
return result == null ? com.google.cloud.visionai.v1.LeaseType.UNRECOGNIZED : result;
}
/**
*
*
* <pre>
* The lease type.
* </pre>
*
* <code>.google.cloud.visionai.v1.LeaseType lease_type = 4;</code>
*
* @param value The leaseType to set.
* @return This builder for chaining.
*/
public Builder setLeaseType(com.google.cloud.visionai.v1.LeaseType value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000008;
leaseType_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* The lease type.
* </pre>
*
* <code>.google.cloud.visionai.v1.LeaseType lease_type = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearLeaseType() {
bitField0_ = (bitField0_ & ~0x00000008);
leaseType_ = 0;
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.AcquireLeaseRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.AcquireLeaseRequest)
private static final com.google.cloud.visionai.v1.AcquireLeaseRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.AcquireLeaseRequest();
}
public static com.google.cloud.visionai.v1.AcquireLeaseRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<AcquireLeaseRequest> PARSER =
new com.google.protobuf.AbstractParser<AcquireLeaseRequest>() {
@java.lang.Override
public AcquireLeaseRequest 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<AcquireLeaseRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<AcquireLeaseRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.visionai.v1.AcquireLeaseRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/xmlgraphics-fop | 35,894 | fop-core/src/main/java/org/apache/fop/layoutmgr/list/ListItemLayoutManager.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$ */
package org.apache.fop.layoutmgr.list;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Stack;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.fop.area.Area;
import org.apache.fop.area.Block;
import org.apache.fop.fo.flow.ListItem;
import org.apache.fop.fo.flow.ListItemBody;
import org.apache.fop.fo.flow.ListItemLabel;
import org.apache.fop.fo.properties.CommonBorderPaddingBackground;
import org.apache.fop.fo.properties.KeepProperty;
import org.apache.fop.layoutmgr.BlockLayoutManager;
import org.apache.fop.layoutmgr.BreakElement;
import org.apache.fop.layoutmgr.BreakOpportunity;
import org.apache.fop.layoutmgr.BreakOpportunityHelper;
import org.apache.fop.layoutmgr.ElementListObserver;
import org.apache.fop.layoutmgr.ElementListUtils;
import org.apache.fop.layoutmgr.FloatContentLayoutManager;
import org.apache.fop.layoutmgr.FootenoteUtil;
import org.apache.fop.layoutmgr.FootnoteBodyLayoutManager;
import org.apache.fop.layoutmgr.Keep;
import org.apache.fop.layoutmgr.KnuthBlockBox;
import org.apache.fop.layoutmgr.KnuthElement;
import org.apache.fop.layoutmgr.KnuthPenalty;
import org.apache.fop.layoutmgr.KnuthPossPosIter;
import org.apache.fop.layoutmgr.LayoutContext;
import org.apache.fop.layoutmgr.LayoutManager;
import org.apache.fop.layoutmgr.LeafPosition;
import org.apache.fop.layoutmgr.ListElement;
import org.apache.fop.layoutmgr.NonLeafPosition;
import org.apache.fop.layoutmgr.PageProvider;
import org.apache.fop.layoutmgr.Position;
import org.apache.fop.layoutmgr.PositionIterator;
import org.apache.fop.layoutmgr.SpaceResolver;
import org.apache.fop.layoutmgr.SpacedBorderedPaddedBlockLayoutManager;
import org.apache.fop.layoutmgr.TraitSetter;
import org.apache.fop.traits.SpaceVal;
import org.apache.fop.util.BreakUtil;
/**
* LayoutManager for a list-item FO.
* The list item contains a list item label and a list item body.
*/
public class ListItemLayoutManager extends SpacedBorderedPaddedBlockLayoutManager
implements BreakOpportunity {
/** logging instance */
private static Log log = LogFactory.getLog(ListItemLayoutManager.class);
private ListItemContentLayoutManager label;
private ListItemContentLayoutManager body;
private Block curBlockArea;
private List<ListElement> labelList;
private List<ListElement> bodyList;
private Keep keepWithNextPendingOnLabel;
private Keep keepWithNextPendingOnBody;
public static class ListItemPosition extends Position {
private int labelFirstIndex;
private int labelLastIndex;
private int bodyFirstIndex;
private int bodyLastIndex;
private Position originalLabelPosition;
private Position originalBodyPosition;
public ListItemPosition(LayoutManager lm, int labelFirst, int labelLast,
int bodyFirst, int bodyLast) {
super(lm);
labelFirstIndex = labelFirst;
labelLastIndex = labelLast;
bodyFirstIndex = bodyFirst;
bodyLastIndex = bodyLast;
}
public int getLabelFirstIndex() {
return labelFirstIndex;
}
public int getLabelLastIndex() {
return labelLastIndex;
}
public int getBodyFirstIndex() {
return bodyFirstIndex;
}
public int getBodyLastIndex() {
return bodyLastIndex;
}
/** {@inheritDoc} */
public boolean generatesAreas() {
return true;
}
/** {@inheritDoc} */
public String toString() {
StringBuffer sb = new StringBuffer("ListItemPosition:");
sb.append(getIndex()).append("(");
sb.append("label:").append(labelFirstIndex).append("-").append(labelLastIndex);
sb.append(" body:").append(bodyFirstIndex).append("-").append(bodyLastIndex);
sb.append(")");
return sb.toString();
}
public Position getOriginalLabelPosition() {
return originalLabelPosition;
}
public void setOriginalLabelPosition(Position originalLabelPosition) {
this.originalLabelPosition = originalLabelPosition;
}
public Position getOriginalBodyPosition() {
return originalBodyPosition;
}
public void setOriginalBodyPosition(Position originalBodyPosition) {
this.originalBodyPosition = originalBodyPosition;
}
}
/**
* Create a new list item layout manager.
* @param node list-item to create the layout manager for
*/
public ListItemLayoutManager(ListItem node) {
super(node);
setLabel(node.getLabel());
setBody(node.getBody());
}
@Override
protected CommonBorderPaddingBackground getCommonBorderPaddingBackground() {
return getListItemFO().getCommonBorderPaddingBackground();
}
/**
* Convenience method.
* @return the ListBlock node
*/
protected ListItem getListItemFO() {
return (ListItem)fobj;
}
/**
* Create a LM for the fo:list-item-label object
* @param node the fo:list-item-label FO
*/
public void setLabel(ListItemLabel node) {
label = new ListItemContentLayoutManager(node);
label.setParent(this);
}
/**
* Create a LM for the fo:list-item-body object
* @param node the fo:list-item-body FO
*/
public void setBody(ListItemBody node) {
body = new ListItemContentLayoutManager(node);
body.setParent(this);
}
/** {@inheritDoc} */
@Override
public void initialize() {
foSpaceBefore = new SpaceVal(
getListItemFO().getCommonMarginBlock().spaceBefore, this).getSpace();
foSpaceAfter = new SpaceVal(
getListItemFO().getCommonMarginBlock().spaceAfter, this).getSpace();
startIndent = getListItemFO().getCommonMarginBlock().startIndent.getValue(this);
endIndent = getListItemFO().getCommonMarginBlock().endIndent.getValue(this);
}
private void resetSpaces() {
this.discardBorderBefore = false;
this.discardBorderAfter = false;
this.discardPaddingBefore = false;
this.discardPaddingAfter = false;
this.effSpaceBefore = null;
this.effSpaceAfter = null;
}
/** {@inheritDoc} */
public List<ListElement> getNextKnuthElements(LayoutContext context, int alignment, Stack lmStack,
Position restartPosition, LayoutManager restartAtLM) {
referenceIPD = context.getRefIPD();
LayoutContext childLC;
List<ListElement> returnList = new LinkedList<ListElement>();
if (!breakBeforeServed(context, returnList)) {
return returnList;
}
addFirstVisibleMarks(returnList, context, alignment);
// label
childLC = makeChildLayoutContext(context);
childLC.setFlags(LayoutContext.SUPPRESS_BREAK_BEFORE);
label.initialize();
boolean labelDone = false;
Stack labelLMStack = null;
Position labelRestartPosition = null;
LayoutManager labelRestartLM = null;
if (restartPosition != null && restartPosition instanceof ListItemPosition) {
ListItemPosition lip = (ListItemPosition) restartPosition;
if (lip.labelLastIndex <= lip.labelFirstIndex) {
labelDone = true;
} else {
labelRestartPosition = lip.getOriginalLabelPosition();
labelRestartLM = labelRestartPosition.getLM();
LayoutManager lm = labelRestartLM;
labelLMStack = new Stack();
while (lm != this) {
labelLMStack.push(lm);
lm = lm.getParent();
if (lm instanceof ListItemContentLayoutManager) {
lm = lm.getParent();
}
}
}
}
labelList = !labelDone ? label.getNextKnuthElements(childLC, alignment, labelLMStack,
labelRestartPosition, labelRestartLM) : (List) new LinkedList<KnuthElement>();
//Space resolution as if the contents were placed in a new reference area
//(see 6.8.3, XSL 1.0, section on Constraints, last paragraph)
SpaceResolver.resolveElementList(labelList);
ElementListObserver.observe(labelList, "list-item-label", label.getPartFO().getId());
context.updateKeepWithPreviousPending(childLC.getKeepWithPreviousPending());
this.keepWithNextPendingOnLabel = childLC.getKeepWithNextPending();
// body
childLC = makeChildLayoutContext(context);
childLC.setFlags(LayoutContext.SUPPRESS_BREAK_BEFORE);
body.initialize();
boolean bodyDone = false;
Stack bodyLMStack = null;
Position bodyRestartPosition = null;
LayoutManager bodyRestartLM = null;
if (restartPosition != null && restartPosition instanceof ListItemPosition) {
ListItemPosition lip = (ListItemPosition) restartPosition;
if (lip.bodyLastIndex <= lip.bodyFirstIndex) {
bodyDone = true;
} else {
bodyRestartPosition = lip.getOriginalBodyPosition();
bodyRestartLM = bodyRestartPosition.getLM();
LayoutManager lm = bodyRestartLM;
bodyLMStack = new Stack();
while (lm != this) {
bodyLMStack.push(lm);
lm = lm.getParent();
if (lm instanceof ListItemContentLayoutManager) {
lm = lm.getParent();
}
}
}
}
bodyList = !bodyDone ? body.getNextKnuthElements(childLC, alignment, bodyLMStack,
bodyRestartPosition, bodyRestartLM) : (List) new LinkedList<KnuthElement>();
//Space resolution as if the contents were placed in a new reference area
//(see 6.8.3, XSL 1.0, section on Constraints, last paragraph)
SpaceResolver.resolveElementList(bodyList);
ElementListObserver.observe(bodyList, "list-item-body", body.getPartFO().getId());
context.updateKeepWithPreviousPending(childLC.getKeepWithPreviousPending());
this.keepWithNextPendingOnBody = childLC.getKeepWithNextPending();
List<ListElement> returnedList = new LinkedList<ListElement>();
if (!labelList.isEmpty() && labelList.get(0) instanceof KnuthBlockBox) {
KnuthBlockBox kbb = (KnuthBlockBox) labelList.get(0);
if (kbb.getWidth() == 0 && kbb.hasFloatAnchors()) {
List<FloatContentLayoutManager> floats = kbb.getFloatContentLMs();
returnedList.add(new KnuthBlockBox(0, Collections.emptyList(), null, false, floats));
Keep keep = getKeepTogether();
returnedList.add(new BreakElement(new LeafPosition(this, 0), keep.getPenalty(), keep
.getContext(), context));
labelList.remove(0);
labelList.remove(0);
}
}
if (!bodyList.isEmpty() && bodyList.get(0) instanceof KnuthBlockBox) {
KnuthBlockBox kbb = (KnuthBlockBox) bodyList.get(0);
if (kbb.getWidth() == 0 && kbb.hasFloatAnchors()) {
List<FloatContentLayoutManager> floats = kbb.getFloatContentLMs();
returnedList.add(new KnuthBlockBox(0, Collections.emptyList(), null, false, floats));
Keep keep = getKeepTogether();
returnedList.add(new BreakElement(new LeafPosition(this, 0), keep.getPenalty(), keep
.getContext(), context));
bodyList.remove(0);
bodyList.remove(0);
}
}
// create a combined list
returnedList.addAll(getCombinedKnuthElementsForListItem(labelList, bodyList, context));
// "wrap" the Position inside each element
wrapPositionElements(returnedList, returnList, true);
addLastVisibleMarks(returnList, context, alignment);
addKnuthElementsForBreakAfter(returnList, context);
context.updateKeepWithNextPending(this.keepWithNextPendingOnLabel);
context.updateKeepWithNextPending(this.keepWithNextPendingOnBody);
context.updateKeepWithNextPending(getKeepWithNext());
context.updateKeepWithPreviousPending(getKeepWithPrevious());
setFinished(true);
resetSpaces();
return returnList;
}
/**
* Overridden to unconditionally add elements for space-before.
* {@inheritDoc}
*/
@Override
protected void addFirstVisibleMarks(List<ListElement> elements,
LayoutContext context, int alignment) {
addKnuthElementsForSpaceBefore(elements, alignment);
addKnuthElementsForBorderPaddingBefore(elements, !firstVisibleMarkServed);
firstVisibleMarkServed = true;
//Spaces, border and padding to be repeated at each break
addPendingMarks(context);
}
private List getCombinedKnuthElementsForListItem(List<ListElement> labelElements,
List<ListElement> bodyElements, LayoutContext context) {
// Copy elements to array lists to improve element access performance
List[] elementLists = {new ArrayList<ListElement>(labelElements),
new ArrayList<ListElement>(bodyElements)};
int[] fullHeights = {ElementListUtils.calcContentLength(elementLists[0]),
ElementListUtils.calcContentLength(elementLists[1])};
int[] partialHeights = {0, 0};
int[] start = {-1, -1};
int[] end = {-1, -1};
int totalHeight = Math.max(fullHeights[0], fullHeights[1]);
int step;
int addedBoxHeight = 0;
Keep keepWithNextActive = Keep.KEEP_AUTO;
LinkedList<ListElement> returnList = new LinkedList<ListElement>();
while ((step = getNextStep(elementLists, start, end, partialHeights)) > 0) {
if (end[0] + 1 == elementLists[0].size()) {
keepWithNextActive = keepWithNextActive.compare(keepWithNextPendingOnLabel);
}
if (end[1] + 1 == elementLists[1].size()) {
keepWithNextActive = keepWithNextActive.compare(keepWithNextPendingOnBody);
}
// compute penalty height and box height
int penaltyHeight = step
+ getMaxRemainingHeight(fullHeights, partialHeights)
- totalHeight;
//Additional penalty height from penalties in the source lists
int additionalPenaltyHeight = 0;
int stepPenalty = 0;
int breakClass = EN_AUTO;
KnuthElement endEl = elementLists[0].size() > 0 ? (KnuthElement) elementLists[0].get(end[0])
: null;
Position originalLabelPosition =
(endEl != null && endEl.getPosition() != null) ? endEl.getPosition().getPosition() : null;
if (endEl instanceof KnuthPenalty) {
additionalPenaltyHeight = endEl.getWidth();
stepPenalty = endEl.getPenalty() == -KnuthElement.INFINITE ? -KnuthElement.INFINITE : Math
.max(stepPenalty, endEl.getPenalty());
breakClass = BreakUtil.compareBreakClasses(breakClass,
((KnuthPenalty) endEl).getBreakClass());
}
endEl = elementLists[1].size() > 0 ? (KnuthElement) elementLists[1].get(end[1]) : null;
Position originalBodyPosition =
(endEl != null && endEl.getPosition() != null) ? endEl.getPosition().getPosition() : null;
if (endEl instanceof KnuthPenalty) {
additionalPenaltyHeight = Math.max(
additionalPenaltyHeight, endEl.getWidth());
stepPenalty = endEl.getPenalty() == -KnuthElement.INFINITE ? -KnuthElement.INFINITE : Math
.max(stepPenalty, endEl.getPenalty());
breakClass = BreakUtil.compareBreakClasses(breakClass,
((KnuthPenalty) endEl).getBreakClass());
}
int boxHeight = step - addedBoxHeight - penaltyHeight;
penaltyHeight += additionalPenaltyHeight; //Add AFTER calculating boxHeight!
// collect footnote information
// TODO this should really not be done like this. ListItemLM should remain as
// footnote-agnostic as possible
LinkedList<FootnoteBodyLayoutManager> footnoteList = new LinkedList<>();
for (int i = 0; i < elementLists.length; i++) {
footnoteList.addAll(FootenoteUtil.getFootnotes(elementLists[i], start[i], end[i]));
}
LinkedList<FloatContentLayoutManager> floats = new LinkedList<FloatContentLayoutManager>();
for (int i = 0; i < elementLists.length; i++) {
floats.addAll(FloatContentLayoutManager.checkForFloats(elementLists[i], start[i], end[i]));
}
// add the new elements
addedBoxHeight += boxHeight;
ListItemPosition stepPosition = new ListItemPosition(this, start[0], end[0], start[1], end[1]);
stepPosition.setOriginalLabelPosition(originalLabelPosition);
if (originalBodyPosition == null || originalBodyPosition.getLM() instanceof ListItemContentLayoutManager) {
// Happens when ListItem has multiple blocks and a block (that's not the last block) ends at the same
// page height as a IPD change (e.g. FOP-3098). originalBodyPosition (reset) position needs to be a
// Block so that BlockStackingLayoutManager can stack it. Lookahead to find next Block.
Position block = extractBlock(elementLists[1], end[1] + 1);
if (block != null) {
originalBodyPosition = block;
}
}
stepPosition.setOriginalBodyPosition(originalBodyPosition);
if (floats.isEmpty()) {
returnList.add(new KnuthBlockBox(boxHeight, footnoteList, stepPosition, false));
} else {
// add a line with height zero and no content and attach float to it
returnList.add(new KnuthBlockBox(0, Collections.emptyList(), stepPosition, false, floats));
// add a break element to signal that we should restart LB at this break
Keep keep = getKeepTogether();
returnList.add(new BreakElement(stepPosition, keep.getPenalty(), keep.getContext(), context));
// add the original line where the float was but without the float now
returnList.add(new KnuthBlockBox(boxHeight, footnoteList, stepPosition, false));
}
if (originalBodyPosition != null && getKeepWithPrevious().isAuto()
&& shouldWeAvoidBreak(returnList, originalBodyPosition.getLM())) {
stepPenalty++;
}
if (addedBoxHeight < totalHeight) {
Keep keep = keepWithNextActive.compare(getKeepTogether());
int p = stepPenalty;
if (p > -KnuthElement.INFINITE) {
p = Math.max(p, keep.getPenalty());
breakClass = keep.getContext();
}
returnList.add(new BreakElement(stepPosition, penaltyHeight, p, breakClass, context));
}
}
return returnList;
}
/**
* Extracts a block Position from a ListElement at a given index in a list of ListItem body elements.
* @param bodyElements The ListItem body elements.
* @param index The index of the ListElement containing the block.
* @return The required block Position as a LeafPosition or null on failure.
*/
private Position extractBlock(List<ListElement> bodyElements, int index) {
ListElement listElement;
Position position = null;
Position retval = null;
do {
if (bodyElements == null || index >= bodyElements.size()) {
break;
}
listElement = bodyElements.get(index);
if (listElement != null
&& listElement.getLayoutManager() instanceof ListItemContentLayoutManager) {
position = listElement.getPosition();
if (position != null
&& position.getLM() instanceof ListItemContentLayoutManager) {
position = position.getPosition();
if (position != null
&& position.getPosition() != null
&& position.getLM() instanceof BlockLayoutManager) {
retval = new LeafPosition(position.getPosition().getLM(), 0);
}
}
}
} while (false);
return retval;
}
private boolean shouldWeAvoidBreak(List<ListElement> returnList, LayoutManager lm) {
if (isChangingIPD(lm)) {
if (lm instanceof BlockLayoutManager) {
return true;
}
if (lm instanceof ListBlockLayoutManager) {
int penaltyShootout = 0;
for (Object o : returnList) {
if (o instanceof BreakElement) {
if (((BreakElement) o).getPenaltyValue() > 0) {
penaltyShootout++;
} else {
penaltyShootout--;
}
}
}
return penaltyShootout > 0;
}
}
return false;
}
private boolean isChangingIPD(LayoutManager lm) {
PageProvider pageProvider = lm.getPSLM().getPageProvider();
int currentIPD = pageProvider.getCurrentIPD();
if (currentIPD == -1) {
return false;
}
int nextIPD = pageProvider.getNextIPD();
return nextIPD != currentIPD;
}
private int getNextStep(List[] elementLists, int[] start, int[] end, int[] partialHeights) {
// backup of partial heights
int[] backupHeights = {partialHeights[0], partialHeights[1]};
// set starting points
start[0] = end[0] + 1;
start[1] = end[1] + 1;
// get next possible sequence for label and body
int seqCount = 0;
for (int i = 0; i < start.length; i++) {
while (end[i] + 1 < elementLists[i].size()) {
end[i]++;
KnuthElement el = (KnuthElement)elementLists[i].get(end[i]);
if (el.isPenalty()) {
if (el.getPenalty() < KnuthElement.INFINITE) {
//First legal break point
break;
}
} else if (el.isGlue()) {
if (end[i] > 0) {
KnuthElement prev = (KnuthElement)elementLists[i].get(end[i] - 1);
if (prev.isBox()) {
//Second legal break point
break;
}
}
partialHeights[i] += el.getWidth();
} else {
partialHeights[i] += el.getWidth();
}
}
if (end[i] < start[i]) {
partialHeights[i] = backupHeights[i];
} else {
seqCount++;
}
}
if (seqCount == 0) {
return 0;
}
// determine next step
int step;
if (backupHeights[0] == 0 && backupHeights[1] == 0) {
// this is the first step: choose the maximum increase, so that
// the smallest area in the first page will contain at least
// a label area and a body area
step = Math.max((end[0] >= start[0] ? partialHeights[0] : Integer.MIN_VALUE),
(end[1] >= start[1] ? partialHeights[1] : Integer.MIN_VALUE));
} else {
// this is not the first step: choose the minimum increase
step = Math.min((end[0] >= start[0] ? partialHeights[0] : Integer.MAX_VALUE),
(end[1] >= start[1] ? partialHeights[1] : Integer.MAX_VALUE));
}
// reset bigger-than-step sequences
for (int i = 0; i < partialHeights.length; i++) {
if (partialHeights[i] > step) {
partialHeights[i] = backupHeights[i];
end[i] = start[i] - 1;
}
}
return step;
}
private int getMaxRemainingHeight(int[] fullHeights, int[] partialHeights) {
return Math.max(fullHeights[0] - partialHeights[0],
fullHeights[1] - partialHeights[1]);
}
/** {@inheritDoc} */
@Override
public List<ListElement> getChangedKnuthElements(List oldList, int alignment) {
// label
labelList = label.getChangedKnuthElements(labelList, alignment);
// body
// "unwrap" the Positions stored in the elements
ListIterator oldListIterator = oldList.listIterator();
KnuthElement oldElement;
while (oldListIterator.hasNext()) {
oldElement = (KnuthElement)oldListIterator.next();
Position innerPosition = oldElement.getPosition().getPosition();
if (innerPosition != null) {
// oldElement was created by a descendant of this BlockLM
oldElement.setPosition(innerPosition);
} else {
// thisElement was created by this BlockLM
// modify its position in order to recognize it was not created
// by a child
oldElement.setPosition(new Position(this));
}
}
List<ListElement> returnedList = body.getChangedKnuthElements(oldList, alignment);
// "wrap" the Position inside each element
List<ListElement> tempList = returnedList;
KnuthElement tempElement;
returnedList = new LinkedList<>();
for (Object aTempList : tempList) {
tempElement = (KnuthElement) aTempList;
tempElement.setPosition(new NonLeafPosition(this, tempElement.getPosition()));
returnedList.add(tempElement);
}
return returnedList;
}
@Override
public boolean hasLineAreaDescendant() {
return label.hasLineAreaDescendant() || body.hasLineAreaDescendant();
}
@Override
public int getBaselineOffset() {
if (label.hasLineAreaDescendant()) {
return label.getBaselineOffset();
} else if (body.hasLineAreaDescendant()) {
return body.getBaselineOffset();
} else {
throw newNoLineAreaDescendantException();
}
}
/**
* Add the areas for the break points.
*
* @param parentIter the position iterator
* @param layoutContext the layout context for adding areas
*/
@Override
public void addAreas(PositionIterator parentIter,
LayoutContext layoutContext) {
getParentArea(null);
addId();
LayoutContext lc = LayoutContext.offspringOf(layoutContext);
Position firstPos = null;
Position lastPos = null;
// "unwrap" the NonLeafPositions stored in parentIter
LinkedList<Position> positionList = new LinkedList<Position>();
Position pos;
while (parentIter.hasNext()) {
pos = parentIter.next();
if (pos.getIndex() >= 0) {
if (firstPos == null) {
firstPos = pos;
}
lastPos = pos;
}
if (pos instanceof NonLeafPosition && pos.getPosition() != null) {
// pos contains a ListItemPosition created by this ListBlockLM
positionList.add(pos.getPosition());
}
}
if (positionList.isEmpty()) {
reset();
return;
}
registerMarkers(true, isFirst(firstPos), isLast(lastPos));
// use the first and the last ListItemPosition to determine the
// corresponding indexes in the original labelList and bodyList
int labelFirstIndex = ((ListItemPosition) positionList.getFirst()).getLabelFirstIndex();
int labelLastIndex = ((ListItemPosition) positionList.getLast()).getLabelLastIndex();
int bodyFirstIndex = ((ListItemPosition) positionList.getFirst()).getBodyFirstIndex();
int bodyLastIndex = ((ListItemPosition) positionList.getLast()).getBodyLastIndex();
//Determine previous break if any (in item label list)
int previousBreak = ElementListUtils.determinePreviousBreak(labelList, labelFirstIndex);
SpaceResolver.performConditionalsNotification(labelList,
labelFirstIndex, labelLastIndex, previousBreak);
//Determine previous break if any (in item body list)
previousBreak = ElementListUtils.determinePreviousBreak(bodyList, bodyFirstIndex);
SpaceResolver.performConditionalsNotification(bodyList,
bodyFirstIndex, bodyLastIndex, previousBreak);
// add label areas
if (labelFirstIndex <= labelLastIndex) {
KnuthPossPosIter labelIter = new KnuthPossPosIter(labelList,
labelFirstIndex, labelLastIndex + 1);
lc.setFlags(LayoutContext.FIRST_AREA, layoutContext.isFirstArea());
lc.setFlags(LayoutContext.LAST_AREA, layoutContext.isLastArea());
// set the space adjustment ratio
lc.setSpaceAdjust(layoutContext.getSpaceAdjust());
// TO DO: use the right stack limit for the label
lc.setStackLimitBP(layoutContext.getStackLimitBP());
label.addAreas(labelIter, lc);
}
// add body areas
if (bodyFirstIndex <= bodyLastIndex) {
KnuthPossPosIter bodyIter = new KnuthPossPosIter(bodyList,
bodyFirstIndex, bodyLastIndex + 1);
lc.setFlags(LayoutContext.FIRST_AREA, layoutContext.isFirstArea());
lc.setFlags(LayoutContext.LAST_AREA, layoutContext.isLastArea());
// set the space adjustment ratio
lc.setSpaceAdjust(layoutContext.getSpaceAdjust());
// TO DO: use the right stack limit for the body
lc.setStackLimitBP(layoutContext.getStackLimitBP());
body.addAreas(bodyIter, lc);
}
// after adding body areas, set the maximum area bpd
int childCount = curBlockArea.getChildAreas().size();
assert childCount >= 1 && childCount <= 2;
int itemBPD = ((Block)curBlockArea.getChildAreas().get(0)).getAllocBPD();
if (childCount == 2) {
itemBPD = Math.max(itemBPD, ((Block)curBlockArea.getChildAreas().get(1)).getAllocBPD());
}
curBlockArea.setBPD(itemBPD);
registerMarkers(false, isFirst(firstPos), isLast(lastPos));
// We are done with this area add the background
TraitSetter.addBackground(curBlockArea,
getListItemFO().getCommonBorderPaddingBackground(),
this);
TraitSetter.addSpaceBeforeAfter(curBlockArea, layoutContext.getSpaceAdjust(),
effSpaceBefore, effSpaceAfter);
flush();
curBlockArea = null;
resetSpaces();
checkEndOfLayout(lastPos);
}
/**
* Return an Area which can contain the passed childArea. The childArea
* may not yet have any content, but it has essential traits set.
* In general, if the LayoutManager already has an Area it simply returns
* it. Otherwise, it makes a new Area of the appropriate class.
* It gets a parent area for its area by calling its parent LM.
* Finally, based on the dimensions of the parent area, it initializes
* its own area. This includes setting the content IPD and the maximum
* BPD.
*
* @param childArea the child area
* @return the parent are for the child
*/
@Override
public Area getParentArea(Area childArea) {
if (curBlockArea == null) {
curBlockArea = new Block();
curBlockArea.setChangeBarList(getChangeBarList());
// Set up dimensions
/*Area parentArea =*/ parentLayoutManager.getParentArea(curBlockArea);
// set traits
ListItem fo = getListItemFO();
TraitSetter.setProducerID(curBlockArea, fo.getId());
TraitSetter.addBorders(curBlockArea, fo.getCommonBorderPaddingBackground(),
discardBorderBefore, discardBorderAfter, false, false, this);
TraitSetter.addPadding(curBlockArea, fo.getCommonBorderPaddingBackground(),
discardPaddingBefore, discardPaddingAfter, false, false, this);
TraitSetter.addMargins(curBlockArea, fo.getCommonBorderPaddingBackground(),
fo.getCommonMarginBlock(), this);
TraitSetter.addBreaks(curBlockArea, fo.getBreakBefore(), fo.getBreakAfter());
int contentIPD = referenceIPD - getIPIndents();
curBlockArea.setIPD(contentIPD);
curBlockArea.setBidiLevel(fo.getBidiLevel());
setCurrentArea(curBlockArea);
}
return curBlockArea;
}
/**
* Add the child.
* Rows return the areas returned by the child elements.
* This simply adds the area to the parent layout manager.
*
* @param childArea the child area
*/
@Override
public void addChildArea(Area childArea) {
if (curBlockArea != null) {
curBlockArea.addBlock((Block) childArea);
}
}
/** {@inheritDoc} */
@Override
public KeepProperty getKeepTogetherProperty() {
return getListItemFO().getKeepTogether();
}
/** {@inheritDoc} */
@Override
public KeepProperty getKeepWithPreviousProperty() {
return getListItemFO().getKeepWithPrevious();
}
/** {@inheritDoc} */
@Override
public KeepProperty getKeepWithNextProperty() {
return getListItemFO().getKeepWithNext();
}
/** {@inheritDoc} */
@Override
public void reset() {
super.reset();
label.reset();
body.reset();
}
@Override
public int getBreakBefore() {
int breakBefore = BreakOpportunityHelper.getBreakBefore(this);
breakBefore = BreakUtil.compareBreakClasses(breakBefore, label.getBreakBefore());
breakBefore = BreakUtil.compareBreakClasses(breakBefore, body.getBreakBefore());
return breakBefore;
}
/** {@inheritDoc} */
public boolean isRestartable() {
return true;
}
}
|
apache/kafka | 35,795 | raft/src/main/java/org/apache/kafka/raft/QuorumState.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.kafka.raft;
import org.apache.kafka.common.Uuid;
import org.apache.kafka.common.feature.SupportedVersionRange;
import org.apache.kafka.common.utils.LogContext;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.raft.internals.BatchAccumulator;
import org.apache.kafka.raft.internals.KRaftControlRecordStateMachine;
import org.apache.kafka.raft.internals.KafkaRaftMetrics;
import org.apache.kafka.server.common.OffsetAndEpoch;
import org.slf4j.Logger;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Random;
/**
* This class is responsible for managing the current state of this node and ensuring
* only valid state transitions. Below we define the possible state transitions and
* how they are triggered:
*
* Resigned transitions to:
* Unattached: After learning of a new election with a higher epoch, or expiration of the election timeout
* Follower: After discovering a leader with a larger epoch
*
* Unattached transitions to:
* Unattached: After learning of a new election with a higher epoch or after giving a binding vote
* Prospective: After expiration of the election timeout
* Follower: After discovering a leader with an equal or larger epoch
*
* Prospective transitions to:
* Unattached: After learning of an election with a higher epoch, or node did not have last
* known leader and loses/times out election
* Candidate: After receiving a majority of PreVotes granted
* Follower: After discovering a leader with a larger epoch, or node had a last known leader
* and loses/times out election
*
* Candidate transitions to:
* Unattached: After learning of a new election with a higher epoch
* Prospective: After expiration of the election timeout or loss of election
* Leader: After receiving a majority of votes
*
* Leader transitions to:
* Unattached: After learning of a new election with a higher epoch
* Resigned: When shutting down gracefully
* Follower: After discovering a leader with a larger epoch
*
* Follower transitions to:
* Unattached: After learning of a new election with a higher epoch
* Prospective: After expiration of the fetch timeout
* Follower: After discovering a leader with a larger epoch
*
* Observers follow a simpler state machine. The Prospective/Candidate/Leader/Resigned
* states are not possible for observers, so the only transitions that are possible
* are between Unattached and Follower.
*
* Unattached transitions to:
* Unattached: After learning of a new election with a higher epoch
* Follower: After discovering a leader with an equal or larger epoch
*
* Follower transitions to:
* Unattached: After learning of a new election with a higher epoch
* Follower: After discovering a leader with a larger epoch
*
*/
public class QuorumState {
private final OptionalInt localId;
private final Uuid localDirectoryId;
private final Time time;
private final Logger log;
private final QuorumStateStore store;
private final KRaftControlRecordStateMachine partitionState;
private final Endpoints localListeners;
private final SupportedVersionRange localSupportedKRaftVersion;
private final Random random;
private final int electionTimeoutMs;
private final int fetchTimeoutMs;
private final LogContext logContext;
private final KafkaRaftMetrics kafkaRaftMetrics;
private volatile EpochState state;
public QuorumState(
OptionalInt localId,
Uuid localDirectoryId,
KRaftControlRecordStateMachine partitionState,
Endpoints localListeners,
SupportedVersionRange localSupportedKRaftVersion,
int electionTimeoutMs,
int fetchTimeoutMs,
QuorumStateStore store,
Time time,
LogContext logContext,
Random random,
KafkaRaftMetrics kafkaRaftMetrics
) {
this.localId = localId;
this.localDirectoryId = localDirectoryId;
this.partitionState = partitionState;
this.localListeners = localListeners;
this.localSupportedKRaftVersion = localSupportedKRaftVersion;
this.electionTimeoutMs = electionTimeoutMs;
this.fetchTimeoutMs = fetchTimeoutMs;
this.store = store;
this.time = time;
this.log = logContext.logger(QuorumState.class);
this.random = random;
this.logContext = logContext;
this.kafkaRaftMetrics = kafkaRaftMetrics;
}
private ElectionState readElectionState() {
ElectionState election;
election = store
.readElectionState()
.orElseGet(
() -> ElectionState.withUnknownLeader(0, partitionState.lastVoterSet().voterIds())
);
return election;
}
public void initialize(OffsetAndEpoch logEndOffsetAndEpoch) throws IllegalStateException {
// We initialize in whatever state we were in on shutdown. If we were a leader
// or candidate, probably an election was held, but we will find out about it
// when we send Vote or BeginEpoch requests.
ElectionState election = readElectionState();
final EpochState initialState;
if (election.hasVoted() && localId.isEmpty()) {
throw new IllegalStateException(
String.format(
"Initialized quorum state (%s) with a voted candidate but without a local id",
election
)
);
} else if (election.epoch() < logEndOffsetAndEpoch.epoch()) {
log.warn(
"Epoch from quorum store file ({}) is {}, which is smaller than last written " +
"epoch {} in the log",
store.path(),
election.epoch(),
logEndOffsetAndEpoch.epoch()
);
initialState = new UnattachedState(
time,
logEndOffsetAndEpoch.epoch(),
OptionalInt.empty(),
Optional.empty(),
partitionState.lastVoterSet().voterIds(),
Optional.empty(),
randomElectionTimeoutMs(),
logContext
);
} else if (localId.isPresent() && election.isLeader(localId.getAsInt())) {
// If we were previously a leader, then we will start out as resigned
// in the same epoch. This serves two purposes:
// 1. It ensures that we cannot vote for another leader in the same epoch.
// 2. It protects the invariant that each record is uniquely identified by
// offset and epoch, which might otherwise be violated if unflushed data
// is lost after restarting.
initialState = new ResignedState(
time,
localId.getAsInt(),
election.epoch(),
partitionState.lastVoterSet().voterIds(),
randomElectionTimeoutMs(),
List.of(),
localListeners,
logContext
);
} else if (
localId.isPresent() &&
election.isVotedCandidate(ReplicaKey.of(localId.getAsInt(), localDirectoryId))
) {
initialState = new CandidateState(
time,
localId.getAsInt(),
localDirectoryId,
election.epoch(),
partitionState.lastVoterSet(),
Optional.empty(),
randomElectionTimeoutMs(),
logContext
);
} else if (election.hasLeader()) {
VoterSet voters = partitionState.lastVoterSet();
Endpoints leaderEndpoints = voters.listeners(election.leaderId());
if (leaderEndpoints.isEmpty()) {
// Since the leader's endpoints are not known, it cannot send Fetch or
// FetchSnapshot requests to the leader.
//
// Transition to unattached instead and discover the leader's endpoint through
// Fetch requests to the bootstrap servers or from a BeginQuorumEpoch request from
// the leader.
log.info(
"The leader in election state {} is not a member of the latest voter set {}; " +
"transitioning to unattached instead of follower because the leader's " +
"endpoints are not known",
election,
voters
);
initialState = new UnattachedState(
time,
election.epoch(),
OptionalInt.of(election.leaderId()),
election.optionalVotedKey(),
partitionState.lastVoterSet().voterIds(),
Optional.empty(),
randomElectionTimeoutMs(),
logContext
);
} else {
initialState = new FollowerState(
time,
election.epoch(),
election.leaderId(),
leaderEndpoints,
election.optionalVotedKey(),
voters.voterIds(),
Optional.empty(),
fetchTimeoutMs,
logContext
);
}
} else {
initialState = new UnattachedState(
time,
election.epoch(),
OptionalInt.empty(),
election.optionalVotedKey(),
partitionState.lastVoterSet().voterIds(),
Optional.empty(),
randomElectionTimeoutMs(),
logContext
);
}
durableTransitionTo(initialState);
}
public boolean isOnlyVoter() {
return localId.isPresent() &&
partitionState
.lastVoterSet()
.isOnlyVoter(ReplicaKey.of(localId.getAsInt(), localDirectoryId));
}
public int localIdOrSentinel() {
return localId.orElse(-1);
}
public int localIdOrThrow() {
return localId.orElseThrow(() -> new IllegalStateException("Required local id is not present"));
}
public OptionalInt localId() {
return localId;
}
public Uuid localDirectoryId() {
return localDirectoryId;
}
public ReplicaKey localReplicaKeyOrThrow() {
return ReplicaKey.of(localIdOrThrow(), localDirectoryId());
}
public VoterSet.VoterNode localVoterNodeOrThrow() {
return VoterSet.VoterNode.of(
localReplicaKeyOrThrow(),
localListeners,
localSupportedKRaftVersion
);
}
public int epoch() {
return state.epoch();
}
public int leaderIdOrSentinel() {
return state.election().leaderIdOrSentinel();
}
public Optional<LogOffsetMetadata> highWatermark() {
return state.highWatermark();
}
public OptionalInt leaderId() {
ElectionState election = state.election();
if (election.hasLeader())
return OptionalInt.of(state.election().leaderId());
else
return OptionalInt.empty();
}
public Optional<ReplicaKey> votedKey() {
return state.election().optionalVotedKey();
}
public boolean hasLeader() {
return leaderId().isPresent();
}
public boolean hasRemoteLeader() {
return hasLeader() && leaderIdOrSentinel() != localIdOrSentinel();
}
public Endpoints leaderEndpoints() {
return state.leaderEndpoints();
}
public boolean isVoter() {
if (localId.isEmpty()) {
return false;
}
return partitionState
.lastVoterSet()
.isVoter(ReplicaKey.of(localId.getAsInt(), localDirectoryId));
}
public boolean isVoter(ReplicaKey nodeKey) {
return partitionState.lastVoterSet().isVoter(nodeKey);
}
public boolean isObserver() {
return !isVoter();
}
public void transitionToResigned(List<ReplicaKey> preferredSuccessors) {
if (!isLeader()) {
throw new IllegalStateException("Invalid transition to Resigned state from " + state);
}
// The Resigned state is a soft state which does not need to be persisted.
// A leader will always be re-initialized in this state.
int epoch = state.epoch();
memoryTransitionTo(
new ResignedState(
time,
localIdOrThrow(),
epoch,
partitionState.lastVoterSet().voterIds(),
randomElectionTimeoutMs(),
preferredSuccessors,
localListeners,
logContext
)
);
}
/**
* Transition to the "unattached" state. This means one of the following
* 1. the replica has found an epoch greater than the current epoch.
* 2. the replica has transitioned from Prospective with the same epoch.
* 3. the replica has transitioned from Resigned with current epoch + 1.
* Note, if the replica is transitioning from unattached to add voted state and there is no epoch change,
* it takes the route of unattachedAddVotedState instead.
*/
public void transitionToUnattached(int epoch, OptionalInt leaderId) {
int currentEpoch = state.epoch();
if (epoch < currentEpoch || (epoch == currentEpoch && !isProspective())) {
throw new IllegalStateException(
String.format(
"Cannot transition to Unattached with epoch %d from current state %s",
epoch,
state
)
);
}
final long electionTimeoutMs;
if (isObserver()) {
electionTimeoutMs = Long.MAX_VALUE;
} else if (isCandidate()) {
electionTimeoutMs = candidateStateOrThrow().remainingElectionTimeMs(time.milliseconds());
} else if (isUnattached()) {
electionTimeoutMs = unattachedStateOrThrow().remainingElectionTimeMs(time.milliseconds());
} else if (isProspective() && !prospectiveStateOrThrow().epochElection().isVoteRejected()) {
electionTimeoutMs = prospectiveStateOrThrow().remainingElectionTimeMs(time.milliseconds());
} else if (isResigned()) {
electionTimeoutMs = resignedStateOrThrow().remainingElectionTimeMs(time.milliseconds());
} else {
electionTimeoutMs = randomElectionTimeoutMs();
}
// If the local replica is transitioning to Unattached in the same epoch (i.e. from Prospective), it
// should retain its voted key if it exists, so that it will not vote again in the same epoch.
Optional<ReplicaKey> votedKey = epoch == currentEpoch ? votedKey() : Optional.empty();
durableTransitionTo(new UnattachedState(
time,
epoch,
leaderId,
votedKey,
partitionState.lastVoterSet().voterIds(),
state.highWatermark(),
electionTimeoutMs,
logContext
));
}
/**
* Grant a vote to a candidate as Unattached. The replica will transition to Unattached with votedKey
* state in the same epoch and remain there until either the election timeout expires or it discovers the leader.
* Note, if the replica discovers a higher epoch or is transitioning from Prospective, it takes
* the route of transitionToUnattached instead.
*/
public void unattachedAddVotedState(
int epoch,
ReplicaKey candidateKey
) {
int currentEpoch = state.epoch();
if (localId.isPresent() && candidateKey.id() == localId.getAsInt()) {
throw new IllegalStateException(
String.format(
"Cannot add voted key (%s) to current state (%s) in epoch %d since it matches the local " +
"broker.id",
candidateKey,
state,
epoch
)
);
} else if (localId.isEmpty()) {
throw new IllegalStateException("Cannot add voted state without a replica id");
} else if (epoch != currentEpoch || !isUnattachedNotVoted()) {
throw new IllegalStateException(
String.format(
"Cannot add voted key (%s) to current state (%s) in epoch %d",
candidateKey,
state,
epoch
)
);
}
// Note that we reset the election timeout after voting for a candidate because we
// know that the candidate has at least as good of a chance of getting elected as us
durableTransitionTo(
new UnattachedState(
time,
epoch,
state.election().optionalLeaderId(),
Optional.of(candidateKey),
partitionState.lastVoterSet().voterIds(),
state.highWatermark(),
randomElectionTimeoutMs(),
logContext
)
);
}
/**
* Grant a vote to a candidate as Prospective. The replica will transition to Prospective with votedKey
* state in the same epoch. Note, if the replica is transitioning to Prospective due to a fetch/election timeout
* or loss of election as candidate, it takes the route of transitionToProspective instead.
*/
public void prospectiveAddVotedState(
int epoch,
ReplicaKey candidateKey
) {
// Verify the current state is prospective, this method should only be used to add voted state to
// prospective state. Transitions from other states to prospective use transitionToProspective instead.
prospectiveStateOrThrow();
int currentEpoch = state.epoch();
if (localId.isPresent() && candidateKey.id() == localId.getAsInt()) {
throw new IllegalStateException(
String.format(
"Cannot add voted key (%s) to current state (%s) in epoch %d since it matches the local " +
"broker.id",
candidateKey,
state,
epoch
)
);
} else if (localId.isEmpty()) {
throw new IllegalStateException("Cannot add voted state without a replica id");
} else if (epoch != currentEpoch || !isProspectiveNotVoted()) {
throw new IllegalStateException(
String.format(
"Cannot add voted key (%s) to current state (%s) in epoch %d",
candidateKey,
state,
epoch
)
);
}
// Note that we reset the election timeout after voting for a candidate because we
// know that the candidate has at least as good of a chance of getting elected as us
durableTransitionTo(
new ProspectiveState(
time,
localIdOrThrow(),
epoch,
state.election().optionalLeaderId(),
state.leaderEndpoints(),
Optional.of(candidateKey),
partitionState.lastVoterSet(),
state.highWatermark(),
randomElectionTimeoutMs(),
logContext
)
);
}
/**
* Become a follower of an elected leader so that we can begin fetching.
*/
public void transitionToFollower(int epoch, int leaderId, Endpoints endpoints) {
int currentEpoch = state.epoch();
if (endpoints.isEmpty()) {
throw new IllegalArgumentException(
String.format(
"Cannot transition to Follower with leader %s and epoch %s without a leader endpoint",
leaderId,
epoch
)
);
} else if (localId.isPresent() && leaderId == localId.getAsInt()) {
throw new IllegalStateException(
String.format(
"Cannot transition to Follower with leader %s and epoch %s since it matches the local node.id %s",
leaderId,
epoch,
localId
)
);
} else if (epoch < currentEpoch) {
throw new IllegalStateException(
String.format(
"Cannot transition to Follower with leader %s and epoch %s since the current epoch %s is larger",
leaderId,
epoch,
currentEpoch
)
);
} else if (epoch == currentEpoch) {
if (isFollower() && state.leaderEndpoints().size() >= endpoints.size()) {
throw new IllegalStateException(
String.format(
"Cannot transition to Follower with leader %s, epoch %s and endpoints %s from state %s",
leaderId,
epoch,
endpoints,
state
)
);
} else if (isLeader()) {
throw new IllegalStateException(
String.format(
"Cannot transition to Follower with leader %s and epoch %s from state %s",
leaderId,
epoch,
state
)
);
}
}
// State transitions within the same epoch should preserve voted key if it exists. This prevents
// replicas from voting multiple times in the same epoch, which could violate the Raft invariant of
// at most one leader elected in an epoch.
Optional<ReplicaKey> votedKey = epoch == currentEpoch ? votedKey() : Optional.empty();
durableTransitionTo(
new FollowerState(
time,
epoch,
leaderId,
endpoints,
votedKey,
partitionState.lastVoterSet().voterIds(),
state.highWatermark(),
fetchTimeoutMs,
logContext
)
);
}
/**
* Transition to the "prospective" state. This means the replica experienced a fetch/election timeout or
* loss of election as candidate. Note, if the replica is transitioning from prospective to add voted state
* and there is no epoch change, it takes the route of prospectiveAddVotedState instead.
*/
public void transitionToProspective() {
if (isObserver()) {
throw new IllegalStateException(
String.format(
"Cannot transition to Prospective since the local id (%s) and directory id (%s) " +
"is not one of the voters %s",
localId,
localDirectoryId,
partitionState.lastVoterSet()
)
);
} else if (isLeader() || isProspective()) {
throw new IllegalStateException("Cannot transition to Prospective since the local broker.id=" + localId +
" is state " + state);
}
// Durable transition is not necessary since there is no change to the persisted electionState
memoryTransitionTo(
new ProspectiveState(
time,
localIdOrThrow(),
epoch(),
leaderId(),
state.leaderEndpoints(),
votedKey(),
partitionState.lastVoterSet(),
state.highWatermark(),
randomElectionTimeoutMs(),
logContext
)
);
}
public void transitionToCandidate() {
checkValidTransitionToCandidate();
int newEpoch = epoch() + 1;
int electionTimeoutMs = randomElectionTimeoutMs();
durableTransitionTo(new CandidateState(
time,
localIdOrThrow(),
localDirectoryId,
newEpoch,
partitionState.lastVoterSet(),
state.highWatermark(),
electionTimeoutMs,
logContext
));
}
private void checkValidTransitionToCandidate() {
if (isObserver()) {
throw new IllegalStateException(
String.format(
"Cannot transition to Candidate since the local id (%s) and directory id (%s) " +
"is not one of the voters %s",
localId,
localDirectoryId,
partitionState.lastVoterSet()
)
);
}
// Only Prospective is allowed to transition to Candidate
if (!isProspective()) {
throw new IllegalStateException(
String.format(
"Cannot transition to Candidate since the local broker.id=%s is state %s",
localId,
state
)
);
}
}
public <T> LeaderState<T> transitionToLeader(long epochStartOffset, BatchAccumulator<T> accumulator) {
if (isObserver()) {
throw new IllegalStateException(
String.format(
"Cannot transition to Leader since the local id (%s) and directory id (%s) " +
"is not one of the voters %s",
localId,
localDirectoryId,
partitionState.lastVoterSet()
)
);
} else if (!isCandidate()) {
throw new IllegalStateException("Cannot transition to Leader from current state " + state);
}
CandidateState candidateState = candidateStateOrThrow();
if (!candidateState.epochElection().isVoteGranted())
throw new IllegalStateException("Cannot become leader without majority votes granted");
// Note that the leader does not retain the high watermark that was known
// in the previous state. The reason for this is to protect the monotonicity
// of the global high watermark, which is exposed through the leader. The
// only way a new leader can be sure that the high watermark is increasing
// monotonically is to wait until a majority of the voters have reached the
// starting offset of the new epoch. The downside of this is that the local
// state machine is temporarily stalled by the advancement of the global
// high watermark even though it only depends on local monotonicity. We
// could address this problem by decoupling the local high watermark, but
// we typically expect the state machine to be caught up anyway.
LeaderState<T> state = new LeaderState<>(
time,
localVoterNodeOrThrow(),
epoch(),
epochStartOffset,
partitionState.lastVoterSet(),
partitionState.lastVoterSetOffset(),
partitionState.lastKraftVersion(),
candidateState.epochElection().grantingVoters(),
accumulator,
fetchTimeoutMs,
logContext,
kafkaRaftMetrics
);
durableTransitionTo(state);
return state;
}
private void durableTransitionTo(EpochState newState) {
log.info("Attempting durable transition to {} from {}", newState, state);
store.writeElectionState(newState.election(), partitionState.lastKraftVersion());
memoryTransitionTo(newState);
}
private void memoryTransitionTo(EpochState newState) {
if (state != null) {
state.close();
}
EpochState from = state;
state = newState;
log.info("Completed transition to {} from {}", newState, from);
}
private int randomElectionTimeoutMs() {
if (electionTimeoutMs == 0)
return 0;
return electionTimeoutMs + random.nextInt(electionTimeoutMs);
}
public boolean canGrantVote(ReplicaKey replicaKey, boolean isLogUpToDate, boolean isPreVote) {
return state.canGrantVote(replicaKey, isLogUpToDate, isPreVote);
}
public FollowerState followerStateOrThrow() {
if (isFollower())
return (FollowerState) state;
throw new IllegalStateException("Expected to be Follower, but the current state is " + state);
}
public Optional<UnattachedState> maybeUnattachedState() {
EpochState fixedState = state;
if (fixedState instanceof UnattachedState) {
return Optional.of((UnattachedState) fixedState);
} else {
return Optional.empty();
}
}
public UnattachedState unattachedStateOrThrow() {
return maybeUnattachedState().orElseThrow(
() -> new IllegalStateException("Expected to be Unattached, but current state is " + state)
);
}
public <T> LeaderState<T> leaderStateOrThrow() {
return this.<T>maybeLeaderState()
.orElseThrow(() -> new IllegalStateException("Expected to be Leader, but current state is " + state));
}
@SuppressWarnings("unchecked")
public <T> Optional<LeaderState<T>> maybeLeaderState() {
EpochState fixedState = state;
if (fixedState instanceof LeaderState) {
return Optional.of((LeaderState<T>) fixedState);
} else {
return Optional.empty();
}
}
public ResignedState resignedStateOrThrow() {
if (isResigned())
return (ResignedState) state;
throw new IllegalStateException("Expected to be Resigned, but current state is " + state);
}
public Optional<ProspectiveState> maybeProspectiveState() {
EpochState fixedState = state;
if (fixedState instanceof ProspectiveState) {
return Optional.of((ProspectiveState) fixedState);
} else {
return Optional.empty();
}
}
public ProspectiveState prospectiveStateOrThrow() {
return maybeProspectiveState().orElseThrow(
() -> new IllegalStateException("Expected to be Prospective, but current state is " + state)
);
}
public boolean isProspectiveNotVoted() {
return maybeProspectiveState().filter(prospective -> prospective.votedKey().isEmpty()).isPresent();
}
public boolean isProspectiveAndVoted() {
return maybeProspectiveState().flatMap(ProspectiveState::votedKey).isPresent();
}
public CandidateState candidateStateOrThrow() {
if (isCandidate())
return (CandidateState) state;
throw new IllegalStateException("Expected to be Candidate, but current state is " + state);
}
public NomineeState nomineeStateOrThrow() {
if (isNomineeState())
return (NomineeState) state;
throw new IllegalStateException("Expected to be a NomineeState (Prospective or Candidate), " +
"but current state is " + state);
}
public LeaderAndEpoch leaderAndEpoch() {
ElectionState election = state.election();
return new LeaderAndEpoch(election.optionalLeaderId(), election.epoch());
}
public boolean isFollower() {
return state instanceof FollowerState;
}
public boolean isUnattached() {
return state instanceof UnattachedState;
}
public boolean isUnattachedNotVoted() {
return maybeUnattachedState().filter(unattached -> unattached.votedKey().isEmpty()).isPresent();
}
public boolean isUnattachedAndVoted() {
return maybeUnattachedState().flatMap(UnattachedState::votedKey).isPresent();
}
public boolean isLeader() {
return state instanceof LeaderState;
}
public boolean isResigned() {
return state instanceof ResignedState;
}
public boolean isProspective() {
return state instanceof ProspectiveState;
}
public boolean isCandidate() {
return state instanceof CandidateState;
}
public boolean isNomineeState() {
return state instanceof NomineeState;
}
/**
* Determines if replica in unattached or prospective state can grant a vote request.
*
* @param leaderId local replica's optional leader id.
* @param votedKey local replica's optional voted key.
* @param epoch local replica's epoch
* @param replicaKey replicaKey of nominee which sent the vote request
* @param isLogUpToDate whether the log of the nominee is up-to-date with the local replica's log
* @param isPreVote whether the vote request is a PreVote request
* @param log logger
* @return true if the local replica can grant the vote request, false otherwise
*/
public static boolean unattachedOrProspectiveCanGrantVote(
OptionalInt leaderId,
Optional<ReplicaKey> votedKey,
int epoch,
ReplicaKey replicaKey,
boolean isLogUpToDate,
boolean isPreVote,
Logger log
) {
if (isPreVote) {
if (!isLogUpToDate) {
log.debug(
"Rejecting Vote request (preVote=true) from prospective ({}) since prospective's log is not up to date with us",
replicaKey
);
}
return isLogUpToDate;
} else if (votedKey.isPresent()) {
ReplicaKey votedReplicaKey = votedKey.get();
if (votedReplicaKey.id() == replicaKey.id()) {
return votedReplicaKey.directoryId().isEmpty() || votedReplicaKey.directoryId().equals(replicaKey.directoryId());
}
log.debug(
"Rejecting Vote request (preVote=false) from candidate ({}), already have voted for another " +
"candidate ({}) in epoch {}",
replicaKey,
votedKey,
epoch
);
return false;
} else if (leaderId.isPresent()) {
// If the leader id is known it should behave similar to the follower state
log.debug(
"Rejecting Vote request (preVote=false) from candidate ({}) since we already have a leader {} in epoch {}",
replicaKey,
leaderId.getAsInt(),
epoch
);
return false;
} else if (!isLogUpToDate) {
log.debug(
"Rejecting Vote request (preVote=false) from candidate ({}) since candidate's log is not up to date with us",
replicaKey
);
}
return isLogUpToDate;
}
}
|
googleapis/google-cloud-java | 35,429 | java-visionai/proto-google-cloud-visionai-v1/src/main/java/com/google/cloud/visionai/v1/AppPlatformEventBody.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/annotations.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.visionai.v1;
/**
*
*
* <pre>
* Message of content of appPlatform event
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.AppPlatformEventBody}
*/
public final class AppPlatformEventBody extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.visionai.v1.AppPlatformEventBody)
AppPlatformEventBodyOrBuilder {
private static final long serialVersionUID = 0L;
// Use AppPlatformEventBody.newBuilder() to construct.
private AppPlatformEventBody(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private AppPlatformEventBody() {
eventMessage_ = "";
eventId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new AppPlatformEventBody();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.AnnotationsProto
.internal_static_google_cloud_visionai_v1_AppPlatformEventBody_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.AnnotationsProto
.internal_static_google_cloud_visionai_v1_AppPlatformEventBody_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.AppPlatformEventBody.class,
com.google.cloud.visionai.v1.AppPlatformEventBody.Builder.class);
}
private int bitField0_;
public static final int EVENT_MESSAGE_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object eventMessage_ = "";
/**
*
*
* <pre>
* Human readable string of the event like "There are more than 6 people in
* the scene". or "Shelf is empty!".
* </pre>
*
* <code>string event_message = 1;</code>
*
* @return The eventMessage.
*/
@java.lang.Override
public java.lang.String getEventMessage() {
java.lang.Object ref = eventMessage_;
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();
eventMessage_ = s;
return s;
}
}
/**
*
*
* <pre>
* Human readable string of the event like "There are more than 6 people in
* the scene". or "Shelf is empty!".
* </pre>
*
* <code>string event_message = 1;</code>
*
* @return The bytes for eventMessage.
*/
@java.lang.Override
public com.google.protobuf.ByteString getEventMessageBytes() {
java.lang.Object ref = eventMessage_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
eventMessage_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int PAYLOAD_FIELD_NUMBER = 2;
private com.google.protobuf.Struct payload_;
/**
*
*
* <pre>
* For the case of Pub/Sub, it will be stored in the message attributes.
* pubsub.proto
* </pre>
*
* <code>.google.protobuf.Struct payload = 2;</code>
*
* @return Whether the payload field is set.
*/
@java.lang.Override
public boolean hasPayload() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* For the case of Pub/Sub, it will be stored in the message attributes.
* pubsub.proto
* </pre>
*
* <code>.google.protobuf.Struct payload = 2;</code>
*
* @return The payload.
*/
@java.lang.Override
public com.google.protobuf.Struct getPayload() {
return payload_ == null ? com.google.protobuf.Struct.getDefaultInstance() : payload_;
}
/**
*
*
* <pre>
* For the case of Pub/Sub, it will be stored in the message attributes.
* pubsub.proto
* </pre>
*
* <code>.google.protobuf.Struct payload = 2;</code>
*/
@java.lang.Override
public com.google.protobuf.StructOrBuilder getPayloadOrBuilder() {
return payload_ == null ? com.google.protobuf.Struct.getDefaultInstance() : payload_;
}
public static final int EVENT_ID_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object eventId_ = "";
/**
*
*
* <pre>
* User defined Event Id, used to classify event, within a delivery interval,
* events from the same application instance with the same id will be
* de-duplicated & only first one will be sent out. Empty event_id will be
* treated as "".
* </pre>
*
* <code>string event_id = 3;</code>
*
* @return The eventId.
*/
@java.lang.Override
public java.lang.String getEventId() {
java.lang.Object ref = eventId_;
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();
eventId_ = s;
return s;
}
}
/**
*
*
* <pre>
* User defined Event Id, used to classify event, within a delivery interval,
* events from the same application instance with the same id will be
* de-duplicated & only first one will be sent out. Empty event_id will be
* treated as "".
* </pre>
*
* <code>string event_id = 3;</code>
*
* @return The bytes for eventId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getEventIdBytes() {
java.lang.Object ref = eventId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
eventId_ = 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(eventMessage_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, eventMessage_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getPayload());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(eventId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, eventId_);
}
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(eventMessage_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, eventMessage_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getPayload());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(eventId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, eventId_);
}
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.AppPlatformEventBody)) {
return super.equals(obj);
}
com.google.cloud.visionai.v1.AppPlatformEventBody other =
(com.google.cloud.visionai.v1.AppPlatformEventBody) obj;
if (!getEventMessage().equals(other.getEventMessage())) return false;
if (hasPayload() != other.hasPayload()) return false;
if (hasPayload()) {
if (!getPayload().equals(other.getPayload())) return false;
}
if (!getEventId().equals(other.getEventId())) 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) + EVENT_MESSAGE_FIELD_NUMBER;
hash = (53 * hash) + getEventMessage().hashCode();
if (hasPayload()) {
hash = (37 * hash) + PAYLOAD_FIELD_NUMBER;
hash = (53 * hash) + getPayload().hashCode();
}
hash = (37 * hash) + EVENT_ID_FIELD_NUMBER;
hash = (53 * hash) + getEventId().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.visionai.v1.AppPlatformEventBody parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.AppPlatformEventBody 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.AppPlatformEventBody parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.AppPlatformEventBody 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.AppPlatformEventBody parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.visionai.v1.AppPlatformEventBody 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.AppPlatformEventBody parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.AppPlatformEventBody 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.AppPlatformEventBody parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.visionai.v1.AppPlatformEventBody 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.AppPlatformEventBody 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.AppPlatformEventBody 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.AppPlatformEventBody 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 of content of appPlatform event
* </pre>
*
* Protobuf type {@code google.cloud.visionai.v1.AppPlatformEventBody}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.visionai.v1.AppPlatformEventBody)
com.google.cloud.visionai.v1.AppPlatformEventBodyOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.visionai.v1.AnnotationsProto
.internal_static_google_cloud_visionai_v1_AppPlatformEventBody_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.visionai.v1.AnnotationsProto
.internal_static_google_cloud_visionai_v1_AppPlatformEventBody_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.visionai.v1.AppPlatformEventBody.class,
com.google.cloud.visionai.v1.AppPlatformEventBody.Builder.class);
}
// Construct using com.google.cloud.visionai.v1.AppPlatformEventBody.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getPayloadFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
eventMessage_ = "";
payload_ = null;
if (payloadBuilder_ != null) {
payloadBuilder_.dispose();
payloadBuilder_ = null;
}
eventId_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.visionai.v1.AnnotationsProto
.internal_static_google_cloud_visionai_v1_AppPlatformEventBody_descriptor;
}
@java.lang.Override
public com.google.cloud.visionai.v1.AppPlatformEventBody getDefaultInstanceForType() {
return com.google.cloud.visionai.v1.AppPlatformEventBody.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.visionai.v1.AppPlatformEventBody build() {
com.google.cloud.visionai.v1.AppPlatformEventBody result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.visionai.v1.AppPlatformEventBody buildPartial() {
com.google.cloud.visionai.v1.AppPlatformEventBody result =
new com.google.cloud.visionai.v1.AppPlatformEventBody(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.visionai.v1.AppPlatformEventBody result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.eventMessage_ = eventMessage_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.payload_ = payloadBuilder_ == null ? payload_ : payloadBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.eventId_ = eventId_;
}
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.AppPlatformEventBody) {
return mergeFrom((com.google.cloud.visionai.v1.AppPlatformEventBody) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.visionai.v1.AppPlatformEventBody other) {
if (other == com.google.cloud.visionai.v1.AppPlatformEventBody.getDefaultInstance())
return this;
if (!other.getEventMessage().isEmpty()) {
eventMessage_ = other.eventMessage_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasPayload()) {
mergePayload(other.getPayload());
}
if (!other.getEventId().isEmpty()) {
eventId_ = other.eventId_;
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:
{
eventMessage_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getPayloadFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
eventId_ = 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 eventMessage_ = "";
/**
*
*
* <pre>
* Human readable string of the event like "There are more than 6 people in
* the scene". or "Shelf is empty!".
* </pre>
*
* <code>string event_message = 1;</code>
*
* @return The eventMessage.
*/
public java.lang.String getEventMessage() {
java.lang.Object ref = eventMessage_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
eventMessage_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Human readable string of the event like "There are more than 6 people in
* the scene". or "Shelf is empty!".
* </pre>
*
* <code>string event_message = 1;</code>
*
* @return The bytes for eventMessage.
*/
public com.google.protobuf.ByteString getEventMessageBytes() {
java.lang.Object ref = eventMessage_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
eventMessage_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Human readable string of the event like "There are more than 6 people in
* the scene". or "Shelf is empty!".
* </pre>
*
* <code>string event_message = 1;</code>
*
* @param value The eventMessage to set.
* @return This builder for chaining.
*/
public Builder setEventMessage(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
eventMessage_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Human readable string of the event like "There are more than 6 people in
* the scene". or "Shelf is empty!".
* </pre>
*
* <code>string event_message = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearEventMessage() {
eventMessage_ = getDefaultInstance().getEventMessage();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Human readable string of the event like "There are more than 6 people in
* the scene". or "Shelf is empty!".
* </pre>
*
* <code>string event_message = 1;</code>
*
* @param value The bytes for eventMessage to set.
* @return This builder for chaining.
*/
public Builder setEventMessageBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
eventMessage_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.protobuf.Struct payload_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Struct,
com.google.protobuf.Struct.Builder,
com.google.protobuf.StructOrBuilder>
payloadBuilder_;
/**
*
*
* <pre>
* For the case of Pub/Sub, it will be stored in the message attributes.
* pubsub.proto
* </pre>
*
* <code>.google.protobuf.Struct payload = 2;</code>
*
* @return Whether the payload field is set.
*/
public boolean hasPayload() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* For the case of Pub/Sub, it will be stored in the message attributes.
* pubsub.proto
* </pre>
*
* <code>.google.protobuf.Struct payload = 2;</code>
*
* @return The payload.
*/
public com.google.protobuf.Struct getPayload() {
if (payloadBuilder_ == null) {
return payload_ == null ? com.google.protobuf.Struct.getDefaultInstance() : payload_;
} else {
return payloadBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* For the case of Pub/Sub, it will be stored in the message attributes.
* pubsub.proto
* </pre>
*
* <code>.google.protobuf.Struct payload = 2;</code>
*/
public Builder setPayload(com.google.protobuf.Struct value) {
if (payloadBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
payload_ = value;
} else {
payloadBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* For the case of Pub/Sub, it will be stored in the message attributes.
* pubsub.proto
* </pre>
*
* <code>.google.protobuf.Struct payload = 2;</code>
*/
public Builder setPayload(com.google.protobuf.Struct.Builder builderForValue) {
if (payloadBuilder_ == null) {
payload_ = builderForValue.build();
} else {
payloadBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* For the case of Pub/Sub, it will be stored in the message attributes.
* pubsub.proto
* </pre>
*
* <code>.google.protobuf.Struct payload = 2;</code>
*/
public Builder mergePayload(com.google.protobuf.Struct value) {
if (payloadBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& payload_ != null
&& payload_ != com.google.protobuf.Struct.getDefaultInstance()) {
getPayloadBuilder().mergeFrom(value);
} else {
payload_ = value;
}
} else {
payloadBuilder_.mergeFrom(value);
}
if (payload_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* For the case of Pub/Sub, it will be stored in the message attributes.
* pubsub.proto
* </pre>
*
* <code>.google.protobuf.Struct payload = 2;</code>
*/
public Builder clearPayload() {
bitField0_ = (bitField0_ & ~0x00000002);
payload_ = null;
if (payloadBuilder_ != null) {
payloadBuilder_.dispose();
payloadBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* For the case of Pub/Sub, it will be stored in the message attributes.
* pubsub.proto
* </pre>
*
* <code>.google.protobuf.Struct payload = 2;</code>
*/
public com.google.protobuf.Struct.Builder getPayloadBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getPayloadFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* For the case of Pub/Sub, it will be stored in the message attributes.
* pubsub.proto
* </pre>
*
* <code>.google.protobuf.Struct payload = 2;</code>
*/
public com.google.protobuf.StructOrBuilder getPayloadOrBuilder() {
if (payloadBuilder_ != null) {
return payloadBuilder_.getMessageOrBuilder();
} else {
return payload_ == null ? com.google.protobuf.Struct.getDefaultInstance() : payload_;
}
}
/**
*
*
* <pre>
* For the case of Pub/Sub, it will be stored in the message attributes.
* pubsub.proto
* </pre>
*
* <code>.google.protobuf.Struct payload = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Struct,
com.google.protobuf.Struct.Builder,
com.google.protobuf.StructOrBuilder>
getPayloadFieldBuilder() {
if (payloadBuilder_ == null) {
payloadBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Struct,
com.google.protobuf.Struct.Builder,
com.google.protobuf.StructOrBuilder>(
getPayload(), getParentForChildren(), isClean());
payload_ = null;
}
return payloadBuilder_;
}
private java.lang.Object eventId_ = "";
/**
*
*
* <pre>
* User defined Event Id, used to classify event, within a delivery interval,
* events from the same application instance with the same id will be
* de-duplicated & only first one will be sent out. Empty event_id will be
* treated as "".
* </pre>
*
* <code>string event_id = 3;</code>
*
* @return The eventId.
*/
public java.lang.String getEventId() {
java.lang.Object ref = eventId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
eventId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* User defined Event Id, used to classify event, within a delivery interval,
* events from the same application instance with the same id will be
* de-duplicated & only first one will be sent out. Empty event_id will be
* treated as "".
* </pre>
*
* <code>string event_id = 3;</code>
*
* @return The bytes for eventId.
*/
public com.google.protobuf.ByteString getEventIdBytes() {
java.lang.Object ref = eventId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
eventId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* User defined Event Id, used to classify event, within a delivery interval,
* events from the same application instance with the same id will be
* de-duplicated & only first one will be sent out. Empty event_id will be
* treated as "".
* </pre>
*
* <code>string event_id = 3;</code>
*
* @param value The eventId to set.
* @return This builder for chaining.
*/
public Builder setEventId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
eventId_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* User defined Event Id, used to classify event, within a delivery interval,
* events from the same application instance with the same id will be
* de-duplicated & only first one will be sent out. Empty event_id will be
* treated as "".
* </pre>
*
* <code>string event_id = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearEventId() {
eventId_ = getDefaultInstance().getEventId();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* User defined Event Id, used to classify event, within a delivery interval,
* events from the same application instance with the same id will be
* de-duplicated & only first one will be sent out. Empty event_id will be
* treated as "".
* </pre>
*
* <code>string event_id = 3;</code>
*
* @param value The bytes for eventId to set.
* @return This builder for chaining.
*/
public Builder setEventIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
eventId_ = 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.visionai.v1.AppPlatformEventBody)
}
// @@protoc_insertion_point(class_scope:google.cloud.visionai.v1.AppPlatformEventBody)
private static final com.google.cloud.visionai.v1.AppPlatformEventBody DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.visionai.v1.AppPlatformEventBody();
}
public static com.google.cloud.visionai.v1.AppPlatformEventBody getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<AppPlatformEventBody> PARSER =
new com.google.protobuf.AbstractParser<AppPlatformEventBody>() {
@java.lang.Override
public AppPlatformEventBody 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<AppPlatformEventBody> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<AppPlatformEventBody> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.visionai.v1.AppPlatformEventBody getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/inlong | 35,868 | inlong-sort/sort-flink/sort-flink-v1.13/sort-connectors/hive/src/main/java/org/apache/inlong/sort/hive/filesystem/HadoopPathBasedPartFileWriter.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.inlong.sort.hive.filesystem;
import org.apache.inlong.sort.base.dirty.DirtyOptions;
import org.apache.inlong.sort.base.dirty.DirtySinkHelper;
import org.apache.inlong.sort.base.dirty.DirtyType;
import org.apache.inlong.sort.base.dirty.sink.DirtySink;
import org.apache.inlong.sort.base.format.DynamicSchemaFormatFactory;
import org.apache.inlong.sort.base.format.JsonDynamicSchemaFormat;
import org.apache.inlong.sort.base.metric.sub.SinkTableMetricData;
import org.apache.inlong.sort.base.sink.PartitionPolicy;
import org.apache.inlong.sort.base.sink.SchemaUpdateExceptionPolicy;
import org.apache.inlong.sort.hive.HiveBulkWriterFactory;
import org.apache.inlong.sort.hive.HiveWriterFactory;
import org.apache.inlong.sort.hive.util.CacheHolder;
import org.apache.inlong.sort.hive.util.HiveTableUtil;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.commons.lang3.tuple.Triple;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.connectors.hive.FlinkHiveException;
import org.apache.flink.core.io.SimpleVersionedSerializer;
import org.apache.flink.formats.hadoop.bulk.HadoopFileCommitter;
import org.apache.flink.formats.hadoop.bulk.HadoopFileCommitterFactory;
import org.apache.flink.formats.hadoop.bulk.HadoopPathBasedBulkWriter;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
import org.apache.flink.streaming.api.functions.sink.filesystem.AbstractPartFileWriter;
import org.apache.flink.streaming.api.functions.sink.filesystem.BucketWriter;
import org.apache.flink.streaming.api.functions.sink.filesystem.InProgressFileWriter;
import org.apache.flink.streaming.api.functions.sink.filesystem.WriterProperties;
import org.apache.flink.table.catalog.ObjectIdentifier;
import org.apache.flink.table.catalog.hive.client.HiveShim;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.binary.BinaryRowData;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.util.ExceptionUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.exec.FileSinkOperator;
import org.apache.hadoop.hive.ql.exec.FileSinkOperator.RecordWriter;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapred.JobConf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static org.apache.inlong.sort.base.Constants.SINK_MULTIPLE_DATABASE_PATTERN;
import static org.apache.inlong.sort.base.Constants.SINK_MULTIPLE_ENABLE;
import static org.apache.inlong.sort.base.Constants.SINK_MULTIPLE_FORMAT;
import static org.apache.inlong.sort.base.Constants.SINK_MULTIPLE_TABLE_PATTERN;
import static org.apache.inlong.sort.hive.HiveOptions.HIVE_SCHEMA_SCAN_INTERVAL;
/**
* The part-file writer that writes to the specified hadoop path.
*/
public class HadoopPathBasedPartFileWriter<IN, BucketID> extends AbstractPartFileWriter<IN, BucketID> {
private static final Logger LOG = LoggerFactory.getLogger(HadoopPathBasedPartFileWriter.class);
private final InLongHadoopPathBasedBulkWriter writer;
private final HadoopFileCommitter fileCommitter;
private BucketID bucketID;
private Path targetPath;
private Path inProgressPath;
private final HiveShim hiveShim;
private final String hiveVersion;
private final boolean sinkMultipleEnable;
private final String sinkMultipleFormat;
private final String databasePattern;
private final String tablePattern;
private final SchemaUpdateExceptionPolicy schemaUpdatePolicy;
private final PartitionPolicy partitionPolicy;
private final String inputFormat;
private final String outputFormat;
private final String serializationLib;
private transient JsonDynamicSchemaFormat jsonFormat;
@Nullable
private final transient SinkTableMetricData metricData;
private final DirtyOptions dirtyOptions;
private final @Nullable DirtySink<Object> dirtySink;
public HadoopPathBasedPartFileWriter(final BucketID bucketID,
Path targetPath,
Path inProgressPath,
InLongHadoopPathBasedBulkWriter writer,
HadoopFileCommitter fileCommitter,
long createTime,
HiveShim hiveShim,
String hiveVersion,
boolean sinkMultipleEnable,
String sinkMultipleFormat,
String databasePattern,
String tablePattern,
@Nullable SinkTableMetricData metricData,
DirtyOptions dirtyOptions,
@Nullable DirtySink<Object> dirtySink,
SchemaUpdateExceptionPolicy schemaUpdatePolicy,
PartitionPolicy partitionPolicy,
String inputFormat,
String outputFormat,
String serializationLib) {
super(bucketID, createTime);
this.bucketID = bucketID;
this.targetPath = targetPath;
this.inProgressPath = inProgressPath;
this.writer = writer;
this.fileCommitter = fileCommitter;
this.hiveShim = hiveShim;
this.hiveVersion = hiveVersion;
this.sinkMultipleEnable = sinkMultipleEnable;
this.sinkMultipleFormat = sinkMultipleFormat;
this.databasePattern = databasePattern;
this.tablePattern = tablePattern;
this.metricData = metricData;
this.schemaUpdatePolicy = schemaUpdatePolicy;
this.dirtyOptions = dirtyOptions;
this.dirtySink = dirtySink;
this.partitionPolicy = partitionPolicy;
this.inputFormat = inputFormat;
this.outputFormat = outputFormat;
this.serializationLib = serializationLib;
}
@Override
public void write(IN element, long currentTime) {
String databaseName = null;
String tableName = null;
int recordNum = 1;
int recordSize = 0;
JsonNode rootNode = null;
ObjectIdentifier identifier = null;
HashMap<ObjectIdentifier, Long> ignoreWritingTableMap = CacheHolder.getIgnoreWritingTableMap();
try {
if (sinkMultipleEnable) {
GenericRowData rowData = (GenericRowData) element;
if (jsonFormat == null) {
jsonFormat = (JsonDynamicSchemaFormat) DynamicSchemaFormatFactory.getFormat(sinkMultipleFormat);
}
byte[] rawData = (byte[]) rowData.getField(0);
rootNode = jsonFormat.deserialize(rawData);
LOG.debug("root node: {}", rootNode);
boolean isDDL = jsonFormat.extractDDLFlag(rootNode);
if (isDDL) {
// Ignore ddl change for now
return;
}
databaseName = jsonFormat.parse(rootNode, databasePattern);
tableName = jsonFormat.parse(rootNode, tablePattern);
List<Map<String, Object>> physicalDataList = HiveTableUtil.jsonNode2Map(
jsonFormat.getPhysicalData(rootNode));
recordNum = physicalDataList.size();
identifier = HiveTableUtil.createObjectIdentifier(databaseName, tableName);
// ignore writing data into this table
if (ignoreWritingTableMap.containsKey(identifier)) {
return;
}
List<String> pkListStr = jsonFormat.extractPrimaryKeyNames(rootNode);
RowType schema = jsonFormat.extractSchema(rootNode, pkListStr);
HiveWriterFactory writerFactory = getHiveWriterFactory(identifier, schema, hiveVersion);
// parse the real location of hive table
Path inProgressFilePath = getInProgressPath(writerFactory);
LOG.debug("in progress file path: {}", inProgressFilePath);
Pair<RecordWriter, Function<RowData, Writable>> pair = getRecordWriterAndRowConverter(writerFactory,
inProgressFilePath);
// reset record writer and row converter
writer.setRecordWriter(pair.getLeft());
writer.setRowConverter(pair.getRight());
writer.setInProgressPath(inProgressFilePath);
boolean replaceLineBreak = writerFactory.getStorageDescriptor().getInputFormat()
.contains("TextInputFormat");
for (Map<String, Object> record : physicalDataList) {
// check and alter hive table if schema has changed
boolean changed = checkSchema(identifier, writerFactory, schema);
if (changed) {
// remove cache and reload hive writer factory
CacheHolder.getFactoryMap().remove(identifier);
writerFactory = HiveTableUtil.getWriterFactory(hiveShim, hiveVersion, identifier);
assert writerFactory != null;
FileSinkOperator.RecordWriter recordWriter = writerFactory.createRecordWriter(
inProgressFilePath);
Function<RowData, Writable> rowConverter = writerFactory.createRowDataConverter();
writer.setRecordWriter(recordWriter);
writer.setRowConverter(rowConverter);
CacheHolder.getRecordWriterHashMap().put(inProgressFilePath, recordWriter);
CacheHolder.getRowConverterHashMap().put(inProgressFilePath, rowConverter);
}
LOG.debug("record: {}", record);
LOG.debug("columns : {}", Arrays.deepToString(writerFactory.getAllColumns()));
LOG.debug("types: {}", Arrays.deepToString(writerFactory.getAllTypes()));
Pair<GenericRowData, Integer> rowDataPair = HiveTableUtil.getRowData(record,
writerFactory.getAllColumns(), writerFactory.getAllTypes(), replaceLineBreak);
GenericRowData genericRowData = rowDataPair.getLeft();
recordSize += rowDataPair.getRight();
LOG.debug("generic row data: {}", genericRowData);
writer.addElement(genericRowData);
}
if (metricData != null) {
metricData.outputMetrics(databaseName, tableName, recordNum, recordSize);
}
} else {
RowData data = (RowData) element;
writer.addElement(data);
if (metricData != null) {
if (data instanceof BinaryRowData) {
// mysql cdc sends BinaryRowData
metricData.invoke(1, ((BinaryRowData) data).getSizeInBytes());
} else {
// oracle cdc sends GenericRowData
metricData.invoke(1, data.toString().getBytes(StandardCharsets.UTF_8).length);
}
}
}
} catch (Exception e) {
if (schemaUpdatePolicy == null || SchemaUpdateExceptionPolicy.THROW_WITH_STOP == schemaUpdatePolicy) {
throw new FlinkHiveException("Failed to write data", e);
} else if (SchemaUpdateExceptionPolicy.STOP_PARTIAL == schemaUpdatePolicy) {
if (identifier != null) {
ignoreWritingTableMap.put(identifier, 1L);
}
} else if (SchemaUpdateExceptionPolicy.LOG_WITH_IGNORE == schemaUpdatePolicy) {
handleDirtyData(databaseName, tableName, recordNum, recordSize, rootNode, jsonFormat, e);
}
LOG.error("Failed to write data", e);
}
markWrite(currentTime);
}
/**
* upload dirty data metrics and write dirty data
*
* @param databaseName database name
* @param tableName table name
* @param recordNum record num
* @param recordSize record byte size
* @param data raw data
* @param jsonFormat json formatter for formatting raw data
* @param e exception
*/
private void handleDirtyData(String databaseName,
String tableName,
int recordNum,
int recordSize,
JsonNode data,
JsonDynamicSchemaFormat jsonFormat,
Exception e) {
// upload metrics for dirty data
if (null != metricData) {
if (sinkMultipleEnable) {
metricData.outputDirtyMetrics(databaseName, tableName, recordNum, recordSize);
} else {
metricData.invokeDirty(recordNum, recordSize);
}
}
if (!dirtyOptions.ignoreDirty()) {
return;
}
if (data == null || jsonFormat == null) {
return;
}
Triple<String, String, String> triple = getDirtyLabelTagAndIdentity(data, jsonFormat);
String label = triple.getLeft();
String tag = triple.getMiddle();
String identify = triple.getRight();
if (label == null || tag == null || identify == null) {
LOG.warn("dirty label or tag or identify is null, ignore dirty data writing");
return;
}
// archive dirty data
DirtySinkHelper<Object> dirtySinkHelper = new DirtySinkHelper<>(dirtyOptions, dirtySink);
List<Map<String, Object>> physicalDataList = HiveTableUtil.jsonNode2Map(jsonFormat.getPhysicalData(data));
for (Map<String, Object> record : physicalDataList) {
JsonNode jsonNode = HiveTableUtil.object2JsonNode(record);
dirtySinkHelper.invoke(jsonNode, DirtyType.BATCH_LOAD_ERROR, label, tag, identify, e);
}
}
/**
* parse dirty label , tag and identify
*
* @param data raw data
* @param jsonFormat json formatter
* @return dirty label, tag and identify
*/
private Triple<String, String, String> getDirtyLabelTagAndIdentity(JsonNode data,
JsonDynamicSchemaFormat jsonFormat) {
String dirtyLabel = null;
String dirtyLogTag = null;
String dirtyIdentify = null;
try {
if (dirtyOptions.ignoreDirty()) {
if (dirtyOptions.getLabels() != null) {
dirtyLabel = jsonFormat.parse(data,
DirtySinkHelper.regexReplace(dirtyOptions.getLabels(), DirtyType.BATCH_LOAD_ERROR, null));
}
if (dirtyOptions.getLogTag() != null) {
dirtyLogTag = jsonFormat.parse(data,
DirtySinkHelper.regexReplace(dirtyOptions.getLogTag(), DirtyType.BATCH_LOAD_ERROR, null));
}
if (dirtyOptions.getIdentifier() != null) {
dirtyIdentify = jsonFormat.parse(data,
DirtySinkHelper.regexReplace(dirtyOptions.getIdentifier(), DirtyType.BATCH_LOAD_ERROR,
null));
}
}
} catch (Exception e) {
LOG.warn("Parse dirty options failed. {}", ExceptionUtils.stringifyException(e));
}
return new ImmutableTriple<>(dirtyLabel, dirtyLogTag, dirtyIdentify);
}
/**
* get hive writer factory, create table if not exists automatically
*
* @param identifier hive database and table name
* @param schema hive field with flink type
* @return hive writer factory
*/
private HiveWriterFactory getHiveWriterFactory(ObjectIdentifier identifier, RowType schema, String hiveVersion) {
HiveWriterFactory writerFactory = HiveTableUtil.getWriterFactory(hiveShim, hiveVersion, identifier);
if (writerFactory == null) {
// hive table may not exist, auto create
HiveTableUtil.createTable(identifier.getDatabaseName(), identifier.getObjectName(), schema, partitionPolicy,
hiveVersion, inputFormat, outputFormat, serializationLib);
writerFactory = HiveTableUtil.getWriterFactory(hiveShim, hiveVersion, identifier);
}
return writerFactory;
}
/**
* get target hdfs path and temp hdfs path for data writing
*
* @param writerFactory hive writer factory
* @return pair of target path and temp path
*/
private Path getInProgressPath(HiveWriterFactory writerFactory) throws IOException, ClassNotFoundException {
String location = writerFactory.getStorageDescriptor().getLocation();
String path = targetPath.toUri().getPath();
path = path.substring(path.indexOf("/tmp/") + 5);
Path targetPath = new Path(location + "/" + path);
return new Path(targetPath.getParent() + "/" + inProgressPath.getName());
}
/**
* get hive record writer and row converter
*
* @param writerFactory hive writer factory
* @param inProgressFilePath temp hdfs file path for writing data
* @return pair of hive record writer and row converter objects
*/
private Pair<RecordWriter, Function<RowData, Writable>> getRecordWriterAndRowConverter(
HiveWriterFactory writerFactory, Path inProgressFilePath) {
FileSinkOperator.RecordWriter recordWriter;
Function<RowData, Writable> rowConverter;
if (!CacheHolder.getRecordWriterHashMap().containsKey(inProgressFilePath)) {
recordWriter = writerFactory.createRecordWriter(inProgressFilePath);
rowConverter = writerFactory.createRowDataConverter();
CacheHolder.getRecordWriterHashMap().put(inProgressFilePath, recordWriter);
CacheHolder.getRowConverterHashMap().put(inProgressFilePath, rowConverter);
} else {
recordWriter = CacheHolder.getRecordWriterHashMap().get(inProgressFilePath);
rowConverter = CacheHolder.getRowConverterHashMap().get(inProgressFilePath);
}
return new ImmutablePair<>(recordWriter, rowConverter);
}
/**
* check if source table schema changes
*
* @param identifier hive database name and table name
* @param writerFactory hive writer factory
* @param schema hive field with flink types
* @return if schema has changed
*/
private boolean checkSchema(ObjectIdentifier identifier, HiveWriterFactory writerFactory, RowType schema) {
HashMap<ObjectIdentifier, Long> schemaCheckTimeMap = CacheHolder.getSchemaCheckTimeMap();
long lastUpdate = schemaCheckTimeMap.getOrDefault(identifier, -1L);
// handle the schema every `HIVE_SCHEMA_SCAN_INTERVAL` milliseconds
int scanSchemaInterval = Integer.parseInt(writerFactory.getJobConf()
.get(HIVE_SCHEMA_SCAN_INTERVAL.key(), HIVE_SCHEMA_SCAN_INTERVAL.defaultValue() + ""));
boolean changed = false;
if (System.currentTimeMillis() - lastUpdate >= scanSchemaInterval) {
changed = HiveTableUtil.changeSchema(schema, writerFactory.getAllColumns(),
writerFactory.getAllTypes(), identifier.getDatabaseName(), identifier.getObjectName(), hiveVersion);
schemaCheckTimeMap.put(identifier, System.currentTimeMillis());
}
return changed;
}
@Override
public InProgressFileRecoverable persist() {
throw new UnsupportedOperationException("The path based writers do not support persisting");
}
@Override
public PendingFileRecoverable closeForCommit() throws IOException {
if (sinkMultipleEnable) {
LOG.info("record writer cache {}", CacheHolder.getRecordWriterHashMap());
Iterator<Path> iterator = CacheHolder.getRecordWriterHashMap().keySet().iterator();
while (iterator.hasNext()) {
Path inProgressFilePath = iterator.next();
// one flink batch writes many hive tables, they are the same inProgressPath
if (inProgressFilePath.getName().equals(this.inProgressPath.getName())) {
FileSinkOperator.RecordWriter recordWriter = CacheHolder.getRecordWriterHashMap()
.get(inProgressFilePath);
writer.setRecordWriter(recordWriter);
writer.flush();
writer.finish();
// clear cache
iterator.remove();
CacheHolder.getRowConverterHashMap().remove(inProgressFilePath);
// parse the target location of hive table
String tmpFileName = inProgressFilePath.getName();
String targetPathName = tmpFileName.substring(1, tmpFileName.lastIndexOf(".inprogress"));
Path targetPath = new Path(inProgressFilePath.getParent() + "/" + targetPathName);
LOG.info("file committer target path {}, in progress file {}", targetPath, inProgressFilePath);
HadoopRenameFileCommitter committer = new HadoopRenameFileCommitter(
((HadoopRenameFileCommitter) fileCommitter).getConfiguration(),
targetPath,
inProgressFilePath,
true);
CacheHolder.getFileCommitterHashMap().put(inProgressFilePath, committer);
}
}
} else {
writer.flush();
writer.finish();
fileCommitter.preCommit();
}
return new HadoopPathBasedPendingFile(fileCommitter, getSize()).getRecoverable();
}
@Override
public void dispose() {
writer.dispose();
}
@Override
public long getSize() throws IOException {
return writer.getSize();
}
static class HadoopPathBasedPendingFile implements BucketWriter.PendingFile {
private final HadoopFileCommitter fileCommitter;
private final long fileSize;
public HadoopPathBasedPendingFile(HadoopFileCommitter fileCommitter, long fileSize) {
this.fileCommitter = fileCommitter;
this.fileSize = fileSize;
}
@Override
public void commit() throws IOException {
fileCommitter.commit();
}
@Override
public void commitAfterRecovery() throws IOException {
fileCommitter.commitAfterRecovery();
}
public PendingFileRecoverable getRecoverable() {
return new HadoopPathBasedPendingFileRecoverable(fileCommitter.getTargetFilePath(),
fileCommitter.getTempFilePath(), fileSize);
}
}
@VisibleForTesting
static class HadoopPathBasedPendingFileRecoverable implements PendingFileRecoverable {
private final Path targetFilePath;
private final Path tempFilePath;
private final long fileSize;
@Deprecated
// Remained for compatibility
public HadoopPathBasedPendingFileRecoverable(Path targetFilePath, Path tempFilePath) {
this.targetFilePath = targetFilePath;
this.tempFilePath = tempFilePath;
this.fileSize = -1L;
}
public HadoopPathBasedPendingFileRecoverable(Path targetFilePath, Path tempFilePath, long fileSize) {
this.targetFilePath = targetFilePath;
this.tempFilePath = tempFilePath;
this.fileSize = fileSize;
}
public Path getTargetFilePath() {
return targetFilePath;
}
public Path getTempFilePath() {
return tempFilePath;
}
public org.apache.flink.core.fs.Path getPath() {
return new org.apache.flink.core.fs.Path(targetFilePath.toString());
}
public long getSize() {
return fileSize;
}
}
@VisibleForTesting
static class HadoopPathBasedPendingFileRecoverableSerializer
implements
SimpleVersionedSerializer<PendingFileRecoverable> {
static final HadoopPathBasedPendingFileRecoverableSerializer INSTANCE =
new HadoopPathBasedPendingFileRecoverableSerializer();
private static final Charset CHARSET = StandardCharsets.UTF_8;
private static final int MAGIC_NUMBER = 0x2c853c90;
@Override
public int getVersion() {
return 2;
}
@Override
public byte[] serialize(PendingFileRecoverable pendingFileRecoverable) {
if (!(pendingFileRecoverable instanceof HadoopPathBasedPartFileWriter.HadoopPathBasedPendingFileRecoverable)) {
throw new UnsupportedOperationException("Only HadoopPathBasedPendingFileRecoverable is supported.");
}
HadoopPathBasedPendingFileRecoverable hadoopRecoverable =
(HadoopPathBasedPendingFileRecoverable) pendingFileRecoverable;
Path path = hadoopRecoverable.getTargetFilePath();
Path inProgressPath = hadoopRecoverable.getTempFilePath();
byte[] pathBytes = path.toUri().toString().getBytes(CHARSET);
byte[] inProgressBytes = inProgressPath.toUri().toString().getBytes(CHARSET);
byte[] targetBytes = new byte[12 + pathBytes.length + inProgressBytes.length + Long.BYTES];
ByteBuffer bb = ByteBuffer.wrap(targetBytes).order(ByteOrder.LITTLE_ENDIAN);
bb.putInt(MAGIC_NUMBER);
bb.putInt(pathBytes.length);
bb.put(pathBytes);
bb.putInt(inProgressBytes.length);
bb.put(inProgressBytes);
bb.putLong(hadoopRecoverable.getSize());
return targetBytes;
}
@Override
public HadoopPathBasedPendingFileRecoverable deserialize(int version, byte[] serialized) throws IOException {
switch (version) {
case 1:
return deserializeV1(serialized);
case 2:
return deserializeV2(serialized);
default:
throw new IOException("Unrecognized version or corrupt state: " + version);
}
}
private HadoopPathBasedPendingFileRecoverable deserializeV1(byte[] serialized) throws IOException {
final ByteBuffer bb = ByteBuffer.wrap(serialized).order(ByteOrder.LITTLE_ENDIAN);
if (bb.getInt() != MAGIC_NUMBER) {
throw new IOException("Corrupt data: Unexpected magic number.");
}
byte[] targetFilePathBytes = new byte[bb.getInt()];
bb.get(targetFilePathBytes);
String targetFilePath = new String(targetFilePathBytes, CHARSET);
byte[] tempFilePathBytes = new byte[bb.getInt()];
bb.get(tempFilePathBytes);
String tempFilePath = new String(tempFilePathBytes, CHARSET);
return new HadoopPathBasedPendingFileRecoverable(new Path(targetFilePath), new Path(tempFilePath));
}
private HadoopPathBasedPendingFileRecoverable deserializeV2(byte[] serialized) throws IOException {
final ByteBuffer bb = ByteBuffer.wrap(serialized).order(ByteOrder.LITTLE_ENDIAN);
if (bb.getInt() != MAGIC_NUMBER) {
throw new IOException("Corrupt data: Unexpected magic number.");
}
byte[] targetFilePathBytes = new byte[bb.getInt()];
bb.get(targetFilePathBytes);
String targetFilePath = new String(targetFilePathBytes, CHARSET);
byte[] tempFilePathBytes = new byte[bb.getInt()];
bb.get(tempFilePathBytes);
String tempFilePath = new String(tempFilePathBytes, CHARSET);
long fileSize = bb.getLong();
return new HadoopPathBasedPendingFileRecoverable(new Path(targetFilePath), new Path(tempFilePath),
fileSize);
}
}
private static class UnsupportedInProgressFileRecoverableSerializable
implements
SimpleVersionedSerializer<InProgressFileRecoverable> {
static final UnsupportedInProgressFileRecoverableSerializable INSTANCE =
new UnsupportedInProgressFileRecoverableSerializable();
@Override
public int getVersion() {
throw new UnsupportedOperationException("Persists the path-based part file write is not supported");
}
@Override
public byte[] serialize(InProgressFileRecoverable obj) {
throw new UnsupportedOperationException("Persists the path-based part file write is not supported");
}
@Override
public InProgressFileRecoverable deserialize(int version, byte[] serialized) {
throw new UnsupportedOperationException("Persists the path-based part file write is not supported");
}
}
/**
* Factory to create {@link HadoopPathBasedPartFileWriter}. This writer does not support
* snapshotting the in-progress files. For pending files, it stores the target path and the
* staging file path into the state.
*/
public static class HadoopPathBasedBucketWriter<IN, BucketID> implements BucketWriter<IN, BucketID> {
private final Configuration configuration;
private final HadoopPathBasedBulkWriter.Factory<IN> bulkWriterFactory;
private final HadoopFileCommitterFactory fileCommitterFactory;
private final HiveWriterFactory hiveWriterFactory;
@Nullable
private final transient SinkTableMetricData metricData;
private final DirtyOptions dirtyOptions;
private final @Nullable DirtySink<Object> dirtySink;
private final SchemaUpdateExceptionPolicy schemaUpdatePolicy;
private final PartitionPolicy partitionPolicy;
private final String inputFormat;
private final String outputFormat;
private final String serializationLib;
private final HiveShim hiveShim;
private final String hiveVersion;
public HadoopPathBasedBucketWriter(Configuration configuration,
HadoopPathBasedBulkWriter.Factory<IN> bulkWriterFactory,
HadoopFileCommitterFactory fileCommitterFactory, @Nullable SinkTableMetricData metricData,
DirtyOptions dirtyOptions, @Nullable DirtySink<Object> dirtySink,
SchemaUpdateExceptionPolicy schemaUpdatePolicy,
PartitionPolicy partitionPolicy,
HiveShim hiveShim,
String hiveVersion,
String inputFormat,
String outputFormat,
String serializationLib) {
this.configuration = configuration;
this.bulkWriterFactory = bulkWriterFactory;
this.hiveWriterFactory = ((HiveBulkWriterFactory) this.bulkWriterFactory).getFactory();
this.fileCommitterFactory = fileCommitterFactory;
this.metricData = metricData;
this.dirtyOptions = dirtyOptions;
this.dirtySink = dirtySink;
this.schemaUpdatePolicy = schemaUpdatePolicy;
this.partitionPolicy = partitionPolicy;
this.hiveShim = hiveShim;
this.hiveVersion = hiveVersion;
this.inputFormat = inputFormat;
this.outputFormat = outputFormat;
this.serializationLib = serializationLib;
}
@Override
public HadoopPathBasedPartFileWriter<IN, BucketID> openNewInProgressFile(BucketID bucketID,
org.apache.flink.core.fs.Path flinkPath, long creationTime) throws IOException {
Path path = new Path(flinkPath.toUri());
HadoopFileCommitter fileCommitter = fileCommitterFactory.create(configuration, path);
Path inProgressFilePath = fileCommitter.getTempFilePath();
InLongHadoopPathBasedBulkWriter writer = (InLongHadoopPathBasedBulkWriter) bulkWriterFactory.create(path,
inProgressFilePath);
JobConf jobConf = hiveWriterFactory.getJobConf();
boolean sinkMultipleEnable = Boolean.parseBoolean(jobConf.get(SINK_MULTIPLE_ENABLE.key(), "false"));
String sinkMultipleFormat = jobConf.get(SINK_MULTIPLE_FORMAT.key());
String databasePattern = jobConf.get(SINK_MULTIPLE_DATABASE_PATTERN.key());
String tablePattern = jobConf.get(SINK_MULTIPLE_TABLE_PATTERN.key());
return new HadoopPathBasedPartFileWriter<>(bucketID,
path,
inProgressFilePath,
writer,
fileCommitter,
creationTime,
hiveShim,
hiveVersion,
sinkMultipleEnable,
sinkMultipleFormat,
databasePattern,
tablePattern,
metricData,
dirtyOptions,
dirtySink,
schemaUpdatePolicy,
partitionPolicy,
inputFormat,
outputFormat,
serializationLib);
}
@Override
public PendingFile recoverPendingFile(PendingFileRecoverable pendingFileRecoverable) throws IOException {
if (!(pendingFileRecoverable instanceof HadoopPathBasedPartFileWriter.HadoopPathBasedPendingFileRecoverable)) {
throw new UnsupportedOperationException("Only HadoopPathBasedPendingFileRecoverable is supported.");
}
HadoopPathBasedPendingFileRecoverable hadoopRecoverable =
(HadoopPathBasedPendingFileRecoverable) pendingFileRecoverable;
return new HadoopPathBasedPendingFile(
fileCommitterFactory.recoverForCommit(configuration, hadoopRecoverable.getTargetFilePath(),
hadoopRecoverable.getTempFilePath()),
hadoopRecoverable.getSize());
}
@Override
public WriterProperties getProperties() {
return new WriterProperties(UnsupportedInProgressFileRecoverableSerializable.INSTANCE,
HadoopPathBasedPendingFileRecoverableSerializer.INSTANCE, false);
}
@Override
public InProgressFileWriter<IN, BucketID> resumeInProgressFileFrom(BucketID bucketID,
InProgressFileRecoverable inProgressFileSnapshot, long creationTime) {
throw new UnsupportedOperationException("Resume is not supported");
}
@Override
public boolean cleanupInProgressFileRecoverable(InProgressFileRecoverable inProgressFileRecoverable) {
return false;
}
}
} |
apache/mina-sshd | 35,754 | sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractConnectionService.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.sshd.common.session.helpers;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.IntUnaryOperator;
import org.apache.sshd.agent.common.AgentForwardSupport;
import org.apache.sshd.agent.common.DefaultAgentForwardSupport;
import org.apache.sshd.client.channel.AbstractClientChannel;
import org.apache.sshd.client.future.OpenFuture;
import org.apache.sshd.common.Closeable;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.SshConstants;
import org.apache.sshd.common.channel.Channel;
import org.apache.sshd.common.channel.ChannelFactory;
import org.apache.sshd.common.channel.ChannelListener;
import org.apache.sshd.common.channel.LocalWindow;
import org.apache.sshd.common.channel.RequestHandler;
import org.apache.sshd.common.channel.exception.SshChannelNotFoundException;
import org.apache.sshd.common.channel.exception.SshChannelOpenException;
import org.apache.sshd.common.forward.Forwarder;
import org.apache.sshd.common.forward.ForwarderFactory;
import org.apache.sshd.common.forward.PortForwardingEventListener;
import org.apache.sshd.common.forward.PortForwardingEventListenerManager;
import org.apache.sshd.common.future.HasException;
import org.apache.sshd.common.io.AbstractIoWriteFuture;
import org.apache.sshd.common.io.IoWriteFuture;
import org.apache.sshd.common.kex.KexState;
import org.apache.sshd.common.session.ConnectionService;
import org.apache.sshd.common.session.ReservedSessionMessagesHandler;
import org.apache.sshd.common.session.Session;
import org.apache.sshd.common.session.UnknownChannelReferenceHandler;
import org.apache.sshd.common.util.EventListenerUtils;
import org.apache.sshd.common.util.GenericUtils;
import org.apache.sshd.common.util.ValidateUtils;
import org.apache.sshd.common.util.buffer.Buffer;
import org.apache.sshd.common.util.closeable.AbstractInnerCloseable;
import org.apache.sshd.common.util.functors.Int2IntFunction;
import org.apache.sshd.core.CoreModuleProperties;
import org.apache.sshd.server.x11.DefaultX11ForwardSupport;
import org.apache.sshd.server.x11.X11ForwardSupport;
/**
* Base implementation of ConnectionService.
*
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public abstract class AbstractConnectionService
extends AbstractInnerCloseable
implements ConnectionService {
/**
* Default growth factor function used to resize response buffers
*/
public static final IntUnaryOperator RESPONSE_BUFFER_GROWTH_FACTOR = Int2IntFunction.add(Byte.SIZE);
/** Used in {@code SSH_MSH_IGNORE} messages for the keep-alive mechanism */
public static final String DEFAULT_SESSION_IGNORE_HEARTBEAT_STRING = "ignore@sshd.apache.org";
/**
* Map of channels keyed by the identifier
*/
protected final Map<Long, Channel> channels = new ConcurrentHashMap<>();
/**
* Next channel identifier - a UINT32 represented as a long
*/
protected final AtomicLong nextChannelId = new AtomicLong(0L);
protected final AtomicLong heartbeatCount = new AtomicLong(0L);
private ScheduledFuture<?> heartBeat;
private final AtomicReference<AgentForwardSupport> agentForwardHolder = new AtomicReference<>();
private final AtomicReference<X11ForwardSupport> x11ForwardHolder = new AtomicReference<>();
private final AtomicReference<Forwarder> forwarderHolder = new AtomicReference<>();
private final AtomicBoolean allowMoreSessions = new AtomicBoolean(true);
private final Collection<PortForwardingEventListener> listeners = new CopyOnWriteArraySet<>();
private final Collection<PortForwardingEventListenerManager> managersHolder = new CopyOnWriteArraySet<>();
private final Map<String, Object> properties = new ConcurrentHashMap<>();
private final PortForwardingEventListener listenerProxy;
private final AbstractSession sessionInstance;
private UnknownChannelReferenceHandler unknownChannelReferenceHandler;
protected AbstractConnectionService(AbstractSession session) {
sessionInstance = Objects.requireNonNull(session, "No session");
listenerProxy = EventListenerUtils.proxyWrapper(PortForwardingEventListener.class, listeners);
}
@Override
public Map<String, Object> getProperties() {
return properties;
}
@Override
public PortForwardingEventListener getPortForwardingEventListenerProxy() {
return listenerProxy;
}
@Override
public void addPortForwardingEventListener(PortForwardingEventListener listener) {
listeners.add(PortForwardingEventListener.validateListener(listener));
}
@Override
public void removePortForwardingEventListener(PortForwardingEventListener listener) {
if (listener == null) {
return;
}
listeners.remove(PortForwardingEventListener.validateListener(listener));
}
@Override
public UnknownChannelReferenceHandler getUnknownChannelReferenceHandler() {
return unknownChannelReferenceHandler;
}
@Override
public void setUnknownChannelReferenceHandler(UnknownChannelReferenceHandler handler) {
unknownChannelReferenceHandler = handler;
}
@Override
public Collection<PortForwardingEventListenerManager> getRegisteredManagers() {
return managersHolder.isEmpty() ? Collections.emptyList() : new ArrayList<>(managersHolder);
}
@Override
public boolean addPortForwardingEventListenerManager(PortForwardingEventListenerManager manager) {
return managersHolder.add(Objects.requireNonNull(manager, "No manager"));
}
@Override
public boolean removePortForwardingEventListenerManager(PortForwardingEventListenerManager manager) {
if (manager == null) {
return false;
}
return managersHolder.remove(manager);
}
public Collection<Channel> getChannels() {
return channels.values();
}
@Override
public AbstractSession getSession() {
return sessionInstance;
}
@Override
public void start() {
heartBeat = startHeartBeat();
}
protected synchronized ScheduledFuture<?> startHeartBeat() {
stopHeartBeat(); // make sure any existing heartbeat is stopped
HeartbeatType heartbeatType = getSessionHeartbeatType();
Duration interval = getSessionHeartbeatInterval();
Session session = getSession();
boolean debugEnabled = log.isDebugEnabled();
if (debugEnabled) {
log.debug("startHeartbeat({}) heartbeat type={}, interval={}", session, heartbeatType, interval);
}
if ((heartbeatType == null) || (heartbeatType == HeartbeatType.NONE) || (GenericUtils.isNegativeOrNull(interval))) {
return null;
}
FactoryManager manager = session.getFactoryManager();
ScheduledExecutorService service = manager.getScheduledExecutorService();
return service.scheduleAtFixedRate(
this::sendHeartBeat, interval.toMillis(), interval.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Sends a heartbeat message/packet
*
* @return {@code true} if heartbeat successfully sent
*/
protected boolean sendHeartBeat() {
HeartbeatType heartbeatType = getSessionHeartbeatType();
Duration interval = getSessionHeartbeatInterval();
Session session = getSession();
boolean traceEnabled = log.isTraceEnabled();
if (traceEnabled) {
log.trace("sendHeartbeat({}) heartbeat type={}, interval={}",
session, heartbeatType, interval);
}
if ((heartbeatType == null) || (GenericUtils.isNegativeOrNull(interval)) || (heartBeat == null)) {
return false;
}
// SSHD-1059
KexState kexState = session.getKexState();
if ((heartbeatType != HeartbeatType.NONE)
&& (kexState != KexState.DONE)) {
if (traceEnabled) {
log.trace("sendHeartbeat({}) heartbeat type={}, interval={} - skip due to KEX state={}",
session, heartbeatType, interval, kexState);
}
return false;
}
try {
switch (heartbeatType) {
case NONE:
return false;
case IGNORE: {
Buffer buffer = session.createBuffer(
SshConstants.SSH_MSG_IGNORE, DEFAULT_SESSION_IGNORE_HEARTBEAT_STRING.length() + Byte.SIZE);
buffer.putString(DEFAULT_SESSION_IGNORE_HEARTBEAT_STRING);
IoWriteFuture future = session.writePacket(buffer);
future.addListener(this::futureDone);
return true;
}
case RESERVED: {
ReservedSessionMessagesHandler handler = Objects.requireNonNull(
session.getReservedSessionMessagesHandler(),
"No customized heartbeat handler registered");
return handler.sendReservedHeartbeat(this);
}
default:
throw new UnsupportedOperationException("Unsupported heartbeat type: " + heartbeatType);
}
} catch (Throwable e) {
session.exceptionCaught(e);
warn("sendHeartBeat({}) failed ({}) to send heartbeat #{} request={}: {}",
session, e.getClass().getSimpleName(), heartbeatCount, heartbeatType, e.getMessage(), e);
return false;
}
}
protected void futureDone(HasException future) {
Throwable t = future.getException();
if (t != null) {
Session session = getSession();
session.exceptionCaught(t);
}
}
protected synchronized void stopHeartBeat() {
boolean debugEnabled = log.isDebugEnabled();
Session session = getSession();
if (heartBeat == null) {
if (debugEnabled) {
log.debug("stopHeartBeat({}) no heartbeat to stop", session);
}
return;
}
if (debugEnabled) {
log.debug("stopHeartBeat({}) stopping", session);
}
try {
heartBeat.cancel(true);
} finally {
heartBeat = null;
}
if (debugEnabled) {
log.debug("stopHeartBeat({}) stopped", session);
}
}
@Override
public Forwarder getForwarder() {
Forwarder forwarder;
Session session = getSession();
synchronized (forwarderHolder) {
forwarder = forwarderHolder.get();
if (forwarder != null) {
return forwarder;
}
forwarder = ValidateUtils.checkNotNull(
createForwardingFilter(session), "No forwarder created for %s", session);
forwarderHolder.set(forwarder);
}
if (log.isDebugEnabled()) {
log.debug("getForwardingFilter({}) created instance", session);
}
return forwarder;
}
@Override
protected void preClose() {
stopHeartBeat();
this.listeners.clear();
this.managersHolder.clear();
super.preClose();
}
protected Forwarder createForwardingFilter(Session session) {
FactoryManager manager = Objects.requireNonNull(session.getFactoryManager(), "No factory manager");
ForwarderFactory factory = Objects.requireNonNull(manager.getForwarderFactory(), "No forwarder factory");
Forwarder forwarder = factory.create(this);
forwarder.addPortForwardingEventListenerManager(this);
return forwarder;
}
@Override
public X11ForwardSupport getX11ForwardSupport() {
X11ForwardSupport x11Support;
Session session = getSession();
synchronized (x11ForwardHolder) {
x11Support = x11ForwardHolder.get();
if (x11Support != null) {
return x11Support;
}
x11Support = ValidateUtils.checkNotNull(
createX11ForwardSupport(session), "No X11 forwarder created for %s", session);
x11ForwardHolder.set(x11Support);
}
if (log.isDebugEnabled()) {
log.debug("getX11ForwardSupport({}) created instance", session);
}
return x11Support;
}
protected X11ForwardSupport createX11ForwardSupport(Session session) {
return new DefaultX11ForwardSupport(this);
}
@Override
public AgentForwardSupport getAgentForwardSupport() {
AgentForwardSupport agentForward;
Session session = getSession();
synchronized (agentForwardHolder) {
agentForward = agentForwardHolder.get();
if (agentForward != null) {
return agentForward;
}
agentForward = ValidateUtils.checkNotNull(
createAgentForwardSupport(session), "No agent forward created for %s", session);
agentForwardHolder.set(agentForward);
}
if (log.isDebugEnabled()) {
log.debug("getAgentForwardSupport({}) created instance", session);
}
return agentForward;
}
protected AgentForwardSupport createAgentForwardSupport(Session session) {
return new DefaultAgentForwardSupport(this);
}
@Override
protected Closeable getInnerCloseable() {
return builder()
.sequential(forwarderHolder.get(), agentForwardHolder.get(), x11ForwardHolder.get())
.parallel(toString(), getChannels())
.build();
}
protected long getNextChannelId() {
return nextChannelId.getAndIncrement();
}
@Override
public long registerChannel(Channel channel) throws IOException {
Session session = getSession();
int maxChannels = CoreModuleProperties.MAX_CONCURRENT_CHANNELS.getRequired(this);
int curSize = channels.size();
if (curSize > maxChannels) {
throw new IllegalStateException("Currently active channels (" + curSize + ") at max.: " + maxChannels);
}
long channelId = getNextChannelId();
channel.init(this, session, channelId);
boolean registered = false;
synchronized (channels) {
if (!isClosing()) {
channels.put(channelId, channel);
registered = true;
}
}
if (log.isDebugEnabled()) {
log.debug("registerChannel({})[id={}, registered={}] {}", this, channelId, registered, channel);
}
channel.handleChannelRegistrationResult(this, session, channelId, registered);
return channelId;
}
/**
* Remove this channel from the list of managed channels
*
* @param channel the channel
*/
@Override
public void unregisterChannel(Channel channel) {
long channelId = channel.getChannelId();
Channel result;
synchronized (channels) {
result = channels.remove(channelId);
}
if (log.isDebugEnabled()) {
log.debug("unregisterChannel({}) result={}", channel, result);
}
if (result != null) {
result.handleChannelUnregistration(this);
}
}
@Override
public void process(int cmd, Buffer buffer) throws Exception {
switch (cmd) {
case SshConstants.SSH_MSG_CHANNEL_OPEN:
channelOpen(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
channelOpenConfirmation(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_OPEN_FAILURE:
channelOpenFailure(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_REQUEST:
channelRequest(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_DATA:
channelData(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_EXTENDED_DATA:
channelExtendedData(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_FAILURE:
channelFailure(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_SUCCESS:
channelSuccess(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_WINDOW_ADJUST:
channelWindowAdjust(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_EOF:
channelEof(buffer);
break;
case SshConstants.SSH_MSG_CHANNEL_CLOSE:
channelClose(buffer);
break;
case SshConstants.SSH_MSG_GLOBAL_REQUEST:
globalRequest(buffer);
break;
case SshConstants.SSH_MSG_REQUEST_SUCCESS:
requestSuccess(buffer);
break;
case SshConstants.SSH_MSG_REQUEST_FAILURE:
requestFailure(buffer);
break;
default: {
/*
* According to https://tools.ietf.org/html/rfc4253#section-11.4
*
* An implementation MUST respond to all unrecognized messages with an SSH_MSG_UNIMPLEMENTED message in
* the order in which the messages were received.
*/
AbstractSession session = getSession();
if (log.isDebugEnabled()) {
log.debug("process({}) Unsupported command: {}",
session, SshConstants.getCommandMessageName(cmd));
}
session.notImplemented(cmd, buffer);
}
}
}
@Override
public boolean isAllowMoreSessions() {
return allowMoreSessions.get();
}
@Override
public void setAllowMoreSessions(boolean allow) {
if (log.isDebugEnabled()) {
log.debug("setAllowMoreSessions({}): {}", this, allow);
}
allowMoreSessions.set(allow);
}
public void channelOpenConfirmation(Buffer buffer) throws IOException {
Channel channel = getChannel(SshConstants.SSH_MSG_CHANNEL_OPEN_CONFIRMATION, buffer);
if (channel == null) {
return; // debug breakpoint
}
long sender = buffer.getUInt();
long rwsize = buffer.getUInt();
long rmpsize = buffer.getUInt();
if (log.isDebugEnabled()) {
log.debug("channelOpenConfirmation({}) SSH_MSG_CHANNEL_OPEN_CONFIRMATION sender={}, window-size={}, packet-size={}",
channel, sender, rwsize, rmpsize);
}
/*
* NOTE: the 'sender' of the SSH_MSG_CHANNEL_OPEN_CONFIRMATION is the recipient on the client side - see rfc4254
* section 5.1:
*
* 'sender channel' is the channel number allocated by the other side
*
* in our case, the server
*/
channel.handleOpenSuccess(sender, rwsize, rmpsize, buffer);
}
public void channelOpenFailure(Buffer buffer) throws IOException {
AbstractClientChannel channel = (AbstractClientChannel) getChannel(SshConstants.SSH_MSG_CHANNEL_OPEN_FAILURE, buffer);
if (channel == null) {
return; // debug breakpoint
}
long id = channel.getChannelId();
boolean debugEnabled = log.isDebugEnabled();
if (debugEnabled) {
log.debug("channelOpenFailure({}) Received SSH_MSG_CHANNEL_OPEN_FAILURE", channel);
}
Channel removed;
synchronized (channels) {
removed = channels.remove(id);
}
if (debugEnabled) {
log.debug("channelOpenFailure({}) unregistered {}", channel, removed);
}
channel.handleOpenFailure(buffer);
}
/**
* Process incoming data on a channel
*
* @param buffer the buffer containing the data
* @throws IOException if an error occurs
*/
public void channelData(Buffer buffer) throws IOException {
Channel channel = getChannel(SshConstants.SSH_MSG_CHANNEL_DATA, buffer);
if (channel == null) {
return; // debug breakpoint
}
channel.handleData(buffer);
}
/**
* Process incoming extended data on a channel
*
* @param buffer the buffer containing the data
* @throws IOException if an error occurs
*/
public void channelExtendedData(Buffer buffer) throws IOException {
Channel channel = getChannel(SshConstants.SSH_MSG_CHANNEL_EXTENDED_DATA, buffer);
if (channel == null) {
return; // debug breakpoint
}
channel.handleExtendedData(buffer);
}
/**
* Process a window adjust packet on a channel
*
* @param buffer the buffer containing the window adjustment parameters
* @throws IOException if an error occurs
*/
public void channelWindowAdjust(Buffer buffer) throws IOException {
Channel channel = getChannel(SshConstants.SSH_MSG_CHANNEL_WINDOW_ADJUST, buffer);
if (channel == null) {
return; // debug breakpoint
}
channel.handleWindowAdjust(buffer);
}
/**
* Process end of file on a channel
*
* @param buffer the buffer containing the packet
* @throws IOException if an error occurs
*/
public void channelEof(Buffer buffer) throws IOException {
Channel channel = getChannel(SshConstants.SSH_MSG_CHANNEL_EOF, buffer);
if (channel == null) {
return; // debug breakpoint
}
channel.handleEof();
}
/**
* Close a channel due to a close packet received
*
* @param buffer the buffer containing the packet
* @throws IOException if an error occurs
*/
public void channelClose(Buffer buffer) throws IOException {
Channel channel = getChannel(SshConstants.SSH_MSG_CHANNEL_CLOSE, buffer);
if (channel == null) {
return; // debug breakpoint
}
channel.handleClose();
}
/**
* Service a request on a channel
*
* @param buffer the buffer containing the request
* @throws IOException if an error occurs
*/
public void channelRequest(Buffer buffer) throws IOException {
Channel channel = getChannel(SshConstants.SSH_MSG_CHANNEL_REQUEST, buffer);
if (channel == null) {
return; // debug breakpoint
}
channel.handleRequest(buffer);
}
/**
* Process a failure on a channel
*
* @param buffer the buffer containing the packet
* @throws IOException if an error occurs
*/
public void channelFailure(Buffer buffer) throws IOException {
Channel channel = getChannel(SshConstants.SSH_MSG_CHANNEL_FAILURE, buffer);
if (channel == null) {
return; // debug breakpoint
}
channel.handleFailure();
}
/**
* Process a success on a channel
*
* @param buffer the buffer containing the packet
* @throws IOException if an error occurs
*/
public void channelSuccess(Buffer buffer) throws IOException {
Channel channel = getChannel(SshConstants.SSH_MSG_CHANNEL_SUCCESS, buffer);
if (channel == null) {
return; // debug breakpoint
}
channel.handleSuccess();
}
/**
* Retrieve the channel designated by the given packet
*
* @param cmd The command being processed for the channel
* @param buffer the incoming packet
* @return the target channel
* @throws IOException if the channel does not exists
*/
protected Channel getChannel(byte cmd, Buffer buffer) throws IOException {
return getChannel(cmd, buffer.getUInt(), buffer);
}
protected Channel getChannel(byte cmd, long recipient, Buffer buffer) throws IOException {
Channel channel = channels.get(recipient);
if (channel != null) {
return channel;
}
UnknownChannelReferenceHandler handler = resolveUnknownChannelReferenceHandler();
if (handler == null) {
// Throw a special exception - SSHD-777
throw new SshChannelNotFoundException(recipient,
"Received " + SshConstants.getCommandMessageName(cmd) + " on unknown channel " + recipient);
}
channel = handler.handleUnknownChannelCommand(this, cmd, recipient, buffer);
return channel;
}
@Override
public UnknownChannelReferenceHandler resolveUnknownChannelReferenceHandler() {
UnknownChannelReferenceHandler handler = getUnknownChannelReferenceHandler();
if (handler != null) {
return handler;
}
Session s = getSession();
return (s == null) ? null : s.resolveUnknownChannelReferenceHandler();
}
protected void channelOpen(Buffer buffer) throws Exception {
String type = buffer.getString();
long sender = buffer.getUInt();
long rwsize = buffer.getUInt();
long rmpsize = buffer.getUInt();
/*
* NOTE: the 'sender' is the identifier assigned by the remote side - the server in this case
*/
boolean debugEnabled = log.isDebugEnabled();
if (debugEnabled) {
log.debug("channelOpen({}) SSH_MSG_CHANNEL_OPEN sender={}, type={}, window-size={}, packet-size={}",
this, sender, type, rwsize, rmpsize);
}
if (isClosing()) {
// TODO add language tag configurable control
sendChannelOpenFailure(buffer, sender, SshConstants.SSH_OPEN_CONNECT_FAILED,
"Server is shutting down while attempting to open channel type=" + type, "");
return;
}
if (!isAllowMoreSessions()) {
// TODO add language tag configurable control
sendChannelOpenFailure(buffer, sender, SshConstants.SSH_OPEN_CONNECT_FAILED, "additional sessions disabled", "");
return;
}
Session session = getSession();
FactoryManager manager = Objects.requireNonNull(session.getFactoryManager(), "No factory manager");
Channel channel = ChannelFactory.createChannel(session, manager.getChannelFactories(), type);
if (channel == null) {
// TODO add language tag configurable control
sendChannelOpenFailure(buffer, sender,
SshConstants.SSH_OPEN_UNKNOWN_CHANNEL_TYPE, "Unsupported channel type: " + type, "");
return;
}
long channelId = registerChannel(channel);
channel.addChannelListener(new ChannelListener() {
@Override
public void channelOpenSuccess(Channel channel) {
// Do not rely on the OpenFuture. We must be sure that we get the SSH_MSG_CHANNEL_OPEN_CONFIRMATION out
// before anything else.
try {
LocalWindow window = channel.getLocalWindow();
if (debugEnabled) {
log.debug(
"channelOpenSuccess({}) send SSH_MSG_CHANNEL_OPEN_CONFIRMATION recipient={}, sender={}, window-size={}, packet-size={}",
channel, sender, channelId, window.getSize(), window.getPacketSize());
}
Buffer buf = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN_CONFIRMATION, Integer.SIZE);
buf.putUInt(sender); // remote (server side) identifier
buf.putUInt(channelId); // local (client side) identifier
buf.putUInt(window.getSize());
buf.putUInt(window.getPacketSize());
session.writePacket(buf);
} catch (IOException e) {
warn("channelOpenSuccess({}) {}: {}", AbstractConnectionService.this, e.getClass().getSimpleName(),
e.getMessage(), e);
session.exceptionCaught(e);
}
}
});
OpenFuture openFuture = channel.open(sender, rwsize, rmpsize, buffer);
openFuture.addListener(future -> {
try {
if (!future.isOpened()) {
int reasonCode = 0;
String message = "Generic error while opening channel: " + channelId;
Throwable exception = future.getException();
if (exception != null) {
if (exception instanceof SshChannelOpenException) {
reasonCode = ((SshChannelOpenException) exception).getReasonCode();
} else {
message = exception.getClass().getSimpleName() + " while opening channel: " + message;
}
} else {
log.warn("operationComplete({}) no exception on closed future={}",
AbstractConnectionService.this, future);
}
Buffer buf = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN_FAILURE, message.length() + Long.SIZE);
sendChannelOpenFailure(buf, sender, reasonCode, message, "");
}
} catch (IOException e) {
warn("operationComplete({}) {}: {}",
AbstractConnectionService.this, e.getClass().getSimpleName(), e.getMessage(), e);
session.exceptionCaught(e);
}
});
}
protected IoWriteFuture sendChannelOpenFailure(
Buffer buffer, long sender, int reasonCode, String message, String lang)
throws IOException {
if (log.isDebugEnabled()) {
log.debug("sendChannelOpenFailure({}) sender={}, reason={}, lang={}, message='{}'",
this, sender, SshConstants.getOpenErrorCodeName(reasonCode), lang, message);
}
Session session = getSession();
Buffer buf = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN_FAILURE,
Long.SIZE + GenericUtils.length(message) + GenericUtils.length(lang));
buf.putUInt(sender);
buf.putUInt(reasonCode);
buf.putString(message);
buf.putString(lang);
return session.writePacket(buf);
}
/**
* Process global requests
*
* @param buffer The request {@link Buffer}
* @return An {@link IoWriteFuture} representing the sent packet - <B>Note:</B> if no reply sent then an
* "empty" future is returned - i.e., any added listeners are triggered immediately with
* a synthetic "success"
* @throws Exception If failed to process the request
*/
protected IoWriteFuture globalRequest(Buffer buffer) throws Exception {
String req = buffer.getString();
boolean wantReply = buffer.getBoolean();
boolean debugEnabled = log.isDebugEnabled();
if (debugEnabled) {
log.debug("globalRequest({}) received SSH_MSG_GLOBAL_REQUEST {} want-reply={}", this, req, wantReply);
}
Session session = getSession();
FactoryManager manager = Objects.requireNonNull(session.getFactoryManager(), "No factory manager");
Collection<RequestHandler<ConnectionService>> handlers = manager.getGlobalRequestHandlers();
if (GenericUtils.size(handlers) > 0) {
boolean traceEnabled = log.isTraceEnabled();
for (RequestHandler<ConnectionService> handler : handlers) {
RequestHandler.Result result;
try {
result = handler.process(this, req, wantReply, buffer);
} catch (Throwable e) {
warn("globalRequest({})[{}, want-reply={}] failed ({}) to process: {}",
this, req, wantReply, e.getClass().getSimpleName(), e.getMessage(), e);
result = RequestHandler.Result.ReplyFailure;
}
// if Unsupported then check the next handler in line
if (RequestHandler.Result.Unsupported.equals(result)) {
if (traceEnabled) {
log.trace("globalRequest({}) {}#process({})[want-reply={}] : {}",
this, handler.getClass().getSimpleName(), req, wantReply, result);
}
} else {
return sendGlobalResponse(buffer, req, result, wantReply);
}
}
}
return handleUnknownRequest(buffer, req, wantReply);
}
protected IoWriteFuture handleUnknownRequest(Buffer buffer, String req, boolean wantReply) throws IOException {
log.warn("handleUnknownRequest({}) unknown global request: {}", this, req);
return sendGlobalResponse(buffer, req, RequestHandler.Result.Unsupported, wantReply);
}
protected IoWriteFuture sendGlobalResponse(
Buffer buffer, String req, RequestHandler.Result result, boolean wantReply)
throws IOException {
if (log.isDebugEnabled()) {
log.debug("sendGlobalResponse({})[{}] result={}, want-reply={}", this, req, result, wantReply);
}
if (RequestHandler.Result.Replied.equals(result) || (!wantReply)) {
return AbstractIoWriteFuture.fulfilled(req, Boolean.TRUE);
}
byte cmd = RequestHandler.Result.ReplySuccess.equals(result)
? SshConstants.SSH_MSG_REQUEST_SUCCESS
: SshConstants.SSH_MSG_REQUEST_FAILURE;
Session session = getSession();
Buffer rsp = session.createBuffer(cmd, 2);
return session.writePacket(rsp);
}
protected void requestSuccess(Buffer buffer) throws Exception {
AbstractSession s = getSession();
s.requestSuccess(buffer);
}
protected void requestFailure(Buffer buffer) throws Exception {
AbstractSession s = getSession();
s.requestFailure(buffer);
}
@Override
public String toString() {
return getClass().getSimpleName() + "[" + getSession() + "]";
}
}
|
googleapis/google-cloud-java | 35,585 | java-container/proto-google-cloud-container-v1/src/main/java/com/google/container/v1/LoggingComponentConfig.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/container/v1/cluster_service.proto
// Protobuf Java Version: 3.25.8
package com.google.container.v1;
/**
*
*
* <pre>
* LoggingComponentConfig is cluster logging component configuration.
* </pre>
*
* Protobuf type {@code google.container.v1.LoggingComponentConfig}
*/
public final class LoggingComponentConfig extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.container.v1.LoggingComponentConfig)
LoggingComponentConfigOrBuilder {
private static final long serialVersionUID = 0L;
// Use LoggingComponentConfig.newBuilder() to construct.
private LoggingComponentConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private LoggingComponentConfig() {
enableComponents_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new LoggingComponentConfig();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.container.v1.ClusterServiceProto
.internal_static_google_container_v1_LoggingComponentConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.container.v1.ClusterServiceProto
.internal_static_google_container_v1_LoggingComponentConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.container.v1.LoggingComponentConfig.class,
com.google.container.v1.LoggingComponentConfig.Builder.class);
}
/**
*
*
* <pre>
* GKE components exposing logs
* </pre>
*
* Protobuf enum {@code google.container.v1.LoggingComponentConfig.Component}
*/
public enum Component implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* Default value. This shouldn't be used.
* </pre>
*
* <code>COMPONENT_UNSPECIFIED = 0;</code>
*/
COMPONENT_UNSPECIFIED(0),
/**
*
*
* <pre>
* system components
* </pre>
*
* <code>SYSTEM_COMPONENTS = 1;</code>
*/
SYSTEM_COMPONENTS(1),
/**
*
*
* <pre>
* workloads
* </pre>
*
* <code>WORKLOADS = 2;</code>
*/
WORKLOADS(2),
/**
*
*
* <pre>
* kube-apiserver
* </pre>
*
* <code>APISERVER = 3;</code>
*/
APISERVER(3),
/**
*
*
* <pre>
* kube-scheduler
* </pre>
*
* <code>SCHEDULER = 4;</code>
*/
SCHEDULER(4),
/**
*
*
* <pre>
* kube-controller-manager
* </pre>
*
* <code>CONTROLLER_MANAGER = 5;</code>
*/
CONTROLLER_MANAGER(5),
/**
*
*
* <pre>
* kcp-sshd
* </pre>
*
* <code>KCP_SSHD = 7;</code>
*/
KCP_SSHD(7),
/**
*
*
* <pre>
* kcp connection logs
* </pre>
*
* <code>KCP_CONNECTION = 8;</code>
*/
KCP_CONNECTION(8),
/**
*
*
* <pre>
* horizontal pod autoscaler decision logs
* </pre>
*
* <code>KCP_HPA = 9;</code>
*/
KCP_HPA(9),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* Default value. This shouldn't be used.
* </pre>
*
* <code>COMPONENT_UNSPECIFIED = 0;</code>
*/
public static final int COMPONENT_UNSPECIFIED_VALUE = 0;
/**
*
*
* <pre>
* system components
* </pre>
*
* <code>SYSTEM_COMPONENTS = 1;</code>
*/
public static final int SYSTEM_COMPONENTS_VALUE = 1;
/**
*
*
* <pre>
* workloads
* </pre>
*
* <code>WORKLOADS = 2;</code>
*/
public static final int WORKLOADS_VALUE = 2;
/**
*
*
* <pre>
* kube-apiserver
* </pre>
*
* <code>APISERVER = 3;</code>
*/
public static final int APISERVER_VALUE = 3;
/**
*
*
* <pre>
* kube-scheduler
* </pre>
*
* <code>SCHEDULER = 4;</code>
*/
public static final int SCHEDULER_VALUE = 4;
/**
*
*
* <pre>
* kube-controller-manager
* </pre>
*
* <code>CONTROLLER_MANAGER = 5;</code>
*/
public static final int CONTROLLER_MANAGER_VALUE = 5;
/**
*
*
* <pre>
* kcp-sshd
* </pre>
*
* <code>KCP_SSHD = 7;</code>
*/
public static final int KCP_SSHD_VALUE = 7;
/**
*
*
* <pre>
* kcp connection logs
* </pre>
*
* <code>KCP_CONNECTION = 8;</code>
*/
public static final int KCP_CONNECTION_VALUE = 8;
/**
*
*
* <pre>
* horizontal pod autoscaler decision logs
* </pre>
*
* <code>KCP_HPA = 9;</code>
*/
public static final int KCP_HPA_VALUE = 9;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static Component valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static Component forNumber(int value) {
switch (value) {
case 0:
return COMPONENT_UNSPECIFIED;
case 1:
return SYSTEM_COMPONENTS;
case 2:
return WORKLOADS;
case 3:
return APISERVER;
case 4:
return SCHEDULER;
case 5:
return CONTROLLER_MANAGER;
case 7:
return KCP_SSHD;
case 8:
return KCP_CONNECTION;
case 9:
return KCP_HPA;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<Component> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<Component> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<Component>() {
public Component findValueByNumber(int number) {
return Component.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
return com.google.container.v1.LoggingComponentConfig.getDescriptor().getEnumTypes().get(0);
}
private static final Component[] VALUES = values();
public static Component valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private Component(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.container.v1.LoggingComponentConfig.Component)
}
public static final int ENABLE_COMPONENTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<java.lang.Integer> enableComponents_;
private static final com.google.protobuf.Internal.ListAdapter.Converter<
java.lang.Integer, com.google.container.v1.LoggingComponentConfig.Component>
enableComponents_converter_ =
new com.google.protobuf.Internal.ListAdapter.Converter<
java.lang.Integer, com.google.container.v1.LoggingComponentConfig.Component>() {
public com.google.container.v1.LoggingComponentConfig.Component convert(
java.lang.Integer from) {
com.google.container.v1.LoggingComponentConfig.Component result =
com.google.container.v1.LoggingComponentConfig.Component.forNumber(from);
return result == null
? com.google.container.v1.LoggingComponentConfig.Component.UNRECOGNIZED
: result;
}
};
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @return A list containing the enableComponents.
*/
@java.lang.Override
public java.util.List<com.google.container.v1.LoggingComponentConfig.Component>
getEnableComponentsList() {
return new com.google.protobuf.Internal.ListAdapter<
java.lang.Integer, com.google.container.v1.LoggingComponentConfig.Component>(
enableComponents_, enableComponents_converter_);
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @return The count of enableComponents.
*/
@java.lang.Override
public int getEnableComponentsCount() {
return enableComponents_.size();
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @param index The index of the element to return.
* @return The enableComponents at the given index.
*/
@java.lang.Override
public com.google.container.v1.LoggingComponentConfig.Component getEnableComponents(int index) {
return enableComponents_converter_.convert(enableComponents_.get(index));
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @return A list containing the enum numeric values on the wire for enableComponents.
*/
@java.lang.Override
public java.util.List<java.lang.Integer> getEnableComponentsValueList() {
return enableComponents_;
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @param index The index of the value to return.
* @return The enum numeric value on the wire of enableComponents at the given index.
*/
@java.lang.Override
public int getEnableComponentsValue(int index) {
return enableComponents_.get(index);
}
private int enableComponentsMemoizedSerializedSize;
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 {
getSerializedSize();
if (getEnableComponentsList().size() > 0) {
output.writeUInt32NoTag(10);
output.writeUInt32NoTag(enableComponentsMemoizedSerializedSize);
}
for (int i = 0; i < enableComponents_.size(); i++) {
output.writeEnumNoTag(enableComponents_.get(i));
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
{
int dataSize = 0;
for (int i = 0; i < enableComponents_.size(); i++) {
dataSize +=
com.google.protobuf.CodedOutputStream.computeEnumSizeNoTag(enableComponents_.get(i));
}
size += dataSize;
if (!getEnableComponentsList().isEmpty()) {
size += 1;
size += com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(dataSize);
}
enableComponentsMemoizedSerializedSize = dataSize;
}
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.container.v1.LoggingComponentConfig)) {
return super.equals(obj);
}
com.google.container.v1.LoggingComponentConfig other =
(com.google.container.v1.LoggingComponentConfig) obj;
if (!enableComponents_.equals(other.enableComponents_)) 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 (getEnableComponentsCount() > 0) {
hash = (37 * hash) + ENABLE_COMPONENTS_FIELD_NUMBER;
hash = (53 * hash) + enableComponents_.hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.container.v1.LoggingComponentConfig parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.container.v1.LoggingComponentConfig parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.container.v1.LoggingComponentConfig parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.container.v1.LoggingComponentConfig 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.container.v1.LoggingComponentConfig parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.container.v1.LoggingComponentConfig parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.container.v1.LoggingComponentConfig parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.container.v1.LoggingComponentConfig 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.container.v1.LoggingComponentConfig parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.container.v1.LoggingComponentConfig 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.container.v1.LoggingComponentConfig parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.container.v1.LoggingComponentConfig 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.container.v1.LoggingComponentConfig 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>
* LoggingComponentConfig is cluster logging component configuration.
* </pre>
*
* Protobuf type {@code google.container.v1.LoggingComponentConfig}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.container.v1.LoggingComponentConfig)
com.google.container.v1.LoggingComponentConfigOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.container.v1.ClusterServiceProto
.internal_static_google_container_v1_LoggingComponentConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.container.v1.ClusterServiceProto
.internal_static_google_container_v1_LoggingComponentConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.container.v1.LoggingComponentConfig.class,
com.google.container.v1.LoggingComponentConfig.Builder.class);
}
// Construct using com.google.container.v1.LoggingComponentConfig.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
enableComponents_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.container.v1.ClusterServiceProto
.internal_static_google_container_v1_LoggingComponentConfig_descriptor;
}
@java.lang.Override
public com.google.container.v1.LoggingComponentConfig getDefaultInstanceForType() {
return com.google.container.v1.LoggingComponentConfig.getDefaultInstance();
}
@java.lang.Override
public com.google.container.v1.LoggingComponentConfig build() {
com.google.container.v1.LoggingComponentConfig result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.container.v1.LoggingComponentConfig buildPartial() {
com.google.container.v1.LoggingComponentConfig result =
new com.google.container.v1.LoggingComponentConfig(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.container.v1.LoggingComponentConfig result) {
if (((bitField0_ & 0x00000001) != 0)) {
enableComponents_ = java.util.Collections.unmodifiableList(enableComponents_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.enableComponents_ = enableComponents_;
}
private void buildPartial0(com.google.container.v1.LoggingComponentConfig 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.container.v1.LoggingComponentConfig) {
return mergeFrom((com.google.container.v1.LoggingComponentConfig) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.container.v1.LoggingComponentConfig other) {
if (other == com.google.container.v1.LoggingComponentConfig.getDefaultInstance()) return this;
if (!other.enableComponents_.isEmpty()) {
if (enableComponents_.isEmpty()) {
enableComponents_ = other.enableComponents_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureEnableComponentsIsMutable();
enableComponents_.addAll(other.enableComponents_);
}
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 8:
{
int tmpRaw = input.readEnum();
ensureEnableComponentsIsMutable();
enableComponents_.add(tmpRaw);
break;
} // case 8
case 10:
{
int length = input.readRawVarint32();
int oldLimit = input.pushLimit(length);
while (input.getBytesUntilLimit() > 0) {
int tmpRaw = input.readEnum();
ensureEnableComponentsIsMutable();
enableComponents_.add(tmpRaw);
}
input.popLimit(oldLimit);
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<java.lang.Integer> enableComponents_ = java.util.Collections.emptyList();
private void ensureEnableComponentsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
enableComponents_ = new java.util.ArrayList<java.lang.Integer>(enableComponents_);
bitField0_ |= 0x00000001;
}
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @return A list containing the enableComponents.
*/
public java.util.List<com.google.container.v1.LoggingComponentConfig.Component>
getEnableComponentsList() {
return new com.google.protobuf.Internal.ListAdapter<
java.lang.Integer, com.google.container.v1.LoggingComponentConfig.Component>(
enableComponents_, enableComponents_converter_);
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @return The count of enableComponents.
*/
public int getEnableComponentsCount() {
return enableComponents_.size();
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @param index The index of the element to return.
* @return The enableComponents at the given index.
*/
public com.google.container.v1.LoggingComponentConfig.Component getEnableComponents(int index) {
return enableComponents_converter_.convert(enableComponents_.get(index));
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @param index The index to set the value at.
* @param value The enableComponents to set.
* @return This builder for chaining.
*/
public Builder setEnableComponents(
int index, com.google.container.v1.LoggingComponentConfig.Component value) {
if (value == null) {
throw new NullPointerException();
}
ensureEnableComponentsIsMutable();
enableComponents_.set(index, value.getNumber());
onChanged();
return this;
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @param value The enableComponents to add.
* @return This builder for chaining.
*/
public Builder addEnableComponents(
com.google.container.v1.LoggingComponentConfig.Component value) {
if (value == null) {
throw new NullPointerException();
}
ensureEnableComponentsIsMutable();
enableComponents_.add(value.getNumber());
onChanged();
return this;
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @param values The enableComponents to add.
* @return This builder for chaining.
*/
public Builder addAllEnableComponents(
java.lang.Iterable<? extends com.google.container.v1.LoggingComponentConfig.Component>
values) {
ensureEnableComponentsIsMutable();
for (com.google.container.v1.LoggingComponentConfig.Component value : values) {
enableComponents_.add(value.getNumber());
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @return This builder for chaining.
*/
public Builder clearEnableComponents() {
enableComponents_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @return A list containing the enum numeric values on the wire for enableComponents.
*/
public java.util.List<java.lang.Integer> getEnableComponentsValueList() {
return java.util.Collections.unmodifiableList(enableComponents_);
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @param index The index of the value to return.
* @return The enum numeric value on the wire of enableComponents at the given index.
*/
public int getEnableComponentsValue(int index) {
return enableComponents_.get(index);
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @param index The index to set the value at.
* @param value The enum numeric value on the wire for enableComponents to set.
* @return This builder for chaining.
*/
public Builder setEnableComponentsValue(int index, int value) {
ensureEnableComponentsIsMutable();
enableComponents_.set(index, value);
onChanged();
return this;
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @param value The enum numeric value on the wire for enableComponents to add.
* @return This builder for chaining.
*/
public Builder addEnableComponentsValue(int value) {
ensureEnableComponentsIsMutable();
enableComponents_.add(value);
onChanged();
return this;
}
/**
*
*
* <pre>
* Select components to collect logs. An empty set would disable all logging.
* </pre>
*
* <code>repeated .google.container.v1.LoggingComponentConfig.Component enable_components = 1;
* </code>
*
* @param values The enum numeric values on the wire for enableComponents to add.
* @return This builder for chaining.
*/
public Builder addAllEnableComponentsValue(java.lang.Iterable<java.lang.Integer> values) {
ensureEnableComponentsIsMutable();
for (int value : values) {
enableComponents_.add(value);
}
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.container.v1.LoggingComponentConfig)
}
// @@protoc_insertion_point(class_scope:google.container.v1.LoggingComponentConfig)
private static final com.google.container.v1.LoggingComponentConfig DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.container.v1.LoggingComponentConfig();
}
public static com.google.container.v1.LoggingComponentConfig getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<LoggingComponentConfig> PARSER =
new com.google.protobuf.AbstractParser<LoggingComponentConfig>() {
@java.lang.Override
public LoggingComponentConfig 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<LoggingComponentConfig> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<LoggingComponentConfig> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.container.v1.LoggingComponentConfig getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/logging-log4j1 | 35,267 | src/main/java/org/apache/log4j/PropertyConfigurator.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.
*/
// Contibutors: "Luke Blanshard" <Luke@quiq.com>
// "Mark DONSZELMANN" <Mark.Donszelmann@cern.ch>
// Anders Kristensen <akristensen@dynamicsoft.com>
package org.apache.log4j;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.Iterator;
import java.util.Map;
import org.apache.log4j.config.PropertySetter;
import org.apache.log4j.helpers.FileWatchdog;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.or.RendererMap;
import org.apache.log4j.spi.Configurator;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggerFactory;
import org.apache.log4j.spi.LoggerRepository;
import org.apache.log4j.spi.OptionHandler;
import org.apache.log4j.spi.RendererSupport;
import org.apache.log4j.spi.ThrowableRenderer;
import org.apache.log4j.spi.ThrowableRendererSupport;
import org.apache.log4j.spi.ErrorHandler;
/**
Allows the configuration of log4j from an external file. See
<b>{@link #doConfigure(String, LoggerRepository)}</b> for the
expected format.
<p>It is sometimes useful to see how log4j is reading configuration
files. You can enable log4j internal logging by defining the
<b>log4j.debug</b> variable.
<P>As of log4j version 0.8.5, at class initialization time class,
the file <b>log4j.properties</b> will be searched from the search
path used to load classes. If the file can be found, then it will
be fed to the {@link PropertyConfigurator#configure(java.net.URL)}
method.
<p>The <code>PropertyConfigurator</code> does not handle the
advanced configuration features supported by the {@link
org.apache.log4j.xml.DOMConfigurator DOMConfigurator} such as
support custom {@link org.apache.log4j.spi.ErrorHandler ErrorHandlers},
nested appenders such as the {@link org.apache.log4j.AsyncAppender
AsyncAppender}, etc.
<p>All option <em>values</em> admit variable substitution. The
syntax of variable substitution is similar to that of Unix
shells. The string between an opening <b>"${"</b> and
closing <b>"}"</b> is interpreted as a key. The value of
the substituted variable can be defined as a system property or in
the configuration file itself. The value of the key is first
searched in the system properties, and if not found there, it is
then searched in the configuration file being parsed. The
corresponding value replaces the ${variableName} sequence. For
example, if <code>java.home</code> system property is set to
<code>/home/xyz</code>, then every occurrence of the sequence
<code>${java.home}</code> will be interpreted as
<code>/home/xyz</code>.
@author Ceki Gülcü
@author Anders Kristensen
@since 0.8.1 */
public class PropertyConfigurator implements Configurator {
/**
Used internally to keep track of configured appenders.
*/
protected Hashtable registry = new Hashtable(11);
private LoggerRepository repository;
protected LoggerFactory loggerFactory = new DefaultCategoryFactory();
static final String CATEGORY_PREFIX = "log4j.category.";
static final String LOGGER_PREFIX = "log4j.logger.";
static final String FACTORY_PREFIX = "log4j.factory";
static final String ADDITIVITY_PREFIX = "log4j.additivity.";
static final String ROOT_CATEGORY_PREFIX = "log4j.rootCategory";
static final String ROOT_LOGGER_PREFIX = "log4j.rootLogger";
static final String APPENDER_PREFIX = "log4j.appender.";
static final String RENDERER_PREFIX = "log4j.renderer.";
static final String THRESHOLD_PREFIX = "log4j.threshold";
private static final String THROWABLE_RENDERER_PREFIX = "log4j.throwableRenderer";
private static final String LOGGER_REF = "logger-ref";
private static final String ROOT_REF = "root-ref";
private static final String APPENDER_REF_TAG = "appender-ref";
/** Key for specifying the {@link org.apache.log4j.spi.LoggerFactory
LoggerFactory}. Currently set to "<code>log4j.loggerFactory</code>". */
public static final String LOGGER_FACTORY_KEY = "log4j.loggerFactory";
/**
* If property set to true, then hierarchy will be reset before configuration.
*/
private static final String RESET_KEY = "log4j.reset";
static final private String INTERNAL_ROOT_NAME = "root";
/**
Read configuration from a file. <b>The existing configuration is
not cleared nor reset.</b> If you require a different behavior,
then call {@link LogManager#resetConfiguration
resetConfiguration} method before calling
<code>doConfigure</code>.
<p>The configuration file consists of statements in the format
<code>key=value</code>. The syntax of different configuration
elements are discussed below.
<h3>Repository-wide threshold</h3>
<p>The repository-wide threshold filters logging requests by level
regardless of logger. The syntax is:
<pre>
log4j.threshold=[level]
</pre>
<p>The level value can consist of the string values OFF, FATAL,
ERROR, WARN, INFO, DEBUG, ALL or a <em>custom level</em> value. A
custom level value can be specified in the form
level#classname. By default the repository-wide threshold is set
to the lowest possible value, namely the level <code>ALL</code>.
</p>
<h3>Appender configuration</h3>
<p>Appender configuration syntax is:
<pre>
# For appender named <i>appenderName</i>, set its class.
# Note: The appender name can contain dots.
log4j.appender.appenderName=fully.qualified.name.of.appender.class
# Set appender specific options.
log4j.appender.appenderName.option1=value1
...
log4j.appender.appenderName.optionN=valueN
</pre>
For each named appender you can configure its {@link Layout}. The
syntax for configuring an appender's layout is:
<pre>
log4j.appender.appenderName.layout=fully.qualified.name.of.layout.class
log4j.appender.appenderName.layout.option1=value1
....
log4j.appender.appenderName.layout.optionN=valueN
</pre>
The syntax for adding {@link Filter}s to an appender is:
<pre>
log4j.appender.appenderName.filter.ID=fully.qualified.name.of.filter.class
log4j.appender.appenderName.filter.ID.option1=value1
...
log4j.appender.appenderName.filter.ID.optionN=valueN
</pre>
The first line defines the class name of the filter identified by ID;
subsequent lines with the same ID specify filter option - value
paris. Multiple filters are added to the appender in the lexicographic
order of IDs.
The syntax for adding an {@link ErrorHandler} to an appender is:
<pre>
log4j.appender.appenderName.errorhandler=fully.qualified.name.of.filter.class
log4j.appender.appenderName.errorhandler.root-ref={true|false}
log4j.appender.appenderName.errorhandler.logger-ref=loggerName
log4j.appender.appenderName.errorhandler.appender-ref=appenderName
log4j.appender.appenderName.errorhandler.option1=value1
...
log4j.appender.appenderName.errorhandler.optionN=valueN
</pre>
<h3>Configuring loggers</h3>
<p>The syntax for configuring the root logger is:
<pre>
log4j.rootLogger=[level], appenderName, appenderName, ...
</pre>
<p>This syntax means that an optional <em>level</em> can be
supplied followed by appender names separated by commas.
<p>The level value can consist of the string values OFF, FATAL,
ERROR, WARN, INFO, DEBUG, ALL or a <em>custom level</em> value. A
custom level value can be specified in the form
<code>level#classname</code>.
<p>If a level value is specified, then the root level is set
to the corresponding level. If no level value is specified,
then the root level remains untouched.
<p>The root logger can be assigned multiple appenders.
<p>Each <i>appenderName</i> (separated by commas) will be added to
the root logger. The named appender is defined using the
appender syntax defined above.
<p>For non-root categories the syntax is almost the same:
<pre>
log4j.logger.logger_name=[level|INHERITED|NULL], appenderName, appenderName, ...
</pre>
<p>The meaning of the optional level value is discussed above
in relation to the root logger. In addition however, the value
INHERITED can be specified meaning that the named logger should
inherit its level from the logger hierarchy.
<p>If no level value is supplied, then the level of the
named logger remains untouched.
<p>By default categories inherit their level from the
hierarchy. However, if you set the level of a logger and later
decide that that logger should inherit its level, then you should
specify INHERITED as the value for the level value. NULL is a
synonym for INHERITED.
<p>Similar to the root logger syntax, each <i>appenderName</i>
(separated by commas) will be attached to the named logger.
<p>See the <a href="../../../../manual.html#additivity">appender
additivity rule</a> in the user manual for the meaning of the
<code>additivity</code> flag.
<h3>ObjectRenderers</h3>
You can customize the way message objects of a given type are
converted to String before being logged. This is done by
specifying an {@link org.apache.log4j.or.ObjectRenderer ObjectRenderer}
for the object type would like to customize.
<p>The syntax is:
<pre>
log4j.renderer.fully.qualified.name.of.rendered.class=fully.qualified.name.of.rendering.class
</pre>
As in,
<pre>
log4j.renderer.my.Fruit=my.FruitRenderer
</pre>
<h3>ThrowableRenderer</h3>
You can customize the way an instance of Throwable is
converted to String before being logged. This is done by
specifying an {@link org.apache.log4j.spi.ThrowableRenderer ThrowableRenderer}.
<p>The syntax is:
<pre>
log4j.throwableRenderer=fully.qualified.name.of.rendering.class
log4j.throwableRenderer.paramName=paramValue
</pre>
As in,
<pre>
log4j.throwableRenderer=org.apache.log4j.EnhancedThrowableRenderer
</pre>
<h3>Logger Factories</h3>
The usage of custom logger factories is discouraged and no longer
documented.
<h3>Resetting Hierarchy</h3>
The hierarchy will be reset before configuration when
log4j.reset=true is present in the properties file.
<h3>Example</h3>
<p>An example configuration is given below. Other configuration
file examples are given in the <code>examples</code> folder.
<pre>
# Set options for appender named "A1".
# Appender "A1" will be a SyslogAppender
log4j.appender.A1=org.apache.log4j.net.SyslogAppender
# The syslog daemon resides on www.abc.net
log4j.appender.A1.SyslogHost=www.abc.net
# A1's layout is a PatternLayout, using the conversion pattern
# <b>%r %-5p %c{2} %M.%L %x - %m\n</b>. Thus, the log output will
# include # the relative time since the start of the application in
# milliseconds, followed by the level of the log request,
# followed by the two rightmost components of the logger name,
# followed by the callers method name, followed by the line number,
# the nested disgnostic context and finally the message itself.
# Refer to the documentation of {@link PatternLayout} for further information
# on the syntax of the ConversionPattern key.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c{2} %M.%L %x - %m\n
# Set options for appender named "A2"
# A2 should be a RollingFileAppender, with maximum file size of 10 MB
# using at most one backup file. A2's layout is TTCC, using the
# ISO8061 date format with context printing enabled.
log4j.appender.A2=org.apache.log4j.RollingFileAppender
log4j.appender.A2.MaxFileSize=10MB
log4j.appender.A2.MaxBackupIndex=1
log4j.appender.A2.layout=org.apache.log4j.TTCCLayout
log4j.appender.A2.layout.ContextPrinting=enabled
log4j.appender.A2.layout.DateFormat=ISO8601
# Root logger set to DEBUG using the A2 appender defined above.
log4j.rootLogger=DEBUG, A2
# Logger definitions:
# The SECURITY logger inherits is level from root. However, it's output
# will go to A1 appender defined above. It's additivity is non-cumulative.
log4j.logger.SECURITY=INHERIT, A1
log4j.additivity.SECURITY=false
# Only warnings or above will be logged for the logger "SECURITY.access".
# Output will go to A1.
log4j.logger.SECURITY.access=WARN
# The logger "class.of.the.day" inherits its level from the
# logger hierarchy. Output will go to the appender's of the root
# logger, A2 in this case.
log4j.logger.class.of.the.day=INHERIT
</pre>
<p>Refer to the <b>setOption</b> method in each Appender and
Layout for class specific options.
<p>Use the <code>#</code> or <code>!</code> characters at the
beginning of a line for comments.
<p>
@param configFileName The name of the configuration file where the
configuration information is stored.
*/
public
void doConfigure(String configFileName, LoggerRepository hierarchy) {
Properties props = new Properties();
FileInputStream istream = null;
try {
istream = new FileInputStream(configFileName);
props.load(istream);
istream.close();
}
catch (Exception e) {
if (e instanceof InterruptedIOException || e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
LogLog.error("Could not read configuration file ["+configFileName+"].", e);
LogLog.error("Ignoring configuration file [" + configFileName+"].");
return;
} finally {
if(istream != null) {
try {
istream.close();
} catch(InterruptedIOException ignore) {
Thread.currentThread().interrupt();
} catch(Throwable ignore) {
}
}
}
// If we reach here, then the config file is alright.
doConfigure(props, hierarchy);
}
/**
*/
static
public
void configure(String configFilename) {
new PropertyConfigurator().doConfigure(configFilename,
LogManager.getLoggerRepository());
}
/**
Read configuration options from url <code>configURL</code>.
@since 0.8.2
*/
public
static
void configure(java.net.URL configURL) {
new PropertyConfigurator().doConfigure(configURL,
LogManager.getLoggerRepository());
}
/**
Reads configuration options from an InputStream.
@since 1.2.17
*/
public
static
void configure(InputStream inputStream) {
new PropertyConfigurator().doConfigure(inputStream,
LogManager.getLoggerRepository());
}
/**
Read configuration options from <code>properties</code>.
See {@link #doConfigure(String, LoggerRepository)} for the expected format.
*/
static
public
void configure(Properties properties) {
new PropertyConfigurator().doConfigure(properties,
LogManager.getLoggerRepository());
}
/**
Like {@link #configureAndWatch(String, long)} except that the
default delay as defined by {@link FileWatchdog#DEFAULT_DELAY} is
used.
@param configFilename A file in key=value format.
*/
static
public
void configureAndWatch(String configFilename) {
configureAndWatch(configFilename, FileWatchdog.DEFAULT_DELAY);
}
/**
Read the configuration file <code>configFilename</code> if it
exists. Moreover, a thread will be created that will periodically
check if <code>configFilename</code> has been created or
modified. The period is determined by the <code>delay</code>
argument. If a change or file creation is detected, then
<code>configFilename</code> is read to configure log4j.
@param configFilename A file in key=value format.
@param delay The delay in milliseconds to wait between each check.
*/
static
public
void configureAndWatch(String configFilename, long delay) {
PropertyWatchdog pdog = new PropertyWatchdog(configFilename);
pdog.setDelay(delay);
pdog.start();
}
/**
Read configuration options from <code>properties</code>.
See {@link #doConfigure(String, LoggerRepository)} for the expected format.
*/
public
void doConfigure(Properties properties, LoggerRepository hierarchy) {
repository = hierarchy;
String value = properties.getProperty(LogLog.DEBUG_KEY);
if(value == null) {
value = properties.getProperty("log4j.configDebug");
if(value != null)
LogLog.warn("[log4j.configDebug] is deprecated. Use [log4j.debug] instead.");
}
if(value != null) {
LogLog.setInternalDebugging(OptionConverter.toBoolean(value, true));
}
//
// if log4j.reset=true then
// reset hierarchy
String reset = properties.getProperty(RESET_KEY);
if (reset != null && OptionConverter.toBoolean(reset, false)) {
hierarchy.resetConfiguration();
}
String thresholdStr = OptionConverter.findAndSubst(THRESHOLD_PREFIX,
properties);
if(thresholdStr != null) {
hierarchy.setThreshold(OptionConverter.toLevel(thresholdStr,
(Level) Level.ALL));
LogLog.debug("Hierarchy threshold set to ["+hierarchy.getThreshold()+"].");
}
configureRootCategory(properties, hierarchy);
configureLoggerFactory(properties);
parseCatsAndRenderers(properties, hierarchy);
LogLog.debug("Finished configuring.");
// We don't want to hold references to appenders preventing their
// garbage collection.
registry.clear();
}
/**
* Read configuration options from url <code>configURL</code>.
*
* @since 1.2.17
*/
public void doConfigure(InputStream inputStream, LoggerRepository hierarchy) {
Properties props = new Properties();
try {
props.load(inputStream);
} catch (IOException e) {
if (e instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
LogLog.error("Could not read configuration file from InputStream [" + inputStream
+ "].", e);
LogLog.error("Ignoring configuration InputStream [" + inputStream +"].");
return;
}
this.doConfigure(props, hierarchy);
}
/**
Read configuration options from url <code>configURL</code>.
*/
public
void doConfigure(java.net.URL configURL, LoggerRepository hierarchy) {
Properties props = new Properties();
LogLog.debug("Reading configuration from URL " + configURL);
InputStream istream = null;
URLConnection uConn = null;
try {
uConn = configURL.openConnection();
uConn.setUseCaches(false);
istream = uConn.getInputStream();
props.load(istream);
}
catch (Exception e) {
if (e instanceof InterruptedIOException || e instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
LogLog.error("Could not read configuration file from URL [" + configURL
+ "].", e);
LogLog.error("Ignoring configuration file [" + configURL +"].");
return;
}
finally {
if (istream != null) {
try {
istream.close();
} catch(InterruptedIOException ignore) {
Thread.currentThread().interrupt();
} catch(IOException ignore) {
} catch(RuntimeException ignore) {
}
}
}
doConfigure(props, hierarchy);
}
// --------------------------------------------------------------------------
// Internal stuff
// --------------------------------------------------------------------------
/**
Check the provided <code>Properties</code> object for a
{@link org.apache.log4j.spi.LoggerFactory LoggerFactory}
entry specified by {@link #LOGGER_FACTORY_KEY}. If such an entry
exists, an attempt is made to create an instance using the default
constructor. This instance is used for subsequent Category creations
within this configurator.
@see #parseCatsAndRenderers
*/
protected void configureLoggerFactory(Properties props) {
String factoryClassName = OptionConverter.findAndSubst(LOGGER_FACTORY_KEY,
props);
if(factoryClassName != null) {
LogLog.debug("Setting category factory to ["+factoryClassName+"].");
loggerFactory = (LoggerFactory)
OptionConverter.instantiateByClassName(factoryClassName,
LoggerFactory.class,
loggerFactory);
PropertySetter.setProperties(loggerFactory, props, FACTORY_PREFIX + ".");
}
}
/*
void configureOptionHandler(OptionHandler oh, String prefix,
Properties props) {
String[] options = oh.getOptionStrings();
if(options == null)
return;
String value;
for(int i = 0; i < options.length; i++) {
value = OptionConverter.findAndSubst(prefix + options[i], props);
LogLog.debug(
"Option " + options[i] + "=[" + (value == null? "N/A" : value)+"].");
// Some option handlers assume that null value are not passed to them.
// So don't remove this check
if(value != null) {
oh.setOption(options[i], value);
}
}
oh.activateOptions();
}
*/
void configureRootCategory(Properties props, LoggerRepository hierarchy) {
String effectiveFrefix = ROOT_LOGGER_PREFIX;
String value = OptionConverter.findAndSubst(ROOT_LOGGER_PREFIX, props);
if(value == null) {
value = OptionConverter.findAndSubst(ROOT_CATEGORY_PREFIX, props);
effectiveFrefix = ROOT_CATEGORY_PREFIX;
}
if(value == null)
LogLog.debug("Could not find root logger information. Is this OK?");
else {
Logger root = hierarchy.getRootLogger();
synchronized(root) {
parseCategory(props, root, effectiveFrefix, INTERNAL_ROOT_NAME, value);
}
}
}
/**
Parse non-root elements, such non-root categories and renderers.
*/
protected
void parseCatsAndRenderers(Properties props, LoggerRepository hierarchy) {
Enumeration enumeration = props.propertyNames();
while(enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
if(key.startsWith(CATEGORY_PREFIX) || key.startsWith(LOGGER_PREFIX)) {
String loggerName = null;
if(key.startsWith(CATEGORY_PREFIX)) {
loggerName = key.substring(CATEGORY_PREFIX.length());
} else if(key.startsWith(LOGGER_PREFIX)) {
loggerName = key.substring(LOGGER_PREFIX.length());
}
String value = OptionConverter.findAndSubst(key, props);
Logger logger = hierarchy.getLogger(loggerName, loggerFactory);
synchronized(logger) {
parseCategory(props, logger, key, loggerName, value);
parseAdditivityForLogger(props, logger, loggerName);
}
} else if(key.startsWith(RENDERER_PREFIX)) {
String renderedClass = key.substring(RENDERER_PREFIX.length());
String renderingClass = OptionConverter.findAndSubst(key, props);
if(hierarchy instanceof RendererSupport) {
RendererMap.addRenderer((RendererSupport) hierarchy, renderedClass,
renderingClass);
}
} else if (key.equals(THROWABLE_RENDERER_PREFIX)) {
if (hierarchy instanceof ThrowableRendererSupport) {
ThrowableRenderer tr = (ThrowableRenderer)
OptionConverter.instantiateByKey(props,
THROWABLE_RENDERER_PREFIX,
org.apache.log4j.spi.ThrowableRenderer.class,
null);
if(tr == null) {
LogLog.error(
"Could not instantiate throwableRenderer.");
} else {
PropertySetter setter = new PropertySetter(tr);
setter.setProperties(props, THROWABLE_RENDERER_PREFIX + ".");
((ThrowableRendererSupport) hierarchy).setThrowableRenderer(tr);
}
}
}
}
}
/**
Parse the additivity option for a non-root category.
*/
void parseAdditivityForLogger(Properties props, Logger cat,
String loggerName) {
String value = OptionConverter.findAndSubst(ADDITIVITY_PREFIX + loggerName,
props);
LogLog.debug("Handling "+ADDITIVITY_PREFIX + loggerName+"=["+value+"]");
// touch additivity only if necessary
if((value != null) && (!value.equals(""))) {
boolean additivity = OptionConverter.toBoolean(value, true);
LogLog.debug("Setting additivity for \""+loggerName+"\" to "+
additivity);
cat.setAdditivity(additivity);
}
}
/**
This method must work for the root category as well.
*/
void parseCategory(Properties props, Logger logger, String optionKey,
String loggerName, String value) {
LogLog.debug("Parsing for [" +loggerName +"] with value=[" + value+"].");
// We must skip over ',' but not white space
StringTokenizer st = new StringTokenizer(value, ",");
// If value is not in the form ", appender.." or "", then we should set
// the level of the loggeregory.
if(!(value.startsWith(",") || value.equals(""))) {
// just to be on the safe side...
if(!st.hasMoreTokens())
return;
String levelStr = st.nextToken();
LogLog.debug("Level token is [" + levelStr + "].");
// If the level value is inherited, set category level value to
// null. We also check that the user has not specified inherited for the
// root category.
if(INHERITED.equalsIgnoreCase(levelStr) ||
NULL.equalsIgnoreCase(levelStr)) {
if(loggerName.equals(INTERNAL_ROOT_NAME)) {
LogLog.warn("The root logger cannot be set to null.");
} else {
logger.setLevel(null);
}
} else {
logger.setLevel(OptionConverter.toLevel(levelStr, (Level) Level.DEBUG));
}
LogLog.debug("Category " + loggerName + " set to " + logger.getLevel());
}
// Begin by removing all existing appenders.
logger.removeAllAppenders();
Appender appender;
String appenderName;
while(st.hasMoreTokens()) {
appenderName = st.nextToken().trim();
if(appenderName == null || appenderName.equals(","))
continue;
LogLog.debug("Parsing appender named \"" + appenderName +"\".");
appender = parseAppender(props, appenderName);
if(appender != null) {
logger.addAppender(appender);
}
}
}
Appender parseAppender(Properties props, String appenderName) {
Appender appender = registryGet(appenderName);
if((appender != null)) {
LogLog.debug("Appender \"" + appenderName + "\" was already parsed.");
return appender;
}
// Appender was not previously initialized.
String prefix = APPENDER_PREFIX + appenderName;
String layoutPrefix = prefix + ".layout";
appender = (Appender) OptionConverter.instantiateByKey(props, prefix,
org.apache.log4j.Appender.class,
null);
if(appender == null) {
LogLog.error(
"Could not instantiate appender named \"" + appenderName+"\".");
return null;
}
appender.setName(appenderName);
if(appender instanceof OptionHandler) {
if(appender.requiresLayout()) {
Layout layout = (Layout) OptionConverter.instantiateByKey(props,
layoutPrefix,
Layout.class,
null);
if(layout != null) {
appender.setLayout(layout);
LogLog.debug("Parsing layout options for \"" + appenderName +"\".");
//configureOptionHandler(layout, layoutPrefix + ".", props);
PropertySetter.setProperties(layout, props, layoutPrefix + ".");
LogLog.debug("End of parsing for \"" + appenderName +"\".");
}
}
final String errorHandlerPrefix = prefix + ".errorhandler";
String errorHandlerClass = OptionConverter.findAndSubst(errorHandlerPrefix, props);
if (errorHandlerClass != null) {
ErrorHandler eh = (ErrorHandler) OptionConverter.instantiateByKey(props,
errorHandlerPrefix,
ErrorHandler.class,
null);
if (eh != null) {
appender.setErrorHandler(eh);
LogLog.debug("Parsing errorhandler options for \"" + appenderName +"\".");
parseErrorHandler(eh, errorHandlerPrefix, props, repository);
final Properties edited = new Properties();
final String[] keys = new String[] {
errorHandlerPrefix + "." + ROOT_REF,
errorHandlerPrefix + "." + LOGGER_REF,
errorHandlerPrefix + "." + APPENDER_REF_TAG
};
for(Iterator iter = props.entrySet().iterator();iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
int i = 0;
for(; i < keys.length; i++) {
if(keys[i].equals(entry.getKey())) break;
}
if (i == keys.length) {
edited.put(entry.getKey(), entry.getValue());
}
}
PropertySetter.setProperties(eh, edited, errorHandlerPrefix + ".");
LogLog.debug("End of errorhandler parsing for \"" + appenderName +"\".");
}
}
//configureOptionHandler((OptionHandler) appender, prefix + ".", props);
PropertySetter.setProperties(appender, props, prefix + ".");
LogLog.debug("Parsed \"" + appenderName +"\" options.");
}
parseAppenderFilters(props, appenderName, appender);
registryPut(appender);
return appender;
}
private void parseErrorHandler(
final ErrorHandler eh,
final String errorHandlerPrefix,
final Properties props,
final LoggerRepository hierarchy) {
boolean rootRef = OptionConverter.toBoolean(
OptionConverter.findAndSubst(errorHandlerPrefix + ROOT_REF, props), false);
if (rootRef) {
eh.setLogger(hierarchy.getRootLogger());
}
String loggerName = OptionConverter.findAndSubst(errorHandlerPrefix + LOGGER_REF , props);
if (loggerName != null) {
Logger logger = (loggerFactory == null) ? hierarchy.getLogger(loggerName)
: hierarchy.getLogger(loggerName, loggerFactory);
eh.setLogger(logger);
}
String appenderName = OptionConverter.findAndSubst(errorHandlerPrefix + APPENDER_REF_TAG, props);
if (appenderName != null) {
Appender backup = parseAppender(props, appenderName);
if (backup != null) {
eh.setBackupAppender(backup);
}
}
}
void parseAppenderFilters(Properties props, String appenderName, Appender appender) {
// extract filters and filter options from props into a hashtable mapping
// the property name defining the filter class to a list of pre-parsed
// name-value pairs associated to that filter
final String filterPrefix = APPENDER_PREFIX + appenderName + ".filter.";
int fIdx = filterPrefix.length();
Hashtable filters = new Hashtable();
Enumeration e = props.keys();
String name = "";
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
if (key.startsWith(filterPrefix)) {
int dotIdx = key.indexOf('.', fIdx);
String filterKey = key;
if (dotIdx != -1) {
filterKey = key.substring(0, dotIdx);
name = key.substring(dotIdx+1);
}
Vector filterOpts = (Vector) filters.get(filterKey);
if (filterOpts == null) {
filterOpts = new Vector();
filters.put(filterKey, filterOpts);
}
if (dotIdx != -1) {
String value = OptionConverter.findAndSubst(key, props);
filterOpts.add(new NameValue(name, value));
}
}
}
// sort filters by IDs, insantiate filters, set filter options,
// add filters to the appender
Enumeration g = new SortedKeyEnumeration(filters);
while (g.hasMoreElements()) {
String key = (String) g.nextElement();
String clazz = props.getProperty(key);
if (clazz != null) {
LogLog.debug("Filter key: ["+key+"] class: ["+props.getProperty(key) +"] props: "+filters.get(key));
Filter filter = (Filter) OptionConverter.instantiateByClassName(clazz, Filter.class, null);
if (filter != null) {
PropertySetter propSetter = new PropertySetter(filter);
Vector v = (Vector)filters.get(key);
Enumeration filterProps = v.elements();
while (filterProps.hasMoreElements()) {
NameValue kv = (NameValue)filterProps.nextElement();
propSetter.setProperty(kv.key, kv.value);
}
propSetter.activate();
LogLog.debug("Adding filter of type ["+filter.getClass()
+"] to appender named ["+appender.getName()+"].");
appender.addFilter(filter);
}
} else {
LogLog.warn("Missing class definition for filter: ["+key+"]");
}
}
}
void registryPut(Appender appender) {
registry.put(appender.getName(), appender);
}
Appender registryGet(String name) {
return (Appender) registry.get(name);
}
}
class PropertyWatchdog extends FileWatchdog {
PropertyWatchdog(String filename) {
super(filename);
}
/**
Call {@link PropertyConfigurator#configure(String)} with the
<code>filename</code> to reconfigure log4j. */
public
void doOnChange() {
new PropertyConfigurator().doConfigure(filename,
LogManager.getLoggerRepository());
}
}
class NameValue {
String key, value;
public NameValue(String key, String value) {
this.key = key;
this.value = value;
}
public String toString() {
return key + "=" + value;
}
}
class SortedKeyEnumeration implements Enumeration {
private Enumeration e;
public SortedKeyEnumeration(Hashtable ht) {
Enumeration f = ht.keys();
Vector keys = new Vector(ht.size());
for (int i, last = 0; f.hasMoreElements(); ++last) {
String key = (String) f.nextElement();
for (i = 0; i < last; ++i) {
String s = (String) keys.get(i);
if (key.compareTo(s) <= 0) break;
}
keys.add(i, key);
}
e = keys.elements();
}
public boolean hasMoreElements() {
return e.hasMoreElements();
}
public Object nextElement() {
return e.nextElement();
}
}
|
googleads/google-ads-java | 35,767 | google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/MutateAccountLinkRequest.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v19/services/account_link_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v19.services;
/**
* <pre>
* Request message for
* [AccountLinkService.MutateAccountLink][google.ads.googleads.v19.services.AccountLinkService.MutateAccountLink].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.services.MutateAccountLinkRequest}
*/
public final class MutateAccountLinkRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v19.services.MutateAccountLinkRequest)
MutateAccountLinkRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use MutateAccountLinkRequest.newBuilder() to construct.
private MutateAccountLinkRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MutateAccountLinkRequest() {
customerId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new MutateAccountLinkRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v19_services_MutateAccountLinkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v19_services_MutateAccountLinkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.services.MutateAccountLinkRequest.class, com.google.ads.googleads.v19.services.MutateAccountLinkRequest.Builder.class);
}
private int bitField0_;
public static final int CUSTOMER_ID_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
@java.lang.Override
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
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();
customerId_ = s;
return s;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int OPERATION_FIELD_NUMBER = 2;
private com.google.ads.googleads.v19.services.AccountLinkOperation operation_;
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v19.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
@java.lang.Override
public boolean hasOperation() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v19.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
@java.lang.Override
public com.google.ads.googleads.v19.services.AccountLinkOperation getOperation() {
return operation_ == null ? com.google.ads.googleads.v19.services.AccountLinkOperation.getDefaultInstance() : operation_;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v19.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v19.services.AccountLinkOperationOrBuilder getOperationOrBuilder() {
return operation_ == null ? com.google.ads.googleads.v19.services.AccountLinkOperation.getDefaultInstance() : operation_;
}
public static final int PARTIAL_FAILURE_FIELD_NUMBER = 3;
private boolean partialFailure_ = false;
/**
* <pre>
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @return The partialFailure.
*/
@java.lang.Override
public boolean getPartialFailure() {
return partialFailure_;
}
public static final int VALIDATE_ONLY_FIELD_NUMBER = 4;
private boolean validateOnly_ = false;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getOperation());
}
if (partialFailure_ != false) {
output.writeBool(3, partialFailure_);
}
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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getOperation());
}
if (partialFailure_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(3, partialFailure_);
}
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.ads.googleads.v19.services.MutateAccountLinkRequest)) {
return super.equals(obj);
}
com.google.ads.googleads.v19.services.MutateAccountLinkRequest other = (com.google.ads.googleads.v19.services.MutateAccountLinkRequest) obj;
if (!getCustomerId()
.equals(other.getCustomerId())) return false;
if (hasOperation() != other.hasOperation()) return false;
if (hasOperation()) {
if (!getOperation()
.equals(other.getOperation())) return false;
}
if (getPartialFailure()
!= other.getPartialFailure()) 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();
hash = (37 * hash) + CUSTOMER_ID_FIELD_NUMBER;
hash = (53 * hash) + getCustomerId().hashCode();
if (hasOperation()) {
hash = (37 * hash) + OPERATION_FIELD_NUMBER;
hash = (53 * hash) + getOperation().hashCode();
}
hash = (37 * hash) + PARTIAL_FAILURE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getPartialFailure());
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.ads.googleads.v19.services.MutateAccountLinkRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.MutateAccountLinkRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.MutateAccountLinkRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.MutateAccountLinkRequest 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.ads.googleads.v19.services.MutateAccountLinkRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.MutateAccountLinkRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.MutateAccountLinkRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.MutateAccountLinkRequest 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.ads.googleads.v19.services.MutateAccountLinkRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.MutateAccountLinkRequest 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.ads.googleads.v19.services.MutateAccountLinkRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.MutateAccountLinkRequest 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.ads.googleads.v19.services.MutateAccountLinkRequest 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
* [AccountLinkService.MutateAccountLink][google.ads.googleads.v19.services.AccountLinkService.MutateAccountLink].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.services.MutateAccountLinkRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.services.MutateAccountLinkRequest)
com.google.ads.googleads.v19.services.MutateAccountLinkRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v19_services_MutateAccountLinkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v19_services_MutateAccountLinkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.services.MutateAccountLinkRequest.class, com.google.ads.googleads.v19.services.MutateAccountLinkRequest.Builder.class);
}
// Construct using com.google.ads.googleads.v19.services.MutateAccountLinkRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getOperationFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
customerId_ = "";
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
partialFailure_ = false;
validateOnly_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v19.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v19_services_MutateAccountLinkRequest_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.MutateAccountLinkRequest getDefaultInstanceForType() {
return com.google.ads.googleads.v19.services.MutateAccountLinkRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v19.services.MutateAccountLinkRequest build() {
com.google.ads.googleads.v19.services.MutateAccountLinkRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.MutateAccountLinkRequest buildPartial() {
com.google.ads.googleads.v19.services.MutateAccountLinkRequest result = new com.google.ads.googleads.v19.services.MutateAccountLinkRequest(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v19.services.MutateAccountLinkRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.customerId_ = customerId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.operation_ = operationBuilder_ == null
? operation_
: operationBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.partialFailure_ = partialFailure_;
}
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.ads.googleads.v19.services.MutateAccountLinkRequest) {
return mergeFrom((com.google.ads.googleads.v19.services.MutateAccountLinkRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v19.services.MutateAccountLinkRequest other) {
if (other == com.google.ads.googleads.v19.services.MutateAccountLinkRequest.getDefaultInstance()) return this;
if (!other.getCustomerId().isEmpty()) {
customerId_ = other.customerId_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasOperation()) {
mergeOperation(other.getOperation());
}
if (other.getPartialFailure() != false) {
setPartialFailure(other.getPartialFailure());
}
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: {
customerId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18: {
input.readMessage(
getOperationFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 24: {
partialFailure_ = 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 java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerId(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
customerId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return This builder for chaining.
*/
public Builder clearCustomerId() {
customerId_ = getDefaultInstance().getCustomerId();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The bytes for customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
customerId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.ads.googleads.v19.services.AccountLinkOperation operation_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.services.AccountLinkOperation, com.google.ads.googleads.v19.services.AccountLinkOperation.Builder, com.google.ads.googleads.v19.services.AccountLinkOperationOrBuilder> operationBuilder_;
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v19.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
public boolean hasOperation() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v19.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
public com.google.ads.googleads.v19.services.AccountLinkOperation getOperation() {
if (operationBuilder_ == null) {
return operation_ == null ? com.google.ads.googleads.v19.services.AccountLinkOperation.getDefaultInstance() : operation_;
} else {
return operationBuilder_.getMessage();
}
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v19.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperation(com.google.ads.googleads.v19.services.AccountLinkOperation value) {
if (operationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
} else {
operationBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v19.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperation(
com.google.ads.googleads.v19.services.AccountLinkOperation.Builder builderForValue) {
if (operationBuilder_ == null) {
operation_ = builderForValue.build();
} else {
operationBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v19.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder mergeOperation(com.google.ads.googleads.v19.services.AccountLinkOperation value) {
if (operationBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
operation_ != null &&
operation_ != com.google.ads.googleads.v19.services.AccountLinkOperation.getDefaultInstance()) {
getOperationBuilder().mergeFrom(value);
} else {
operation_ = value;
}
} else {
operationBuilder_.mergeFrom(value);
}
if (operation_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v19.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearOperation() {
bitField0_ = (bitField0_ & ~0x00000002);
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v19.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v19.services.AccountLinkOperation.Builder getOperationBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getOperationFieldBuilder().getBuilder();
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v19.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v19.services.AccountLinkOperationOrBuilder getOperationOrBuilder() {
if (operationBuilder_ != null) {
return operationBuilder_.getMessageOrBuilder();
} else {
return operation_ == null ?
com.google.ads.googleads.v19.services.AccountLinkOperation.getDefaultInstance() : operation_;
}
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v19.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.services.AccountLinkOperation, com.google.ads.googleads.v19.services.AccountLinkOperation.Builder, com.google.ads.googleads.v19.services.AccountLinkOperationOrBuilder>
getOperationFieldBuilder() {
if (operationBuilder_ == null) {
operationBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.services.AccountLinkOperation, com.google.ads.googleads.v19.services.AccountLinkOperation.Builder, com.google.ads.googleads.v19.services.AccountLinkOperationOrBuilder>(
getOperation(),
getParentForChildren(),
isClean());
operation_ = null;
}
return operationBuilder_;
}
private boolean partialFailure_ ;
/**
* <pre>
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @return The partialFailure.
*/
@java.lang.Override
public boolean getPartialFailure() {
return partialFailure_;
}
/**
* <pre>
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @param value The partialFailure to set.
* @return This builder for chaining.
*/
public Builder setPartialFailure(boolean value) {
partialFailure_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @return This builder for chaining.
*/
public Builder clearPartialFailure() {
bitField0_ = (bitField0_ & ~0x00000004);
partialFailure_ = false;
onChanged();
return this;
}
private boolean validateOnly_ ;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</code>
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</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>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</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.ads.googleads.v19.services.MutateAccountLinkRequest)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v19.services.MutateAccountLinkRequest)
private static final com.google.ads.googleads.v19.services.MutateAccountLinkRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v19.services.MutateAccountLinkRequest();
}
public static com.google.ads.googleads.v19.services.MutateAccountLinkRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MutateAccountLinkRequest>
PARSER = new com.google.protobuf.AbstractParser<MutateAccountLinkRequest>() {
@java.lang.Override
public MutateAccountLinkRequest 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<MutateAccountLinkRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<MutateAccountLinkRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.MutateAccountLinkRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 35,767 | google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/MutateAccountLinkRequest.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v20/services/account_link_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v20.services;
/**
* <pre>
* Request message for
* [AccountLinkService.MutateAccountLink][google.ads.googleads.v20.services.AccountLinkService.MutateAccountLink].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.services.MutateAccountLinkRequest}
*/
public final class MutateAccountLinkRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v20.services.MutateAccountLinkRequest)
MutateAccountLinkRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use MutateAccountLinkRequest.newBuilder() to construct.
private MutateAccountLinkRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MutateAccountLinkRequest() {
customerId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new MutateAccountLinkRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v20_services_MutateAccountLinkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v20_services_MutateAccountLinkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.services.MutateAccountLinkRequest.class, com.google.ads.googleads.v20.services.MutateAccountLinkRequest.Builder.class);
}
private int bitField0_;
public static final int CUSTOMER_ID_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
@java.lang.Override
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
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();
customerId_ = s;
return s;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int OPERATION_FIELD_NUMBER = 2;
private com.google.ads.googleads.v20.services.AccountLinkOperation operation_;
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v20.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
@java.lang.Override
public boolean hasOperation() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v20.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
@java.lang.Override
public com.google.ads.googleads.v20.services.AccountLinkOperation getOperation() {
return operation_ == null ? com.google.ads.googleads.v20.services.AccountLinkOperation.getDefaultInstance() : operation_;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v20.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v20.services.AccountLinkOperationOrBuilder getOperationOrBuilder() {
return operation_ == null ? com.google.ads.googleads.v20.services.AccountLinkOperation.getDefaultInstance() : operation_;
}
public static final int PARTIAL_FAILURE_FIELD_NUMBER = 3;
private boolean partialFailure_ = false;
/**
* <pre>
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @return The partialFailure.
*/
@java.lang.Override
public boolean getPartialFailure() {
return partialFailure_;
}
public static final int VALIDATE_ONLY_FIELD_NUMBER = 4;
private boolean validateOnly_ = false;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getOperation());
}
if (partialFailure_ != false) {
output.writeBool(3, partialFailure_);
}
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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getOperation());
}
if (partialFailure_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(3, partialFailure_);
}
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.ads.googleads.v20.services.MutateAccountLinkRequest)) {
return super.equals(obj);
}
com.google.ads.googleads.v20.services.MutateAccountLinkRequest other = (com.google.ads.googleads.v20.services.MutateAccountLinkRequest) obj;
if (!getCustomerId()
.equals(other.getCustomerId())) return false;
if (hasOperation() != other.hasOperation()) return false;
if (hasOperation()) {
if (!getOperation()
.equals(other.getOperation())) return false;
}
if (getPartialFailure()
!= other.getPartialFailure()) 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();
hash = (37 * hash) + CUSTOMER_ID_FIELD_NUMBER;
hash = (53 * hash) + getCustomerId().hashCode();
if (hasOperation()) {
hash = (37 * hash) + OPERATION_FIELD_NUMBER;
hash = (53 * hash) + getOperation().hashCode();
}
hash = (37 * hash) + PARTIAL_FAILURE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getPartialFailure());
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.ads.googleads.v20.services.MutateAccountLinkRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.MutateAccountLinkRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.MutateAccountLinkRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.MutateAccountLinkRequest 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.ads.googleads.v20.services.MutateAccountLinkRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.MutateAccountLinkRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.MutateAccountLinkRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.MutateAccountLinkRequest 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.ads.googleads.v20.services.MutateAccountLinkRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.MutateAccountLinkRequest 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.ads.googleads.v20.services.MutateAccountLinkRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.MutateAccountLinkRequest 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.ads.googleads.v20.services.MutateAccountLinkRequest 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
* [AccountLinkService.MutateAccountLink][google.ads.googleads.v20.services.AccountLinkService.MutateAccountLink].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.services.MutateAccountLinkRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.services.MutateAccountLinkRequest)
com.google.ads.googleads.v20.services.MutateAccountLinkRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v20_services_MutateAccountLinkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v20_services_MutateAccountLinkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.services.MutateAccountLinkRequest.class, com.google.ads.googleads.v20.services.MutateAccountLinkRequest.Builder.class);
}
// Construct using com.google.ads.googleads.v20.services.MutateAccountLinkRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getOperationFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
customerId_ = "";
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
partialFailure_ = false;
validateOnly_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v20.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v20_services_MutateAccountLinkRequest_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.MutateAccountLinkRequest getDefaultInstanceForType() {
return com.google.ads.googleads.v20.services.MutateAccountLinkRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v20.services.MutateAccountLinkRequest build() {
com.google.ads.googleads.v20.services.MutateAccountLinkRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.MutateAccountLinkRequest buildPartial() {
com.google.ads.googleads.v20.services.MutateAccountLinkRequest result = new com.google.ads.googleads.v20.services.MutateAccountLinkRequest(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v20.services.MutateAccountLinkRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.customerId_ = customerId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.operation_ = operationBuilder_ == null
? operation_
: operationBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.partialFailure_ = partialFailure_;
}
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.ads.googleads.v20.services.MutateAccountLinkRequest) {
return mergeFrom((com.google.ads.googleads.v20.services.MutateAccountLinkRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v20.services.MutateAccountLinkRequest other) {
if (other == com.google.ads.googleads.v20.services.MutateAccountLinkRequest.getDefaultInstance()) return this;
if (!other.getCustomerId().isEmpty()) {
customerId_ = other.customerId_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasOperation()) {
mergeOperation(other.getOperation());
}
if (other.getPartialFailure() != false) {
setPartialFailure(other.getPartialFailure());
}
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: {
customerId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18: {
input.readMessage(
getOperationFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 24: {
partialFailure_ = 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 java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerId(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
customerId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return This builder for chaining.
*/
public Builder clearCustomerId() {
customerId_ = getDefaultInstance().getCustomerId();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The bytes for customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
customerId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.ads.googleads.v20.services.AccountLinkOperation operation_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.services.AccountLinkOperation, com.google.ads.googleads.v20.services.AccountLinkOperation.Builder, com.google.ads.googleads.v20.services.AccountLinkOperationOrBuilder> operationBuilder_;
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v20.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
public boolean hasOperation() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v20.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
public com.google.ads.googleads.v20.services.AccountLinkOperation getOperation() {
if (operationBuilder_ == null) {
return operation_ == null ? com.google.ads.googleads.v20.services.AccountLinkOperation.getDefaultInstance() : operation_;
} else {
return operationBuilder_.getMessage();
}
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v20.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperation(com.google.ads.googleads.v20.services.AccountLinkOperation value) {
if (operationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
} else {
operationBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v20.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperation(
com.google.ads.googleads.v20.services.AccountLinkOperation.Builder builderForValue) {
if (operationBuilder_ == null) {
operation_ = builderForValue.build();
} else {
operationBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v20.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder mergeOperation(com.google.ads.googleads.v20.services.AccountLinkOperation value) {
if (operationBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
operation_ != null &&
operation_ != com.google.ads.googleads.v20.services.AccountLinkOperation.getDefaultInstance()) {
getOperationBuilder().mergeFrom(value);
} else {
operation_ = value;
}
} else {
operationBuilder_.mergeFrom(value);
}
if (operation_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v20.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearOperation() {
bitField0_ = (bitField0_ & ~0x00000002);
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v20.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v20.services.AccountLinkOperation.Builder getOperationBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getOperationFieldBuilder().getBuilder();
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v20.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v20.services.AccountLinkOperationOrBuilder getOperationOrBuilder() {
if (operationBuilder_ != null) {
return operationBuilder_.getMessageOrBuilder();
} else {
return operation_ == null ?
com.google.ads.googleads.v20.services.AccountLinkOperation.getDefaultInstance() : operation_;
}
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v20.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.services.AccountLinkOperation, com.google.ads.googleads.v20.services.AccountLinkOperation.Builder, com.google.ads.googleads.v20.services.AccountLinkOperationOrBuilder>
getOperationFieldBuilder() {
if (operationBuilder_ == null) {
operationBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.services.AccountLinkOperation, com.google.ads.googleads.v20.services.AccountLinkOperation.Builder, com.google.ads.googleads.v20.services.AccountLinkOperationOrBuilder>(
getOperation(),
getParentForChildren(),
isClean());
operation_ = null;
}
return operationBuilder_;
}
private boolean partialFailure_ ;
/**
* <pre>
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @return The partialFailure.
*/
@java.lang.Override
public boolean getPartialFailure() {
return partialFailure_;
}
/**
* <pre>
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @param value The partialFailure to set.
* @return This builder for chaining.
*/
public Builder setPartialFailure(boolean value) {
partialFailure_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @return This builder for chaining.
*/
public Builder clearPartialFailure() {
bitField0_ = (bitField0_ & ~0x00000004);
partialFailure_ = false;
onChanged();
return this;
}
private boolean validateOnly_ ;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</code>
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</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>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</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.ads.googleads.v20.services.MutateAccountLinkRequest)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v20.services.MutateAccountLinkRequest)
private static final com.google.ads.googleads.v20.services.MutateAccountLinkRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v20.services.MutateAccountLinkRequest();
}
public static com.google.ads.googleads.v20.services.MutateAccountLinkRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MutateAccountLinkRequest>
PARSER = new com.google.protobuf.AbstractParser<MutateAccountLinkRequest>() {
@java.lang.Override
public MutateAccountLinkRequest 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<MutateAccountLinkRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<MutateAccountLinkRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.MutateAccountLinkRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 35,767 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/services/MutateAccountLinkRequest.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/services/account_link_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.services;
/**
* <pre>
* Request message for
* [AccountLinkService.MutateAccountLink][google.ads.googleads.v21.services.AccountLinkService.MutateAccountLink].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.services.MutateAccountLinkRequest}
*/
public final class MutateAccountLinkRequest extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.services.MutateAccountLinkRequest)
MutateAccountLinkRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use MutateAccountLinkRequest.newBuilder() to construct.
private MutateAccountLinkRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private MutateAccountLinkRequest() {
customerId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new MutateAccountLinkRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v21_services_MutateAccountLinkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v21_services_MutateAccountLinkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.services.MutateAccountLinkRequest.class, com.google.ads.googleads.v21.services.MutateAccountLinkRequest.Builder.class);
}
private int bitField0_;
public static final int CUSTOMER_ID_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
@java.lang.Override
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
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();
customerId_ = s;
return s;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
@java.lang.Override
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int OPERATION_FIELD_NUMBER = 2;
private com.google.ads.googleads.v21.services.AccountLinkOperation operation_;
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v21.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
@java.lang.Override
public boolean hasOperation() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v21.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
@java.lang.Override
public com.google.ads.googleads.v21.services.AccountLinkOperation getOperation() {
return operation_ == null ? com.google.ads.googleads.v21.services.AccountLinkOperation.getDefaultInstance() : operation_;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v21.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
@java.lang.Override
public com.google.ads.googleads.v21.services.AccountLinkOperationOrBuilder getOperationOrBuilder() {
return operation_ == null ? com.google.ads.googleads.v21.services.AccountLinkOperation.getDefaultInstance() : operation_;
}
public static final int PARTIAL_FAILURE_FIELD_NUMBER = 3;
private boolean partialFailure_ = false;
/**
* <pre>
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @return The partialFailure.
*/
@java.lang.Override
public boolean getPartialFailure() {
return partialFailure_;
}
public static final int VALIDATE_ONLY_FIELD_NUMBER = 4;
private boolean validateOnly_ = false;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, customerId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getOperation());
}
if (partialFailure_ != false) {
output.writeBool(3, partialFailure_);
}
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 (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(customerId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, customerId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getOperation());
}
if (partialFailure_ != false) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(3, partialFailure_);
}
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.ads.googleads.v21.services.MutateAccountLinkRequest)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.services.MutateAccountLinkRequest other = (com.google.ads.googleads.v21.services.MutateAccountLinkRequest) obj;
if (!getCustomerId()
.equals(other.getCustomerId())) return false;
if (hasOperation() != other.hasOperation()) return false;
if (hasOperation()) {
if (!getOperation()
.equals(other.getOperation())) return false;
}
if (getPartialFailure()
!= other.getPartialFailure()) 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();
hash = (37 * hash) + CUSTOMER_ID_FIELD_NUMBER;
hash = (53 * hash) + getCustomerId().hashCode();
if (hasOperation()) {
hash = (37 * hash) + OPERATION_FIELD_NUMBER;
hash = (53 * hash) + getOperation().hashCode();
}
hash = (37 * hash) + PARTIAL_FAILURE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(
getPartialFailure());
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.ads.googleads.v21.services.MutateAccountLinkRequest parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.services.MutateAccountLinkRequest parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.MutateAccountLinkRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.services.MutateAccountLinkRequest 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.ads.googleads.v21.services.MutateAccountLinkRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.services.MutateAccountLinkRequest parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.MutateAccountLinkRequest parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.services.MutateAccountLinkRequest 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.ads.googleads.v21.services.MutateAccountLinkRequest parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.services.MutateAccountLinkRequest 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.ads.googleads.v21.services.MutateAccountLinkRequest parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.services.MutateAccountLinkRequest 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.ads.googleads.v21.services.MutateAccountLinkRequest 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
* [AccountLinkService.MutateAccountLink][google.ads.googleads.v21.services.AccountLinkService.MutateAccountLink].
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.services.MutateAccountLinkRequest}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.services.MutateAccountLinkRequest)
com.google.ads.googleads.v21.services.MutateAccountLinkRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v21_services_MutateAccountLinkRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v21_services_MutateAccountLinkRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.services.MutateAccountLinkRequest.class, com.google.ads.googleads.v21.services.MutateAccountLinkRequest.Builder.class);
}
// Construct using com.google.ads.googleads.v21.services.MutateAccountLinkRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getOperationFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
customerId_ = "";
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
partialFailure_ = false;
validateOnly_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.services.AccountLinkServiceProto.internal_static_google_ads_googleads_v21_services_MutateAccountLinkRequest_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.services.MutateAccountLinkRequest getDefaultInstanceForType() {
return com.google.ads.googleads.v21.services.MutateAccountLinkRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.services.MutateAccountLinkRequest build() {
com.google.ads.googleads.v21.services.MutateAccountLinkRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.services.MutateAccountLinkRequest buildPartial() {
com.google.ads.googleads.v21.services.MutateAccountLinkRequest result = new com.google.ads.googleads.v21.services.MutateAccountLinkRequest(this);
if (bitField0_ != 0) { buildPartial0(result); }
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v21.services.MutateAccountLinkRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.customerId_ = customerId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.operation_ = operationBuilder_ == null
? operation_
: operationBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.partialFailure_ = partialFailure_;
}
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.ads.googleads.v21.services.MutateAccountLinkRequest) {
return mergeFrom((com.google.ads.googleads.v21.services.MutateAccountLinkRequest)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.services.MutateAccountLinkRequest other) {
if (other == com.google.ads.googleads.v21.services.MutateAccountLinkRequest.getDefaultInstance()) return this;
if (!other.getCustomerId().isEmpty()) {
customerId_ = other.customerId_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasOperation()) {
mergeOperation(other.getOperation());
}
if (other.getPartialFailure() != false) {
setPartialFailure(other.getPartialFailure());
}
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: {
customerId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18: {
input.readMessage(
getOperationFieldBuilder().getBuilder(),
extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 24: {
partialFailure_ = 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 java.lang.Object customerId_ = "";
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
public java.lang.String getCustomerId() {
java.lang.Object ref = customerId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
customerId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
public com.google.protobuf.ByteString
getCustomerIdBytes() {
java.lang.Object ref = customerId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
customerId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerId(
java.lang.String value) {
if (value == null) { throw new NullPointerException(); }
customerId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return This builder for chaining.
*/
public Builder clearCustomerId() {
customerId_ = getDefaultInstance().getCustomerId();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
* <pre>
* Required. The ID of the customer being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @param value The bytes for customerId to set.
* @return This builder for chaining.
*/
public Builder setCustomerIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) { throw new NullPointerException(); }
checkByteStringIsUtf8(value);
customerId_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.ads.googleads.v21.services.AccountLinkOperation operation_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.services.AccountLinkOperation, com.google.ads.googleads.v21.services.AccountLinkOperation.Builder, com.google.ads.googleads.v21.services.AccountLinkOperationOrBuilder> operationBuilder_;
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v21.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
public boolean hasOperation() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v21.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
public com.google.ads.googleads.v21.services.AccountLinkOperation getOperation() {
if (operationBuilder_ == null) {
return operation_ == null ? com.google.ads.googleads.v21.services.AccountLinkOperation.getDefaultInstance() : operation_;
} else {
return operationBuilder_.getMessage();
}
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v21.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperation(com.google.ads.googleads.v21.services.AccountLinkOperation value) {
if (operationBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
} else {
operationBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v21.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder setOperation(
com.google.ads.googleads.v21.services.AccountLinkOperation.Builder builderForValue) {
if (operationBuilder_ == null) {
operation_ = builderForValue.build();
} else {
operationBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v21.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder mergeOperation(com.google.ads.googleads.v21.services.AccountLinkOperation value) {
if (operationBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0) &&
operation_ != null &&
operation_ != com.google.ads.googleads.v21.services.AccountLinkOperation.getDefaultInstance()) {
getOperationBuilder().mergeFrom(value);
} else {
operation_ = value;
}
} else {
operationBuilder_.mergeFrom(value);
}
if (operation_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v21.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public Builder clearOperation() {
bitField0_ = (bitField0_ & ~0x00000002);
operation_ = null;
if (operationBuilder_ != null) {
operationBuilder_.dispose();
operationBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v21.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v21.services.AccountLinkOperation.Builder getOperationBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getOperationFieldBuilder().getBuilder();
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v21.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
public com.google.ads.googleads.v21.services.AccountLinkOperationOrBuilder getOperationOrBuilder() {
if (operationBuilder_ != null) {
return operationBuilder_.getMessageOrBuilder();
} else {
return operation_ == null ?
com.google.ads.googleads.v21.services.AccountLinkOperation.getDefaultInstance() : operation_;
}
}
/**
* <pre>
* Required. The operation to perform on the link.
* </pre>
*
* <code>.google.ads.googleads.v21.services.AccountLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.services.AccountLinkOperation, com.google.ads.googleads.v21.services.AccountLinkOperation.Builder, com.google.ads.googleads.v21.services.AccountLinkOperationOrBuilder>
getOperationFieldBuilder() {
if (operationBuilder_ == null) {
operationBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.services.AccountLinkOperation, com.google.ads.googleads.v21.services.AccountLinkOperation.Builder, com.google.ads.googleads.v21.services.AccountLinkOperationOrBuilder>(
getOperation(),
getParentForChildren(),
isClean());
operation_ = null;
}
return operationBuilder_;
}
private boolean partialFailure_ ;
/**
* <pre>
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @return The partialFailure.
*/
@java.lang.Override
public boolean getPartialFailure() {
return partialFailure_;
}
/**
* <pre>
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @param value The partialFailure to set.
* @return This builder for chaining.
*/
public Builder setPartialFailure(boolean value) {
partialFailure_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
* <pre>
* If true, successful operations will be carried out and invalid
* operations will return errors. If false, all operations will be carried
* out in one transaction if and only if they are all valid.
* Default is false.
* </pre>
*
* <code>bool partial_failure = 3;</code>
* @return This builder for chaining.
*/
public Builder clearPartialFailure() {
bitField0_ = (bitField0_ & ~0x00000004);
partialFailure_ = false;
onChanged();
return this;
}
private boolean validateOnly_ ;
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</code>
* @return The validateOnly.
*/
@java.lang.Override
public boolean getValidateOnly() {
return validateOnly_;
}
/**
* <pre>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</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>
* If true, the request is validated but not executed. Only errors are
* returned, not results.
* </pre>
*
* <code>bool validate_only = 4;</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.ads.googleads.v21.services.MutateAccountLinkRequest)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.services.MutateAccountLinkRequest)
private static final com.google.ads.googleads.v21.services.MutateAccountLinkRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.services.MutateAccountLinkRequest();
}
public static com.google.ads.googleads.v21.services.MutateAccountLinkRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<MutateAccountLinkRequest>
PARSER = new com.google.protobuf.AbstractParser<MutateAccountLinkRequest>() {
@java.lang.Override
public MutateAccountLinkRequest 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<MutateAccountLinkRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<MutateAccountLinkRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.services.MutateAccountLinkRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,609 | java-bare-metal-solution/proto-google-cloud-bare-metal-solution-v2/src/main/java/com/google/cloud/baremetalsolution/v2/UpdateInstanceRequest.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/baremetalsolution/v2/instance.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.baremetalsolution.v2;
/**
*
*
* <pre>
* Message requesting to updating a server.
* </pre>
*
* Protobuf type {@code google.cloud.baremetalsolution.v2.UpdateInstanceRequest}
*/
public final class UpdateInstanceRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.baremetalsolution.v2.UpdateInstanceRequest)
UpdateInstanceRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateInstanceRequest.newBuilder() to construct.
private UpdateInstanceRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateInstanceRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateInstanceRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.baremetalsolution.v2.InstanceProto
.internal_static_google_cloud_baremetalsolution_v2_UpdateInstanceRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.baremetalsolution.v2.InstanceProto
.internal_static_google_cloud_baremetalsolution_v2_UpdateInstanceRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest.class,
com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest.Builder.class);
}
private int bitField0_;
public static final int INSTANCE_FIELD_NUMBER = 1;
private com.google.cloud.baremetalsolution.v2.Instance instance_;
/**
*
*
* <pre>
* Required. The server to update.
*
* The `name` field is used to identify the instance to update.
* Format: projects/{project}/locations/{location}/instances/{instance}
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.Instance instance = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the instance field is set.
*/
@java.lang.Override
public boolean hasInstance() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The server to update.
*
* The `name` field is used to identify the instance to update.
* Format: projects/{project}/locations/{location}/instances/{instance}
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.Instance instance = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
@java.lang.Override
public com.google.cloud.baremetalsolution.v2.Instance getInstance() {
return instance_ == null
? com.google.cloud.baremetalsolution.v2.Instance.getDefaultInstance()
: instance_;
}
/**
*
*
* <pre>
* Required. The server to update.
*
* The `name` field is used to identify the instance to update.
* Format: projects/{project}/locations/{location}/instances/{instance}
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.Instance instance = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.baremetalsolution.v2.InstanceOrBuilder getInstanceOrBuilder() {
return instance_ == null
? com.google.cloud.baremetalsolution.v2.Instance.getDefaultInstance()
: instance_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* The list of fields to update.
* The currently supported fields are:
* `labels`
* `hyperthreading_enabled`
* `os_image`
* </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 update.
* The currently supported fields are:
* `labels`
* `hyperthreading_enabled`
* `os_image`
* </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 update.
* The currently supported fields are:
* `labels`
* `hyperthreading_enabled`
* `os_image`
* </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, getInstance());
}
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, getInstance());
}
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.baremetalsolution.v2.UpdateInstanceRequest)) {
return super.equals(obj);
}
com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest other =
(com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest) obj;
if (hasInstance() != other.hasInstance()) return false;
if (hasInstance()) {
if (!getInstance().equals(other.getInstance())) 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 (hasInstance()) {
hash = (37 * hash) + INSTANCE_FIELD_NUMBER;
hash = (53 * hash) + getInstance().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.baremetalsolution.v2.UpdateInstanceRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest 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.baremetalsolution.v2.UpdateInstanceRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest 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.baremetalsolution.v2.UpdateInstanceRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest 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.baremetalsolution.v2.UpdateInstanceRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest 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.baremetalsolution.v2.UpdateInstanceRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest 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.baremetalsolution.v2.UpdateInstanceRequest 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 requesting to updating a server.
* </pre>
*
* Protobuf type {@code google.cloud.baremetalsolution.v2.UpdateInstanceRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.baremetalsolution.v2.UpdateInstanceRequest)
com.google.cloud.baremetalsolution.v2.UpdateInstanceRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.baremetalsolution.v2.InstanceProto
.internal_static_google_cloud_baremetalsolution_v2_UpdateInstanceRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.baremetalsolution.v2.InstanceProto
.internal_static_google_cloud_baremetalsolution_v2_UpdateInstanceRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest.class,
com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest.Builder.class);
}
// Construct using com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getInstanceFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
instance_ = null;
if (instanceBuilder_ != null) {
instanceBuilder_.dispose();
instanceBuilder_ = 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.baremetalsolution.v2.InstanceProto
.internal_static_google_cloud_baremetalsolution_v2_UpdateInstanceRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest getDefaultInstanceForType() {
return com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest build() {
com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest buildPartial() {
com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest result =
new com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.instance_ = instanceBuilder_ == null ? instance_ : instanceBuilder_.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.baremetalsolution.v2.UpdateInstanceRequest) {
return mergeFrom((com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest other) {
if (other == com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest.getDefaultInstance())
return this;
if (other.hasInstance()) {
mergeInstance(other.getInstance());
}
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(getInstanceFieldBuilder().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.baremetalsolution.v2.Instance instance_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.baremetalsolution.v2.Instance,
com.google.cloud.baremetalsolution.v2.Instance.Builder,
com.google.cloud.baremetalsolution.v2.InstanceOrBuilder>
instanceBuilder_;
/**
*
*
* <pre>
* Required. The server to update.
*
* The `name` field is used to identify the instance to update.
* Format: projects/{project}/locations/{location}/instances/{instance}
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.Instance instance = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the instance field is set.
*/
public boolean hasInstance() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The server to update.
*
* The `name` field is used to identify the instance to update.
* Format: projects/{project}/locations/{location}/instances/{instance}
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.Instance instance = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The instance.
*/
public com.google.cloud.baremetalsolution.v2.Instance getInstance() {
if (instanceBuilder_ == null) {
return instance_ == null
? com.google.cloud.baremetalsolution.v2.Instance.getDefaultInstance()
: instance_;
} else {
return instanceBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The server to update.
*
* The `name` field is used to identify the instance to update.
* Format: projects/{project}/locations/{location}/instances/{instance}
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.Instance instance = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(com.google.cloud.baremetalsolution.v2.Instance value) {
if (instanceBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
instance_ = value;
} else {
instanceBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The server to update.
*
* The `name` field is used to identify the instance to update.
* Format: projects/{project}/locations/{location}/instances/{instance}
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.Instance instance = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setInstance(
com.google.cloud.baremetalsolution.v2.Instance.Builder builderForValue) {
if (instanceBuilder_ == null) {
instance_ = builderForValue.build();
} else {
instanceBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The server to update.
*
* The `name` field is used to identify the instance to update.
* Format: projects/{project}/locations/{location}/instances/{instance}
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.Instance instance = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeInstance(com.google.cloud.baremetalsolution.v2.Instance value) {
if (instanceBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& instance_ != null
&& instance_ != com.google.cloud.baremetalsolution.v2.Instance.getDefaultInstance()) {
getInstanceBuilder().mergeFrom(value);
} else {
instance_ = value;
}
} else {
instanceBuilder_.mergeFrom(value);
}
if (instance_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The server to update.
*
* The `name` field is used to identify the instance to update.
* Format: projects/{project}/locations/{location}/instances/{instance}
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.Instance instance = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearInstance() {
bitField0_ = (bitField0_ & ~0x00000001);
instance_ = null;
if (instanceBuilder_ != null) {
instanceBuilder_.dispose();
instanceBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The server to update.
*
* The `name` field is used to identify the instance to update.
* Format: projects/{project}/locations/{location}/instances/{instance}
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.Instance instance = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.baremetalsolution.v2.Instance.Builder getInstanceBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getInstanceFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The server to update.
*
* The `name` field is used to identify the instance to update.
* Format: projects/{project}/locations/{location}/instances/{instance}
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.Instance instance = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.baremetalsolution.v2.InstanceOrBuilder getInstanceOrBuilder() {
if (instanceBuilder_ != null) {
return instanceBuilder_.getMessageOrBuilder();
} else {
return instance_ == null
? com.google.cloud.baremetalsolution.v2.Instance.getDefaultInstance()
: instance_;
}
}
/**
*
*
* <pre>
* Required. The server to update.
*
* The `name` field is used to identify the instance to update.
* Format: projects/{project}/locations/{location}/instances/{instance}
* </pre>
*
* <code>
* .google.cloud.baremetalsolution.v2.Instance instance = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.baremetalsolution.v2.Instance,
com.google.cloud.baremetalsolution.v2.Instance.Builder,
com.google.cloud.baremetalsolution.v2.InstanceOrBuilder>
getInstanceFieldBuilder() {
if (instanceBuilder_ == null) {
instanceBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.baremetalsolution.v2.Instance,
com.google.cloud.baremetalsolution.v2.Instance.Builder,
com.google.cloud.baremetalsolution.v2.InstanceOrBuilder>(
getInstance(), getParentForChildren(), isClean());
instance_ = null;
}
return instanceBuilder_;
}
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 update.
* The currently supported fields are:
* `labels`
* `hyperthreading_enabled`
* `os_image`
* </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 update.
* The currently supported fields are:
* `labels`
* `hyperthreading_enabled`
* `os_image`
* </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 update.
* The currently supported fields are:
* `labels`
* `hyperthreading_enabled`
* `os_image`
* </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 update.
* The currently supported fields are:
* `labels`
* `hyperthreading_enabled`
* `os_image`
* </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 update.
* The currently supported fields are:
* `labels`
* `hyperthreading_enabled`
* `os_image`
* </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 update.
* The currently supported fields are:
* `labels`
* `hyperthreading_enabled`
* `os_image`
* </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 update.
* The currently supported fields are:
* `labels`
* `hyperthreading_enabled`
* `os_image`
* </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 update.
* The currently supported fields are:
* `labels`
* `hyperthreading_enabled`
* `os_image`
* </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 update.
* The currently supported fields are:
* `labels`
* `hyperthreading_enabled`
* `os_image`
* </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.baremetalsolution.v2.UpdateInstanceRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.baremetalsolution.v2.UpdateInstanceRequest)
private static final com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest();
}
public static com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateInstanceRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateInstanceRequest>() {
@java.lang.Override
public UpdateInstanceRequest 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<UpdateInstanceRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateInstanceRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.baremetalsolution.v2.UpdateInstanceRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,670 | java-os-config/proto-google-cloud-os-config-v1alpha/src/main/java/com/google/cloud/osconfig/v1alpha/UpdateOSPolicyAssignmentRequest.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/osconfig/v1alpha/os_policy_assignments.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.osconfig.v1alpha;
/**
*
*
* <pre>
* A request message to update an OS policy assignment
* </pre>
*
* Protobuf type {@code google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest}
*/
public final class UpdateOSPolicyAssignmentRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest)
UpdateOSPolicyAssignmentRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateOSPolicyAssignmentRequest.newBuilder() to construct.
private UpdateOSPolicyAssignmentRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateOSPolicyAssignmentRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateOSPolicyAssignmentRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.osconfig.v1alpha.OsPolicyAssignmentsProto
.internal_static_google_cloud_osconfig_v1alpha_UpdateOSPolicyAssignmentRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.osconfig.v1alpha.OsPolicyAssignmentsProto
.internal_static_google_cloud_osconfig_v1alpha_UpdateOSPolicyAssignmentRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest.class,
com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest.Builder.class);
}
private int bitField0_;
public static final int OS_POLICY_ASSIGNMENT_FIELD_NUMBER = 1;
private com.google.cloud.osconfig.v1alpha.OSPolicyAssignment osPolicyAssignment_;
/**
*
*
* <pre>
* Required. The updated OS policy assignment.
* </pre>
*
* <code>
* .google.cloud.osconfig.v1alpha.OSPolicyAssignment os_policy_assignment = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the osPolicyAssignment field is set.
*/
@java.lang.Override
public boolean hasOsPolicyAssignment() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The updated OS policy assignment.
* </pre>
*
* <code>
* .google.cloud.osconfig.v1alpha.OSPolicyAssignment os_policy_assignment = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The osPolicyAssignment.
*/
@java.lang.Override
public com.google.cloud.osconfig.v1alpha.OSPolicyAssignment getOsPolicyAssignment() {
return osPolicyAssignment_ == null
? com.google.cloud.osconfig.v1alpha.OSPolicyAssignment.getDefaultInstance()
: osPolicyAssignment_;
}
/**
*
*
* <pre>
* Required. The updated OS policy assignment.
* </pre>
*
* <code>
* .google.cloud.osconfig.v1alpha.OSPolicyAssignment os_policy_assignment = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.osconfig.v1alpha.OSPolicyAssignmentOrBuilder
getOsPolicyAssignmentOrBuilder() {
return osPolicyAssignment_ == null
? com.google.cloud.osconfig.v1alpha.OSPolicyAssignment.getDefaultInstance()
: osPolicyAssignment_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Optional. Field mask that controls which fields of the assignment should be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Optional. Field mask that controls which fields of the assignment should be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Optional. Field mask that controls which fields of the assignment should be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </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, getOsPolicyAssignment());
}
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, getOsPolicyAssignment());
}
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.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest)) {
return super.equals(obj);
}
com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest other =
(com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest) obj;
if (hasOsPolicyAssignment() != other.hasOsPolicyAssignment()) return false;
if (hasOsPolicyAssignment()) {
if (!getOsPolicyAssignment().equals(other.getOsPolicyAssignment())) 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 (hasOsPolicyAssignment()) {
hash = (37 * hash) + OS_POLICY_ASSIGNMENT_FIELD_NUMBER;
hash = (53 * hash) + getOsPolicyAssignment().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.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest 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.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest 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.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest 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.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest
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.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest 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.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest 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 to update an OS policy assignment
* </pre>
*
* Protobuf type {@code google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest)
com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.osconfig.v1alpha.OsPolicyAssignmentsProto
.internal_static_google_cloud_osconfig_v1alpha_UpdateOSPolicyAssignmentRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.osconfig.v1alpha.OsPolicyAssignmentsProto
.internal_static_google_cloud_osconfig_v1alpha_UpdateOSPolicyAssignmentRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest.class,
com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest.Builder.class);
}
// Construct using
// com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getOsPolicyAssignmentFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
osPolicyAssignment_ = null;
if (osPolicyAssignmentBuilder_ != null) {
osPolicyAssignmentBuilder_.dispose();
osPolicyAssignmentBuilder_ = 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.osconfig.v1alpha.OsPolicyAssignmentsProto
.internal_static_google_cloud_osconfig_v1alpha_UpdateOSPolicyAssignmentRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest
getDefaultInstanceForType() {
return com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest build() {
com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest buildPartial() {
com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest result =
new com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.osPolicyAssignment_ =
osPolicyAssignmentBuilder_ == null
? osPolicyAssignment_
: osPolicyAssignmentBuilder_.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.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest) {
return mergeFrom((com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest other) {
if (other
== com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest.getDefaultInstance())
return this;
if (other.hasOsPolicyAssignment()) {
mergeOsPolicyAssignment(other.getOsPolicyAssignment());
}
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(
getOsPolicyAssignmentFieldBuilder().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.osconfig.v1alpha.OSPolicyAssignment osPolicyAssignment_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.osconfig.v1alpha.OSPolicyAssignment,
com.google.cloud.osconfig.v1alpha.OSPolicyAssignment.Builder,
com.google.cloud.osconfig.v1alpha.OSPolicyAssignmentOrBuilder>
osPolicyAssignmentBuilder_;
/**
*
*
* <pre>
* Required. The updated OS policy assignment.
* </pre>
*
* <code>
* .google.cloud.osconfig.v1alpha.OSPolicyAssignment os_policy_assignment = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the osPolicyAssignment field is set.
*/
public boolean hasOsPolicyAssignment() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The updated OS policy assignment.
* </pre>
*
* <code>
* .google.cloud.osconfig.v1alpha.OSPolicyAssignment os_policy_assignment = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The osPolicyAssignment.
*/
public com.google.cloud.osconfig.v1alpha.OSPolicyAssignment getOsPolicyAssignment() {
if (osPolicyAssignmentBuilder_ == null) {
return osPolicyAssignment_ == null
? com.google.cloud.osconfig.v1alpha.OSPolicyAssignment.getDefaultInstance()
: osPolicyAssignment_;
} else {
return osPolicyAssignmentBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The updated OS policy assignment.
* </pre>
*
* <code>
* .google.cloud.osconfig.v1alpha.OSPolicyAssignment os_policy_assignment = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setOsPolicyAssignment(
com.google.cloud.osconfig.v1alpha.OSPolicyAssignment value) {
if (osPolicyAssignmentBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
osPolicyAssignment_ = value;
} else {
osPolicyAssignmentBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The updated OS policy assignment.
* </pre>
*
* <code>
* .google.cloud.osconfig.v1alpha.OSPolicyAssignment os_policy_assignment = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setOsPolicyAssignment(
com.google.cloud.osconfig.v1alpha.OSPolicyAssignment.Builder builderForValue) {
if (osPolicyAssignmentBuilder_ == null) {
osPolicyAssignment_ = builderForValue.build();
} else {
osPolicyAssignmentBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The updated OS policy assignment.
* </pre>
*
* <code>
* .google.cloud.osconfig.v1alpha.OSPolicyAssignment os_policy_assignment = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeOsPolicyAssignment(
com.google.cloud.osconfig.v1alpha.OSPolicyAssignment value) {
if (osPolicyAssignmentBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& osPolicyAssignment_ != null
&& osPolicyAssignment_
!= com.google.cloud.osconfig.v1alpha.OSPolicyAssignment.getDefaultInstance()) {
getOsPolicyAssignmentBuilder().mergeFrom(value);
} else {
osPolicyAssignment_ = value;
}
} else {
osPolicyAssignmentBuilder_.mergeFrom(value);
}
if (osPolicyAssignment_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The updated OS policy assignment.
* </pre>
*
* <code>
* .google.cloud.osconfig.v1alpha.OSPolicyAssignment os_policy_assignment = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearOsPolicyAssignment() {
bitField0_ = (bitField0_ & ~0x00000001);
osPolicyAssignment_ = null;
if (osPolicyAssignmentBuilder_ != null) {
osPolicyAssignmentBuilder_.dispose();
osPolicyAssignmentBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The updated OS policy assignment.
* </pre>
*
* <code>
* .google.cloud.osconfig.v1alpha.OSPolicyAssignment os_policy_assignment = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.osconfig.v1alpha.OSPolicyAssignment.Builder
getOsPolicyAssignmentBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getOsPolicyAssignmentFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The updated OS policy assignment.
* </pre>
*
* <code>
* .google.cloud.osconfig.v1alpha.OSPolicyAssignment os_policy_assignment = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.osconfig.v1alpha.OSPolicyAssignmentOrBuilder
getOsPolicyAssignmentOrBuilder() {
if (osPolicyAssignmentBuilder_ != null) {
return osPolicyAssignmentBuilder_.getMessageOrBuilder();
} else {
return osPolicyAssignment_ == null
? com.google.cloud.osconfig.v1alpha.OSPolicyAssignment.getDefaultInstance()
: osPolicyAssignment_;
}
}
/**
*
*
* <pre>
* Required. The updated OS policy assignment.
* </pre>
*
* <code>
* .google.cloud.osconfig.v1alpha.OSPolicyAssignment os_policy_assignment = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.osconfig.v1alpha.OSPolicyAssignment,
com.google.cloud.osconfig.v1alpha.OSPolicyAssignment.Builder,
com.google.cloud.osconfig.v1alpha.OSPolicyAssignmentOrBuilder>
getOsPolicyAssignmentFieldBuilder() {
if (osPolicyAssignmentBuilder_ == null) {
osPolicyAssignmentBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.osconfig.v1alpha.OSPolicyAssignment,
com.google.cloud.osconfig.v1alpha.OSPolicyAssignment.Builder,
com.google.cloud.osconfig.v1alpha.OSPolicyAssignmentOrBuilder>(
getOsPolicyAssignment(), getParentForChildren(), isClean());
osPolicyAssignment_ = null;
}
return osPolicyAssignmentBuilder_;
}
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>
* Optional. Field mask that controls which fields of the assignment should be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Optional. Field mask that controls which fields of the assignment should be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </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>
* Optional. Field mask that controls which fields of the assignment should be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </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>
* Optional. Field mask that controls which fields of the assignment should be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </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>
* Optional. Field mask that controls which fields of the assignment should be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </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>
* Optional. Field mask that controls which fields of the assignment should be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Field mask that controls which fields of the assignment should be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Optional. Field mask that controls which fields of the assignment should be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Optional. Field mask that controls which fields of the assignment should be updated.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </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.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest)
private static final com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest();
}
public static com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateOSPolicyAssignmentRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateOSPolicyAssignmentRequest>() {
@java.lang.Override
public UpdateOSPolicyAssignmentRequest 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<UpdateOSPolicyAssignmentRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateOSPolicyAssignmentRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.osconfig.v1alpha.UpdateOSPolicyAssignmentRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/flink-cdc | 35,450 | flink-cdc-cli/src/test/java/org/apache/flink/cdc/cli/parser/YamlPipelineDefinitionParserTest.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.flink.cdc.cli.parser;
import org.apache.flink.cdc.common.configuration.Configuration;
import org.apache.flink.cdc.common.event.SchemaChangeEventType;
import org.apache.flink.cdc.common.pipeline.PipelineOptions;
import org.apache.flink.cdc.composer.definition.ModelDef;
import org.apache.flink.cdc.composer.definition.PipelineDef;
import org.apache.flink.cdc.composer.definition.RouteDef;
import org.apache.flink.cdc.composer.definition.SinkDef;
import org.apache.flink.cdc.composer.definition.SourceDef;
import org.apache.flink.cdc.composer.definition.TransformDef;
import org.apache.flink.cdc.composer.definition.UdfDef;
import org.apache.flink.core.fs.Path;
import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableMap;
import org.apache.flink.shaded.guava31.com.google.common.collect.ImmutableSet;
import org.apache.flink.shaded.guava31.com.google.common.io.Resources;
import org.junit.jupiter.api.Test;
import java.net.URL;
import java.time.Duration;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Set;
import static org.apache.flink.cdc.common.event.SchemaChangeEventType.ADD_COLUMN;
import static org.apache.flink.cdc.common.event.SchemaChangeEventType.ALTER_COLUMN_TYPE;
import static org.apache.flink.cdc.common.event.SchemaChangeEventType.CREATE_TABLE;
import static org.apache.flink.cdc.common.event.SchemaChangeEventType.DROP_COLUMN;
import static org.apache.flink.cdc.common.event.SchemaChangeEventType.DROP_TABLE;
import static org.apache.flink.cdc.common.event.SchemaChangeEventType.RENAME_COLUMN;
import static org.apache.flink.cdc.common.event.SchemaChangeEventType.TRUNCATE_TABLE;
import static org.apache.flink.cdc.common.pipeline.PipelineOptions.PIPELINE_LOCAL_TIME_ZONE;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
/** Unit test for {@link org.apache.flink.cdc.cli.parser.YamlPipelineDefinitionParser}. */
class YamlPipelineDefinitionParserTest {
@Test
void testParsingFullDefinition() throws Exception {
URL resource = Resources.getResource("definitions/pipeline-definition-full.yaml");
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef = parser.parse(new Path(resource.toURI()), new Configuration());
assertThat(pipelineDef).isEqualTo(fullDef);
}
@Test
void testParsingNecessaryOnlyDefinition() throws Exception {
URL resource = Resources.getResource("definitions/pipeline-definition-with-optional.yaml");
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef = parser.parse(new Path(resource.toURI()), new Configuration());
assertThat(pipelineDef).isEqualTo(defWithOptional);
}
@Test
void testMinimizedDefinition() throws Exception {
URL resource = Resources.getResource("definitions/pipeline-definition-minimized.yaml");
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef = parser.parse(new Path(resource.toURI()), new Configuration());
assertThat(pipelineDef).isEqualTo(minimizedDef);
}
@Test
void testOverridingGlobalConfig() throws Exception {
URL resource = Resources.getResource("definitions/pipeline-definition-full.yaml");
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef =
parser.parse(
new Path(resource.toURI()),
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("parallelism", "1")
.build()));
assertThat(pipelineDef).isEqualTo(fullDefWithGlobalConf);
}
@Test
void testEvaluateDefaultLocalTimeZone() throws Exception {
URL resource = Resources.getResource("definitions/pipeline-definition-minimized.yaml");
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef = parser.parse(new Path(resource.toURI()), new Configuration());
assertThat(pipelineDef.getConfig().get(PIPELINE_LOCAL_TIME_ZONE))
.isNotEqualTo(PIPELINE_LOCAL_TIME_ZONE.defaultValue());
}
@Test
void testEvaluateDefaultRpcTimeOut() throws Exception {
URL resource = Resources.getResource("definitions/pipeline-definition-minimized.yaml");
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef =
parser.parse(
new Path(resource.toURI()),
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put(
PipelineOptions.PIPELINE_SCHEMA_OPERATOR_RPC_TIMEOUT
.key(),
"1h")
.build()));
assertThat(
pipelineDef
.getConfig()
.get(PipelineOptions.PIPELINE_SCHEMA_OPERATOR_RPC_TIMEOUT))
.isEqualTo(Duration.ofSeconds(60 * 60));
}
@Test
void testValidTimeZone() throws Exception {
URL resource = Resources.getResource("definitions/pipeline-definition-minimized.yaml");
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef =
parser.parse(
new Path(resource.toURI()),
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put(PIPELINE_LOCAL_TIME_ZONE.key(), "Asia/Shanghai")
.build()));
assertThat(pipelineDef.getConfig().get(PIPELINE_LOCAL_TIME_ZONE))
.isEqualTo("Asia/Shanghai");
pipelineDef =
parser.parse(
new Path(resource.toURI()),
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put(PIPELINE_LOCAL_TIME_ZONE.key(), "GMT+08:00")
.build()));
assertThat(pipelineDef.getConfig().get(PIPELINE_LOCAL_TIME_ZONE)).isEqualTo("GMT+08:00");
pipelineDef =
parser.parse(
new Path(resource.toURI()),
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put(PIPELINE_LOCAL_TIME_ZONE.key(), "UTC")
.build()));
assertThat(pipelineDef.getConfig().get(PIPELINE_LOCAL_TIME_ZONE)).isEqualTo("UTC");
}
@Test
void testInvalidTimeZone() {
URL resource = Resources.getResource("definitions/pipeline-definition-minimized.yaml");
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
assertThatThrownBy(
() ->
parser.parse(
new Path(resource.toURI()),
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put(
PIPELINE_LOCAL_TIME_ZONE.key(),
"invalid time zone")
.build())))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(
"Invalid time zone. The valid value should be a Time Zone Database ID"
+ " such as 'America/Los_Angeles' to include daylight saving time. "
+ "Fixed offsets are supported using 'GMT-08:00' or 'GMT+08:00'. "
+ "Or use 'UTC' without time zone and daylight saving time.");
}
@Test
void testRouteWithReplacementSymbol() throws Exception {
URL resource =
Resources.getResource("definitions/pipeline-definition-full-with-repsym.yaml");
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef = parser.parse(new Path(resource.toURI()), new Configuration());
assertThat(pipelineDef).isEqualTo(fullDefWithRouteRepSym);
}
@Test
void testUdfDefinition() throws Exception {
URL resource = Resources.getResource("definitions/pipeline-definition-with-udf.yaml");
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef = parser.parse(new Path(resource.toURI()), new Configuration());
assertThat(pipelineDef).isEqualTo(pipelineDefWithUdf);
}
@Test
void testSchemaEvolutionTypesConfiguration() throws Exception {
testSchemaEvolutionTypesParsing(
"evolve",
null,
null,
ImmutableSet.of(
ADD_COLUMN,
ALTER_COLUMN_TYPE,
CREATE_TABLE,
DROP_COLUMN,
DROP_TABLE,
RENAME_COLUMN,
TRUNCATE_TABLE));
testSchemaEvolutionTypesParsing(
"try_evolve",
null,
null,
ImmutableSet.of(
ADD_COLUMN,
ALTER_COLUMN_TYPE,
CREATE_TABLE,
DROP_COLUMN,
DROP_TABLE,
RENAME_COLUMN,
TRUNCATE_TABLE));
testSchemaEvolutionTypesParsing(
"evolve",
"[column, table]",
"[drop]",
ImmutableSet.of(
ADD_COLUMN,
ALTER_COLUMN_TYPE,
CREATE_TABLE,
RENAME_COLUMN,
TRUNCATE_TABLE));
testSchemaEvolutionTypesParsing(
"lenient",
null,
null,
ImmutableSet.of(
ADD_COLUMN, ALTER_COLUMN_TYPE, CREATE_TABLE, DROP_COLUMN, RENAME_COLUMN));
testSchemaEvolutionTypesParsing(
"lenient",
null,
"[]",
ImmutableSet.of(
ADD_COLUMN,
ALTER_COLUMN_TYPE,
CREATE_TABLE,
DROP_COLUMN,
DROP_TABLE,
RENAME_COLUMN,
TRUNCATE_TABLE));
}
private void testSchemaEvolutionTypesParsing(
String behavior, String included, String excluded, Set<SchemaChangeEventType> expected)
throws Exception {
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef =
parser.parse(
"source:\n"
+ " type: foo\n"
+ "sink:\n"
+ " type: bar\n"
+ (included != null
? String.format(" include.schema.changes: %s\n", included)
: "")
+ (excluded != null
? String.format(" exclude.schema.changes: %s\n", excluded)
: "")
+ "pipeline:\n"
+ " schema.change.behavior: "
+ behavior
+ "\n"
+ " parallelism: 1\n",
new Configuration());
assertThat(pipelineDef)
.isEqualTo(
new PipelineDef(
new SourceDef("foo", null, new Configuration()),
new SinkDef("bar", null, new Configuration(), expected),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("schema.change.behavior", behavior)
.put("parallelism", "1")
.build())));
}
private final PipelineDef fullDef =
new PipelineDef(
new SourceDef(
"mysql",
"source-database",
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("host", "localhost")
.put("port", "3306")
.put("username", "admin")
.put("password", "pass")
.put(
"tables",
"adb.*, bdb.user_table_[0-9]+, [app|web]_order_.*")
.put(
"chunk-column",
"app_order_.*:id,web_order:product_id")
.put("capture-new-tables", "true")
.build())),
new SinkDef(
"kafka",
"sink-queue",
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("bootstrap-servers", "localhost:9092")
.put("auto-create-table", "true")
.build())),
Arrays.asList(
new RouteDef(
"mydb.default.app_order_.*",
"odsdb.default.app_order",
null,
"sync all sharding tables to one"),
new RouteDef(
"mydb.default.web_order",
"odsdb.default.ods_web_order",
null,
"sync table to with given prefix ods_")),
Arrays.asList(
new TransformDef(
"mydb.app_order_.*",
"id, order_id, TO_UPPER(product_name)",
"id > 10 AND order_id > 100",
"id",
"product_name",
"comment=app order",
"project fields from source table",
"SOFT_DELETE"),
new TransformDef(
"mydb.web_order_.*",
"CONCAT(id, order_id) as uniq_id, *",
"uniq_id > 10",
null,
null,
null,
"add new uniq_id for each row",
null)),
Collections.emptyList(),
Collections.singletonList(
new ModelDef(
"GET_EMBEDDING",
"OpenAIEmbeddingModel",
new LinkedHashMap<>(
ImmutableMap.<String, String>builder()
.put("model-name", "GET_EMBEDDING")
.put("class-name", "OpenAIEmbeddingModel")
.put("openai.model", "text-embedding-3-small")
.put("openai.host", "https://xxxx")
.put("openai.apikey", "abcd1234")
.build()))),
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("name", "source-database-sync-pipe")
.put("parallelism", "4")
.put("execution.runtime-mode", "STREAMING")
.put("schema.change.behavior", "evolve")
.put("schema-operator.rpc-timeout", "1 h")
.build()));
@Test
void testParsingFullDefinitionFromString() throws Exception {
String pipelineDefText =
"source:\n"
+ " type: mysql\n"
+ " name: source-database\n"
+ " host: localhost\n"
+ " port: 3306\n"
+ " username: admin\n"
+ " password: pass\n"
+ " tables: adb.*, bdb.user_table_[0-9]+, [app|web]_order_.*\n"
+ " chunk-column: app_order_.*:id,web_order:product_id\n"
+ " capture-new-tables: true\n"
+ "\n"
+ "sink:\n"
+ " type: kafka\n"
+ " name: sink-queue\n"
+ " bootstrap-servers: localhost:9092\n"
+ " auto-create-table: true\n"
+ "\n"
+ "route:\n"
+ " - source-table: mydb.default.app_order_.*\n"
+ " sink-table: odsdb.default.app_order\n"
+ " description: sync all sharding tables to one\n"
+ " - source-table: mydb.default.web_order\n"
+ " sink-table: odsdb.default.ods_web_order\n"
+ " description: sync table to with given prefix ods_\n"
+ "\n"
+ "transform:\n"
+ " - source-table: mydb.app_order_.*\n"
+ " projection: id, order_id, TO_UPPER(product_name)\n"
+ " filter: id > 10 AND order_id > 100\n"
+ " primary-keys: id\n"
+ " partition-keys: product_name\n"
+ " table-options: comment=app order\n"
+ " description: project fields from source table\n"
+ " converter-after-transform: SOFT_DELETE\n"
+ " - source-table: mydb.web_order_.*\n"
+ " projection: CONCAT(id, order_id) as uniq_id, *\n"
+ " filter: uniq_id > 10\n"
+ " description: add new uniq_id for each row\n"
+ "\n"
+ "pipeline:\n"
+ " name: source-database-sync-pipe\n"
+ " parallelism: 4\n"
+ " schema.change.behavior: evolve\n"
+ " schema-operator.rpc-timeout: 1 h\n"
+ " execution.runtime-mode: STREAMING\n"
+ " model:\n"
+ " - model-name: GET_EMBEDDING\n"
+ " class-name: OpenAIEmbeddingModel\n"
+ " openai.model: text-embedding-3-small\n"
+ " openai.host: https://xxxx\n"
+ " openai.apikey: abcd1234";
YamlPipelineDefinitionParser parser = new YamlPipelineDefinitionParser();
PipelineDef pipelineDef = parser.parse(pipelineDefText, new Configuration());
assertThat(pipelineDef).isEqualTo(fullDef);
}
private final PipelineDef fullDefWithGlobalConf =
new PipelineDef(
new SourceDef(
"mysql",
"source-database",
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("host", "localhost")
.put("port", "3306")
.put("username", "admin")
.put("password", "pass")
.put(
"tables",
"adb.*, bdb.user_table_[0-9]+, [app|web]_order_.*")
.put(
"chunk-column",
"app_order_.*:id,web_order:product_id")
.put("capture-new-tables", "true")
.build())),
new SinkDef(
"kafka",
"sink-queue",
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("bootstrap-servers", "localhost:9092")
.put("auto-create-table", "true")
.build())),
Arrays.asList(
new RouteDef(
"mydb.default.app_order_.*",
"odsdb.default.app_order",
null,
"sync all sharding tables to one"),
new RouteDef(
"mydb.default.web_order",
"odsdb.default.ods_web_order",
null,
"sync table to with given prefix ods_")),
Arrays.asList(
new TransformDef(
"mydb.app_order_.*",
"id, order_id, TO_UPPER(product_name)",
"id > 10 AND order_id > 100",
"id",
"product_name",
"comment=app order",
"project fields from source table",
"SOFT_DELETE"),
new TransformDef(
"mydb.web_order_.*",
"CONCAT(id, order_id) as uniq_id, *",
"uniq_id > 10",
null,
null,
null,
"add new uniq_id for each row",
null)),
Collections.emptyList(),
Collections.singletonList(
new ModelDef(
"GET_EMBEDDING",
"OpenAIEmbeddingModel",
new LinkedHashMap<>(
ImmutableMap.<String, String>builder()
.put("model-name", "GET_EMBEDDING")
.put("class-name", "OpenAIEmbeddingModel")
.put("openai.model", "text-embedding-3-small")
.put("openai.host", "https://xxxx")
.put("openai.apikey", "abcd1234")
.build()))),
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("name", "source-database-sync-pipe")
.put("parallelism", "4")
.put("schema.change.behavior", "evolve")
.put("schema-operator.rpc-timeout", "1 h")
.put("execution.runtime-mode", "STREAMING")
.build()));
private final PipelineDef defWithOptional =
new PipelineDef(
new SourceDef(
"mysql",
null,
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("host", "localhost")
.put("port", "3306")
.put("username", "admin")
.put("password", "pass")
.put(
"tables",
"adb.*, bdb.user_table_[0-9]+, [app|web]_order_.*")
.build())),
new SinkDef(
"kafka",
null,
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("bootstrap-servers", "localhost:9092")
.build()),
ImmutableSet.of(
DROP_COLUMN,
ALTER_COLUMN_TYPE,
ADD_COLUMN,
CREATE_TABLE,
RENAME_COLUMN)),
Collections.singletonList(
new RouteDef(
"mydb.default.app_order_.*",
"odsdb.default.app_order",
null,
null)),
Collections.emptyList(),
Collections.emptyList(),
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("parallelism", "4")
.build()));
private final PipelineDef minimizedDef =
new PipelineDef(
new SourceDef("mysql", null, new Configuration()),
new SinkDef(
"kafka",
null,
new Configuration(),
ImmutableSet.of(
DROP_COLUMN,
ALTER_COLUMN_TYPE,
ADD_COLUMN,
CREATE_TABLE,
RENAME_COLUMN)),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList(),
Configuration.fromMap(
Collections.singletonMap(
"local-time-zone", ZoneId.systemDefault().toString())));
private final PipelineDef fullDefWithRouteRepSym =
new PipelineDef(
new SourceDef(
"mysql",
"source-database",
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("host", "localhost")
.put("port", "3306")
.put("username", "admin")
.put("password", "pass")
.put(
"tables",
"adb.*, bdb.user_table_[0-9]+, [app|web]_order_.*")
.put(
"chunk-column",
"app_order_.*:id,web_order:product_id")
.put("capture-new-tables", "true")
.build())),
new SinkDef(
"kafka",
"sink-queue",
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("bootstrap-servers", "localhost:9092")
.put("auto-create-table", "true")
.build())),
Arrays.asList(
new RouteDef(
"mydb.default.app_order_.*",
"odsdb.default.app_order_<>",
"<>",
"sync all sharding tables to one"),
new RouteDef(
"mydb.default.web_order",
"odsdb.default.ods_web_order_>_<",
">_<",
"sync table to with given prefix ods_")),
Arrays.asList(
new TransformDef(
"mydb.app_order_.*",
"id, order_id, TO_UPPER(product_name)",
"id > 10 AND order_id > 100",
"id",
"product_name",
"comment=app order",
"project fields from source table",
"SOFT_DELETE"),
new TransformDef(
"mydb.web_order_.*",
"CONCAT(id, order_id) as uniq_id, *",
"uniq_id > 10",
null,
null,
null,
"add new uniq_id for each row",
null)),
Collections.emptyList(),
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("name", "source-database-sync-pipe")
.put("parallelism", "4")
.put("schema.change.behavior", "evolve")
.put("schema-operator.rpc-timeout", "1 h")
.build()));
private final PipelineDef pipelineDefWithUdf =
new PipelineDef(
new SourceDef("values", null, new Configuration()),
new SinkDef(
"values",
null,
new Configuration(),
ImmutableSet.of(
DROP_COLUMN,
ALTER_COLUMN_TYPE,
ADD_COLUMN,
CREATE_TABLE,
RENAME_COLUMN)),
Collections.emptyList(),
Collections.singletonList(
new TransformDef(
"mydb.web_order",
"*, inc(inc(inc(id))) as inc_id, format(id, 'id -> %d') as formatted_id",
"inc(id) < 100",
null,
null,
null,
null,
null)),
Arrays.asList(
new UdfDef(
"inc",
"org.apache.flink.cdc.udf.examples.java.AddOneFunctionClass"),
new UdfDef(
"format",
"org.apache.flink.cdc.udf.examples.java.FormatFunctionClass")),
Configuration.fromMap(
ImmutableMap.<String, String>builder()
.put("parallelism", "1")
.build()));
}
|
googleads/google-ads-java | 35,781 | google-ads-stubs-v19/src/main/java/com/google/ads/googleads/v19/services/CustomerManagerLinkOperation.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v19/services/customer_manager_link_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v19.services;
/**
* <pre>
* Updates the status of a CustomerManagerLink.
* The following actions are possible:
* 1. Update operation with status ACTIVE accepts a pending invitation.
* 2. Update operation with status REFUSED declines a pending invitation.
* 3. Update operation with status INACTIVE terminates link to manager.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.services.CustomerManagerLinkOperation}
*/
public final class CustomerManagerLinkOperation extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v19.services.CustomerManagerLinkOperation)
CustomerManagerLinkOperationOrBuilder {
private static final long serialVersionUID = 0L;
// Use CustomerManagerLinkOperation.newBuilder() to construct.
private CustomerManagerLinkOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CustomerManagerLinkOperation() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new CustomerManagerLinkOperation();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v19_services_CustomerManagerLinkOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v19_services_CustomerManagerLinkOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.services.CustomerManagerLinkOperation.class, com.google.ads.googleads.v19.services.CustomerManagerLinkOperation.Builder.class);
}
private int bitField0_;
private int operationCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object operation_;
public enum OperationCase
implements com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
UPDATE(2),
OPERATION_NOT_SET(0);
private final int value;
private OperationCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static OperationCase valueOf(int value) {
return forNumber(value);
}
public static OperationCase forNumber(int value) {
switch (value) {
case 2: return UPDATE;
case 0: return OPERATION_NOT_SET;
default: return null;
}
}
public int getNumber() {
return this.value;
}
};
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public static final int UPDATE_MASK_FIELD_NUMBER = 4;
private com.google.protobuf.FieldMask updateMask_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
public static final int UPDATE_FIELD_NUMBER = 2;
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v19.resources.CustomerManagerLink update = 2;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 2;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v19.resources.CustomerManagerLink update = 2;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v19.resources.CustomerManagerLink getUpdate() {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v19.resources.CustomerManagerLink) operation_;
}
return com.google.ads.googleads.v19.resources.CustomerManagerLink.getDefaultInstance();
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v19.resources.CustomerManagerLink update = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v19.resources.CustomerManagerLinkOrBuilder getUpdateOrBuilder() {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v19.resources.CustomerManagerLink) operation_;
}
return com.google.ads.googleads.v19.resources.CustomerManagerLink.getDefaultInstance();
}
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 (operationCase_ == 2) {
output.writeMessage(2, (com.google.ads.googleads.v19.resources.CustomerManagerLink) operation_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(4, getUpdateMask());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (operationCase_ == 2) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, (com.google.ads.googleads.v19.resources.CustomerManagerLink) operation_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, 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.ads.googleads.v19.services.CustomerManagerLinkOperation)) {
return super.equals(obj);
}
com.google.ads.googleads.v19.services.CustomerManagerLinkOperation other = (com.google.ads.googleads.v19.services.CustomerManagerLinkOperation) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask()
.equals(other.getUpdateMask())) return false;
}
if (!getOperationCase().equals(other.getOperationCase())) return false;
switch (operationCase_) {
case 2:
if (!getUpdate()
.equals(other.getUpdate())) return false;
break;
case 0:
default:
}
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 (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
switch (operationCase_) {
case 2:
hash = (37 * hash) + UPDATE_FIELD_NUMBER;
hash = (53 * hash) + getUpdate().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v19.services.CustomerManagerLinkOperation parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.CustomerManagerLinkOperation parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.CustomerManagerLinkOperation parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.CustomerManagerLinkOperation 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.ads.googleads.v19.services.CustomerManagerLinkOperation parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v19.services.CustomerManagerLinkOperation parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v19.services.CustomerManagerLinkOperation parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.CustomerManagerLinkOperation 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.ads.googleads.v19.services.CustomerManagerLinkOperation parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.CustomerManagerLinkOperation 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.ads.googleads.v19.services.CustomerManagerLinkOperation parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v19.services.CustomerManagerLinkOperation 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.ads.googleads.v19.services.CustomerManagerLinkOperation 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>
* Updates the status of a CustomerManagerLink.
* The following actions are possible:
* 1. Update operation with status ACTIVE accepts a pending invitation.
* 2. Update operation with status REFUSED declines a pending invitation.
* 3. Update operation with status INACTIVE terminates link to manager.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v19.services.CustomerManagerLinkOperation}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v19.services.CustomerManagerLinkOperation)
com.google.ads.googleads.v19.services.CustomerManagerLinkOperationOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v19.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v19_services_CustomerManagerLinkOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v19.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v19_services_CustomerManagerLinkOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v19.services.CustomerManagerLinkOperation.class, com.google.ads.googleads.v19.services.CustomerManagerLinkOperation.Builder.class);
}
// Construct using com.google.ads.googleads.v19.services.CustomerManagerLinkOperation.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
if (updateBuilder_ != null) {
updateBuilder_.clear();
}
operationCase_ = 0;
operation_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v19.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v19_services_CustomerManagerLinkOperation_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.CustomerManagerLinkOperation getDefaultInstanceForType() {
return com.google.ads.googleads.v19.services.CustomerManagerLinkOperation.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v19.services.CustomerManagerLinkOperation build() {
com.google.ads.googleads.v19.services.CustomerManagerLinkOperation result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.CustomerManagerLinkOperation buildPartial() {
com.google.ads.googleads.v19.services.CustomerManagerLinkOperation result = new com.google.ads.googleads.v19.services.CustomerManagerLinkOperation(this);
if (bitField0_ != 0) { buildPartial0(result); }
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v19.services.CustomerManagerLinkOperation result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null
? updateMask_
: updateMaskBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
private void buildPartialOneofs(com.google.ads.googleads.v19.services.CustomerManagerLinkOperation result) {
result.operationCase_ = operationCase_;
result.operation_ = this.operation_;
if (operationCase_ == 2 &&
updateBuilder_ != null) {
result.operation_ = updateBuilder_.build();
}
}
@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.ads.googleads.v19.services.CustomerManagerLinkOperation) {
return mergeFrom((com.google.ads.googleads.v19.services.CustomerManagerLinkOperation)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v19.services.CustomerManagerLinkOperation other) {
if (other == com.google.ads.googleads.v19.services.CustomerManagerLinkOperation.getDefaultInstance()) return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
switch (other.getOperationCase()) {
case UPDATE: {
mergeUpdate(other.getUpdate());
break;
}
case OPERATION_NOT_SET: {
break;
}
}
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(
getUpdateFieldBuilder().getBuilder(),
extensionRegistry);
operationCase_ = 2;
break;
} // case 18
case 34: {
input.readMessage(
getUpdateMaskFieldBuilder().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 operationCase_ = 0;
private java.lang.Object operation_;
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public Builder clearOperation() {
operationCase_ = 0;
operation_ = null;
onChanged();
return this;
}
private int bitField0_;
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>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</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>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</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_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder setUpdateMask(
com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0) &&
updateMask_ != null &&
updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000001);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null ?
com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</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 com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.resources.CustomerManagerLink, com.google.ads.googleads.v19.resources.CustomerManagerLink.Builder, com.google.ads.googleads.v19.resources.CustomerManagerLinkOrBuilder> updateBuilder_;
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v19.resources.CustomerManagerLink update = 2;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 2;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v19.resources.CustomerManagerLink update = 2;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v19.resources.CustomerManagerLink getUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v19.resources.CustomerManagerLink) operation_;
}
return com.google.ads.googleads.v19.resources.CustomerManagerLink.getDefaultInstance();
} else {
if (operationCase_ == 2) {
return updateBuilder_.getMessage();
}
return com.google.ads.googleads.v19.resources.CustomerManagerLink.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v19.resources.CustomerManagerLink update = 2;</code>
*/
public Builder setUpdate(com.google.ads.googleads.v19.resources.CustomerManagerLink value) {
if (updateBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
onChanged();
} else {
updateBuilder_.setMessage(value);
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v19.resources.CustomerManagerLink update = 2;</code>
*/
public Builder setUpdate(
com.google.ads.googleads.v19.resources.CustomerManagerLink.Builder builderForValue) {
if (updateBuilder_ == null) {
operation_ = builderForValue.build();
onChanged();
} else {
updateBuilder_.setMessage(builderForValue.build());
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v19.resources.CustomerManagerLink update = 2;</code>
*/
public Builder mergeUpdate(com.google.ads.googleads.v19.resources.CustomerManagerLink value) {
if (updateBuilder_ == null) {
if (operationCase_ == 2 &&
operation_ != com.google.ads.googleads.v19.resources.CustomerManagerLink.getDefaultInstance()) {
operation_ = com.google.ads.googleads.v19.resources.CustomerManagerLink.newBuilder((com.google.ads.googleads.v19.resources.CustomerManagerLink) operation_)
.mergeFrom(value).buildPartial();
} else {
operation_ = value;
}
onChanged();
} else {
if (operationCase_ == 2) {
updateBuilder_.mergeFrom(value);
} else {
updateBuilder_.setMessage(value);
}
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v19.resources.CustomerManagerLink update = 2;</code>
*/
public Builder clearUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 2) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
} else {
if (operationCase_ == 2) {
operationCase_ = 0;
operation_ = null;
}
updateBuilder_.clear();
}
return this;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v19.resources.CustomerManagerLink update = 2;</code>
*/
public com.google.ads.googleads.v19.resources.CustomerManagerLink.Builder getUpdateBuilder() {
return getUpdateFieldBuilder().getBuilder();
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v19.resources.CustomerManagerLink update = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v19.resources.CustomerManagerLinkOrBuilder getUpdateOrBuilder() {
if ((operationCase_ == 2) && (updateBuilder_ != null)) {
return updateBuilder_.getMessageOrBuilder();
} else {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v19.resources.CustomerManagerLink) operation_;
}
return com.google.ads.googleads.v19.resources.CustomerManagerLink.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v19.resources.CustomerManagerLink update = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.resources.CustomerManagerLink, com.google.ads.googleads.v19.resources.CustomerManagerLink.Builder, com.google.ads.googleads.v19.resources.CustomerManagerLinkOrBuilder>
getUpdateFieldBuilder() {
if (updateBuilder_ == null) {
if (!(operationCase_ == 2)) {
operation_ = com.google.ads.googleads.v19.resources.CustomerManagerLink.getDefaultInstance();
}
updateBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v19.resources.CustomerManagerLink, com.google.ads.googleads.v19.resources.CustomerManagerLink.Builder, com.google.ads.googleads.v19.resources.CustomerManagerLinkOrBuilder>(
(com.google.ads.googleads.v19.resources.CustomerManagerLink) operation_,
getParentForChildren(),
isClean());
operation_ = null;
}
operationCase_ = 2;
onChanged();
return updateBuilder_;
}
@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.ads.googleads.v19.services.CustomerManagerLinkOperation)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v19.services.CustomerManagerLinkOperation)
private static final com.google.ads.googleads.v19.services.CustomerManagerLinkOperation DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v19.services.CustomerManagerLinkOperation();
}
public static com.google.ads.googleads.v19.services.CustomerManagerLinkOperation getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CustomerManagerLinkOperation>
PARSER = new com.google.protobuf.AbstractParser<CustomerManagerLinkOperation>() {
@java.lang.Override
public CustomerManagerLinkOperation 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<CustomerManagerLinkOperation> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CustomerManagerLinkOperation> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v19.services.CustomerManagerLinkOperation getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 35,781 | google-ads-stubs-v20/src/main/java/com/google/ads/googleads/v20/services/CustomerManagerLinkOperation.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v20/services/customer_manager_link_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v20.services;
/**
* <pre>
* Updates the status of a CustomerManagerLink.
* The following actions are possible:
* 1. Update operation with status ACTIVE accepts a pending invitation.
* 2. Update operation with status REFUSED declines a pending invitation.
* 3. Update operation with status INACTIVE terminates link to manager.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.services.CustomerManagerLinkOperation}
*/
public final class CustomerManagerLinkOperation extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v20.services.CustomerManagerLinkOperation)
CustomerManagerLinkOperationOrBuilder {
private static final long serialVersionUID = 0L;
// Use CustomerManagerLinkOperation.newBuilder() to construct.
private CustomerManagerLinkOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CustomerManagerLinkOperation() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new CustomerManagerLinkOperation();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v20_services_CustomerManagerLinkOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v20_services_CustomerManagerLinkOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.services.CustomerManagerLinkOperation.class, com.google.ads.googleads.v20.services.CustomerManagerLinkOperation.Builder.class);
}
private int bitField0_;
private int operationCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object operation_;
public enum OperationCase
implements com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
UPDATE(2),
OPERATION_NOT_SET(0);
private final int value;
private OperationCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static OperationCase valueOf(int value) {
return forNumber(value);
}
public static OperationCase forNumber(int value) {
switch (value) {
case 2: return UPDATE;
case 0: return OPERATION_NOT_SET;
default: return null;
}
}
public int getNumber() {
return this.value;
}
};
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public static final int UPDATE_MASK_FIELD_NUMBER = 4;
private com.google.protobuf.FieldMask updateMask_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
public static final int UPDATE_FIELD_NUMBER = 2;
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v20.resources.CustomerManagerLink update = 2;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 2;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v20.resources.CustomerManagerLink update = 2;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v20.resources.CustomerManagerLink getUpdate() {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v20.resources.CustomerManagerLink) operation_;
}
return com.google.ads.googleads.v20.resources.CustomerManagerLink.getDefaultInstance();
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v20.resources.CustomerManagerLink update = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v20.resources.CustomerManagerLinkOrBuilder getUpdateOrBuilder() {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v20.resources.CustomerManagerLink) operation_;
}
return com.google.ads.googleads.v20.resources.CustomerManagerLink.getDefaultInstance();
}
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 (operationCase_ == 2) {
output.writeMessage(2, (com.google.ads.googleads.v20.resources.CustomerManagerLink) operation_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(4, getUpdateMask());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (operationCase_ == 2) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, (com.google.ads.googleads.v20.resources.CustomerManagerLink) operation_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, 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.ads.googleads.v20.services.CustomerManagerLinkOperation)) {
return super.equals(obj);
}
com.google.ads.googleads.v20.services.CustomerManagerLinkOperation other = (com.google.ads.googleads.v20.services.CustomerManagerLinkOperation) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask()
.equals(other.getUpdateMask())) return false;
}
if (!getOperationCase().equals(other.getOperationCase())) return false;
switch (operationCase_) {
case 2:
if (!getUpdate()
.equals(other.getUpdate())) return false;
break;
case 0:
default:
}
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 (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
switch (operationCase_) {
case 2:
hash = (37 * hash) + UPDATE_FIELD_NUMBER;
hash = (53 * hash) + getUpdate().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v20.services.CustomerManagerLinkOperation parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.CustomerManagerLinkOperation parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.CustomerManagerLinkOperation parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.CustomerManagerLinkOperation 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.ads.googleads.v20.services.CustomerManagerLinkOperation parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v20.services.CustomerManagerLinkOperation parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v20.services.CustomerManagerLinkOperation parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.CustomerManagerLinkOperation 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.ads.googleads.v20.services.CustomerManagerLinkOperation parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.CustomerManagerLinkOperation 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.ads.googleads.v20.services.CustomerManagerLinkOperation parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v20.services.CustomerManagerLinkOperation 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.ads.googleads.v20.services.CustomerManagerLinkOperation 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>
* Updates the status of a CustomerManagerLink.
* The following actions are possible:
* 1. Update operation with status ACTIVE accepts a pending invitation.
* 2. Update operation with status REFUSED declines a pending invitation.
* 3. Update operation with status INACTIVE terminates link to manager.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v20.services.CustomerManagerLinkOperation}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v20.services.CustomerManagerLinkOperation)
com.google.ads.googleads.v20.services.CustomerManagerLinkOperationOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v20.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v20_services_CustomerManagerLinkOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v20.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v20_services_CustomerManagerLinkOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v20.services.CustomerManagerLinkOperation.class, com.google.ads.googleads.v20.services.CustomerManagerLinkOperation.Builder.class);
}
// Construct using com.google.ads.googleads.v20.services.CustomerManagerLinkOperation.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
if (updateBuilder_ != null) {
updateBuilder_.clear();
}
operationCase_ = 0;
operation_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v20.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v20_services_CustomerManagerLinkOperation_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.CustomerManagerLinkOperation getDefaultInstanceForType() {
return com.google.ads.googleads.v20.services.CustomerManagerLinkOperation.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v20.services.CustomerManagerLinkOperation build() {
com.google.ads.googleads.v20.services.CustomerManagerLinkOperation result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.CustomerManagerLinkOperation buildPartial() {
com.google.ads.googleads.v20.services.CustomerManagerLinkOperation result = new com.google.ads.googleads.v20.services.CustomerManagerLinkOperation(this);
if (bitField0_ != 0) { buildPartial0(result); }
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v20.services.CustomerManagerLinkOperation result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null
? updateMask_
: updateMaskBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
private void buildPartialOneofs(com.google.ads.googleads.v20.services.CustomerManagerLinkOperation result) {
result.operationCase_ = operationCase_;
result.operation_ = this.operation_;
if (operationCase_ == 2 &&
updateBuilder_ != null) {
result.operation_ = updateBuilder_.build();
}
}
@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.ads.googleads.v20.services.CustomerManagerLinkOperation) {
return mergeFrom((com.google.ads.googleads.v20.services.CustomerManagerLinkOperation)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v20.services.CustomerManagerLinkOperation other) {
if (other == com.google.ads.googleads.v20.services.CustomerManagerLinkOperation.getDefaultInstance()) return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
switch (other.getOperationCase()) {
case UPDATE: {
mergeUpdate(other.getUpdate());
break;
}
case OPERATION_NOT_SET: {
break;
}
}
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(
getUpdateFieldBuilder().getBuilder(),
extensionRegistry);
operationCase_ = 2;
break;
} // case 18
case 34: {
input.readMessage(
getUpdateMaskFieldBuilder().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 operationCase_ = 0;
private java.lang.Object operation_;
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public Builder clearOperation() {
operationCase_ = 0;
operation_ = null;
onChanged();
return this;
}
private int bitField0_;
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>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</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>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</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_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder setUpdateMask(
com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0) &&
updateMask_ != null &&
updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000001);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null ?
com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</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 com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.resources.CustomerManagerLink, com.google.ads.googleads.v20.resources.CustomerManagerLink.Builder, com.google.ads.googleads.v20.resources.CustomerManagerLinkOrBuilder> updateBuilder_;
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v20.resources.CustomerManagerLink update = 2;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 2;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v20.resources.CustomerManagerLink update = 2;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v20.resources.CustomerManagerLink getUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v20.resources.CustomerManagerLink) operation_;
}
return com.google.ads.googleads.v20.resources.CustomerManagerLink.getDefaultInstance();
} else {
if (operationCase_ == 2) {
return updateBuilder_.getMessage();
}
return com.google.ads.googleads.v20.resources.CustomerManagerLink.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v20.resources.CustomerManagerLink update = 2;</code>
*/
public Builder setUpdate(com.google.ads.googleads.v20.resources.CustomerManagerLink value) {
if (updateBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
onChanged();
} else {
updateBuilder_.setMessage(value);
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v20.resources.CustomerManagerLink update = 2;</code>
*/
public Builder setUpdate(
com.google.ads.googleads.v20.resources.CustomerManagerLink.Builder builderForValue) {
if (updateBuilder_ == null) {
operation_ = builderForValue.build();
onChanged();
} else {
updateBuilder_.setMessage(builderForValue.build());
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v20.resources.CustomerManagerLink update = 2;</code>
*/
public Builder mergeUpdate(com.google.ads.googleads.v20.resources.CustomerManagerLink value) {
if (updateBuilder_ == null) {
if (operationCase_ == 2 &&
operation_ != com.google.ads.googleads.v20.resources.CustomerManagerLink.getDefaultInstance()) {
operation_ = com.google.ads.googleads.v20.resources.CustomerManagerLink.newBuilder((com.google.ads.googleads.v20.resources.CustomerManagerLink) operation_)
.mergeFrom(value).buildPartial();
} else {
operation_ = value;
}
onChanged();
} else {
if (operationCase_ == 2) {
updateBuilder_.mergeFrom(value);
} else {
updateBuilder_.setMessage(value);
}
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v20.resources.CustomerManagerLink update = 2;</code>
*/
public Builder clearUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 2) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
} else {
if (operationCase_ == 2) {
operationCase_ = 0;
operation_ = null;
}
updateBuilder_.clear();
}
return this;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v20.resources.CustomerManagerLink update = 2;</code>
*/
public com.google.ads.googleads.v20.resources.CustomerManagerLink.Builder getUpdateBuilder() {
return getUpdateFieldBuilder().getBuilder();
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v20.resources.CustomerManagerLink update = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v20.resources.CustomerManagerLinkOrBuilder getUpdateOrBuilder() {
if ((operationCase_ == 2) && (updateBuilder_ != null)) {
return updateBuilder_.getMessageOrBuilder();
} else {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v20.resources.CustomerManagerLink) operation_;
}
return com.google.ads.googleads.v20.resources.CustomerManagerLink.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v20.resources.CustomerManagerLink update = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.resources.CustomerManagerLink, com.google.ads.googleads.v20.resources.CustomerManagerLink.Builder, com.google.ads.googleads.v20.resources.CustomerManagerLinkOrBuilder>
getUpdateFieldBuilder() {
if (updateBuilder_ == null) {
if (!(operationCase_ == 2)) {
operation_ = com.google.ads.googleads.v20.resources.CustomerManagerLink.getDefaultInstance();
}
updateBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v20.resources.CustomerManagerLink, com.google.ads.googleads.v20.resources.CustomerManagerLink.Builder, com.google.ads.googleads.v20.resources.CustomerManagerLinkOrBuilder>(
(com.google.ads.googleads.v20.resources.CustomerManagerLink) operation_,
getParentForChildren(),
isClean());
operation_ = null;
}
operationCase_ = 2;
onChanged();
return updateBuilder_;
}
@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.ads.googleads.v20.services.CustomerManagerLinkOperation)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v20.services.CustomerManagerLinkOperation)
private static final com.google.ads.googleads.v20.services.CustomerManagerLinkOperation DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v20.services.CustomerManagerLinkOperation();
}
public static com.google.ads.googleads.v20.services.CustomerManagerLinkOperation getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CustomerManagerLinkOperation>
PARSER = new com.google.protobuf.AbstractParser<CustomerManagerLinkOperation>() {
@java.lang.Override
public CustomerManagerLinkOperation 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<CustomerManagerLinkOperation> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CustomerManagerLinkOperation> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v20.services.CustomerManagerLinkOperation getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleads/google-ads-java | 35,781 | google-ads-stubs-v21/src/main/java/com/google/ads/googleads/v21/services/CustomerManagerLinkOperation.java | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v21/services/customer_manager_link_service.proto
// Protobuf Java Version: 3.25.7
package com.google.ads.googleads.v21.services;
/**
* <pre>
* Updates the status of a CustomerManagerLink.
* The following actions are possible:
* 1. Update operation with status ACTIVE accepts a pending invitation.
* 2. Update operation with status REFUSED declines a pending invitation.
* 3. Update operation with status INACTIVE terminates link to manager.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.services.CustomerManagerLinkOperation}
*/
public final class CustomerManagerLinkOperation extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v21.services.CustomerManagerLinkOperation)
CustomerManagerLinkOperationOrBuilder {
private static final long serialVersionUID = 0L;
// Use CustomerManagerLinkOperation.newBuilder() to construct.
private CustomerManagerLinkOperation(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CustomerManagerLinkOperation() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new CustomerManagerLinkOperation();
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v21_services_CustomerManagerLinkOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v21_services_CustomerManagerLinkOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.services.CustomerManagerLinkOperation.class, com.google.ads.googleads.v21.services.CustomerManagerLinkOperation.Builder.class);
}
private int bitField0_;
private int operationCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object operation_;
public enum OperationCase
implements com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
UPDATE(2),
OPERATION_NOT_SET(0);
private final int value;
private OperationCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static OperationCase valueOf(int value) {
return forNumber(value);
}
public static OperationCase forNumber(int value) {
switch (value) {
case 2: return UPDATE;
case 0: return OPERATION_NOT_SET;
default: return null;
}
}
public int getNumber() {
return this.value;
}
};
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public static final int UPDATE_MASK_FIELD_NUMBER = 4;
private com.google.protobuf.FieldMask updateMask_;
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
@java.lang.Override
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
public static final int UPDATE_FIELD_NUMBER = 2;
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v21.resources.CustomerManagerLink update = 2;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 2;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v21.resources.CustomerManagerLink update = 2;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v21.resources.CustomerManagerLink getUpdate() {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v21.resources.CustomerManagerLink) operation_;
}
return com.google.ads.googleads.v21.resources.CustomerManagerLink.getDefaultInstance();
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v21.resources.CustomerManagerLink update = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v21.resources.CustomerManagerLinkOrBuilder getUpdateOrBuilder() {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v21.resources.CustomerManagerLink) operation_;
}
return com.google.ads.googleads.v21.resources.CustomerManagerLink.getDefaultInstance();
}
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 (operationCase_ == 2) {
output.writeMessage(2, (com.google.ads.googleads.v21.resources.CustomerManagerLink) operation_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(4, getUpdateMask());
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (operationCase_ == 2) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, (com.google.ads.googleads.v21.resources.CustomerManagerLink) operation_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(4, 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.ads.googleads.v21.services.CustomerManagerLinkOperation)) {
return super.equals(obj);
}
com.google.ads.googleads.v21.services.CustomerManagerLinkOperation other = (com.google.ads.googleads.v21.services.CustomerManagerLinkOperation) obj;
if (hasUpdateMask() != other.hasUpdateMask()) return false;
if (hasUpdateMask()) {
if (!getUpdateMask()
.equals(other.getUpdateMask())) return false;
}
if (!getOperationCase().equals(other.getOperationCase())) return false;
switch (operationCase_) {
case 2:
if (!getUpdate()
.equals(other.getUpdate())) return false;
break;
case 0:
default:
}
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 (hasUpdateMask()) {
hash = (37 * hash) + UPDATE_MASK_FIELD_NUMBER;
hash = (53 * hash) + getUpdateMask().hashCode();
}
switch (operationCase_) {
case 2:
hash = (37 * hash) + UPDATE_FIELD_NUMBER;
hash = (53 * hash) + getUpdate().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v21.services.CustomerManagerLinkOperation parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.services.CustomerManagerLinkOperation parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.CustomerManagerLinkOperation parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.services.CustomerManagerLinkOperation 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.ads.googleads.v21.services.CustomerManagerLinkOperation parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v21.services.CustomerManagerLinkOperation parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v21.services.CustomerManagerLinkOperation parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.services.CustomerManagerLinkOperation 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.ads.googleads.v21.services.CustomerManagerLinkOperation parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.services.CustomerManagerLinkOperation 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.ads.googleads.v21.services.CustomerManagerLinkOperation parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v21.services.CustomerManagerLinkOperation 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.ads.googleads.v21.services.CustomerManagerLinkOperation 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>
* Updates the status of a CustomerManagerLink.
* The following actions are possible:
* 1. Update operation with status ACTIVE accepts a pending invitation.
* 2. Update operation with status REFUSED declines a pending invitation.
* 3. Update operation with status INACTIVE terminates link to manager.
* </pre>
*
* Protobuf type {@code google.ads.googleads.v21.services.CustomerManagerLinkOperation}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v21.services.CustomerManagerLinkOperation)
com.google.ads.googleads.v21.services.CustomerManagerLinkOperationOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v21.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v21_services_CustomerManagerLinkOperation_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v21.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v21_services_CustomerManagerLinkOperation_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v21.services.CustomerManagerLinkOperation.class, com.google.ads.googleads.v21.services.CustomerManagerLinkOperation.Builder.class);
}
// Construct using com.google.ads.googleads.v21.services.CustomerManagerLinkOperation.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
if (updateBuilder_ != null) {
updateBuilder_.clear();
}
operationCase_ = 0;
operation_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v21.services.CustomerManagerLinkServiceProto.internal_static_google_ads_googleads_v21_services_CustomerManagerLinkOperation_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v21.services.CustomerManagerLinkOperation getDefaultInstanceForType() {
return com.google.ads.googleads.v21.services.CustomerManagerLinkOperation.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v21.services.CustomerManagerLinkOperation build() {
com.google.ads.googleads.v21.services.CustomerManagerLinkOperation result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v21.services.CustomerManagerLinkOperation buildPartial() {
com.google.ads.googleads.v21.services.CustomerManagerLinkOperation result = new com.google.ads.googleads.v21.services.CustomerManagerLinkOperation(this);
if (bitField0_ != 0) { buildPartial0(result); }
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.ads.googleads.v21.services.CustomerManagerLinkOperation result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.updateMask_ = updateMaskBuilder_ == null
? updateMask_
: updateMaskBuilder_.build();
to_bitField0_ |= 0x00000001;
}
result.bitField0_ |= to_bitField0_;
}
private void buildPartialOneofs(com.google.ads.googleads.v21.services.CustomerManagerLinkOperation result) {
result.operationCase_ = operationCase_;
result.operation_ = this.operation_;
if (operationCase_ == 2 &&
updateBuilder_ != null) {
result.operation_ = updateBuilder_.build();
}
}
@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.ads.googleads.v21.services.CustomerManagerLinkOperation) {
return mergeFrom((com.google.ads.googleads.v21.services.CustomerManagerLinkOperation)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v21.services.CustomerManagerLinkOperation other) {
if (other == com.google.ads.googleads.v21.services.CustomerManagerLinkOperation.getDefaultInstance()) return this;
if (other.hasUpdateMask()) {
mergeUpdateMask(other.getUpdateMask());
}
switch (other.getOperationCase()) {
case UPDATE: {
mergeUpdate(other.getUpdate());
break;
}
case OPERATION_NOT_SET: {
break;
}
}
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(
getUpdateFieldBuilder().getBuilder(),
extensionRegistry);
operationCase_ = 2;
break;
} // case 18
case 34: {
input.readMessage(
getUpdateMaskFieldBuilder().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 operationCase_ = 0;
private java.lang.Object operation_;
public OperationCase
getOperationCase() {
return OperationCase.forNumber(
operationCase_);
}
public Builder clearOperation() {
operationCase_ = 0;
operation_ = null;
onChanged();
return this;
}
private int bitField0_;
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>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</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>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</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_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder setUpdateMask(
com.google.protobuf.FieldMask.Builder builderForValue) {
if (updateMaskBuilder_ == null) {
updateMask_ = builderForValue.build();
} else {
updateMaskBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder mergeUpdateMask(com.google.protobuf.FieldMask value) {
if (updateMaskBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0) &&
updateMask_ != null &&
updateMask_ != com.google.protobuf.FieldMask.getDefaultInstance()) {
getUpdateMaskBuilder().mergeFrom(value);
} else {
updateMask_ = value;
}
} else {
updateMaskBuilder_.mergeFrom(value);
}
if (updateMask_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000001);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null ?
com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
}
/**
* <pre>
* FieldMask that determines which resource fields are modified in an update.
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 4;</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 com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.resources.CustomerManagerLink, com.google.ads.googleads.v21.resources.CustomerManagerLink.Builder, com.google.ads.googleads.v21.resources.CustomerManagerLinkOrBuilder> updateBuilder_;
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v21.resources.CustomerManagerLink update = 2;</code>
* @return Whether the update field is set.
*/
@java.lang.Override
public boolean hasUpdate() {
return operationCase_ == 2;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v21.resources.CustomerManagerLink update = 2;</code>
* @return The update.
*/
@java.lang.Override
public com.google.ads.googleads.v21.resources.CustomerManagerLink getUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v21.resources.CustomerManagerLink) operation_;
}
return com.google.ads.googleads.v21.resources.CustomerManagerLink.getDefaultInstance();
} else {
if (operationCase_ == 2) {
return updateBuilder_.getMessage();
}
return com.google.ads.googleads.v21.resources.CustomerManagerLink.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v21.resources.CustomerManagerLink update = 2;</code>
*/
public Builder setUpdate(com.google.ads.googleads.v21.resources.CustomerManagerLink value) {
if (updateBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
operation_ = value;
onChanged();
} else {
updateBuilder_.setMessage(value);
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v21.resources.CustomerManagerLink update = 2;</code>
*/
public Builder setUpdate(
com.google.ads.googleads.v21.resources.CustomerManagerLink.Builder builderForValue) {
if (updateBuilder_ == null) {
operation_ = builderForValue.build();
onChanged();
} else {
updateBuilder_.setMessage(builderForValue.build());
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v21.resources.CustomerManagerLink update = 2;</code>
*/
public Builder mergeUpdate(com.google.ads.googleads.v21.resources.CustomerManagerLink value) {
if (updateBuilder_ == null) {
if (operationCase_ == 2 &&
operation_ != com.google.ads.googleads.v21.resources.CustomerManagerLink.getDefaultInstance()) {
operation_ = com.google.ads.googleads.v21.resources.CustomerManagerLink.newBuilder((com.google.ads.googleads.v21.resources.CustomerManagerLink) operation_)
.mergeFrom(value).buildPartial();
} else {
operation_ = value;
}
onChanged();
} else {
if (operationCase_ == 2) {
updateBuilder_.mergeFrom(value);
} else {
updateBuilder_.setMessage(value);
}
}
operationCase_ = 2;
return this;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v21.resources.CustomerManagerLink update = 2;</code>
*/
public Builder clearUpdate() {
if (updateBuilder_ == null) {
if (operationCase_ == 2) {
operationCase_ = 0;
operation_ = null;
onChanged();
}
} else {
if (operationCase_ == 2) {
operationCase_ = 0;
operation_ = null;
}
updateBuilder_.clear();
}
return this;
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v21.resources.CustomerManagerLink update = 2;</code>
*/
public com.google.ads.googleads.v21.resources.CustomerManagerLink.Builder getUpdateBuilder() {
return getUpdateFieldBuilder().getBuilder();
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v21.resources.CustomerManagerLink update = 2;</code>
*/
@java.lang.Override
public com.google.ads.googleads.v21.resources.CustomerManagerLinkOrBuilder getUpdateOrBuilder() {
if ((operationCase_ == 2) && (updateBuilder_ != null)) {
return updateBuilder_.getMessageOrBuilder();
} else {
if (operationCase_ == 2) {
return (com.google.ads.googleads.v21.resources.CustomerManagerLink) operation_;
}
return com.google.ads.googleads.v21.resources.CustomerManagerLink.getDefaultInstance();
}
}
/**
* <pre>
* Update operation: The link is expected to have a valid resource name.
* </pre>
*
* <code>.google.ads.googleads.v21.resources.CustomerManagerLink update = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.resources.CustomerManagerLink, com.google.ads.googleads.v21.resources.CustomerManagerLink.Builder, com.google.ads.googleads.v21.resources.CustomerManagerLinkOrBuilder>
getUpdateFieldBuilder() {
if (updateBuilder_ == null) {
if (!(operationCase_ == 2)) {
operation_ = com.google.ads.googleads.v21.resources.CustomerManagerLink.getDefaultInstance();
}
updateBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.ads.googleads.v21.resources.CustomerManagerLink, com.google.ads.googleads.v21.resources.CustomerManagerLink.Builder, com.google.ads.googleads.v21.resources.CustomerManagerLinkOrBuilder>(
(com.google.ads.googleads.v21.resources.CustomerManagerLink) operation_,
getParentForChildren(),
isClean());
operation_ = null;
}
operationCase_ = 2;
onChanged();
return updateBuilder_;
}
@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.ads.googleads.v21.services.CustomerManagerLinkOperation)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v21.services.CustomerManagerLinkOperation)
private static final com.google.ads.googleads.v21.services.CustomerManagerLinkOperation DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v21.services.CustomerManagerLinkOperation();
}
public static com.google.ads.googleads.v21.services.CustomerManagerLinkOperation getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CustomerManagerLinkOperation>
PARSER = new com.google.protobuf.AbstractParser<CustomerManagerLinkOperation>() {
@java.lang.Override
public CustomerManagerLinkOperation 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<CustomerManagerLinkOperation> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CustomerManagerLinkOperation> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v21.services.CustomerManagerLinkOperation getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,573 | java-notebooks/proto-google-cloud-notebooks-v1beta1/src/main/java/com/google/cloud/notebooks/v1beta1/IsInstanceUpgradeableResponse.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/v1beta1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.notebooks.v1beta1;
/**
*
*
* <pre>
* Response for checking if a notebook instance is upgradeable.
* </pre>
*
* Protobuf type {@code google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse}
*/
public final class IsInstanceUpgradeableResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse)
IsInstanceUpgradeableResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use IsInstanceUpgradeableResponse.newBuilder() to construct.
private IsInstanceUpgradeableResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private IsInstanceUpgradeableResponse() {
upgradeVersion_ = "";
upgradeInfo_ = "";
upgradeImage_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new IsInstanceUpgradeableResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.notebooks.v1beta1.NotebooksProto
.internal_static_google_cloud_notebooks_v1beta1_IsInstanceUpgradeableResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.notebooks.v1beta1.NotebooksProto
.internal_static_google_cloud_notebooks_v1beta1_IsInstanceUpgradeableResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse.class,
com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse.Builder.class);
}
public static final int UPGRADEABLE_FIELD_NUMBER = 1;
private boolean upgradeable_ = false;
/**
*
*
* <pre>
* If an instance is upgradeable.
* </pre>
*
* <code>bool upgradeable = 1;</code>
*
* @return The upgradeable.
*/
@java.lang.Override
public boolean getUpgradeable() {
return upgradeable_;
}
public static final int UPGRADE_VERSION_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object upgradeVersion_ = "";
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @return The upgradeVersion.
*/
@java.lang.Override
public java.lang.String getUpgradeVersion() {
java.lang.Object ref = upgradeVersion_;
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();
upgradeVersion_ = s;
return s;
}
}
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @return The bytes for upgradeVersion.
*/
@java.lang.Override
public com.google.protobuf.ByteString getUpgradeVersionBytes() {
java.lang.Object ref = upgradeVersion_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
upgradeVersion_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int UPGRADE_INFO_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object upgradeInfo_ = "";
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @return The upgradeInfo.
*/
@java.lang.Override
public java.lang.String getUpgradeInfo() {
java.lang.Object ref = upgradeInfo_;
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();
upgradeInfo_ = s;
return s;
}
}
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @return The bytes for upgradeInfo.
*/
@java.lang.Override
public com.google.protobuf.ByteString getUpgradeInfoBytes() {
java.lang.Object ref = upgradeInfo_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
upgradeInfo_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int UPGRADE_IMAGE_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object upgradeImage_ = "";
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @return The upgradeImage.
*/
@java.lang.Override
public java.lang.String getUpgradeImage() {
java.lang.Object ref = upgradeImage_;
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();
upgradeImage_ = s;
return s;
}
}
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @return The bytes for upgradeImage.
*/
@java.lang.Override
public com.google.protobuf.ByteString getUpgradeImageBytes() {
java.lang.Object ref = upgradeImage_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
upgradeImage_ = 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 (upgradeable_ != false) {
output.writeBool(1, upgradeable_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(upgradeVersion_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, upgradeVersion_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(upgradeInfo_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, upgradeInfo_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(upgradeImage_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, upgradeImage_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (upgradeable_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(1, upgradeable_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(upgradeVersion_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, upgradeVersion_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(upgradeInfo_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, upgradeInfo_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(upgradeImage_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, upgradeImage_);
}
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.v1beta1.IsInstanceUpgradeableResponse)) {
return super.equals(obj);
}
com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse other =
(com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse) obj;
if (getUpgradeable() != other.getUpgradeable()) return false;
if (!getUpgradeVersion().equals(other.getUpgradeVersion())) return false;
if (!getUpgradeInfo().equals(other.getUpgradeInfo())) return false;
if (!getUpgradeImage().equals(other.getUpgradeImage())) 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) + UPGRADEABLE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getUpgradeable());
hash = (37 * hash) + UPGRADE_VERSION_FIELD_NUMBER;
hash = (53 * hash) + getUpgradeVersion().hashCode();
hash = (37 * hash) + UPGRADE_INFO_FIELD_NUMBER;
hash = (53 * hash) + getUpgradeInfo().hashCode();
hash = (37 * hash) + UPGRADE_IMAGE_FIELD_NUMBER;
hash = (53 * hash) + getUpgradeImage().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse 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.v1beta1.IsInstanceUpgradeableResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse 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.v1beta1.IsInstanceUpgradeableResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse 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.v1beta1.IsInstanceUpgradeableResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse 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.v1beta1.IsInstanceUpgradeableResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse 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.v1beta1.IsInstanceUpgradeableResponse 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 checking if a notebook instance is upgradeable.
* </pre>
*
* Protobuf type {@code google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse)
com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.notebooks.v1beta1.NotebooksProto
.internal_static_google_cloud_notebooks_v1beta1_IsInstanceUpgradeableResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.notebooks.v1beta1.NotebooksProto
.internal_static_google_cloud_notebooks_v1beta1_IsInstanceUpgradeableResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse.class,
com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse.Builder.class);
}
// Construct using com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
upgradeable_ = false;
upgradeVersion_ = "";
upgradeInfo_ = "";
upgradeImage_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.notebooks.v1beta1.NotebooksProto
.internal_static_google_cloud_notebooks_v1beta1_IsInstanceUpgradeableResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse
getDefaultInstanceForType() {
return com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse build() {
com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse buildPartial() {
com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse result =
new com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.upgradeable_ = upgradeable_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.upgradeVersion_ = upgradeVersion_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.upgradeInfo_ = upgradeInfo_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.upgradeImage_ = upgradeImage_;
}
}
@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.v1beta1.IsInstanceUpgradeableResponse) {
return mergeFrom((com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse other) {
if (other
== com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse.getDefaultInstance())
return this;
if (other.getUpgradeable() != false) {
setUpgradeable(other.getUpgradeable());
}
if (!other.getUpgradeVersion().isEmpty()) {
upgradeVersion_ = other.upgradeVersion_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getUpgradeInfo().isEmpty()) {
upgradeInfo_ = other.upgradeInfo_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getUpgradeImage().isEmpty()) {
upgradeImage_ = other.upgradeImage_;
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 8:
{
upgradeable_ = input.readBool();
bitField0_ |= 0x00000001;
break;
} // case 8
case 18:
{
upgradeVersion_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
upgradeInfo_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
upgradeImage_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
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 boolean upgradeable_;
/**
*
*
* <pre>
* If an instance is upgradeable.
* </pre>
*
* <code>bool upgradeable = 1;</code>
*
* @return The upgradeable.
*/
@java.lang.Override
public boolean getUpgradeable() {
return upgradeable_;
}
/**
*
*
* <pre>
* If an instance is upgradeable.
* </pre>
*
* <code>bool upgradeable = 1;</code>
*
* @param value The upgradeable to set.
* @return This builder for chaining.
*/
public Builder setUpgradeable(boolean value) {
upgradeable_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* If an instance is upgradeable.
* </pre>
*
* <code>bool upgradeable = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearUpgradeable() {
bitField0_ = (bitField0_ & ~0x00000001);
upgradeable_ = false;
onChanged();
return this;
}
private java.lang.Object upgradeVersion_ = "";
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @return The upgradeVersion.
*/
public java.lang.String getUpgradeVersion() {
java.lang.Object ref = upgradeVersion_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
upgradeVersion_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @return The bytes for upgradeVersion.
*/
public com.google.protobuf.ByteString getUpgradeVersionBytes() {
java.lang.Object ref = upgradeVersion_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
upgradeVersion_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @param value The upgradeVersion to set.
* @return This builder for chaining.
*/
public Builder setUpgradeVersion(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
upgradeVersion_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearUpgradeVersion() {
upgradeVersion_ = getDefaultInstance().getUpgradeVersion();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @param value The bytes for upgradeVersion to set.
* @return This builder for chaining.
*/
public Builder setUpgradeVersionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
upgradeVersion_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object upgradeInfo_ = "";
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @return The upgradeInfo.
*/
public java.lang.String getUpgradeInfo() {
java.lang.Object ref = upgradeInfo_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
upgradeInfo_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @return The bytes for upgradeInfo.
*/
public com.google.protobuf.ByteString getUpgradeInfoBytes() {
java.lang.Object ref = upgradeInfo_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
upgradeInfo_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @param value The upgradeInfo to set.
* @return This builder for chaining.
*/
public Builder setUpgradeInfo(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
upgradeInfo_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearUpgradeInfo() {
upgradeInfo_ = getDefaultInstance().getUpgradeInfo();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @param value The bytes for upgradeInfo to set.
* @return This builder for chaining.
*/
public Builder setUpgradeInfoBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
upgradeInfo_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object upgradeImage_ = "";
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @return The upgradeImage.
*/
public java.lang.String getUpgradeImage() {
java.lang.Object ref = upgradeImage_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
upgradeImage_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @return The bytes for upgradeImage.
*/
public com.google.protobuf.ByteString getUpgradeImageBytes() {
java.lang.Object ref = upgradeImage_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
upgradeImage_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @param value The upgradeImage to set.
* @return This builder for chaining.
*/
public Builder setUpgradeImage(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
upgradeImage_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearUpgradeImage() {
upgradeImage_ = getDefaultInstance().getUpgradeImage();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @param value The bytes for upgradeImage to set.
* @return This builder for chaining.
*/
public Builder setUpgradeImageBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
upgradeImage_ = 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.notebooks.v1beta1.IsInstanceUpgradeableResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse)
private static final com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse();
}
public static com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<IsInstanceUpgradeableResponse> PARSER =
new com.google.protobuf.AbstractParser<IsInstanceUpgradeableResponse>() {
@java.lang.Override
public IsInstanceUpgradeableResponse 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<IsInstanceUpgradeableResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<IsInstanceUpgradeableResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.notebooks.v1beta1.IsInstanceUpgradeableResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,695 | java-channel/proto-google-cloud-channel-v1/src/main/java/com/google/cloud/channel/v1/CheckCloudIdentityAccountsExistResponse.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/channel/v1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.channel.v1;
/**
*
*
* <pre>
* Response message for
* [CloudChannelService.CheckCloudIdentityAccountsExist][google.cloud.channel.v1.CloudChannelService.CheckCloudIdentityAccountsExist].
* </pre>
*
* Protobuf type {@code google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse}
*/
public final class CheckCloudIdentityAccountsExistResponse
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse)
CheckCloudIdentityAccountsExistResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use CheckCloudIdentityAccountsExistResponse.newBuilder() to construct.
private CheckCloudIdentityAccountsExistResponse(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CheckCloudIdentityAccountsExistResponse() {
cloudIdentityAccounts_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CheckCloudIdentityAccountsExistResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.channel.v1.ServiceProto
.internal_static_google_cloud_channel_v1_CheckCloudIdentityAccountsExistResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.channel.v1.ServiceProto
.internal_static_google_cloud_channel_v1_CheckCloudIdentityAccountsExistResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse.class,
com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse.Builder.class);
}
public static final int CLOUD_IDENTITY_ACCOUNTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.channel.v1.CloudIdentityCustomerAccount>
cloudIdentityAccounts_;
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.channel.v1.CloudIdentityCustomerAccount>
getCloudIdentityAccountsList() {
return cloudIdentityAccounts_;
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.channel.v1.CloudIdentityCustomerAccountOrBuilder>
getCloudIdentityAccountsOrBuilderList() {
return cloudIdentityAccounts_;
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
@java.lang.Override
public int getCloudIdentityAccountsCount() {
return cloudIdentityAccounts_.size();
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
@java.lang.Override
public com.google.cloud.channel.v1.CloudIdentityCustomerAccount getCloudIdentityAccounts(
int index) {
return cloudIdentityAccounts_.get(index);
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
@java.lang.Override
public com.google.cloud.channel.v1.CloudIdentityCustomerAccountOrBuilder
getCloudIdentityAccountsOrBuilder(int index) {
return cloudIdentityAccounts_.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 < cloudIdentityAccounts_.size(); i++) {
output.writeMessage(1, cloudIdentityAccounts_.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 < cloudIdentityAccounts_.size(); i++) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, cloudIdentityAccounts_.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.channel.v1.CheckCloudIdentityAccountsExistResponse)) {
return super.equals(obj);
}
com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse other =
(com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse) obj;
if (!getCloudIdentityAccountsList().equals(other.getCloudIdentityAccountsList())) 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 (getCloudIdentityAccountsCount() > 0) {
hash = (37 * hash) + CLOUD_IDENTITY_ACCOUNTS_FIELD_NUMBER;
hash = (53 * hash) + getCloudIdentityAccountsList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse 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.channel.v1.CheckCloudIdentityAccountsExistResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse 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.channel.v1.CheckCloudIdentityAccountsExistResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse 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.channel.v1.CheckCloudIdentityAccountsExistResponse
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse
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.channel.v1.CheckCloudIdentityAccountsExistResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse 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.channel.v1.CheckCloudIdentityAccountsExistResponse 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
* [CloudChannelService.CheckCloudIdentityAccountsExist][google.cloud.channel.v1.CloudChannelService.CheckCloudIdentityAccountsExist].
* </pre>
*
* Protobuf type {@code google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse)
com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.channel.v1.ServiceProto
.internal_static_google_cloud_channel_v1_CheckCloudIdentityAccountsExistResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.channel.v1.ServiceProto
.internal_static_google_cloud_channel_v1_CheckCloudIdentityAccountsExistResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse.class,
com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse.Builder.class);
}
// Construct using
// com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (cloudIdentityAccountsBuilder_ == null) {
cloudIdentityAccounts_ = java.util.Collections.emptyList();
} else {
cloudIdentityAccounts_ = null;
cloudIdentityAccountsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.channel.v1.ServiceProto
.internal_static_google_cloud_channel_v1_CheckCloudIdentityAccountsExistResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse
getDefaultInstanceForType() {
return com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse
.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse build() {
com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse buildPartial() {
com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse result =
new com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse result) {
if (cloudIdentityAccountsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
cloudIdentityAccounts_ = java.util.Collections.unmodifiableList(cloudIdentityAccounts_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.cloudIdentityAccounts_ = cloudIdentityAccounts_;
} else {
result.cloudIdentityAccounts_ = cloudIdentityAccountsBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse 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.channel.v1.CheckCloudIdentityAccountsExistResponse) {
return mergeFrom(
(com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse other) {
if (other
== com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse
.getDefaultInstance()) return this;
if (cloudIdentityAccountsBuilder_ == null) {
if (!other.cloudIdentityAccounts_.isEmpty()) {
if (cloudIdentityAccounts_.isEmpty()) {
cloudIdentityAccounts_ = other.cloudIdentityAccounts_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureCloudIdentityAccountsIsMutable();
cloudIdentityAccounts_.addAll(other.cloudIdentityAccounts_);
}
onChanged();
}
} else {
if (!other.cloudIdentityAccounts_.isEmpty()) {
if (cloudIdentityAccountsBuilder_.isEmpty()) {
cloudIdentityAccountsBuilder_.dispose();
cloudIdentityAccountsBuilder_ = null;
cloudIdentityAccounts_ = other.cloudIdentityAccounts_;
bitField0_ = (bitField0_ & ~0x00000001);
cloudIdentityAccountsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getCloudIdentityAccountsFieldBuilder()
: null;
} else {
cloudIdentityAccountsBuilder_.addAllMessages(other.cloudIdentityAccounts_);
}
}
}
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.channel.v1.CloudIdentityCustomerAccount m =
input.readMessage(
com.google.cloud.channel.v1.CloudIdentityCustomerAccount.parser(),
extensionRegistry);
if (cloudIdentityAccountsBuilder_ == null) {
ensureCloudIdentityAccountsIsMutable();
cloudIdentityAccounts_.add(m);
} else {
cloudIdentityAccountsBuilder_.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.channel.v1.CloudIdentityCustomerAccount>
cloudIdentityAccounts_ = java.util.Collections.emptyList();
private void ensureCloudIdentityAccountsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
cloudIdentityAccounts_ =
new java.util.ArrayList<com.google.cloud.channel.v1.CloudIdentityCustomerAccount>(
cloudIdentityAccounts_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.channel.v1.CloudIdentityCustomerAccount,
com.google.cloud.channel.v1.CloudIdentityCustomerAccount.Builder,
com.google.cloud.channel.v1.CloudIdentityCustomerAccountOrBuilder>
cloudIdentityAccountsBuilder_;
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public java.util.List<com.google.cloud.channel.v1.CloudIdentityCustomerAccount>
getCloudIdentityAccountsList() {
if (cloudIdentityAccountsBuilder_ == null) {
return java.util.Collections.unmodifiableList(cloudIdentityAccounts_);
} else {
return cloudIdentityAccountsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public int getCloudIdentityAccountsCount() {
if (cloudIdentityAccountsBuilder_ == null) {
return cloudIdentityAccounts_.size();
} else {
return cloudIdentityAccountsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public com.google.cloud.channel.v1.CloudIdentityCustomerAccount getCloudIdentityAccounts(
int index) {
if (cloudIdentityAccountsBuilder_ == null) {
return cloudIdentityAccounts_.get(index);
} else {
return cloudIdentityAccountsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public Builder setCloudIdentityAccounts(
int index, com.google.cloud.channel.v1.CloudIdentityCustomerAccount value) {
if (cloudIdentityAccountsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCloudIdentityAccountsIsMutable();
cloudIdentityAccounts_.set(index, value);
onChanged();
} else {
cloudIdentityAccountsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public Builder setCloudIdentityAccounts(
int index,
com.google.cloud.channel.v1.CloudIdentityCustomerAccount.Builder builderForValue) {
if (cloudIdentityAccountsBuilder_ == null) {
ensureCloudIdentityAccountsIsMutable();
cloudIdentityAccounts_.set(index, builderForValue.build());
onChanged();
} else {
cloudIdentityAccountsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public Builder addCloudIdentityAccounts(
com.google.cloud.channel.v1.CloudIdentityCustomerAccount value) {
if (cloudIdentityAccountsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCloudIdentityAccountsIsMutable();
cloudIdentityAccounts_.add(value);
onChanged();
} else {
cloudIdentityAccountsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public Builder addCloudIdentityAccounts(
int index, com.google.cloud.channel.v1.CloudIdentityCustomerAccount value) {
if (cloudIdentityAccountsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureCloudIdentityAccountsIsMutable();
cloudIdentityAccounts_.add(index, value);
onChanged();
} else {
cloudIdentityAccountsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public Builder addCloudIdentityAccounts(
com.google.cloud.channel.v1.CloudIdentityCustomerAccount.Builder builderForValue) {
if (cloudIdentityAccountsBuilder_ == null) {
ensureCloudIdentityAccountsIsMutable();
cloudIdentityAccounts_.add(builderForValue.build());
onChanged();
} else {
cloudIdentityAccountsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public Builder addCloudIdentityAccounts(
int index,
com.google.cloud.channel.v1.CloudIdentityCustomerAccount.Builder builderForValue) {
if (cloudIdentityAccountsBuilder_ == null) {
ensureCloudIdentityAccountsIsMutable();
cloudIdentityAccounts_.add(index, builderForValue.build());
onChanged();
} else {
cloudIdentityAccountsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public Builder addAllCloudIdentityAccounts(
java.lang.Iterable<? extends com.google.cloud.channel.v1.CloudIdentityCustomerAccount>
values) {
if (cloudIdentityAccountsBuilder_ == null) {
ensureCloudIdentityAccountsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, cloudIdentityAccounts_);
onChanged();
} else {
cloudIdentityAccountsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public Builder clearCloudIdentityAccounts() {
if (cloudIdentityAccountsBuilder_ == null) {
cloudIdentityAccounts_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
cloudIdentityAccountsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public Builder removeCloudIdentityAccounts(int index) {
if (cloudIdentityAccountsBuilder_ == null) {
ensureCloudIdentityAccountsIsMutable();
cloudIdentityAccounts_.remove(index);
onChanged();
} else {
cloudIdentityAccountsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public com.google.cloud.channel.v1.CloudIdentityCustomerAccount.Builder
getCloudIdentityAccountsBuilder(int index) {
return getCloudIdentityAccountsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public com.google.cloud.channel.v1.CloudIdentityCustomerAccountOrBuilder
getCloudIdentityAccountsOrBuilder(int index) {
if (cloudIdentityAccountsBuilder_ == null) {
return cloudIdentityAccounts_.get(index);
} else {
return cloudIdentityAccountsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public java.util.List<
? extends com.google.cloud.channel.v1.CloudIdentityCustomerAccountOrBuilder>
getCloudIdentityAccountsOrBuilderList() {
if (cloudIdentityAccountsBuilder_ != null) {
return cloudIdentityAccountsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(cloudIdentityAccounts_);
}
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public com.google.cloud.channel.v1.CloudIdentityCustomerAccount.Builder
addCloudIdentityAccountsBuilder() {
return getCloudIdentityAccountsFieldBuilder()
.addBuilder(
com.google.cloud.channel.v1.CloudIdentityCustomerAccount.getDefaultInstance());
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public com.google.cloud.channel.v1.CloudIdentityCustomerAccount.Builder
addCloudIdentityAccountsBuilder(int index) {
return getCloudIdentityAccountsFieldBuilder()
.addBuilder(
index, com.google.cloud.channel.v1.CloudIdentityCustomerAccount.getDefaultInstance());
}
/**
*
*
* <pre>
* The Cloud Identity accounts associated with the domain.
* </pre>
*
* <code>
* repeated .google.cloud.channel.v1.CloudIdentityCustomerAccount cloud_identity_accounts = 1;
* </code>
*/
public java.util.List<com.google.cloud.channel.v1.CloudIdentityCustomerAccount.Builder>
getCloudIdentityAccountsBuilderList() {
return getCloudIdentityAccountsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.channel.v1.CloudIdentityCustomerAccount,
com.google.cloud.channel.v1.CloudIdentityCustomerAccount.Builder,
com.google.cloud.channel.v1.CloudIdentityCustomerAccountOrBuilder>
getCloudIdentityAccountsFieldBuilder() {
if (cloudIdentityAccountsBuilder_ == null) {
cloudIdentityAccountsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.channel.v1.CloudIdentityCustomerAccount,
com.google.cloud.channel.v1.CloudIdentityCustomerAccount.Builder,
com.google.cloud.channel.v1.CloudIdentityCustomerAccountOrBuilder>(
cloudIdentityAccounts_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
cloudIdentityAccounts_ = null;
}
return cloudIdentityAccountsBuilder_;
}
@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.channel.v1.CheckCloudIdentityAccountsExistResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse)
private static final com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse();
}
public static com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CheckCloudIdentityAccountsExistResponse> PARSER =
new com.google.protobuf.AbstractParser<CheckCloudIdentityAccountsExistResponse>() {
@java.lang.Override
public CheckCloudIdentityAccountsExistResponse 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<CheckCloudIdentityAccountsExistResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CheckCloudIdentityAccountsExistResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.channel.v1.CheckCloudIdentityAccountsExistResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
openjdk/jdk8 | 35,856 | jdk/src/share/classes/com/sun/java/swing/plaf/windows/WindowsIconFactory.java | /*
* Copyright (c) 1998, 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.java.swing.plaf.windows;
import javax.swing.*;
import javax.swing.plaf.ButtonUI;
import javax.swing.plaf.UIResource;
import java.awt.*;
import java.io.Serializable;
import static com.sun.java.swing.plaf.windows.TMSchema.*;
import static com.sun.java.swing.plaf.windows.XPStyle.Skin;
import sun.swing.MenuItemCheckIconFactory;
/**
* Factory object that can vend Icons appropriate for the Windows L & F.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is appropriate
* for short term storage or RMI between applications running the same
* version of Swing. A future release of Swing will provide support for
* long term persistence.
*
* @author David Kloba
* @author Georges Saab
* @author Rich Schiavi
*/
public class WindowsIconFactory implements Serializable
{
private static Icon frame_closeIcon;
private static Icon frame_iconifyIcon;
private static Icon frame_maxIcon;
private static Icon frame_minIcon;
private static Icon frame_resizeIcon;
private static Icon checkBoxIcon;
private static Icon radioButtonIcon;
private static Icon checkBoxMenuItemIcon;
private static Icon radioButtonMenuItemIcon;
private static Icon menuItemCheckIcon;
private static Icon menuItemArrowIcon;
private static Icon menuArrowIcon;
private static VistaMenuItemCheckIconFactory menuItemCheckIconFactory;
public static Icon getMenuItemCheckIcon() {
if (menuItemCheckIcon == null) {
menuItemCheckIcon = new MenuItemCheckIcon();
}
return menuItemCheckIcon;
}
public static Icon getMenuItemArrowIcon() {
if (menuItemArrowIcon == null) {
menuItemArrowIcon = new MenuItemArrowIcon();
}
return menuItemArrowIcon;
}
public static Icon getMenuArrowIcon() {
if (menuArrowIcon == null) {
menuArrowIcon = new MenuArrowIcon();
}
return menuArrowIcon;
}
public static Icon getCheckBoxIcon() {
if (checkBoxIcon == null) {
checkBoxIcon = new CheckBoxIcon();
}
return checkBoxIcon;
}
public static Icon getRadioButtonIcon() {
if (radioButtonIcon == null) {
radioButtonIcon = new RadioButtonIcon();
}
return radioButtonIcon;
}
public static Icon getCheckBoxMenuItemIcon() {
if (checkBoxMenuItemIcon == null) {
checkBoxMenuItemIcon = new CheckBoxMenuItemIcon();
}
return checkBoxMenuItemIcon;
}
public static Icon getRadioButtonMenuItemIcon() {
if (radioButtonMenuItemIcon == null) {
radioButtonMenuItemIcon = new RadioButtonMenuItemIcon();
}
return radioButtonMenuItemIcon;
}
static
synchronized VistaMenuItemCheckIconFactory getMenuItemCheckIconFactory() {
if (menuItemCheckIconFactory == null) {
menuItemCheckIconFactory =
new VistaMenuItemCheckIconFactory();
}
return menuItemCheckIconFactory;
}
public static Icon createFrameCloseIcon() {
if (frame_closeIcon == null) {
frame_closeIcon = new FrameButtonIcon(Part.WP_CLOSEBUTTON);
}
return frame_closeIcon;
}
public static Icon createFrameIconifyIcon() {
if (frame_iconifyIcon == null) {
frame_iconifyIcon = new FrameButtonIcon(Part.WP_MINBUTTON);
}
return frame_iconifyIcon;
}
public static Icon createFrameMaximizeIcon() {
if (frame_maxIcon == null) {
frame_maxIcon = new FrameButtonIcon(Part.WP_MAXBUTTON);
}
return frame_maxIcon;
}
public static Icon createFrameMinimizeIcon() {
if (frame_minIcon == null) {
frame_minIcon = new FrameButtonIcon(Part.WP_RESTOREBUTTON);
}
return frame_minIcon;
}
public static Icon createFrameResizeIcon() {
if(frame_resizeIcon == null)
frame_resizeIcon = new ResizeIcon();
return frame_resizeIcon;
}
private static class FrameButtonIcon implements Icon, Serializable {
private Part part;
private FrameButtonIcon(Part part) {
this.part = part;
}
public void paintIcon(Component c, Graphics g, int x0, int y0) {
int width = getIconWidth();
int height = getIconHeight();
XPStyle xp = XPStyle.getXP();
if (xp != null) {
Skin skin = xp.getSkin(c, part);
AbstractButton b = (AbstractButton)c;
ButtonModel model = b.getModel();
// Find out if frame is inactive
JInternalFrame jif = (JInternalFrame)SwingUtilities.
getAncestorOfClass(JInternalFrame.class, b);
boolean jifSelected = (jif != null && jif.isSelected());
State state;
if (jifSelected) {
if (!model.isEnabled()) {
state = State.DISABLED;
} else if (model.isArmed() && model.isPressed()) {
state = State.PUSHED;
} else if (model.isRollover()) {
state = State.HOT;
} else {
state = State.NORMAL;
}
} else {
if (!model.isEnabled()) {
state = State.INACTIVEDISABLED;
} else if (model.isArmed() && model.isPressed()) {
state = State.INACTIVEPUSHED;
} else if (model.isRollover()) {
state = State.INACTIVEHOT;
} else {
state = State.INACTIVENORMAL;
}
}
skin.paintSkin(g, 0, 0, width, height, state);
} else {
g.setColor(Color.black);
int x = width / 12 + 2;
int y = height / 5;
int h = height - y * 2 - 1;
int w = width * 3/4 -3;
int thickness2 = Math.max(height / 8, 2);
int thickness = Math.max(width / 15, 1);
if (part == Part.WP_CLOSEBUTTON) {
int lineWidth;
if (width > 47) lineWidth = 6;
else if (width > 37) lineWidth = 5;
else if (width > 26) lineWidth = 4;
else if (width > 16) lineWidth = 3;
else if (width > 12) lineWidth = 2;
else lineWidth = 1;
y = height / 12 + 2;
if (lineWidth == 1) {
if (w % 2 == 1) { x++; w++; }
g.drawLine(x, y, x+w-2, y+w-2);
g.drawLine(x+w-2, y, x, y+w-2);
} else if (lineWidth == 2) {
if (w > 6) { x++; w--; }
g.drawLine(x, y, x+w-2, y+w-2);
g.drawLine(x+w-2, y, x, y+w-2);
g.drawLine(x+1, y, x+w-1, y+w-2);
g.drawLine(x+w-1, y, x+1, y+w-2);
} else {
x += 2; y++; w -= 2;
g.drawLine(x, y, x+w-1, y+w-1);
g.drawLine(x+w-1, y, x, y+w-1);
g.drawLine(x+1, y, x+w-1, y+w-2);
g.drawLine(x+w-2, y, x, y+w-2);
g.drawLine(x, y+1, x+w-2, y+w-1);
g.drawLine(x+w-1, y+1, x+1, y+w-1);
for (int i = 4; i <= lineWidth; i++) {
g.drawLine(x+i-2, y, x+w-1, y+w-i+1);
g.drawLine(x, y+i-2, x+w-i+1, y+w-1);
g.drawLine(x+w-i+1, y, x, y+w-i+1);
g.drawLine(x+w-1, y+i-2, x+i-2, y+w-1);
}
}
} else if (part == Part.WP_MINBUTTON) {
g.fillRect(x, y+h-thickness2, w-w/3, thickness2);
} else if (part == Part.WP_MAXBUTTON) {
g.fillRect(x, y, w, thickness2);
g.fillRect(x, y, thickness, h);
g.fillRect(x+w-thickness, y, thickness, h);
g.fillRect(x, y+h-thickness, w, thickness);
} else if (part == Part.WP_RESTOREBUTTON) {
g.fillRect(x+w/3, y, w-w/3, thickness2);
g.fillRect(x+w/3, y, thickness, h/3);
g.fillRect(x+w-thickness, y, thickness, h-h/3);
g.fillRect(x+w-w/3, y+h-h/3-thickness, w/3, thickness);
g.fillRect(x, y+h/3, w-w/3, thickness2);
g.fillRect(x, y+h/3, thickness, h-h/3);
g.fillRect(x+w-w/3-thickness, y+h/3, thickness, h-h/3);
g.fillRect(x, y+h-thickness, w-w/3, thickness);
}
}
}
public int getIconWidth() {
int width;
if (XPStyle.getXP() != null) {
// Fix for XP bug where sometimes these sizes aren't updated properly
// Assume for now that height is correct and derive width using the
// ratio from the uxtheme part
width = UIManager.getInt("InternalFrame.titleButtonHeight") -2;
Dimension d = XPStyle.getPartSize(Part.WP_CLOSEBUTTON, State.NORMAL);
if (d != null && d.width != 0 && d.height != 0) {
width = (int) ((float) width * d.width / d.height);
}
} else {
width = UIManager.getInt("InternalFrame.titleButtonWidth") -2;
}
if (XPStyle.getXP() != null) {
width -= 2;
}
return width;
}
public int getIconHeight() {
int height = UIManager.getInt("InternalFrame.titleButtonHeight")-4;
return height;
}
}
private static class ResizeIcon implements Icon, Serializable {
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(UIManager.getColor("InternalFrame.resizeIconHighlight"));
g.drawLine(0, 11, 11, 0);
g.drawLine(4, 11, 11, 4);
g.drawLine(8, 11, 11, 8);
g.setColor(UIManager.getColor("InternalFrame.resizeIconShadow"));
g.drawLine(1, 11, 11, 1);
g.drawLine(2, 11, 11, 2);
g.drawLine(5, 11, 11, 5);
g.drawLine(6, 11, 11, 6);
g.drawLine(9, 11, 11, 9);
g.drawLine(10, 11, 11, 10);
}
public int getIconWidth() { return 13; }
public int getIconHeight() { return 13; }
};
private static class CheckBoxIcon implements Icon, Serializable
{
final static int csize = 13;
public void paintIcon(Component c, Graphics g, int x, int y) {
JCheckBox cb = (JCheckBox) c;
ButtonModel model = cb.getModel();
XPStyle xp = XPStyle.getXP();
if (xp != null) {
State state;
if (model.isSelected()) {
state = State.CHECKEDNORMAL;
if (!model.isEnabled()) {
state = State.CHECKEDDISABLED;
} else if (model.isPressed() && model.isArmed()) {
state = State.CHECKEDPRESSED;
} else if (model.isRollover()) {
state = State.CHECKEDHOT;
}
} else {
state = State.UNCHECKEDNORMAL;
if (!model.isEnabled()) {
state = State.UNCHECKEDDISABLED;
} else if (model.isPressed() && model.isArmed()) {
state = State.UNCHECKEDPRESSED;
} else if (model.isRollover()) {
state = State.UNCHECKEDHOT;
}
}
Part part = Part.BP_CHECKBOX;
xp.getSkin(c, part).paintSkin(g, x, y, state);
} else {
// outer bevel
if(!cb.isBorderPaintedFlat()) {
// Outer top/left
g.setColor(UIManager.getColor("CheckBox.shadow"));
g.drawLine(x, y, x+11, y);
g.drawLine(x, y+1, x, y+11);
// Outer bottom/right
g.setColor(UIManager.getColor("CheckBox.highlight"));
g.drawLine(x+12, y, x+12, y+12);
g.drawLine(x, y+12, x+11, y+12);
// Inner top.left
g.setColor(UIManager.getColor("CheckBox.darkShadow"));
g.drawLine(x+1, y+1, x+10, y+1);
g.drawLine(x+1, y+2, x+1, y+10);
// Inner bottom/right
g.setColor(UIManager.getColor("CheckBox.light"));
g.drawLine(x+1, y+11, x+11, y+11);
g.drawLine(x+11, y+1, x+11, y+10);
// inside box
if((model.isPressed() && model.isArmed()) || !model.isEnabled()) {
g.setColor(UIManager.getColor("CheckBox.background"));
} else {
g.setColor(UIManager.getColor("CheckBox.interiorBackground"));
}
g.fillRect(x+2, y+2, csize-4, csize-4);
} else {
g.setColor(UIManager.getColor("CheckBox.shadow"));
g.drawRect(x+1, y+1, csize-3, csize-3);
if((model.isPressed() && model.isArmed()) || !model.isEnabled()) {
g.setColor(UIManager.getColor("CheckBox.background"));
} else {
g.setColor(UIManager.getColor("CheckBox.interiorBackground"));
}
g.fillRect(x+2, y+2, csize-4, csize-4);
}
if(model.isEnabled()) {
g.setColor(UIManager.getColor("CheckBox.foreground"));
} else {
g.setColor(UIManager.getColor("CheckBox.shadow"));
}
// paint check
if (model.isSelected()) {
g.drawLine(x+9, y+3, x+9, y+3);
g.drawLine(x+8, y+4, x+9, y+4);
g.drawLine(x+7, y+5, x+9, y+5);
g.drawLine(x+6, y+6, x+8, y+6);
g.drawLine(x+3, y+7, x+7, y+7);
g.drawLine(x+4, y+8, x+6, y+8);
g.drawLine(x+5, y+9, x+5, y+9);
g.drawLine(x+3, y+5, x+3, y+5);
g.drawLine(x+3, y+6, x+4, y+6);
}
}
}
public int getIconWidth() {
XPStyle xp = XPStyle.getXP();
if (xp != null) {
return xp.getSkin(null, Part.BP_CHECKBOX).getWidth();
} else {
return csize;
}
}
public int getIconHeight() {
XPStyle xp = XPStyle.getXP();
if (xp != null) {
return xp.getSkin(null, Part.BP_CHECKBOX).getHeight();
} else {
return csize;
}
}
}
private static class RadioButtonIcon implements Icon, UIResource, Serializable
{
public void paintIcon(Component c, Graphics g, int x, int y) {
AbstractButton b = (AbstractButton) c;
ButtonModel model = b.getModel();
XPStyle xp = XPStyle.getXP();
if (xp != null) {
Part part = Part.BP_RADIOBUTTON;
Skin skin = xp.getSkin(b, part);
State state;
int index = 0;
if (model.isSelected()) {
state = State.CHECKEDNORMAL;
if (!model.isEnabled()) {
state = State.CHECKEDDISABLED;
} else if (model.isPressed() && model.isArmed()) {
state = State.CHECKEDPRESSED;
} else if (model.isRollover()) {
state = State.CHECKEDHOT;
}
} else {
state = State.UNCHECKEDNORMAL;
if (!model.isEnabled()) {
state = State.UNCHECKEDDISABLED;
} else if (model.isPressed() && model.isArmed()) {
state = State.UNCHECKEDPRESSED;
} else if (model.isRollover()) {
state = State.UNCHECKEDHOT;
}
}
skin.paintSkin(g, x, y, state);
} else {
// fill interior
if((model.isPressed() && model.isArmed()) || !model.isEnabled()) {
g.setColor(UIManager.getColor("RadioButton.background"));
} else {
g.setColor(UIManager.getColor("RadioButton.interiorBackground"));
}
g.fillRect(x+2, y+2, 8, 8);
// outter left arc
g.setColor(UIManager.getColor("RadioButton.shadow"));
g.drawLine(x+4, y+0, x+7, y+0);
g.drawLine(x+2, y+1, x+3, y+1);
g.drawLine(x+8, y+1, x+9, y+1);
g.drawLine(x+1, y+2, x+1, y+3);
g.drawLine(x+0, y+4, x+0, y+7);
g.drawLine(x+1, y+8, x+1, y+9);
// outter right arc
g.setColor(UIManager.getColor("RadioButton.highlight"));
g.drawLine(x+2, y+10, x+3, y+10);
g.drawLine(x+4, y+11, x+7, y+11);
g.drawLine(x+8, y+10, x+9, y+10);
g.drawLine(x+10, y+9, x+10, y+8);
g.drawLine(x+11, y+7, x+11, y+4);
g.drawLine(x+10, y+3, x+10, y+2);
// inner left arc
g.setColor(UIManager.getColor("RadioButton.darkShadow"));
g.drawLine(x+4, y+1, x+7, y+1);
g.drawLine(x+2, y+2, x+3, y+2);
g.drawLine(x+8, y+2, x+9, y+2);
g.drawLine(x+2, y+3, x+2, y+3);
g.drawLine(x+1, y+4, x+1, y+7);
g.drawLine(x+2, y+8, x+2, y+8);
// inner right arc
g.setColor(UIManager.getColor("RadioButton.light"));
g.drawLine(x+2, y+9, x+3, y+9);
g.drawLine(x+4, y+10, x+7, y+10);
g.drawLine(x+8, y+9, x+9, y+9);
g.drawLine(x+9, y+8, x+9, y+8);
g.drawLine(x+10, y+7, x+10, y+4);
g.drawLine(x+9, y+3, x+9, y+3);
// indicate whether selected or not
if (model.isSelected()) {
if (model.isEnabled()) {
g.setColor(UIManager.getColor("RadioButton.foreground"));
} else {
g.setColor(UIManager.getColor("RadioButton.shadow"));
}
g.fillRect(x+4, y+5, 4, 2);
g.fillRect(x+5, y+4, 2, 4);
}
}
}
public int getIconWidth() {
XPStyle xp = XPStyle.getXP();
if (xp != null) {
return xp.getSkin(null, Part.BP_RADIOBUTTON).getWidth();
} else {
return 13;
}
}
public int getIconHeight() {
XPStyle xp = XPStyle.getXP();
if (xp != null) {
return xp.getSkin(null, Part.BP_RADIOBUTTON).getHeight();
} else {
return 13;
}
}
} // end class RadioButtonIcon
private static class CheckBoxMenuItemIcon implements Icon, UIResource, Serializable
{
public void paintIcon(Component c, Graphics g, int x, int y) {
AbstractButton b = (AbstractButton) c;
ButtonModel model = b.getModel();
boolean isSelected = model.isSelected();
if (isSelected) {
y = y - getIconHeight() / 2;
g.drawLine(x+9, y+3, x+9, y+3);
g.drawLine(x+8, y+4, x+9, y+4);
g.drawLine(x+7, y+5, x+9, y+5);
g.drawLine(x+6, y+6, x+8, y+6);
g.drawLine(x+3, y+7, x+7, y+7);
g.drawLine(x+4, y+8, x+6, y+8);
g.drawLine(x+5, y+9, x+5, y+9);
g.drawLine(x+3, y+5, x+3, y+5);
g.drawLine(x+3, y+6, x+4, y+6);
}
}
public int getIconWidth() { return 9; }
public int getIconHeight() { return 9; }
} // End class CheckBoxMenuItemIcon
private static class RadioButtonMenuItemIcon implements Icon, UIResource, Serializable
{
public void paintIcon(Component c, Graphics g, int x, int y) {
AbstractButton b = (AbstractButton) c;
ButtonModel model = b.getModel();
if (b.isSelected() == true) {
g.fillRoundRect(x+3,y+3, getIconWidth()-6, getIconHeight()-6,
4, 4);
}
}
public int getIconWidth() { return 12; }
public int getIconHeight() { return 12; }
} // End class RadioButtonMenuItemIcon
private static class MenuItemCheckIcon implements Icon, UIResource, Serializable{
public void paintIcon(Component c, Graphics g, int x, int y) {
/* For debugging:
Color oldColor = g.getColor();
g.setColor(Color.orange);
g.fill3DRect(x,y,getIconWidth(), getIconHeight(), true);
g.setColor(oldColor);
*/
}
public int getIconWidth() { return 9; }
public int getIconHeight() { return 9; }
} // End class MenuItemCheckIcon
private static class MenuItemArrowIcon implements Icon, UIResource, Serializable {
public void paintIcon(Component c, Graphics g, int x, int y) {
/* For debugging:
Color oldColor = g.getColor();
g.setColor(Color.green);
g.fill3DRect(x,y,getIconWidth(), getIconHeight(), true);
g.setColor(oldColor);
*/
}
public int getIconWidth() { return 4; }
public int getIconHeight() { return 8; }
} // End class MenuItemArrowIcon
private static class MenuArrowIcon implements Icon, UIResource, Serializable {
public void paintIcon(Component c, Graphics g, int x, int y) {
if (WindowsMenuItemUI.isVistaPainting()) {
XPStyle xp = XPStyle.getXP();
State state = State.NORMAL;
if (c instanceof JMenuItem) {
state = ((JMenuItem) c).getModel().isEnabled()
? State.NORMAL : State.DISABLED;
}
Skin skin = xp.getSkin(c, Part.MP_POPUPSUBMENU);
if (WindowsGraphicsUtils.isLeftToRight(c)) {
skin.paintSkin(g, x, y, state);
} else {
Graphics2D g2d = (Graphics2D)g.create();
g2d.translate(x + skin.getWidth(), y);
g2d.scale(-1, 1);
skin.paintSkin(g2d, 0, 0, state);
g2d.dispose();
}
} else {
g.translate(x,y);
if( WindowsGraphicsUtils.isLeftToRight(c) ) {
g.drawLine( 0, 0, 0, 7 );
g.drawLine( 1, 1, 1, 6 );
g.drawLine( 2, 2, 2, 5 );
g.drawLine( 3, 3, 3, 4 );
} else {
g.drawLine( 4, 0, 4, 7 );
g.drawLine( 3, 1, 3, 6 );
g.drawLine( 2, 2, 2, 5 );
g.drawLine( 1, 3, 1, 4 );
}
g.translate(-x,-y);
}
}
public int getIconWidth() {
if (WindowsMenuItemUI.isVistaPainting()) {
Skin skin = XPStyle.getXP().getSkin(null, Part.MP_POPUPSUBMENU);
return skin.getWidth();
} else {
return 4;
}
}
public int getIconHeight() {
if (WindowsMenuItemUI.isVistaPainting()) {
Skin skin = XPStyle.getXP().getSkin(null, Part.MP_POPUPSUBMENU);
return skin.getHeight();
} else {
return 8;
}
}
} // End class MenuArrowIcon
static class VistaMenuItemCheckIconFactory
implements MenuItemCheckIconFactory {
private static final int OFFSET = 3;
public Icon getIcon(JMenuItem component) {
return new VistaMenuItemCheckIcon(component);
}
public boolean isCompatible(Object icon, String prefix) {
return icon instanceof VistaMenuItemCheckIcon
&& ((VistaMenuItemCheckIcon) icon).type == getType(prefix);
}
public Icon getIcon(String type) {
return new VistaMenuItemCheckIcon(type);
}
static int getIconWidth() {
return XPStyle.getXP().getSkin(null, Part.MP_POPUPCHECK).getWidth()
+ 2 * OFFSET;
}
private static Class<? extends JMenuItem> getType(Component c) {
Class<? extends JMenuItem> rv = null;
if (c instanceof JCheckBoxMenuItem) {
rv = JCheckBoxMenuItem.class;
} else if (c instanceof JRadioButtonMenuItem) {
rv = JRadioButtonMenuItem.class;
} else if (c instanceof JMenu) {
rv = JMenu.class;
} else if (c instanceof JMenuItem) {
rv = JMenuItem.class;
}
return rv;
}
private static Class<? extends JMenuItem> getType(String type) {
Class<? extends JMenuItem> rv = null;
if (type == "CheckBoxMenuItem") {
rv = JCheckBoxMenuItem.class;
} else if (type == "RadioButtonMenuItem") {
rv = JRadioButtonMenuItem.class;
} else if (type == "Menu") {
rv = JMenu.class;
} else if (type == "MenuItem") {
rv = JMenuItem.class;
} else {
// this should never happen
rv = JMenuItem.class;
}
return rv;
}
/**
* CheckIcon for JMenuItem, JMenu, JCheckBoxMenuItem and
* JRadioButtonMenuItem.
* Note: to be used on Vista only.
*/
private static class VistaMenuItemCheckIcon
implements Icon, UIResource, Serializable {
private final JMenuItem menuItem;
private final Class<? extends JMenuItem> type;
VistaMenuItemCheckIcon(JMenuItem menuItem) {
this.type = getType(menuItem);
this.menuItem = menuItem;
}
VistaMenuItemCheckIcon(String type) {
this.type = getType(type);
this.menuItem = null;
}
public int getIconHeight() {
Icon lafIcon = getLaFIcon();
if (lafIcon != null) {
return lafIcon.getIconHeight();
}
Icon icon = getIcon();
int height = 0;
if (icon != null) {
height = icon.getIconHeight() + 2 * OFFSET;
} else {
Skin skin =
XPStyle.getXP().getSkin(null, Part.MP_POPUPCHECK);
height = skin.getHeight() + 2 * OFFSET;
}
return height;
}
public int getIconWidth() {
Icon lafIcon = getLaFIcon();
if (lafIcon != null) {
return lafIcon.getIconWidth();
}
Icon icon = getIcon();
int width = 0;
if (icon != null) {
width = icon.getIconWidth() + 2 * OFFSET;
} else {
width = VistaMenuItemCheckIconFactory.getIconWidth();
}
return width;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Icon lafIcon = getLaFIcon();
if (lafIcon != null) {
lafIcon.paintIcon(c, g, x, y);
return;
}
assert menuItem == null || c == menuItem;
Icon icon = getIcon();
if (type == JCheckBoxMenuItem.class
|| type == JRadioButtonMenuItem.class) {
AbstractButton b = (AbstractButton) c;
if (b.isSelected()) {
Part backgroundPart = Part.MP_POPUPCHECKBACKGROUND;
Part part = Part.MP_POPUPCHECK;
State backgroundState;
State state;
if (isEnabled(c, null)) {
backgroundState =
(icon != null) ? State.BITMAP : State.NORMAL;
state = (type == JRadioButtonMenuItem.class)
? State.BULLETNORMAL
: State.CHECKMARKNORMAL;
} else {
backgroundState = State.DISABLEDPUSHED;
state =
(type == JRadioButtonMenuItem.class)
? State.BULLETDISABLED
: State.CHECKMARKDISABLED;
}
Skin skin;
XPStyle xp = XPStyle.getXP();
skin = xp.getSkin(c, backgroundPart);
skin.paintSkin(g, x, y,
getIconWidth(), getIconHeight(), backgroundState);
if (icon == null) {
skin = xp.getSkin(c, part);
skin.paintSkin(g, x + OFFSET, y + OFFSET, state);
}
}
}
if (icon != null) {
icon.paintIcon(c, g, x + OFFSET, y + OFFSET);
}
}
private static WindowsMenuItemUIAccessor getAccessor(
JMenuItem menuItem) {
WindowsMenuItemUIAccessor rv = null;
ButtonUI uiObject = (menuItem != null) ? menuItem.getUI()
: null;
if (uiObject instanceof WindowsMenuItemUI) {
rv = ((WindowsMenuItemUI) uiObject).accessor;
} else if (uiObject instanceof WindowsMenuUI) {
rv = ((WindowsMenuUI) uiObject).accessor;
} else if (uiObject instanceof WindowsCheckBoxMenuItemUI) {
rv = ((WindowsCheckBoxMenuItemUI) uiObject).accessor;
} else if (uiObject instanceof WindowsRadioButtonMenuItemUI) {
rv = ((WindowsRadioButtonMenuItemUI) uiObject).accessor;
}
return rv;
}
private static boolean isEnabled(Component c, State state) {
if (state == null && c instanceof JMenuItem) {
WindowsMenuItemUIAccessor accessor =
getAccessor((JMenuItem) c);
if (accessor != null) {
state = accessor.getState((JMenuItem) c);
}
}
if (state == null) {
if (c != null) {
return c.isEnabled();
} else {
return true;
}
} else {
return (state != State.DISABLED)
&& (state != State.DISABLEDHOT)
&& (state != State.DISABLEDPUSHED);
}
}
private Icon getIcon() {
Icon rv = null;
if (menuItem == null) {
return rv;
}
WindowsMenuItemUIAccessor accessor =
getAccessor(menuItem);
State state = (accessor != null) ? accessor.getState(menuItem)
: null;
if (isEnabled(menuItem, null)) {
if (state == State.PUSHED) {
rv = menuItem.getPressedIcon();
} else {
rv = menuItem.getIcon();
}
} else {
rv = menuItem.getDisabledIcon();
}
return rv;
}
/**
* Check if developer changed icon in the UI table.
*
* @return the icon to use or {@code null} if the current one is to
* be used
*/
private Icon getLaFIcon() {
// use icon from the UI table if it does not match this one.
Icon rv = (Icon) UIManager.getDefaults().get(typeToString(type));
if (rv instanceof VistaMenuItemCheckIcon
&& ((VistaMenuItemCheckIcon) rv).type == type) {
rv = null;
}
return rv;
}
private static String typeToString(
Class<? extends JMenuItem> type) {
assert type == JMenuItem.class
|| type == JMenu.class
|| type == JCheckBoxMenuItem.class
|| type == JRadioButtonMenuItem.class;
StringBuilder sb = new StringBuilder(type.getName());
// remove package name, dot and the first character
sb.delete(0, sb.lastIndexOf("J") + 1);
sb.append(".checkIcon");
return sb.toString();
}
}
} // End class VistaMenuItemCheckIconFactory
}
|
googleapis/google-cloud-java | 35,592 | java-modelarmor/google-cloud-modelarmor/src/test/java/com/google/cloud/modelarmor/v1/ModelArmorClientHttpJsonTest.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.modelarmor.v1;
import static com.google.cloud.modelarmor.v1.ModelArmorClient.ListLocationsPagedResponse;
import static com.google.cloud.modelarmor.v1.ModelArmorClient.ListTemplatesPagedResponse;
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.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.cloud.modelarmor.v1.stub.HttpJsonModelArmorStub;
import com.google.common.collect.Lists;
import com.google.protobuf.Any;
import com.google.protobuf.Empty;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Timestamp;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
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 ModelArmorClientHttpJsonTest {
private static MockHttpService mockService;
private static ModelArmorClient client;
@BeforeClass
public static void startStaticServer() throws IOException {
mockService =
new MockHttpService(
HttpJsonModelArmorStub.getMethodDescriptors(), ModelArmorSettings.getDefaultEndpoint());
ModelArmorSettings settings =
ModelArmorSettings.newHttpJsonBuilder()
.setTransportChannelProvider(
ModelArmorSettings.defaultHttpJsonTransportProviderBuilder()
.setHttpTransport(mockService)
.build())
.setCredentialsProvider(NoCredentialsProvider.create())
.build();
client = ModelArmorClient.create(settings);
}
@AfterClass
public static void stopServer() {
client.close();
}
@Before
public void setUp() {}
@After
public void tearDown() throws Exception {
mockService.reset();
}
@Test
public void listTemplatesTest() throws Exception {
Template responsesElement = Template.newBuilder().build();
ListTemplatesResponse expectedResponse =
ListTemplatesResponse.newBuilder()
.setNextPageToken("")
.addAllTemplates(Arrays.asList(responsesElement))
.build();
mockService.addResponse(expectedResponse);
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
ListTemplatesPagedResponse pagedListResponse = client.listTemplates(parent);
List<Template> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getTemplatesList().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 listTemplatesExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
client.listTemplates(parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listTemplatesTest2() throws Exception {
Template responsesElement = Template.newBuilder().build();
ListTemplatesResponse expectedResponse =
ListTemplatesResponse.newBuilder()
.setNextPageToken("")
.addAllTemplates(Arrays.asList(responsesElement))
.build();
mockService.addResponse(expectedResponse);
String parent = "projects/project-5833/locations/location-5833";
ListTemplatesPagedResponse pagedListResponse = client.listTemplates(parent);
List<Template> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getTemplatesList().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 listTemplatesExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String parent = "projects/project-5833/locations/location-5833";
client.listTemplates(parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getTemplateTest() throws Exception {
Template expectedResponse =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
TemplateName name = TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]");
Template actualResponse = client.getTemplate(name);
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 getTemplateExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
TemplateName name = TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]");
client.getTemplate(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getTemplateTest2() throws Exception {
Template expectedResponse =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
String name = "projects/project-127/locations/location-127/templates/template-127";
Template actualResponse = client.getTemplate(name);
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 getTemplateExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String name = "projects/project-127/locations/location-127/templates/template-127";
client.getTemplate(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void createTemplateTest() throws Exception {
Template expectedResponse =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
Template template = Template.newBuilder().build();
String templateId = "templateId1304010549";
Template actualResponse = client.createTemplate(parent, template, templateId);
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 createTemplateExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
Template template = Template.newBuilder().build();
String templateId = "templateId1304010549";
client.createTemplate(parent, template, templateId);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void createTemplateTest2() throws Exception {
Template expectedResponse =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
String parent = "projects/project-5833/locations/location-5833";
Template template = Template.newBuilder().build();
String templateId = "templateId1304010549";
Template actualResponse = client.createTemplate(parent, template, templateId);
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 createTemplateExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String parent = "projects/project-5833/locations/location-5833";
Template template = Template.newBuilder().build();
String templateId = "templateId1304010549";
client.createTemplate(parent, template, templateId);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updateTemplateTest() throws Exception {
Template expectedResponse =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
Template template =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
Template actualResponse = client.updateTemplate(template, updateMask);
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 updateTemplateExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
Template template =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
client.updateTemplate(template, updateMask);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void deleteTemplateTest() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
mockService.addResponse(expectedResponse);
TemplateName name = TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]");
client.deleteTemplate(name);
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 deleteTemplateExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
TemplateName name = TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]");
client.deleteTemplate(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void deleteTemplateTest2() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
mockService.addResponse(expectedResponse);
String name = "projects/project-127/locations/location-127/templates/template-127";
client.deleteTemplate(name);
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 deleteTemplateExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String name = "projects/project-127/locations/location-127/templates/template-127";
client.deleteTemplate(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getFloorSettingTest() throws Exception {
FloorSetting expectedResponse =
FloorSetting.newBuilder()
.setName(FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.setFilterConfig(FilterConfig.newBuilder().build())
.setEnableFloorSettingEnforcement(true)
.addAllIntegratedServices(new ArrayList<FloorSetting.IntegratedService>())
.setAiPlatformFloorSetting(AiPlatformFloorSetting.newBuilder().build())
.setFloorSettingMetadata(FloorSetting.FloorSettingMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
FloorSettingName name = FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]");
FloorSetting actualResponse = client.getFloorSetting(name);
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 getFloorSettingExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
FloorSettingName name = FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]");
client.getFloorSetting(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getFloorSettingTest2() throws Exception {
FloorSetting expectedResponse =
FloorSetting.newBuilder()
.setName(FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.setFilterConfig(FilterConfig.newBuilder().build())
.setEnableFloorSettingEnforcement(true)
.addAllIntegratedServices(new ArrayList<FloorSetting.IntegratedService>())
.setAiPlatformFloorSetting(AiPlatformFloorSetting.newBuilder().build())
.setFloorSettingMetadata(FloorSetting.FloorSettingMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
String name = "projects/project-535/locations/location-535/floorSetting";
FloorSetting actualResponse = client.getFloorSetting(name);
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 getFloorSettingExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String name = "projects/project-535/locations/location-535/floorSetting";
client.getFloorSetting(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updateFloorSettingTest() throws Exception {
FloorSetting expectedResponse =
FloorSetting.newBuilder()
.setName(FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.setFilterConfig(FilterConfig.newBuilder().build())
.setEnableFloorSettingEnforcement(true)
.addAllIntegratedServices(new ArrayList<FloorSetting.IntegratedService>())
.setAiPlatformFloorSetting(AiPlatformFloorSetting.newBuilder().build())
.setFloorSettingMetadata(FloorSetting.FloorSettingMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
FloorSetting floorSetting =
FloorSetting.newBuilder()
.setName(FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.setFilterConfig(FilterConfig.newBuilder().build())
.setEnableFloorSettingEnforcement(true)
.addAllIntegratedServices(new ArrayList<FloorSetting.IntegratedService>())
.setAiPlatformFloorSetting(AiPlatformFloorSetting.newBuilder().build())
.setFloorSettingMetadata(FloorSetting.FloorSettingMetadata.newBuilder().build())
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
FloorSetting actualResponse = client.updateFloorSetting(floorSetting, updateMask);
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 updateFloorSettingExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
FloorSetting floorSetting =
FloorSetting.newBuilder()
.setName(FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.setFilterConfig(FilterConfig.newBuilder().build())
.setEnableFloorSettingEnforcement(true)
.addAllIntegratedServices(new ArrayList<FloorSetting.IntegratedService>())
.setAiPlatformFloorSetting(AiPlatformFloorSetting.newBuilder().build())
.setFloorSettingMetadata(FloorSetting.FloorSettingMetadata.newBuilder().build())
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
client.updateFloorSetting(floorSetting, updateMask);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void sanitizeUserPromptTest() throws Exception {
SanitizeUserPromptResponse expectedResponse =
SanitizeUserPromptResponse.newBuilder()
.setSanitizationResult(SanitizationResult.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
SanitizeUserPromptRequest request =
SanitizeUserPromptRequest.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setUserPromptData(DataItem.newBuilder().build())
.setMultiLanguageDetectionMetadata(MultiLanguageDetectionMetadata.newBuilder().build())
.build();
SanitizeUserPromptResponse actualResponse = client.sanitizeUserPrompt(request);
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 sanitizeUserPromptExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
SanitizeUserPromptRequest request =
SanitizeUserPromptRequest.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setUserPromptData(DataItem.newBuilder().build())
.setMultiLanguageDetectionMetadata(
MultiLanguageDetectionMetadata.newBuilder().build())
.build();
client.sanitizeUserPrompt(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void sanitizeModelResponseTest() throws Exception {
SanitizeModelResponseResponse expectedResponse =
SanitizeModelResponseResponse.newBuilder()
.setSanitizationResult(SanitizationResult.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
SanitizeModelResponseRequest request =
SanitizeModelResponseRequest.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setModelResponseData(DataItem.newBuilder().build())
.setUserPrompt("userPrompt1504308495")
.setMultiLanguageDetectionMetadata(MultiLanguageDetectionMetadata.newBuilder().build())
.build();
SanitizeModelResponseResponse actualResponse = client.sanitizeModelResponse(request);
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 sanitizeModelResponseExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
SanitizeModelResponseRequest request =
SanitizeModelResponseRequest.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setModelResponseData(DataItem.newBuilder().build())
.setUserPrompt("userPrompt1504308495")
.setMultiLanguageDetectionMetadata(
MultiLanguageDetectionMetadata.newBuilder().build())
.build();
client.sanitizeModelResponse(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listLocationsTest() throws Exception {
Location responsesElement = Location.newBuilder().build();
ListLocationsResponse expectedResponse =
ListLocationsResponse.newBuilder()
.setNextPageToken("")
.addAllLocations(Arrays.asList(responsesElement))
.build();
mockService.addResponse(expectedResponse);
ListLocationsRequest request =
ListLocationsRequest.newBuilder()
.setName("projects/project-3664")
.setFilter("filter-1274492040")
.setPageSize(883849137)
.setPageToken("pageToken873572522")
.build();
ListLocationsPagedResponse pagedListResponse = client.listLocations(request);
List<Location> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getLocationsList().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 listLocationsExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
ListLocationsRequest request =
ListLocationsRequest.newBuilder()
.setName("projects/project-3664")
.setFilter("filter-1274492040")
.setPageSize(883849137)
.setPageToken("pageToken873572522")
.build();
client.listLocations(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getLocationTest() throws Exception {
Location expectedResponse =
Location.newBuilder()
.setName("name3373707")
.setLocationId("locationId1541836720")
.setDisplayName("displayName1714148973")
.putAllLabels(new HashMap<String, String>())
.setMetadata(Any.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
GetLocationRequest request =
GetLocationRequest.newBuilder()
.setName("projects/project-9062/locations/location-9062")
.build();
Location actualResponse = client.getLocation(request);
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 getLocationExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
GetLocationRequest request =
GetLocationRequest.newBuilder()
.setName("projects/project-9062/locations/location-9062")
.build();
client.getLocation(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
}
|
googleapis/google-cloud-java | 35,581 | java-notebooks/proto-google-cloud-notebooks-v1/src/main/java/com/google/cloud/notebooks/v1/CreateExecutionRequest.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 to create notebook execution
* </pre>
*
* Protobuf type {@code google.cloud.notebooks.v1.CreateExecutionRequest}
*/
public final class CreateExecutionRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.notebooks.v1.CreateExecutionRequest)
CreateExecutionRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use CreateExecutionRequest.newBuilder() to construct.
private CreateExecutionRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CreateExecutionRequest() {
parent_ = "";
executionId_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CreateExecutionRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_CreateExecutionRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_CreateExecutionRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.notebooks.v1.CreateExecutionRequest.class,
com.google.cloud.notebooks.v1.CreateExecutionRequest.Builder.class);
}
private int bitField0_;
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 EXECUTION_ID_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object executionId_ = "";
/**
*
*
* <pre>
* Required. User-defined unique ID of this execution.
* </pre>
*
* <code>string execution_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The executionId.
*/
@java.lang.Override
public java.lang.String getExecutionId() {
java.lang.Object ref = executionId_;
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();
executionId_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. User-defined unique ID of this execution.
* </pre>
*
* <code>string execution_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for executionId.
*/
@java.lang.Override
public com.google.protobuf.ByteString getExecutionIdBytes() {
java.lang.Object ref = executionId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
executionId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int EXECUTION_FIELD_NUMBER = 3;
private com.google.cloud.notebooks.v1.Execution execution_;
/**
*
*
* <pre>
* Required. The execution to be created.
* </pre>
*
* <code>
* .google.cloud.notebooks.v1.Execution execution = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the execution field is set.
*/
@java.lang.Override
public boolean hasExecution() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The execution to be created.
* </pre>
*
* <code>
* .google.cloud.notebooks.v1.Execution execution = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The execution.
*/
@java.lang.Override
public com.google.cloud.notebooks.v1.Execution getExecution() {
return execution_ == null
? com.google.cloud.notebooks.v1.Execution.getDefaultInstance()
: execution_;
}
/**
*
*
* <pre>
* Required. The execution to be created.
* </pre>
*
* <code>
* .google.cloud.notebooks.v1.Execution execution = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.notebooks.v1.ExecutionOrBuilder getExecutionOrBuilder() {
return execution_ == null
? com.google.cloud.notebooks.v1.Execution.getDefaultInstance()
: execution_;
}
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(executionId_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, executionId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(3, getExecution());
}
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(executionId_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, executionId_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getExecution());
}
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.CreateExecutionRequest)) {
return super.equals(obj);
}
com.google.cloud.notebooks.v1.CreateExecutionRequest other =
(com.google.cloud.notebooks.v1.CreateExecutionRequest) obj;
if (!getParent().equals(other.getParent())) return false;
if (!getExecutionId().equals(other.getExecutionId())) return false;
if (hasExecution() != other.hasExecution()) return false;
if (hasExecution()) {
if (!getExecution().equals(other.getExecution())) 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) + EXECUTION_ID_FIELD_NUMBER;
hash = (53 * hash) + getExecutionId().hashCode();
if (hasExecution()) {
hash = (37 * hash) + EXECUTION_FIELD_NUMBER;
hash = (53 * hash) + getExecution().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.notebooks.v1.CreateExecutionRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1.CreateExecutionRequest 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.CreateExecutionRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1.CreateExecutionRequest 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.CreateExecutionRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v1.CreateExecutionRequest 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.CreateExecutionRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1.CreateExecutionRequest 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.CreateExecutionRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v1.CreateExecutionRequest 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.CreateExecutionRequest 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.CreateExecutionRequest 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.CreateExecutionRequest 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 create notebook execution
* </pre>
*
* Protobuf type {@code google.cloud.notebooks.v1.CreateExecutionRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.notebooks.v1.CreateExecutionRequest)
com.google.cloud.notebooks.v1.CreateExecutionRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_CreateExecutionRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.notebooks.v1.NotebooksProto
.internal_static_google_cloud_notebooks_v1_CreateExecutionRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.notebooks.v1.CreateExecutionRequest.class,
com.google.cloud.notebooks.v1.CreateExecutionRequest.Builder.class);
}
// Construct using com.google.cloud.notebooks.v1.CreateExecutionRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getExecutionFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
parent_ = "";
executionId_ = "";
execution_ = null;
if (executionBuilder_ != null) {
executionBuilder_.dispose();
executionBuilder_ = null;
}
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_CreateExecutionRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.notebooks.v1.CreateExecutionRequest getDefaultInstanceForType() {
return com.google.cloud.notebooks.v1.CreateExecutionRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.notebooks.v1.CreateExecutionRequest build() {
com.google.cloud.notebooks.v1.CreateExecutionRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.notebooks.v1.CreateExecutionRequest buildPartial() {
com.google.cloud.notebooks.v1.CreateExecutionRequest result =
new com.google.cloud.notebooks.v1.CreateExecutionRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.notebooks.v1.CreateExecutionRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.parent_ = parent_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.executionId_ = executionId_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000004) != 0)) {
result.execution_ = executionBuilder_ == null ? execution_ : executionBuilder_.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.notebooks.v1.CreateExecutionRequest) {
return mergeFrom((com.google.cloud.notebooks.v1.CreateExecutionRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.notebooks.v1.CreateExecutionRequest other) {
if (other == com.google.cloud.notebooks.v1.CreateExecutionRequest.getDefaultInstance())
return this;
if (!other.getParent().isEmpty()) {
parent_ = other.parent_;
bitField0_ |= 0x00000001;
onChanged();
}
if (!other.getExecutionId().isEmpty()) {
executionId_ = other.executionId_;
bitField0_ |= 0x00000002;
onChanged();
}
if (other.hasExecution()) {
mergeExecution(other.getExecution());
}
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:
{
executionId_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
input.readMessage(getExecutionFieldBuilder().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. 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 java.lang.Object executionId_ = "";
/**
*
*
* <pre>
* Required. User-defined unique ID of this execution.
* </pre>
*
* <code>string execution_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The executionId.
*/
public java.lang.String getExecutionId() {
java.lang.Object ref = executionId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
executionId_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. User-defined unique ID of this execution.
* </pre>
*
* <code>string execution_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for executionId.
*/
public com.google.protobuf.ByteString getExecutionIdBytes() {
java.lang.Object ref = executionId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
executionId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. User-defined unique ID of this execution.
* </pre>
*
* <code>string execution_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The executionId to set.
* @return This builder for chaining.
*/
public Builder setExecutionId(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
executionId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. User-defined unique ID of this execution.
* </pre>
*
* <code>string execution_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearExecutionId() {
executionId_ = getDefaultInstance().getExecutionId();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. User-defined unique ID of this execution.
* </pre>
*
* <code>string execution_id = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for executionId to set.
* @return This builder for chaining.
*/
public Builder setExecutionIdBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
executionId_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private com.google.cloud.notebooks.v1.Execution execution_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.notebooks.v1.Execution,
com.google.cloud.notebooks.v1.Execution.Builder,
com.google.cloud.notebooks.v1.ExecutionOrBuilder>
executionBuilder_;
/**
*
*
* <pre>
* Required. The execution to be created.
* </pre>
*
* <code>
* .google.cloud.notebooks.v1.Execution execution = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the execution field is set.
*/
public boolean hasExecution() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* Required. The execution to be created.
* </pre>
*
* <code>
* .google.cloud.notebooks.v1.Execution execution = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The execution.
*/
public com.google.cloud.notebooks.v1.Execution getExecution() {
if (executionBuilder_ == null) {
return execution_ == null
? com.google.cloud.notebooks.v1.Execution.getDefaultInstance()
: execution_;
} else {
return executionBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The execution to be created.
* </pre>
*
* <code>
* .google.cloud.notebooks.v1.Execution execution = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setExecution(com.google.cloud.notebooks.v1.Execution value) {
if (executionBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
execution_ = value;
} else {
executionBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The execution to be created.
* </pre>
*
* <code>
* .google.cloud.notebooks.v1.Execution execution = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setExecution(com.google.cloud.notebooks.v1.Execution.Builder builderForValue) {
if (executionBuilder_ == null) {
execution_ = builderForValue.build();
} else {
executionBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The execution to be created.
* </pre>
*
* <code>
* .google.cloud.notebooks.v1.Execution execution = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeExecution(com.google.cloud.notebooks.v1.Execution value) {
if (executionBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& execution_ != null
&& execution_ != com.google.cloud.notebooks.v1.Execution.getDefaultInstance()) {
getExecutionBuilder().mergeFrom(value);
} else {
execution_ = value;
}
} else {
executionBuilder_.mergeFrom(value);
}
if (execution_ != null) {
bitField0_ |= 0x00000004;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The execution to be created.
* </pre>
*
* <code>
* .google.cloud.notebooks.v1.Execution execution = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearExecution() {
bitField0_ = (bitField0_ & ~0x00000004);
execution_ = null;
if (executionBuilder_ != null) {
executionBuilder_.dispose();
executionBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The execution to be created.
* </pre>
*
* <code>
* .google.cloud.notebooks.v1.Execution execution = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.notebooks.v1.Execution.Builder getExecutionBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getExecutionFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The execution to be created.
* </pre>
*
* <code>
* .google.cloud.notebooks.v1.Execution execution = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.notebooks.v1.ExecutionOrBuilder getExecutionOrBuilder() {
if (executionBuilder_ != null) {
return executionBuilder_.getMessageOrBuilder();
} else {
return execution_ == null
? com.google.cloud.notebooks.v1.Execution.getDefaultInstance()
: execution_;
}
}
/**
*
*
* <pre>
* Required. The execution to be created.
* </pre>
*
* <code>
* .google.cloud.notebooks.v1.Execution execution = 3 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.notebooks.v1.Execution,
com.google.cloud.notebooks.v1.Execution.Builder,
com.google.cloud.notebooks.v1.ExecutionOrBuilder>
getExecutionFieldBuilder() {
if (executionBuilder_ == null) {
executionBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.notebooks.v1.Execution,
com.google.cloud.notebooks.v1.Execution.Builder,
com.google.cloud.notebooks.v1.ExecutionOrBuilder>(
getExecution(), getParentForChildren(), isClean());
execution_ = null;
}
return executionBuilder_;
}
@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.CreateExecutionRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.notebooks.v1.CreateExecutionRequest)
private static final com.google.cloud.notebooks.v1.CreateExecutionRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.notebooks.v1.CreateExecutionRequest();
}
public static com.google.cloud.notebooks.v1.CreateExecutionRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CreateExecutionRequest> PARSER =
new com.google.protobuf.AbstractParser<CreateExecutionRequest>() {
@java.lang.Override
public CreateExecutionRequest 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<CreateExecutionRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CreateExecutionRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.notebooks.v1.CreateExecutionRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,655 | java-retail/proto-google-cloud-retail-v2/src/main/java/com/google/cloud/retail/v2/UpdateServingConfigRequest.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/v2/serving_config_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.retail.v2;
/**
*
*
* <pre>
* Request for UpdateServingConfig method.
* </pre>
*
* Protobuf type {@code google.cloud.retail.v2.UpdateServingConfigRequest}
*/
public final class UpdateServingConfigRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.retail.v2.UpdateServingConfigRequest)
UpdateServingConfigRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateServingConfigRequest.newBuilder() to construct.
private UpdateServingConfigRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateServingConfigRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateServingConfigRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.retail.v2.ServingConfigServiceProto
.internal_static_google_cloud_retail_v2_UpdateServingConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.retail.v2.ServingConfigServiceProto
.internal_static_google_cloud_retail_v2_UpdateServingConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.retail.v2.UpdateServingConfigRequest.class,
com.google.cloud.retail.v2.UpdateServingConfigRequest.Builder.class);
}
private int bitField0_;
public static final int SERVING_CONFIG_FIELD_NUMBER = 1;
private com.google.cloud.retail.v2.ServingConfig servingConfig_;
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the servingConfig field is set.
*/
@java.lang.Override
public boolean hasServingConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The servingConfig.
*/
@java.lang.Override
public com.google.cloud.retail.v2.ServingConfig getServingConfig() {
return servingConfig_ == null
? com.google.cloud.retail.v2.ServingConfig.getDefaultInstance()
: servingConfig_;
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.retail.v2.ServingConfigOrBuilder getServingConfigOrBuilder() {
return servingConfig_ == null
? com.google.cloud.retail.v2.ServingConfig.getDefaultInstance()
: servingConfig_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Indicates which fields in the provided
* [ServingConfig][google.cloud.retail.v2.ServingConfig] to update. The
* following are NOT supported:
*
* * [ServingConfig.name][google.cloud.retail.v2.ServingConfig.name]
*
* 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
* [ServingConfig][google.cloud.retail.v2.ServingConfig] to update. The
* following are NOT supported:
*
* * [ServingConfig.name][google.cloud.retail.v2.ServingConfig.name]
*
* 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
* [ServingConfig][google.cloud.retail.v2.ServingConfig] to update. The
* following are NOT supported:
*
* * [ServingConfig.name][google.cloud.retail.v2.ServingConfig.name]
*
* 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, getServingConfig());
}
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, getServingConfig());
}
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.v2.UpdateServingConfigRequest)) {
return super.equals(obj);
}
com.google.cloud.retail.v2.UpdateServingConfigRequest other =
(com.google.cloud.retail.v2.UpdateServingConfigRequest) obj;
if (hasServingConfig() != other.hasServingConfig()) return false;
if (hasServingConfig()) {
if (!getServingConfig().equals(other.getServingConfig())) 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 (hasServingConfig()) {
hash = (37 * hash) + SERVING_CONFIG_FIELD_NUMBER;
hash = (53 * hash) + getServingConfig().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.v2.UpdateServingConfigRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.retail.v2.UpdateServingConfigRequest 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.v2.UpdateServingConfigRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.retail.v2.UpdateServingConfigRequest 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.v2.UpdateServingConfigRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.retail.v2.UpdateServingConfigRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.retail.v2.UpdateServingConfigRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.retail.v2.UpdateServingConfigRequest 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.v2.UpdateServingConfigRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.retail.v2.UpdateServingConfigRequest 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.v2.UpdateServingConfigRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.retail.v2.UpdateServingConfigRequest 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.v2.UpdateServingConfigRequest 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 UpdateServingConfig method.
* </pre>
*
* Protobuf type {@code google.cloud.retail.v2.UpdateServingConfigRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.retail.v2.UpdateServingConfigRequest)
com.google.cloud.retail.v2.UpdateServingConfigRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.retail.v2.ServingConfigServiceProto
.internal_static_google_cloud_retail_v2_UpdateServingConfigRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.retail.v2.ServingConfigServiceProto
.internal_static_google_cloud_retail_v2_UpdateServingConfigRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.retail.v2.UpdateServingConfigRequest.class,
com.google.cloud.retail.v2.UpdateServingConfigRequest.Builder.class);
}
// Construct using com.google.cloud.retail.v2.UpdateServingConfigRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getServingConfigFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
servingConfig_ = null;
if (servingConfigBuilder_ != null) {
servingConfigBuilder_.dispose();
servingConfigBuilder_ = 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.v2.ServingConfigServiceProto
.internal_static_google_cloud_retail_v2_UpdateServingConfigRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.retail.v2.UpdateServingConfigRequest getDefaultInstanceForType() {
return com.google.cloud.retail.v2.UpdateServingConfigRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.retail.v2.UpdateServingConfigRequest build() {
com.google.cloud.retail.v2.UpdateServingConfigRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.retail.v2.UpdateServingConfigRequest buildPartial() {
com.google.cloud.retail.v2.UpdateServingConfigRequest result =
new com.google.cloud.retail.v2.UpdateServingConfigRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.retail.v2.UpdateServingConfigRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.servingConfig_ =
servingConfigBuilder_ == null ? servingConfig_ : servingConfigBuilder_.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.v2.UpdateServingConfigRequest) {
return mergeFrom((com.google.cloud.retail.v2.UpdateServingConfigRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.retail.v2.UpdateServingConfigRequest other) {
if (other == com.google.cloud.retail.v2.UpdateServingConfigRequest.getDefaultInstance())
return this;
if (other.hasServingConfig()) {
mergeServingConfig(other.getServingConfig());
}
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(getServingConfigFieldBuilder().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.v2.ServingConfig servingConfig_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.retail.v2.ServingConfig,
com.google.cloud.retail.v2.ServingConfig.Builder,
com.google.cloud.retail.v2.ServingConfigOrBuilder>
servingConfigBuilder_;
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the servingConfig field is set.
*/
public boolean hasServingConfig() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The servingConfig.
*/
public com.google.cloud.retail.v2.ServingConfig getServingConfig() {
if (servingConfigBuilder_ == null) {
return servingConfig_ == null
? com.google.cloud.retail.v2.ServingConfig.getDefaultInstance()
: servingConfig_;
} else {
return servingConfigBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setServingConfig(com.google.cloud.retail.v2.ServingConfig value) {
if (servingConfigBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
servingConfig_ = value;
} else {
servingConfigBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setServingConfig(
com.google.cloud.retail.v2.ServingConfig.Builder builderForValue) {
if (servingConfigBuilder_ == null) {
servingConfig_ = builderForValue.build();
} else {
servingConfigBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeServingConfig(com.google.cloud.retail.v2.ServingConfig value) {
if (servingConfigBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& servingConfig_ != null
&& servingConfig_ != com.google.cloud.retail.v2.ServingConfig.getDefaultInstance()) {
getServingConfigBuilder().mergeFrom(value);
} else {
servingConfig_ = value;
}
} else {
servingConfigBuilder_.mergeFrom(value);
}
if (servingConfig_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearServingConfig() {
bitField0_ = (bitField0_ & ~0x00000001);
servingConfig_ = null;
if (servingConfigBuilder_ != null) {
servingConfigBuilder_.dispose();
servingConfigBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.retail.v2.ServingConfig.Builder getServingConfigBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getServingConfigFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.retail.v2.ServingConfigOrBuilder getServingConfigOrBuilder() {
if (servingConfigBuilder_ != null) {
return servingConfigBuilder_.getMessageOrBuilder();
} else {
return servingConfig_ == null
? com.google.cloud.retail.v2.ServingConfig.getDefaultInstance()
: servingConfig_;
}
}
/**
*
*
* <pre>
* Required. The ServingConfig to update.
* </pre>
*
* <code>
* .google.cloud.retail.v2.ServingConfig serving_config = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.retail.v2.ServingConfig,
com.google.cloud.retail.v2.ServingConfig.Builder,
com.google.cloud.retail.v2.ServingConfigOrBuilder>
getServingConfigFieldBuilder() {
if (servingConfigBuilder_ == null) {
servingConfigBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.retail.v2.ServingConfig,
com.google.cloud.retail.v2.ServingConfig.Builder,
com.google.cloud.retail.v2.ServingConfigOrBuilder>(
getServingConfig(), getParentForChildren(), isClean());
servingConfig_ = null;
}
return servingConfigBuilder_;
}
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
* [ServingConfig][google.cloud.retail.v2.ServingConfig] to update. The
* following are NOT supported:
*
* * [ServingConfig.name][google.cloud.retail.v2.ServingConfig.name]
*
* 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
* [ServingConfig][google.cloud.retail.v2.ServingConfig] to update. The
* following are NOT supported:
*
* * [ServingConfig.name][google.cloud.retail.v2.ServingConfig.name]
*
* 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
* [ServingConfig][google.cloud.retail.v2.ServingConfig] to update. The
* following are NOT supported:
*
* * [ServingConfig.name][google.cloud.retail.v2.ServingConfig.name]
*
* 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
* [ServingConfig][google.cloud.retail.v2.ServingConfig] to update. The
* following are NOT supported:
*
* * [ServingConfig.name][google.cloud.retail.v2.ServingConfig.name]
*
* 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
* [ServingConfig][google.cloud.retail.v2.ServingConfig] to update. The
* following are NOT supported:
*
* * [ServingConfig.name][google.cloud.retail.v2.ServingConfig.name]
*
* 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
* [ServingConfig][google.cloud.retail.v2.ServingConfig] to update. The
* following are NOT supported:
*
* * [ServingConfig.name][google.cloud.retail.v2.ServingConfig.name]
*
* 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
* [ServingConfig][google.cloud.retail.v2.ServingConfig] to update. The
* following are NOT supported:
*
* * [ServingConfig.name][google.cloud.retail.v2.ServingConfig.name]
*
* 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
* [ServingConfig][google.cloud.retail.v2.ServingConfig] to update. The
* following are NOT supported:
*
* * [ServingConfig.name][google.cloud.retail.v2.ServingConfig.name]
*
* 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
* [ServingConfig][google.cloud.retail.v2.ServingConfig] to update. The
* following are NOT supported:
*
* * [ServingConfig.name][google.cloud.retail.v2.ServingConfig.name]
*
* 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.v2.UpdateServingConfigRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.retail.v2.UpdateServingConfigRequest)
private static final com.google.cloud.retail.v2.UpdateServingConfigRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.retail.v2.UpdateServingConfigRequest();
}
public static com.google.cloud.retail.v2.UpdateServingConfigRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateServingConfigRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateServingConfigRequest>() {
@java.lang.Override
public UpdateServingConfigRequest 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<UpdateServingConfigRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateServingConfigRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.retail.v2.UpdateServingConfigRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,589 | java-vision/proto-google-cloud-vision-v1p3beta1/src/main/java/com/google/cloud/vision/v1p3beta1/ListProductsResponse.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/vision/v1p3beta1/product_search_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.vision.v1p3beta1;
/**
*
*
* <pre>
* Response message for the `ListProducts` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p3beta1.ListProductsResponse}
*/
public final class ListProductsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.vision.v1p3beta1.ListProductsResponse)
ListProductsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListProductsResponse.newBuilder() to construct.
private ListProductsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListProductsResponse() {
products_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListProductsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p3beta1_ListProductsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p3beta1_ListProductsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p3beta1.ListProductsResponse.class,
com.google.cloud.vision.v1p3beta1.ListProductsResponse.Builder.class);
}
public static final int PRODUCTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.vision.v1p3beta1.Product> products_;
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.vision.v1p3beta1.Product> getProductsList() {
return products_;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.vision.v1p3beta1.ProductOrBuilder>
getProductsOrBuilderList() {
return products_;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
@java.lang.Override
public int getProductsCount() {
return products_.size();
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
@java.lang.Override
public com.google.cloud.vision.v1p3beta1.Product getProducts(int index) {
return products_.get(index);
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
@java.lang.Override
public com.google.cloud.vision.v1p3beta1.ProductOrBuilder getProductsOrBuilder(int index) {
return products_.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 < products_.size(); i++) {
output.writeMessage(1, products_.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 < products_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, products_.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.vision.v1p3beta1.ListProductsResponse)) {
return super.equals(obj);
}
com.google.cloud.vision.v1p3beta1.ListProductsResponse other =
(com.google.cloud.vision.v1p3beta1.ListProductsResponse) obj;
if (!getProductsList().equals(other.getProductsList())) 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 (getProductsCount() > 0) {
hash = (37 * hash) + PRODUCTS_FIELD_NUMBER;
hash = (53 * hash) + getProductsList().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.vision.v1p3beta1.ListProductsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p3beta1.ListProductsResponse 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.vision.v1p3beta1.ListProductsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p3beta1.ListProductsResponse 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.vision.v1p3beta1.ListProductsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p3beta1.ListProductsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p3beta1.ListProductsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p3beta1.ListProductsResponse 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.vision.v1p3beta1.ListProductsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p3beta1.ListProductsResponse 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.vision.v1p3beta1.ListProductsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p3beta1.ListProductsResponse 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.vision.v1p3beta1.ListProductsResponse 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 the `ListProducts` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p3beta1.ListProductsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.vision.v1p3beta1.ListProductsResponse)
com.google.cloud.vision.v1p3beta1.ListProductsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p3beta1_ListProductsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p3beta1_ListProductsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p3beta1.ListProductsResponse.class,
com.google.cloud.vision.v1p3beta1.ListProductsResponse.Builder.class);
}
// Construct using com.google.cloud.vision.v1p3beta1.ListProductsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (productsBuilder_ == null) {
products_ = java.util.Collections.emptyList();
} else {
products_ = null;
productsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.vision.v1p3beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p3beta1_ListProductsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.vision.v1p3beta1.ListProductsResponse getDefaultInstanceForType() {
return com.google.cloud.vision.v1p3beta1.ListProductsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.vision.v1p3beta1.ListProductsResponse build() {
com.google.cloud.vision.v1p3beta1.ListProductsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.vision.v1p3beta1.ListProductsResponse buildPartial() {
com.google.cloud.vision.v1p3beta1.ListProductsResponse result =
new com.google.cloud.vision.v1p3beta1.ListProductsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.vision.v1p3beta1.ListProductsResponse result) {
if (productsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
products_ = java.util.Collections.unmodifiableList(products_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.products_ = products_;
} else {
result.products_ = productsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.vision.v1p3beta1.ListProductsResponse 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.vision.v1p3beta1.ListProductsResponse) {
return mergeFrom((com.google.cloud.vision.v1p3beta1.ListProductsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.vision.v1p3beta1.ListProductsResponse other) {
if (other == com.google.cloud.vision.v1p3beta1.ListProductsResponse.getDefaultInstance())
return this;
if (productsBuilder_ == null) {
if (!other.products_.isEmpty()) {
if (products_.isEmpty()) {
products_ = other.products_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureProductsIsMutable();
products_.addAll(other.products_);
}
onChanged();
}
} else {
if (!other.products_.isEmpty()) {
if (productsBuilder_.isEmpty()) {
productsBuilder_.dispose();
productsBuilder_ = null;
products_ = other.products_;
bitField0_ = (bitField0_ & ~0x00000001);
productsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getProductsFieldBuilder()
: null;
} else {
productsBuilder_.addAllMessages(other.products_);
}
}
}
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.vision.v1p3beta1.Product m =
input.readMessage(
com.google.cloud.vision.v1p3beta1.Product.parser(), extensionRegistry);
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.add(m);
} else {
productsBuilder_.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.vision.v1p3beta1.Product> products_ =
java.util.Collections.emptyList();
private void ensureProductsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
products_ = new java.util.ArrayList<com.google.cloud.vision.v1p3beta1.Product>(products_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vision.v1p3beta1.Product,
com.google.cloud.vision.v1p3beta1.Product.Builder,
com.google.cloud.vision.v1p3beta1.ProductOrBuilder>
productsBuilder_;
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public java.util.List<com.google.cloud.vision.v1p3beta1.Product> getProductsList() {
if (productsBuilder_ == null) {
return java.util.Collections.unmodifiableList(products_);
} else {
return productsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public int getProductsCount() {
if (productsBuilder_ == null) {
return products_.size();
} else {
return productsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1p3beta1.Product getProducts(int index) {
if (productsBuilder_ == null) {
return products_.get(index);
} else {
return productsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public Builder setProducts(int index, com.google.cloud.vision.v1p3beta1.Product value) {
if (productsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProductsIsMutable();
products_.set(index, value);
onChanged();
} else {
productsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public Builder setProducts(
int index, com.google.cloud.vision.v1p3beta1.Product.Builder builderForValue) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.set(index, builderForValue.build());
onChanged();
} else {
productsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public Builder addProducts(com.google.cloud.vision.v1p3beta1.Product value) {
if (productsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProductsIsMutable();
products_.add(value);
onChanged();
} else {
productsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public Builder addProducts(int index, com.google.cloud.vision.v1p3beta1.Product value) {
if (productsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProductsIsMutable();
products_.add(index, value);
onChanged();
} else {
productsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public Builder addProducts(com.google.cloud.vision.v1p3beta1.Product.Builder builderForValue) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.add(builderForValue.build());
onChanged();
} else {
productsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public Builder addProducts(
int index, com.google.cloud.vision.v1p3beta1.Product.Builder builderForValue) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.add(index, builderForValue.build());
onChanged();
} else {
productsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public Builder addAllProducts(
java.lang.Iterable<? extends com.google.cloud.vision.v1p3beta1.Product> values) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, products_);
onChanged();
} else {
productsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public Builder clearProducts() {
if (productsBuilder_ == null) {
products_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
productsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public Builder removeProducts(int index) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.remove(index);
onChanged();
} else {
productsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1p3beta1.Product.Builder getProductsBuilder(int index) {
return getProductsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1p3beta1.ProductOrBuilder getProductsOrBuilder(int index) {
if (productsBuilder_ == null) {
return products_.get(index);
} else {
return productsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public java.util.List<? extends com.google.cloud.vision.v1p3beta1.ProductOrBuilder>
getProductsOrBuilderList() {
if (productsBuilder_ != null) {
return productsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(products_);
}
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1p3beta1.Product.Builder addProductsBuilder() {
return getProductsFieldBuilder()
.addBuilder(com.google.cloud.vision.v1p3beta1.Product.getDefaultInstance());
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1p3beta1.Product.Builder addProductsBuilder(int index) {
return getProductsFieldBuilder()
.addBuilder(index, com.google.cloud.vision.v1p3beta1.Product.getDefaultInstance());
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p3beta1.Product products = 1;</code>
*/
public java.util.List<com.google.cloud.vision.v1p3beta1.Product.Builder>
getProductsBuilderList() {
return getProductsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vision.v1p3beta1.Product,
com.google.cloud.vision.v1p3beta1.Product.Builder,
com.google.cloud.vision.v1p3beta1.ProductOrBuilder>
getProductsFieldBuilder() {
if (productsBuilder_ == null) {
productsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vision.v1p3beta1.Product,
com.google.cloud.vision.v1p3beta1.Product.Builder,
com.google.cloud.vision.v1p3beta1.ProductOrBuilder>(
products_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
products_ = null;
}
return productsBuilder_;
}
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.vision.v1p3beta1.ListProductsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.vision.v1p3beta1.ListProductsResponse)
private static final com.google.cloud.vision.v1p3beta1.ListProductsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.vision.v1p3beta1.ListProductsResponse();
}
public static com.google.cloud.vision.v1p3beta1.ListProductsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListProductsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListProductsResponse>() {
@java.lang.Override
public ListProductsResponse 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<ListProductsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListProductsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.vision.v1p3beta1.ListProductsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,589 | java-vision/proto-google-cloud-vision-v1p4beta1/src/main/java/com/google/cloud/vision/v1p4beta1/ListProductsResponse.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/vision/v1p4beta1/product_search_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.vision.v1p4beta1;
/**
*
*
* <pre>
* Response message for the `ListProducts` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p4beta1.ListProductsResponse}
*/
public final class ListProductsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.vision.v1p4beta1.ListProductsResponse)
ListProductsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListProductsResponse.newBuilder() to construct.
private ListProductsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListProductsResponse() {
products_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListProductsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p4beta1_ListProductsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p4beta1_ListProductsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p4beta1.ListProductsResponse.class,
com.google.cloud.vision.v1p4beta1.ListProductsResponse.Builder.class);
}
public static final int PRODUCTS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.vision.v1p4beta1.Product> products_;
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.vision.v1p4beta1.Product> getProductsList() {
return products_;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.vision.v1p4beta1.ProductOrBuilder>
getProductsOrBuilderList() {
return products_;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
@java.lang.Override
public int getProductsCount() {
return products_.size();
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.Product getProducts(int index) {
return products_.get(index);
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.ProductOrBuilder getProductsOrBuilder(int index) {
return products_.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 < products_.size(); i++) {
output.writeMessage(1, products_.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 < products_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, products_.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.vision.v1p4beta1.ListProductsResponse)) {
return super.equals(obj);
}
com.google.cloud.vision.v1p4beta1.ListProductsResponse other =
(com.google.cloud.vision.v1p4beta1.ListProductsResponse) obj;
if (!getProductsList().equals(other.getProductsList())) 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 (getProductsCount() > 0) {
hash = (37 * hash) + PRODUCTS_FIELD_NUMBER;
hash = (53 * hash) + getProductsList().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.vision.v1p4beta1.ListProductsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p4beta1.ListProductsResponse 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.vision.v1p4beta1.ListProductsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p4beta1.ListProductsResponse 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.vision.v1p4beta1.ListProductsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vision.v1p4beta1.ListProductsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vision.v1p4beta1.ListProductsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p4beta1.ListProductsResponse 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.vision.v1p4beta1.ListProductsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p4beta1.ListProductsResponse 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.vision.v1p4beta1.ListProductsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vision.v1p4beta1.ListProductsResponse 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.vision.v1p4beta1.ListProductsResponse 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 the `ListProducts` method.
* </pre>
*
* Protobuf type {@code google.cloud.vision.v1p4beta1.ListProductsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.vision.v1p4beta1.ListProductsResponse)
com.google.cloud.vision.v1p4beta1.ListProductsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p4beta1_ListProductsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p4beta1_ListProductsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vision.v1p4beta1.ListProductsResponse.class,
com.google.cloud.vision.v1p4beta1.ListProductsResponse.Builder.class);
}
// Construct using com.google.cloud.vision.v1p4beta1.ListProductsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (productsBuilder_ == null) {
products_ = java.util.Collections.emptyList();
} else {
products_ = null;
productsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.vision.v1p4beta1.ProductSearchServiceProto
.internal_static_google_cloud_vision_v1p4beta1_ListProductsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.ListProductsResponse getDefaultInstanceForType() {
return com.google.cloud.vision.v1p4beta1.ListProductsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.ListProductsResponse build() {
com.google.cloud.vision.v1p4beta1.ListProductsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.ListProductsResponse buildPartial() {
com.google.cloud.vision.v1p4beta1.ListProductsResponse result =
new com.google.cloud.vision.v1p4beta1.ListProductsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.vision.v1p4beta1.ListProductsResponse result) {
if (productsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
products_ = java.util.Collections.unmodifiableList(products_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.products_ = products_;
} else {
result.products_ = productsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.vision.v1p4beta1.ListProductsResponse 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.vision.v1p4beta1.ListProductsResponse) {
return mergeFrom((com.google.cloud.vision.v1p4beta1.ListProductsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.vision.v1p4beta1.ListProductsResponse other) {
if (other == com.google.cloud.vision.v1p4beta1.ListProductsResponse.getDefaultInstance())
return this;
if (productsBuilder_ == null) {
if (!other.products_.isEmpty()) {
if (products_.isEmpty()) {
products_ = other.products_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureProductsIsMutable();
products_.addAll(other.products_);
}
onChanged();
}
} else {
if (!other.products_.isEmpty()) {
if (productsBuilder_.isEmpty()) {
productsBuilder_.dispose();
productsBuilder_ = null;
products_ = other.products_;
bitField0_ = (bitField0_ & ~0x00000001);
productsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getProductsFieldBuilder()
: null;
} else {
productsBuilder_.addAllMessages(other.products_);
}
}
}
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.vision.v1p4beta1.Product m =
input.readMessage(
com.google.cloud.vision.v1p4beta1.Product.parser(), extensionRegistry);
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.add(m);
} else {
productsBuilder_.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.vision.v1p4beta1.Product> products_ =
java.util.Collections.emptyList();
private void ensureProductsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
products_ = new java.util.ArrayList<com.google.cloud.vision.v1p4beta1.Product>(products_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.Product,
com.google.cloud.vision.v1p4beta1.Product.Builder,
com.google.cloud.vision.v1p4beta1.ProductOrBuilder>
productsBuilder_;
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public java.util.List<com.google.cloud.vision.v1p4beta1.Product> getProductsList() {
if (productsBuilder_ == null) {
return java.util.Collections.unmodifiableList(products_);
} else {
return productsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public int getProductsCount() {
if (productsBuilder_ == null) {
return products_.size();
} else {
return productsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1p4beta1.Product getProducts(int index) {
if (productsBuilder_ == null) {
return products_.get(index);
} else {
return productsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public Builder setProducts(int index, com.google.cloud.vision.v1p4beta1.Product value) {
if (productsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProductsIsMutable();
products_.set(index, value);
onChanged();
} else {
productsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public Builder setProducts(
int index, com.google.cloud.vision.v1p4beta1.Product.Builder builderForValue) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.set(index, builderForValue.build());
onChanged();
} else {
productsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public Builder addProducts(com.google.cloud.vision.v1p4beta1.Product value) {
if (productsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProductsIsMutable();
products_.add(value);
onChanged();
} else {
productsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public Builder addProducts(int index, com.google.cloud.vision.v1p4beta1.Product value) {
if (productsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureProductsIsMutable();
products_.add(index, value);
onChanged();
} else {
productsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public Builder addProducts(com.google.cloud.vision.v1p4beta1.Product.Builder builderForValue) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.add(builderForValue.build());
onChanged();
} else {
productsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public Builder addProducts(
int index, com.google.cloud.vision.v1p4beta1.Product.Builder builderForValue) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.add(index, builderForValue.build());
onChanged();
} else {
productsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public Builder addAllProducts(
java.lang.Iterable<? extends com.google.cloud.vision.v1p4beta1.Product> values) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, products_);
onChanged();
} else {
productsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public Builder clearProducts() {
if (productsBuilder_ == null) {
products_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
productsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public Builder removeProducts(int index) {
if (productsBuilder_ == null) {
ensureProductsIsMutable();
products_.remove(index);
onChanged();
} else {
productsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1p4beta1.Product.Builder getProductsBuilder(int index) {
return getProductsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1p4beta1.ProductOrBuilder getProductsOrBuilder(int index) {
if (productsBuilder_ == null) {
return products_.get(index);
} else {
return productsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public java.util.List<? extends com.google.cloud.vision.v1p4beta1.ProductOrBuilder>
getProductsOrBuilderList() {
if (productsBuilder_ != null) {
return productsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(products_);
}
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1p4beta1.Product.Builder addProductsBuilder() {
return getProductsFieldBuilder()
.addBuilder(com.google.cloud.vision.v1p4beta1.Product.getDefaultInstance());
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public com.google.cloud.vision.v1p4beta1.Product.Builder addProductsBuilder(int index) {
return getProductsFieldBuilder()
.addBuilder(index, com.google.cloud.vision.v1p4beta1.Product.getDefaultInstance());
}
/**
*
*
* <pre>
* List of products.
* </pre>
*
* <code>repeated .google.cloud.vision.v1p4beta1.Product products = 1;</code>
*/
public java.util.List<com.google.cloud.vision.v1p4beta1.Product.Builder>
getProductsBuilderList() {
return getProductsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.Product,
com.google.cloud.vision.v1p4beta1.Product.Builder,
com.google.cloud.vision.v1p4beta1.ProductOrBuilder>
getProductsFieldBuilder() {
if (productsBuilder_ == null) {
productsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vision.v1p4beta1.Product,
com.google.cloud.vision.v1p4beta1.Product.Builder,
com.google.cloud.vision.v1p4beta1.ProductOrBuilder>(
products_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
products_ = null;
}
return productsBuilder_;
}
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.vision.v1p4beta1.ListProductsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.vision.v1p4beta1.ListProductsResponse)
private static final com.google.cloud.vision.v1p4beta1.ListProductsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.vision.v1p4beta1.ListProductsResponse();
}
public static com.google.cloud.vision.v1p4beta1.ListProductsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListProductsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListProductsResponse>() {
@java.lang.Override
public ListProductsResponse 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<ListProductsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListProductsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.vision.v1p4beta1.ListProductsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 36,015 | java-apphub/google-cloud-apphub/src/main/java/com/google/cloud/apphub/v1/AppHubSettings.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.apphub.v1;
import static com.google.cloud.apphub.v1.AppHubClient.ListApplicationsPagedResponse;
import static com.google.cloud.apphub.v1.AppHubClient.ListDiscoveredServicesPagedResponse;
import static com.google.cloud.apphub.v1.AppHubClient.ListDiscoveredWorkloadsPagedResponse;
import static com.google.cloud.apphub.v1.AppHubClient.ListLocationsPagedResponse;
import static com.google.cloud.apphub.v1.AppHubClient.ListServiceProjectAttachmentsPagedResponse;
import static com.google.cloud.apphub.v1.AppHubClient.ListServicesPagedResponse;
import static com.google.cloud.apphub.v1.AppHubClient.ListWorkloadsPagedResponse;
import com.google.api.core.ApiFunction;
import com.google.api.core.BetaApi;
import com.google.api.gax.core.GoogleCredentialsProvider;
import com.google.api.gax.core.InstantiatingExecutorProvider;
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.api.gax.httpjson.InstantiatingHttpJsonChannelProvider;
import com.google.api.gax.rpc.ApiClientHeaderProvider;
import com.google.api.gax.rpc.ClientContext;
import com.google.api.gax.rpc.ClientSettings;
import com.google.api.gax.rpc.OperationCallSettings;
import com.google.api.gax.rpc.PagedCallSettings;
import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.api.gax.rpc.UnaryCallSettings;
import com.google.cloud.apphub.v1.stub.AppHubStubSettings;
import com.google.cloud.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
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.longrunning.Operation;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.List;
import javax.annotation.Generated;
// AUTO-GENERATED DOCUMENTATION AND CLASS.
/**
* Settings class to configure an instance of {@link AppHubClient}.
*
* <p>The default instance has everything set to sensible defaults:
*
* <ul>
* <li>The default service address (apphub.googleapis.com) and default port (443) are used.
* <li>Credentials are acquired automatically through Application Default Credentials.
* <li>Retries are configured for idempotent methods but not for non-idempotent methods.
* </ul>
*
* <p>The builder of this class is recursive, so contained classes are themselves builders. When
* build() is called, the tree of builders is called to create the complete settings object.
*
* <p>For example, to set the
* [RetrySettings](https://cloud.google.com/java/docs/reference/gax/latest/com.google.api.gax.retrying.RetrySettings)
* of lookupServiceProjectAttachment:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* AppHubSettings.Builder appHubSettingsBuilder = AppHubSettings.newBuilder();
* appHubSettingsBuilder
* .lookupServiceProjectAttachmentSettings()
* .setRetrySettings(
* appHubSettingsBuilder
* .lookupServiceProjectAttachmentSettings()
* .getRetrySettings()
* .toBuilder()
* .setInitialRetryDelayDuration(Duration.ofSeconds(1))
* .setInitialRpcTimeoutDuration(Duration.ofSeconds(5))
* .setMaxAttempts(5)
* .setMaxRetryDelayDuration(Duration.ofSeconds(30))
* .setMaxRpcTimeoutDuration(Duration.ofSeconds(60))
* .setRetryDelayMultiplier(1.3)
* .setRpcTimeoutMultiplier(1.5)
* .setTotalTimeoutDuration(Duration.ofSeconds(300))
* .build());
* AppHubSettings appHubSettings = appHubSettingsBuilder.build();
* }</pre>
*
* Please refer to the [Client Side Retry
* Guide](https://github.com/googleapis/google-cloud-java/blob/main/docs/client_retries.md) for
* additional support in setting retries.
*
* <p>To configure the RetrySettings of a Long Running Operation method, create an
* OperationTimedPollAlgorithm object and update the RPC's polling algorithm. For example, to
* configure the RetrySettings for createServiceProjectAttachment:
*
* <pre>{@code
* // This snippet has been automatically generated and should be regarded as a code template only.
* // It will require modifications to work:
* // - It may require correct/in-range values for request initialization.
* // - It may require specifying regional endpoints when creating the service client as shown in
* // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
* AppHubSettings.Builder appHubSettingsBuilder = AppHubSettings.newBuilder();
* TimedRetryAlgorithm timedRetryAlgorithm =
* OperationalTimedPollAlgorithm.create(
* RetrySettings.newBuilder()
* .setInitialRetryDelayDuration(Duration.ofMillis(500))
* .setRetryDelayMultiplier(1.5)
* .setMaxRetryDelayDuration(Duration.ofMillis(5000))
* .setTotalTimeoutDuration(Duration.ofHours(24))
* .build());
* appHubSettingsBuilder
* .createClusterOperationSettings()
* .setPollingAlgorithm(timedRetryAlgorithm)
* .build();
* }</pre>
*/
@Generated("by gapic-generator-java")
public class AppHubSettings extends ClientSettings<AppHubSettings> {
/** Returns the object with the settings used for calls to lookupServiceProjectAttachment. */
public UnaryCallSettings<
LookupServiceProjectAttachmentRequest, LookupServiceProjectAttachmentResponse>
lookupServiceProjectAttachmentSettings() {
return ((AppHubStubSettings) getStubSettings()).lookupServiceProjectAttachmentSettings();
}
/** Returns the object with the settings used for calls to listServiceProjectAttachments. */
public PagedCallSettings<
ListServiceProjectAttachmentsRequest,
ListServiceProjectAttachmentsResponse,
ListServiceProjectAttachmentsPagedResponse>
listServiceProjectAttachmentsSettings() {
return ((AppHubStubSettings) getStubSettings()).listServiceProjectAttachmentsSettings();
}
/** Returns the object with the settings used for calls to createServiceProjectAttachment. */
public UnaryCallSettings<CreateServiceProjectAttachmentRequest, Operation>
createServiceProjectAttachmentSettings() {
return ((AppHubStubSettings) getStubSettings()).createServiceProjectAttachmentSettings();
}
/** Returns the object with the settings used for calls to createServiceProjectAttachment. */
public OperationCallSettings<
CreateServiceProjectAttachmentRequest, ServiceProjectAttachment, OperationMetadata>
createServiceProjectAttachmentOperationSettings() {
return ((AppHubStubSettings) getStubSettings())
.createServiceProjectAttachmentOperationSettings();
}
/** Returns the object with the settings used for calls to getServiceProjectAttachment. */
public UnaryCallSettings<GetServiceProjectAttachmentRequest, ServiceProjectAttachment>
getServiceProjectAttachmentSettings() {
return ((AppHubStubSettings) getStubSettings()).getServiceProjectAttachmentSettings();
}
/** Returns the object with the settings used for calls to deleteServiceProjectAttachment. */
public UnaryCallSettings<DeleteServiceProjectAttachmentRequest, Operation>
deleteServiceProjectAttachmentSettings() {
return ((AppHubStubSettings) getStubSettings()).deleteServiceProjectAttachmentSettings();
}
/** Returns the object with the settings used for calls to deleteServiceProjectAttachment. */
public OperationCallSettings<DeleteServiceProjectAttachmentRequest, Empty, OperationMetadata>
deleteServiceProjectAttachmentOperationSettings() {
return ((AppHubStubSettings) getStubSettings())
.deleteServiceProjectAttachmentOperationSettings();
}
/** Returns the object with the settings used for calls to detachServiceProjectAttachment. */
public UnaryCallSettings<
DetachServiceProjectAttachmentRequest, DetachServiceProjectAttachmentResponse>
detachServiceProjectAttachmentSettings() {
return ((AppHubStubSettings) getStubSettings()).detachServiceProjectAttachmentSettings();
}
/** Returns the object with the settings used for calls to listDiscoveredServices. */
public PagedCallSettings<
ListDiscoveredServicesRequest,
ListDiscoveredServicesResponse,
ListDiscoveredServicesPagedResponse>
listDiscoveredServicesSettings() {
return ((AppHubStubSettings) getStubSettings()).listDiscoveredServicesSettings();
}
/** Returns the object with the settings used for calls to getDiscoveredService. */
public UnaryCallSettings<GetDiscoveredServiceRequest, DiscoveredService>
getDiscoveredServiceSettings() {
return ((AppHubStubSettings) getStubSettings()).getDiscoveredServiceSettings();
}
/** Returns the object with the settings used for calls to lookupDiscoveredService. */
public UnaryCallSettings<LookupDiscoveredServiceRequest, LookupDiscoveredServiceResponse>
lookupDiscoveredServiceSettings() {
return ((AppHubStubSettings) getStubSettings()).lookupDiscoveredServiceSettings();
}
/** Returns the object with the settings used for calls to listServices. */
public PagedCallSettings<ListServicesRequest, ListServicesResponse, ListServicesPagedResponse>
listServicesSettings() {
return ((AppHubStubSettings) getStubSettings()).listServicesSettings();
}
/** Returns the object with the settings used for calls to createService. */
public UnaryCallSettings<CreateServiceRequest, Operation> createServiceSettings() {
return ((AppHubStubSettings) getStubSettings()).createServiceSettings();
}
/** Returns the object with the settings used for calls to createService. */
public OperationCallSettings<CreateServiceRequest, Service, OperationMetadata>
createServiceOperationSettings() {
return ((AppHubStubSettings) getStubSettings()).createServiceOperationSettings();
}
/** Returns the object with the settings used for calls to getService. */
public UnaryCallSettings<GetServiceRequest, Service> getServiceSettings() {
return ((AppHubStubSettings) getStubSettings()).getServiceSettings();
}
/** Returns the object with the settings used for calls to updateService. */
public UnaryCallSettings<UpdateServiceRequest, Operation> updateServiceSettings() {
return ((AppHubStubSettings) getStubSettings()).updateServiceSettings();
}
/** Returns the object with the settings used for calls to updateService. */
public OperationCallSettings<UpdateServiceRequest, Service, OperationMetadata>
updateServiceOperationSettings() {
return ((AppHubStubSettings) getStubSettings()).updateServiceOperationSettings();
}
/** Returns the object with the settings used for calls to deleteService. */
public UnaryCallSettings<DeleteServiceRequest, Operation> deleteServiceSettings() {
return ((AppHubStubSettings) getStubSettings()).deleteServiceSettings();
}
/** Returns the object with the settings used for calls to deleteService. */
public OperationCallSettings<DeleteServiceRequest, Empty, OperationMetadata>
deleteServiceOperationSettings() {
return ((AppHubStubSettings) getStubSettings()).deleteServiceOperationSettings();
}
/** Returns the object with the settings used for calls to listDiscoveredWorkloads. */
public PagedCallSettings<
ListDiscoveredWorkloadsRequest,
ListDiscoveredWorkloadsResponse,
ListDiscoveredWorkloadsPagedResponse>
listDiscoveredWorkloadsSettings() {
return ((AppHubStubSettings) getStubSettings()).listDiscoveredWorkloadsSettings();
}
/** Returns the object with the settings used for calls to getDiscoveredWorkload. */
public UnaryCallSettings<GetDiscoveredWorkloadRequest, DiscoveredWorkload>
getDiscoveredWorkloadSettings() {
return ((AppHubStubSettings) getStubSettings()).getDiscoveredWorkloadSettings();
}
/** Returns the object with the settings used for calls to lookupDiscoveredWorkload. */
public UnaryCallSettings<LookupDiscoveredWorkloadRequest, LookupDiscoveredWorkloadResponse>
lookupDiscoveredWorkloadSettings() {
return ((AppHubStubSettings) getStubSettings()).lookupDiscoveredWorkloadSettings();
}
/** Returns the object with the settings used for calls to listWorkloads. */
public PagedCallSettings<ListWorkloadsRequest, ListWorkloadsResponse, ListWorkloadsPagedResponse>
listWorkloadsSettings() {
return ((AppHubStubSettings) getStubSettings()).listWorkloadsSettings();
}
/** Returns the object with the settings used for calls to createWorkload. */
public UnaryCallSettings<CreateWorkloadRequest, Operation> createWorkloadSettings() {
return ((AppHubStubSettings) getStubSettings()).createWorkloadSettings();
}
/** Returns the object with the settings used for calls to createWorkload. */
public OperationCallSettings<CreateWorkloadRequest, Workload, OperationMetadata>
createWorkloadOperationSettings() {
return ((AppHubStubSettings) getStubSettings()).createWorkloadOperationSettings();
}
/** Returns the object with the settings used for calls to getWorkload. */
public UnaryCallSettings<GetWorkloadRequest, Workload> getWorkloadSettings() {
return ((AppHubStubSettings) getStubSettings()).getWorkloadSettings();
}
/** Returns the object with the settings used for calls to updateWorkload. */
public UnaryCallSettings<UpdateWorkloadRequest, Operation> updateWorkloadSettings() {
return ((AppHubStubSettings) getStubSettings()).updateWorkloadSettings();
}
/** Returns the object with the settings used for calls to updateWorkload. */
public OperationCallSettings<UpdateWorkloadRequest, Workload, OperationMetadata>
updateWorkloadOperationSettings() {
return ((AppHubStubSettings) getStubSettings()).updateWorkloadOperationSettings();
}
/** Returns the object with the settings used for calls to deleteWorkload. */
public UnaryCallSettings<DeleteWorkloadRequest, Operation> deleteWorkloadSettings() {
return ((AppHubStubSettings) getStubSettings()).deleteWorkloadSettings();
}
/** Returns the object with the settings used for calls to deleteWorkload. */
public OperationCallSettings<DeleteWorkloadRequest, Empty, OperationMetadata>
deleteWorkloadOperationSettings() {
return ((AppHubStubSettings) getStubSettings()).deleteWorkloadOperationSettings();
}
/** Returns the object with the settings used for calls to listApplications. */
public PagedCallSettings<
ListApplicationsRequest, ListApplicationsResponse, ListApplicationsPagedResponse>
listApplicationsSettings() {
return ((AppHubStubSettings) getStubSettings()).listApplicationsSettings();
}
/** Returns the object with the settings used for calls to createApplication. */
public UnaryCallSettings<CreateApplicationRequest, Operation> createApplicationSettings() {
return ((AppHubStubSettings) getStubSettings()).createApplicationSettings();
}
/** Returns the object with the settings used for calls to createApplication. */
public OperationCallSettings<CreateApplicationRequest, Application, OperationMetadata>
createApplicationOperationSettings() {
return ((AppHubStubSettings) getStubSettings()).createApplicationOperationSettings();
}
/** Returns the object with the settings used for calls to getApplication. */
public UnaryCallSettings<GetApplicationRequest, Application> getApplicationSettings() {
return ((AppHubStubSettings) getStubSettings()).getApplicationSettings();
}
/** Returns the object with the settings used for calls to updateApplication. */
public UnaryCallSettings<UpdateApplicationRequest, Operation> updateApplicationSettings() {
return ((AppHubStubSettings) getStubSettings()).updateApplicationSettings();
}
/** Returns the object with the settings used for calls to updateApplication. */
public OperationCallSettings<UpdateApplicationRequest, Application, OperationMetadata>
updateApplicationOperationSettings() {
return ((AppHubStubSettings) getStubSettings()).updateApplicationOperationSettings();
}
/** Returns the object with the settings used for calls to deleteApplication. */
public UnaryCallSettings<DeleteApplicationRequest, Operation> deleteApplicationSettings() {
return ((AppHubStubSettings) getStubSettings()).deleteApplicationSettings();
}
/** Returns the object with the settings used for calls to deleteApplication. */
public OperationCallSettings<DeleteApplicationRequest, Empty, OperationMetadata>
deleteApplicationOperationSettings() {
return ((AppHubStubSettings) getStubSettings()).deleteApplicationOperationSettings();
}
/** Returns the object with the settings used for calls to listLocations. */
public PagedCallSettings<ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>
listLocationsSettings() {
return ((AppHubStubSettings) getStubSettings()).listLocationsSettings();
}
/** Returns the object with the settings used for calls to getLocation. */
public UnaryCallSettings<GetLocationRequest, Location> getLocationSettings() {
return ((AppHubStubSettings) getStubSettings()).getLocationSettings();
}
/** Returns the object with the settings used for calls to setIamPolicy. */
public UnaryCallSettings<SetIamPolicyRequest, Policy> setIamPolicySettings() {
return ((AppHubStubSettings) getStubSettings()).setIamPolicySettings();
}
/** Returns the object with the settings used for calls to getIamPolicy. */
public UnaryCallSettings<GetIamPolicyRequest, Policy> getIamPolicySettings() {
return ((AppHubStubSettings) getStubSettings()).getIamPolicySettings();
}
/** Returns the object with the settings used for calls to testIamPermissions. */
public UnaryCallSettings<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsSettings() {
return ((AppHubStubSettings) getStubSettings()).testIamPermissionsSettings();
}
public static final AppHubSettings create(AppHubStubSettings stub) throws IOException {
return new AppHubSettings.Builder(stub.toBuilder()).build();
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return AppHubStubSettings.defaultExecutorProviderBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return AppHubStubSettings.getDefaultEndpoint();
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return AppHubStubSettings.getDefaultServiceScopes();
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return AppHubStubSettings.defaultCredentialsProviderBuilder();
}
/** Returns a builder for the default gRPC ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return AppHubStubSettings.defaultGrpcTransportProviderBuilder();
}
/** Returns a builder for the default REST ChannelProvider for this service. */
@BetaApi
public static InstantiatingHttpJsonChannelProvider.Builder
defaultHttpJsonTransportProviderBuilder() {
return AppHubStubSettings.defaultHttpJsonTransportProviderBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return AppHubStubSettings.defaultTransportChannelProvider();
}
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return AppHubStubSettings.defaultApiClientHeaderProviderBuilder();
}
/** Returns a new gRPC builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new REST builder for this class. */
public static Builder newHttpJsonBuilder() {
return Builder.createHttpJsonDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected AppHubSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
}
/** Builder for AppHubSettings. */
public static class Builder extends ClientSettings.Builder<AppHubSettings, Builder> {
protected Builder() throws IOException {
this(((ClientContext) null));
}
protected Builder(ClientContext clientContext) {
super(AppHubStubSettings.newBuilder(clientContext));
}
protected Builder(AppHubSettings settings) {
super(settings.getStubSettings().toBuilder());
}
protected Builder(AppHubStubSettings.Builder stubSettings) {
super(stubSettings);
}
private static Builder createDefault() {
return new Builder(AppHubStubSettings.newBuilder());
}
private static Builder createHttpJsonDefault() {
return new Builder(AppHubStubSettings.newHttpJsonBuilder());
}
public AppHubStubSettings.Builder getStubSettingsBuilder() {
return ((AppHubStubSettings.Builder) getStubSettings());
}
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(
getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater);
return this;
}
/** Returns the builder for the settings used for calls to lookupServiceProjectAttachment. */
public UnaryCallSettings.Builder<
LookupServiceProjectAttachmentRequest, LookupServiceProjectAttachmentResponse>
lookupServiceProjectAttachmentSettings() {
return getStubSettingsBuilder().lookupServiceProjectAttachmentSettings();
}
/** Returns the builder for the settings used for calls to listServiceProjectAttachments. */
public PagedCallSettings.Builder<
ListServiceProjectAttachmentsRequest,
ListServiceProjectAttachmentsResponse,
ListServiceProjectAttachmentsPagedResponse>
listServiceProjectAttachmentsSettings() {
return getStubSettingsBuilder().listServiceProjectAttachmentsSettings();
}
/** Returns the builder for the settings used for calls to createServiceProjectAttachment. */
public UnaryCallSettings.Builder<CreateServiceProjectAttachmentRequest, Operation>
createServiceProjectAttachmentSettings() {
return getStubSettingsBuilder().createServiceProjectAttachmentSettings();
}
/** Returns the builder for the settings used for calls to createServiceProjectAttachment. */
public OperationCallSettings.Builder<
CreateServiceProjectAttachmentRequest, ServiceProjectAttachment, OperationMetadata>
createServiceProjectAttachmentOperationSettings() {
return getStubSettingsBuilder().createServiceProjectAttachmentOperationSettings();
}
/** Returns the builder for the settings used for calls to getServiceProjectAttachment. */
public UnaryCallSettings.Builder<GetServiceProjectAttachmentRequest, ServiceProjectAttachment>
getServiceProjectAttachmentSettings() {
return getStubSettingsBuilder().getServiceProjectAttachmentSettings();
}
/** Returns the builder for the settings used for calls to deleteServiceProjectAttachment. */
public UnaryCallSettings.Builder<DeleteServiceProjectAttachmentRequest, Operation>
deleteServiceProjectAttachmentSettings() {
return getStubSettingsBuilder().deleteServiceProjectAttachmentSettings();
}
/** Returns the builder for the settings used for calls to deleteServiceProjectAttachment. */
public OperationCallSettings.Builder<
DeleteServiceProjectAttachmentRequest, Empty, OperationMetadata>
deleteServiceProjectAttachmentOperationSettings() {
return getStubSettingsBuilder().deleteServiceProjectAttachmentOperationSettings();
}
/** Returns the builder for the settings used for calls to detachServiceProjectAttachment. */
public UnaryCallSettings.Builder<
DetachServiceProjectAttachmentRequest, DetachServiceProjectAttachmentResponse>
detachServiceProjectAttachmentSettings() {
return getStubSettingsBuilder().detachServiceProjectAttachmentSettings();
}
/** Returns the builder for the settings used for calls to listDiscoveredServices. */
public PagedCallSettings.Builder<
ListDiscoveredServicesRequest,
ListDiscoveredServicesResponse,
ListDiscoveredServicesPagedResponse>
listDiscoveredServicesSettings() {
return getStubSettingsBuilder().listDiscoveredServicesSettings();
}
/** Returns the builder for the settings used for calls to getDiscoveredService. */
public UnaryCallSettings.Builder<GetDiscoveredServiceRequest, DiscoveredService>
getDiscoveredServiceSettings() {
return getStubSettingsBuilder().getDiscoveredServiceSettings();
}
/** Returns the builder for the settings used for calls to lookupDiscoveredService. */
public UnaryCallSettings.Builder<
LookupDiscoveredServiceRequest, LookupDiscoveredServiceResponse>
lookupDiscoveredServiceSettings() {
return getStubSettingsBuilder().lookupDiscoveredServiceSettings();
}
/** Returns the builder for the settings used for calls to listServices. */
public PagedCallSettings.Builder<
ListServicesRequest, ListServicesResponse, ListServicesPagedResponse>
listServicesSettings() {
return getStubSettingsBuilder().listServicesSettings();
}
/** Returns the builder for the settings used for calls to createService. */
public UnaryCallSettings.Builder<CreateServiceRequest, Operation> createServiceSettings() {
return getStubSettingsBuilder().createServiceSettings();
}
/** Returns the builder for the settings used for calls to createService. */
public OperationCallSettings.Builder<CreateServiceRequest, Service, OperationMetadata>
createServiceOperationSettings() {
return getStubSettingsBuilder().createServiceOperationSettings();
}
/** Returns the builder for the settings used for calls to getService. */
public UnaryCallSettings.Builder<GetServiceRequest, Service> getServiceSettings() {
return getStubSettingsBuilder().getServiceSettings();
}
/** Returns the builder for the settings used for calls to updateService. */
public UnaryCallSettings.Builder<UpdateServiceRequest, Operation> updateServiceSettings() {
return getStubSettingsBuilder().updateServiceSettings();
}
/** Returns the builder for the settings used for calls to updateService. */
public OperationCallSettings.Builder<UpdateServiceRequest, Service, OperationMetadata>
updateServiceOperationSettings() {
return getStubSettingsBuilder().updateServiceOperationSettings();
}
/** Returns the builder for the settings used for calls to deleteService. */
public UnaryCallSettings.Builder<DeleteServiceRequest, Operation> deleteServiceSettings() {
return getStubSettingsBuilder().deleteServiceSettings();
}
/** Returns the builder for the settings used for calls to deleteService. */
public OperationCallSettings.Builder<DeleteServiceRequest, Empty, OperationMetadata>
deleteServiceOperationSettings() {
return getStubSettingsBuilder().deleteServiceOperationSettings();
}
/** Returns the builder for the settings used for calls to listDiscoveredWorkloads. */
public PagedCallSettings.Builder<
ListDiscoveredWorkloadsRequest,
ListDiscoveredWorkloadsResponse,
ListDiscoveredWorkloadsPagedResponse>
listDiscoveredWorkloadsSettings() {
return getStubSettingsBuilder().listDiscoveredWorkloadsSettings();
}
/** Returns the builder for the settings used for calls to getDiscoveredWorkload. */
public UnaryCallSettings.Builder<GetDiscoveredWorkloadRequest, DiscoveredWorkload>
getDiscoveredWorkloadSettings() {
return getStubSettingsBuilder().getDiscoveredWorkloadSettings();
}
/** Returns the builder for the settings used for calls to lookupDiscoveredWorkload. */
public UnaryCallSettings.Builder<
LookupDiscoveredWorkloadRequest, LookupDiscoveredWorkloadResponse>
lookupDiscoveredWorkloadSettings() {
return getStubSettingsBuilder().lookupDiscoveredWorkloadSettings();
}
/** Returns the builder for the settings used for calls to listWorkloads. */
public PagedCallSettings.Builder<
ListWorkloadsRequest, ListWorkloadsResponse, ListWorkloadsPagedResponse>
listWorkloadsSettings() {
return getStubSettingsBuilder().listWorkloadsSettings();
}
/** Returns the builder for the settings used for calls to createWorkload. */
public UnaryCallSettings.Builder<CreateWorkloadRequest, Operation> createWorkloadSettings() {
return getStubSettingsBuilder().createWorkloadSettings();
}
/** Returns the builder for the settings used for calls to createWorkload. */
public OperationCallSettings.Builder<CreateWorkloadRequest, Workload, OperationMetadata>
createWorkloadOperationSettings() {
return getStubSettingsBuilder().createWorkloadOperationSettings();
}
/** Returns the builder for the settings used for calls to getWorkload. */
public UnaryCallSettings.Builder<GetWorkloadRequest, Workload> getWorkloadSettings() {
return getStubSettingsBuilder().getWorkloadSettings();
}
/** Returns the builder for the settings used for calls to updateWorkload. */
public UnaryCallSettings.Builder<UpdateWorkloadRequest, Operation> updateWorkloadSettings() {
return getStubSettingsBuilder().updateWorkloadSettings();
}
/** Returns the builder for the settings used for calls to updateWorkload. */
public OperationCallSettings.Builder<UpdateWorkloadRequest, Workload, OperationMetadata>
updateWorkloadOperationSettings() {
return getStubSettingsBuilder().updateWorkloadOperationSettings();
}
/** Returns the builder for the settings used for calls to deleteWorkload. */
public UnaryCallSettings.Builder<DeleteWorkloadRequest, Operation> deleteWorkloadSettings() {
return getStubSettingsBuilder().deleteWorkloadSettings();
}
/** Returns the builder for the settings used for calls to deleteWorkload. */
public OperationCallSettings.Builder<DeleteWorkloadRequest, Empty, OperationMetadata>
deleteWorkloadOperationSettings() {
return getStubSettingsBuilder().deleteWorkloadOperationSettings();
}
/** Returns the builder for the settings used for calls to listApplications. */
public PagedCallSettings.Builder<
ListApplicationsRequest, ListApplicationsResponse, ListApplicationsPagedResponse>
listApplicationsSettings() {
return getStubSettingsBuilder().listApplicationsSettings();
}
/** Returns the builder for the settings used for calls to createApplication. */
public UnaryCallSettings.Builder<CreateApplicationRequest, Operation>
createApplicationSettings() {
return getStubSettingsBuilder().createApplicationSettings();
}
/** Returns the builder for the settings used for calls to createApplication. */
public OperationCallSettings.Builder<CreateApplicationRequest, Application, OperationMetadata>
createApplicationOperationSettings() {
return getStubSettingsBuilder().createApplicationOperationSettings();
}
/** Returns the builder for the settings used for calls to getApplication. */
public UnaryCallSettings.Builder<GetApplicationRequest, Application> getApplicationSettings() {
return getStubSettingsBuilder().getApplicationSettings();
}
/** Returns the builder for the settings used for calls to updateApplication. */
public UnaryCallSettings.Builder<UpdateApplicationRequest, Operation>
updateApplicationSettings() {
return getStubSettingsBuilder().updateApplicationSettings();
}
/** Returns the builder for the settings used for calls to updateApplication. */
public OperationCallSettings.Builder<UpdateApplicationRequest, Application, OperationMetadata>
updateApplicationOperationSettings() {
return getStubSettingsBuilder().updateApplicationOperationSettings();
}
/** Returns the builder for the settings used for calls to deleteApplication. */
public UnaryCallSettings.Builder<DeleteApplicationRequest, Operation>
deleteApplicationSettings() {
return getStubSettingsBuilder().deleteApplicationSettings();
}
/** Returns the builder for the settings used for calls to deleteApplication. */
public OperationCallSettings.Builder<DeleteApplicationRequest, Empty, OperationMetadata>
deleteApplicationOperationSettings() {
return getStubSettingsBuilder().deleteApplicationOperationSettings();
}
/** Returns the builder for the settings used for calls to listLocations. */
public PagedCallSettings.Builder<
ListLocationsRequest, ListLocationsResponse, ListLocationsPagedResponse>
listLocationsSettings() {
return getStubSettingsBuilder().listLocationsSettings();
}
/** Returns the builder for the settings used for calls to getLocation. */
public UnaryCallSettings.Builder<GetLocationRequest, Location> getLocationSettings() {
return getStubSettingsBuilder().getLocationSettings();
}
/** Returns the builder for the settings used for calls to setIamPolicy. */
public UnaryCallSettings.Builder<SetIamPolicyRequest, Policy> setIamPolicySettings() {
return getStubSettingsBuilder().setIamPolicySettings();
}
/** Returns the builder for the settings used for calls to getIamPolicy. */
public UnaryCallSettings.Builder<GetIamPolicyRequest, Policy> getIamPolicySettings() {
return getStubSettingsBuilder().getIamPolicySettings();
}
/** Returns the builder for the settings used for calls to testIamPermissions. */
public UnaryCallSettings.Builder<TestIamPermissionsRequest, TestIamPermissionsResponse>
testIamPermissionsSettings() {
return getStubSettingsBuilder().testIamPermissionsSettings();
}
@Override
public AppHubSettings build() throws IOException {
return new AppHubSettings(this);
}
}
}
|
apache/ignite-3 | 35,955 | modules/api/src/main/java/org/apache/ignite/lang/ErrorGroups.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.ignite.lang;
import static java.util.regex.Pattern.DOTALL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.ignite.error.code.annotations.ErrorCodeGroup;
import org.jetbrains.annotations.Nullable;
/**
* Defines error groups and its errors.
*/
@SuppressWarnings("PublicInnerClass")
public class ErrorGroups {
/** Additional prefix that is used in a human-readable format of ignite errors. */
public static final String IGNITE_ERR_PREFIX = "IGN";
private static final String PLACEHOLDER = "${ERROR_PREFIX}";
private static final String EXCEPTION_MESSAGE_STRING_PATTERN =
"(.*)(" + PLACEHOLDER + ")-([A-Z]+)-(\\d+)(\\s?)(.*)( TraceId:)([a-f0-9]{8})";
/** Error message pattern. */
private static Pattern EXCEPTION_MESSAGE_PATTERN;
private static final HashSet<String> REGISTERED_ERROR_PREFIXES = new HashSet<>();
/** List of all registered error groups. */
private static final Map<Short, ErrorGroup> registeredGroups = new HashMap<>();
/**
* Initializes and register all error groups and error codes.
*/
public static synchronized void initialize() {
for (Class<?> cls : ErrorGroups.class.getDeclaredClasses()) {
try {
cls.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to initialize error groups", e);
}
}
}
/**
* Creates a new error group with the given {@code groupName} and {@code groupCode} and default error prefix.
*
* @param groupName Group name to be created.
* @param groupCode Group code to be created.
* @return New error group.
* @throws IllegalArgumentException If the specified name or group code already registered. Also, this exception is thrown if
* the given {@code groupName} is {@code null} or empty.
*/
public static synchronized ErrorGroup registerGroup(String groupName, short groupCode) {
return registerGroup(IGNITE_ERR_PREFIX, groupName, groupCode);
}
/**
* Creates a new error group with the given {@code groupName} and {@code groupCode}.
*
* @param errorPrefix Error prefix which should be used for the created error group.
* @param groupName Group name to be created.
* @param groupCode Group code to be created.
* @return New error group.
* @throws IllegalArgumentException If the specified name or group code already registered. Also, this exception is thrown if
* the given {@code groupName} is {@code null} or empty.
*/
public static synchronized ErrorGroup registerGroup(String errorPrefix, String groupName, short groupCode) {
if (groupName == null || groupName.isEmpty()) {
throw new IllegalArgumentException("Group name is null or empty");
}
String grpName = groupName.toUpperCase(Locale.ENGLISH);
if (registeredGroups.containsKey(groupCode)) {
throw new IllegalArgumentException(
"Error group already registered [groupName=" + groupName + ", groupCode=" + groupCode
+ ", registeredGroup=" + registeredGroups.get(groupCode) + ']');
}
for (ErrorGroup group : registeredGroups.values()) {
if (group.name().equals(groupName)) {
throw new IllegalArgumentException(
"Error group already registered [groupName=" + groupName + ", groupCode=" + groupCode
+ ", registeredGroup=" + group + ']');
}
}
if (REGISTERED_ERROR_PREFIXES.add(errorPrefix)) {
String errorPrefixes = String.join("|", REGISTERED_ERROR_PREFIXES);
String pattern = EXCEPTION_MESSAGE_STRING_PATTERN.replace(PLACEHOLDER, errorPrefixes);
EXCEPTION_MESSAGE_PATTERN = Pattern.compile(pattern, DOTALL);
}
ErrorGroup newGroup = new ErrorGroup(errorPrefix, grpName, groupCode);
registeredGroups.put(groupCode, newGroup);
return newGroup;
}
/**
* Returns a message extracted from the given {@code errorMessage} if this {@code errorMessage} matches
* {@link #EXCEPTION_MESSAGE_PATTERN}. If {@code errorMessage} does not match the pattern or {@code null} then returns the original
* {@code errorMessage}.
*
* @param errorMessage Message that is returned by {@link Throwable#getMessage()}
* @return Extracted message.
*/
public static @Nullable String extractCauseMessage(String errorMessage) {
if (errorMessage == null) {
return null;
}
Matcher m = EXCEPTION_MESSAGE_PATTERN.matcher(errorMessage);
return (m.matches()) ? m.group(6) : errorMessage;
}
/**
* Returns group code extracted from the given full error code.
*
* @param code Full error code.
* @return Group code.
*/
public static short extractGroupCode(int code) {
return (short) (code >>> 16);
}
/**
* Returns error group identified by the given {@code groupCode}.
*
* @param groupCode Group code
* @return Error Group.
*/
public static ErrorGroup errorGroupByGroupCode(short groupCode) {
return registeredGroups.get(groupCode);
}
/**
* Returns error group identified by the given error {@code code}.
*
* @param code Full error code
* @return Error Group.
*/
public static ErrorGroup errorGroupByCode(int code) {
ErrorGroup grp = registeredGroups.get(extractGroupCode(code));
assert grp != null : "group not found, code=" + code;
return grp;
}
/** Common error group. */
@ErrorCodeGroup
public static class Common {
/** Common error group. */
public static final ErrorGroup COMMON_ERR_GROUP = registerGroup("CMN", (short) 1);
/** Node stopping error. */
public static final int NODE_STOPPING_ERR = COMMON_ERR_GROUP.registerErrorCode((short) 1);
/** Component not started error. */
public static final int COMPONENT_NOT_STARTED_ERR = COMMON_ERR_GROUP.registerErrorCode((short) 2);
/** Illegal argument or argument in a wrong format has been passed. */
public static final int ILLEGAL_ARGUMENT_ERR = COMMON_ERR_GROUP.registerErrorCode((short) 3);
/** SSL can not be configured error. */
public static final int SSL_CONFIGURATION_ERR = COMMON_ERR_GROUP.registerErrorCode((short) 4);
/** Operation failed because a node has left the cluster. */
public static final int NODE_LEFT_ERR = COMMON_ERR_GROUP.registerErrorCode((short) 5);
/** Cursor is already closed error. */
public static final int CURSOR_ALREADY_CLOSED_ERR = COMMON_ERR_GROUP.registerErrorCode((short) 6);
/** Resource closing error. */
public static final int RESOURCE_CLOSING_ERR = COMMON_ERR_GROUP.registerErrorCode((short) 7);
/** Can't marshal/unmarshal a user object. */
public static final int USER_OBJECT_SERIALIZATION_ERR = COMMON_ERR_GROUP.registerErrorCode((short) 8);
/**
* This error code indicates that a method can't return a {@code null} value due it's ambiguity
* (whether the value is absent or is {@code null}).
**/
public static final int NULLABLE_VALUE_ERR = COMMON_ERR_GROUP.registerErrorCode((short) 9);
/**
* This error code represents an internal error caused by faulty logic or coding in the Ignite codebase. In general, this error code
* should be considered as a non-recoverable error
*/
public static final int INTERNAL_ERR = COMMON_ERR_GROUP.registerErrorCode((short) 0xFFFF);
}
/** Tables error group. */
@ErrorCodeGroup
public static class Table {
/** Table error group. */
public static final ErrorGroup TABLE_ERR_GROUP = registerGroup("TBL", (short) 2);
/**
* Table already exists.
*
* @deprecated Unused. Replaced with {@link ErrorGroups.Sql#STMT_VALIDATION_ERR}.
*/
@Deprecated
public static final int TABLE_ALREADY_EXISTS_ERR = TABLE_ERR_GROUP.registerErrorCode((short) 1);
/** Table not found. */
public static final int TABLE_NOT_FOUND_ERR = TABLE_ERR_GROUP.registerErrorCode((short) 2);
/**
* Column already exists.
*
* @deprecated Unused. Replaced with {@link ErrorGroups.Sql#STMT_VALIDATION_ERR}.
*/
@Deprecated
public static final int COLUMN_ALREADY_EXISTS_ERR = TABLE_ERR_GROUP.registerErrorCode((short) 3);
/** Column not found. */
public static final int COLUMN_NOT_FOUND_ERR = TABLE_ERR_GROUP.registerErrorCode((short) 4);
/** Schema version mismatch. */
public static final int SCHEMA_VERSION_MISMATCH_ERR = TABLE_ERR_GROUP.registerErrorCode((short) 5);
/** Unsupported partition type. */
public static final int UNSUPPORTED_PARTITION_TYPE_ERR = TABLE_ERR_GROUP.registerErrorCode((short) 6);
}
/** Client error group. */
@ErrorCodeGroup
public static class Client {
/** Client error group. */
public static final ErrorGroup CLIENT_ERR_GROUP = registerGroup("CLIENT", (short) 3);
/** Connection failed. */
public static final int CONNECTION_ERR = CLIENT_ERR_GROUP.registerErrorCode((short) 1);
/** Protocol breakdown. */
public static final int PROTOCOL_ERR = CLIENT_ERR_GROUP.registerErrorCode((short) 2);
/** Incompatible protocol version. */
public static final int PROTOCOL_COMPATIBILITY_ERR = CLIENT_ERR_GROUP.registerErrorCode((short) 3);
/** Table not found by ID. */
public static final int TABLE_ID_NOT_FOUND_ERR = CLIENT_ERR_GROUP.registerErrorCode((short) 4);
/** Configuration error. */
public static final int CONFIGURATION_ERR = CLIENT_ERR_GROUP.registerErrorCode((short) 5);
/** Cluster ID mismatch error. */
public static final int CLUSTER_ID_MISMATCH_ERR = CLIENT_ERR_GROUP.registerErrorCode((short) 6);
/** Client SSL configuration error. */
public static final int CLIENT_SSL_CONFIGURATION_ERR = CLIENT_ERR_GROUP.registerErrorCode((short) 7);
/** Client handshake header error. */
public static final int HANDSHAKE_HEADER_ERR = CLIENT_ERR_GROUP.registerErrorCode((short) 8);
/** Server to client request failed. */
public static final int SERVER_TO_CLIENT_REQUEST_ERR = CLIENT_ERR_GROUP.registerErrorCode((short) 9);
}
/** SQL error group. */
@ErrorCodeGroup
public static class Sql {
/** SQL error group. */
public static final ErrorGroup SQL_ERR_GROUP = registerGroup("SQL", (short) 4);
/** Query without a result set error. */
public static final int QUERY_NO_RESULT_SET_ERR = SQL_ERR_GROUP.registerErrorCode((short) 1);
/**
* Schema not found.
*
* @deprecated Unused. Replaced with {@link ErrorGroups.Sql#STMT_VALIDATION_ERR}.
*/
@Deprecated
public static final int SCHEMA_NOT_FOUND_ERR = SQL_ERR_GROUP.registerErrorCode((short) 2);
/** Statement parsing error. This error is returned when an SQL statement string is not valid according to syntax rules. */
public static final int STMT_PARSE_ERR = SQL_ERR_GROUP.registerErrorCode((short) 3);
/**
* Statement validation error. Although statement is grammatically correct, the semantic is in question. This error may appear in
* following cases:
* <ul>
* <li>the statement refer to relation that doesn't exists.</li>
* <li>the statement describes action that is prohibited by the system, like changing columns belonging to primary keys.</li>
* <li>the statement contains operation that is not defined for given operands' types, like addition of DATE and DECIMAL.</li>
* <li>etc</li>
* </ul>
*
* <p>See message for details.
*/
public static final int STMT_VALIDATION_ERR = SQL_ERR_GROUP.registerErrorCode((short) 4);
/** Constraint violation error such as primary key violation. */
public static final int CONSTRAINT_VIOLATION_ERR = SQL_ERR_GROUP.registerErrorCode((short) 5);
/** Statement canceled error. Statement is canceled due to timeout, admin action, etc. */
public static final int EXECUTION_CANCELLED_ERR = SQL_ERR_GROUP.registerErrorCode((short) 6);
/**
* Runtime error. Errors caused by programming errors in SQL statement itself, such errors happen during statement execution:
* <ul>
* <li>Numeric overflow errors.</li>
* <li>Type conversion errors such as {@code SELECT CAST('abc' AS INTEGER)}.</li>
* <li>Function execution errors.</li>
* </ul>
*/
public static final int RUNTIME_ERR = SQL_ERR_GROUP.registerErrorCode((short) 7);
/**
* SQL engine was unable to map query on current cluster topology.
*
* <p>This may be due to a variety of reasons, but most probably because of all nodes hosting certain system view
* or a table partition went offline.
*
* <p>See error message for details.
*/
public static final int MAPPING_ERR = SQL_ERR_GROUP.registerErrorCode((short) 8);
/** Execution of transaction control statement inside an external transaction is forbidden. */
public static final int TX_CONTROL_INSIDE_EXTERNAL_TX_ERR = SQL_ERR_GROUP.registerErrorCode((short) 9);
}
/** Meta storage error group. */
@ErrorCodeGroup
public static class MetaStorage {
/** Meta storage error group. */
public static final ErrorGroup META_STORAGE_ERR_GROUP = registerGroup("META", (short) 5);
/** Failed to start the underlying key value storage. */
public static final int STARTING_STORAGE_ERR = META_STORAGE_ERR_GROUP.registerErrorCode((short) 1);
/** Failed to restore the underlying key value storage. */
public static final int RESTORING_STORAGE_ERR = META_STORAGE_ERR_GROUP.registerErrorCode((short) 2);
/** Failed to compact the underlying key value storage. */
public static final int COMPACTION_ERR = META_STORAGE_ERR_GROUP.registerErrorCode((short) 3);
/** Failed to perform an operation on the underlying key value storage. */
public static final int OP_EXECUTION_ERR = META_STORAGE_ERR_GROUP.registerErrorCode((short) 4);
/** Failed to perform an operation within a specified time period. Usually in such cases the operation should be retried. */
public static final int OP_EXECUTION_TIMEOUT_ERR = META_STORAGE_ERR_GROUP.registerErrorCode((short) 5);
/** Failed to perform a read operation on the underlying key value storage because the revision has already been compacted. */
public static final int COMPACTED_ERR = META_STORAGE_ERR_GROUP.registerErrorCode((short) 6);
/** Failed to start a node because Metastorage has diverged. The node has to be cleared and entered the cluster as a blank node. */
public static final int DIVERGED_ERR = META_STORAGE_ERR_GROUP.registerErrorCode((short) 7);
}
/**
* Index error group.
*
* @deprecated The whole group is unused.
*/
@ErrorCodeGroup
@Deprecated
public static class Index {
/** Index error group. */
@Deprecated
public static final ErrorGroup INDEX_ERR_GROUP = registerGroup("IDX", (short) 6);
/** Index not found. */
@Deprecated
public static final int INDEX_NOT_FOUND_ERR = INDEX_ERR_GROUP.registerErrorCode((short) 1);
/** Index already exists. */
@Deprecated
public static final int INDEX_ALREADY_EXISTS_ERR = INDEX_ERR_GROUP.registerErrorCode((short) 2);
}
/** Transactions error group. */
@ErrorCodeGroup
public static class Transactions {
/** Transactions error group. */
public static final ErrorGroup TX_ERR_GROUP = registerGroup("TX", (short) 7);
/** Error of tx state storage. */
public static final int TX_STATE_STORAGE_ERR = TX_ERR_GROUP.registerErrorCode((short) 1);
/** Tx state storage is stopped. */
public static final int TX_STATE_STORAGE_STOPPED_ERR = TX_ERR_GROUP.registerErrorCode((short) 2);
/** Error of unexpected tx state on state change. */
public static final int TX_UNEXPECTED_STATE_ERR = TX_ERR_GROUP.registerErrorCode((short) 3);
/** Failed to acquire a lock on a key due to a conflict. */
public static final int ACQUIRE_LOCK_ERR = TX_ERR_GROUP.registerErrorCode((short) 4);
/** Failed to acquire a lock on a key within a timeout. */
public static final int ACQUIRE_LOCK_TIMEOUT_ERR = TX_ERR_GROUP.registerErrorCode((short) 5);
/** Failed to commit a transaction. */
public static final int TX_COMMIT_ERR = TX_ERR_GROUP.registerErrorCode((short) 6);
/** Failed to rollback a transaction. */
public static final int TX_ROLLBACK_ERR = TX_ERR_GROUP.registerErrorCode((short) 7);
/** Failed to enlist read-write operation into read-only transaction. */
public static final int TX_FAILED_READ_WRITE_OPERATION_ERR = TX_ERR_GROUP.registerErrorCode((short) 8);
/** Tx state storage rebalancing error. */
public static final int TX_STATE_STORAGE_REBALANCE_ERR = TX_ERR_GROUP.registerErrorCode((short) 9);
/** Error occurred when trying to create a read-only transaction with a timestamp older than the data available in the tables. */
public static final int TX_READ_ONLY_TOO_OLD_ERR = TX_ERR_GROUP.registerErrorCode((short) 10);
/** Failure due to an incompatible schema change. */
public static final int TX_INCOMPATIBLE_SCHEMA_ERR = TX_ERR_GROUP.registerErrorCode((short) 11);
/** Failure due to primary replica expiration. */
public static final int TX_PRIMARY_REPLICA_EXPIRED_ERR = TX_ERR_GROUP.registerErrorCode((short) 12);
/** Operation failed because the transaction is already finished. */
public static final int TX_ALREADY_FINISHED_ERR = TX_ERR_GROUP.registerErrorCode((short) 13);
/** Failure due to a stale operation of a completed transaction is detected. */
public static final int TX_STALE_OPERATION_ERR = TX_ERR_GROUP.registerErrorCode((short) 14);
/**
* Error occurred when trying to execute an operation in a read-only transaction on a node that has already destroyed data for
* read timestamp of the transaction.
*/
public static final int TX_STALE_READ_ONLY_OPERATION_ERR = TX_ERR_GROUP.registerErrorCode((short) 15);
/** Operation failed because the transaction is already finished with timeout. */
public static final int TX_ALREADY_FINISHED_WITH_TIMEOUT_ERR = TX_ERR_GROUP.registerErrorCode((short) 16);
}
/** Replicator error group. */
@ErrorCodeGroup
public static class Replicator {
/** Replicator error group. */
public static final ErrorGroup REPLICATOR_ERR_GROUP = registerGroup("REP", (short) 8);
/** Common error for the replication procedure. */
public static final int REPLICA_COMMON_ERR = REPLICATOR_ERR_GROUP.registerErrorCode((short) 1);
/** Replica with the same identifier is already existed. */
public static final int REPLICA_IS_ALREADY_STARTED_ERR = REPLICATOR_ERR_GROUP.registerErrorCode((short) 2);
/** Timeout has happened during the replication procedure. */
public static final int REPLICA_TIMEOUT_ERR = REPLICATOR_ERR_GROUP.registerErrorCode((short) 3);
/** The error happens when the replication level try to handle an unsupported request. */
public static final int REPLICA_UNSUPPORTED_REQUEST_ERR = REPLICATOR_ERR_GROUP.registerErrorCode((short) 4);
/** The error happens when the replica is not ready to handle a request. */
public static final int REPLICA_UNAVAILABLE_ERR = REPLICATOR_ERR_GROUP.registerErrorCode((short) 5);
/** The error happens when the replica is not the current primary replica. */
public static final int REPLICA_MISS_ERR = REPLICATOR_ERR_GROUP.registerErrorCode((short) 6);
/** Failed to close cursor. */
public static final int CURSOR_CLOSE_ERR = REPLICATOR_ERR_GROUP.registerErrorCode((short) 7);
/** Stopping replica exception code. */
public static final int REPLICA_STOPPING_ERR = REPLICATOR_ERR_GROUP.registerErrorCode((short) 8);
/** Replication group overloaded exception code. */
public static final int GROUP_OVERLOADED_ERR = REPLICATOR_ERR_GROUP.registerErrorCode((short) 9);
}
/** Storage error group. */
@ErrorCodeGroup
public static class Storage {
/** Storage error group. */
public static final ErrorGroup STORAGE_ERR_GROUP = registerGroup("STORAGE", (short) 9);
/** Error reading from an index that has not yet been built. */
public static final int INDEX_NOT_BUILT_ERR = STORAGE_ERR_GROUP.registerErrorCode((short) 1);
/** Error indicating a possible data corruption in the storage. */
public static final int STORAGE_CORRUPTED_ERR = STORAGE_ERR_GROUP.registerErrorCode((short) 2);
}
/** Distribution zones error group. */
@ErrorCodeGroup
public static class DistributionZones {
/** Distribution zones group. */
public static final ErrorGroup DISTRIBUTION_ZONES_ERR_GROUP = registerGroup("DISTRZONES", (short) 10);
/** Distribution zone was not found. */
public static final int ZONE_NOT_FOUND_ERR = DISTRIBUTION_ZONES_ERR_GROUP.registerErrorCode((short) 1);
/** Empty data nodes. */
public static final int EMPTY_DATA_NODES_ERR = DISTRIBUTION_ZONES_ERR_GROUP.registerErrorCode((short) 2);
}
/** Network error group. */
@ErrorCodeGroup
public static class Network {
/** Network error group. */
public static final ErrorGroup NETWORK_ERR_GROUP = registerGroup("NETWORK", (short) 11);
/** Unresolvable consistent ID. */
public static final int UNRESOLVABLE_CONSISTENT_ID_ERR = NETWORK_ERR_GROUP.registerErrorCode((short) 1);
/** Address or port bind error. */
public static final int BIND_ERR = NETWORK_ERR_GROUP.registerErrorCode((short) 2);
/** File transfer error. */
public static final int FILE_TRANSFER_ERR = NETWORK_ERR_GROUP.registerErrorCode((short) 3);
/** File validation error. */
public static final int FILE_VALIDATION_ERR = NETWORK_ERR_GROUP.registerErrorCode((short) 4);
/** Recipient node has left the physical topology. */
public static final int RECIPIENT_LEFT_ERR = NETWORK_ERR_GROUP.registerErrorCode((short) 5);
/** Could not resolve address. */
public static final int ADDRESS_UNRESOLVED_ERR = NETWORK_ERR_GROUP.registerErrorCode((short) 6);
/** Alias for BIND_ERROR. This was the old name, now deprecated. */
@Deprecated
public static final int PORT_IN_USE_ERR = BIND_ERR;
}
/** Node configuration error group. */
@ErrorCodeGroup
public static class NodeConfiguration {
/** Node configuration error group. */
public static final ErrorGroup NODE_CONFIGURATION_ERR_GROUP = registerGroup("NODECFG", (short) 12);
/** Config read error. */
public static final int CONFIG_READ_ERR = NODE_CONFIGURATION_ERR_GROUP.registerErrorCode((short) 1);
/** Config file creation error. */
public static final int CONFIG_FILE_CREATE_ERR = NODE_CONFIGURATION_ERR_GROUP.registerErrorCode((short) 2);
/** Config write error. */
public static final int CONFIG_WRITE_ERR = NODE_CONFIGURATION_ERR_GROUP.registerErrorCode((short) 3);
/** Config parse error. */
public static final int CONFIG_PARSE_ERR = NODE_CONFIGURATION_ERR_GROUP.registerErrorCode((short) 4);
}
/** Code deployment error group. */
@ErrorCodeGroup
public static class CodeDeployment {
/** Code deployment error group. */
public static final ErrorGroup CODE_DEPLOYMENT_ERR_GROUP = registerGroup("CODEDEPLOY", (short) 13);
/** Access to non-existing deployment unit. */
public static final int UNIT_NOT_FOUND_ERR = CODE_DEPLOYMENT_ERR_GROUP.registerErrorCode((short) 1);
/** Unit duplicate error. */
public static final int UNIT_ALREADY_EXISTS_ERR = CODE_DEPLOYMENT_ERR_GROUP.registerErrorCode((short) 2);
/** Deployment unit content read error. */
public static final int UNIT_CONTENT_READ_ERR = CODE_DEPLOYMENT_ERR_GROUP.registerErrorCode((short) 3);
/** Deployment unit is unavailable for computing. */
public static final int UNIT_UNAVAILABLE_ERR = CODE_DEPLOYMENT_ERR_GROUP.registerErrorCode((short) 4);
/** Deployment unit zip deploy error. */
public static final int UNIT_ZIP_ERR = CODE_DEPLOYMENT_ERR_GROUP.registerErrorCode((short) 5);
/** Deployment unit write to fs error. */
public static final int UNIT_WRITE_ERR = CODE_DEPLOYMENT_ERR_GROUP.registerErrorCode((short) 6);
}
/**
* Garbage collector error group.
*/
@ErrorCodeGroup
public static class GarbageCollector {
/** Garbage collector error group. */
public static final ErrorGroup GC_ERR_GROUP = registerGroup("GC", (short) 14);
/** Garbage collector closed error. */
public static final int CLOSED_ERR = GC_ERR_GROUP.registerErrorCode((short) 1);
}
/**
* Authentication error group.
*/
@ErrorCodeGroup
public static class Authentication {
/** Authentication error group. */
public static final ErrorGroup AUTHENTICATION_ERR_GROUP = registerGroup("AUTHENTICATION", (short) 15);
/** Authentication error caused by unsupported authentication type. */
public static final int UNSUPPORTED_AUTHENTICATION_TYPE_ERR = AUTHENTICATION_ERR_GROUP.registerErrorCode((short) 1);
/** Authentication error caused by invalid credentials. */
public static final int INVALID_CREDENTIALS_ERR = AUTHENTICATION_ERR_GROUP.registerErrorCode((short) 2);
/** Basic authentication provider is not found. */
public static final int BASIC_PROVIDER_ERR = AUTHENTICATION_ERR_GROUP.registerErrorCode((short) 3);
}
/**
* Compute error group.
*/
@ErrorCodeGroup
public static class Compute {
/** Compute error group. */
public static final ErrorGroup COMPUTE_ERR_GROUP = registerGroup("COMPUTE", (short) 16);
/** Classpath error. */
public static final int CLASS_PATH_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 1);
/** Class loader error. */
public static final int CLASS_LOADER_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 2);
/** Job class initialization error. */
public static final int CLASS_INITIALIZATION_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 3);
/** Compute execution queue overflow error. */
public static final int QUEUE_OVERFLOW_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 4);
/** Compute job status transition error. */
public static final int COMPUTE_JOB_STATUS_TRANSITION_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 5);
/** Compute job cancel failed error. */
public static final int CANCELLING_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 6);
/** Compute job result not found error. */
public static final int RESULT_NOT_FOUND_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 7);
/** Compute job state can't be retrieved. */
public static final int FAIL_TO_GET_JOB_STATE_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 8);
/** Compute job failed. */
public static final int COMPUTE_JOB_FAILED_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 9);
/** Cannot resolve primary replica for colocated execution. */
public static final int PRIMARY_REPLICA_RESOLVE_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 10);
/** Cannot change job priority. */
public static final int CHANGE_JOB_PRIORITY_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 11);
/** Specified node is not found in the cluster. */
public static final int NODE_NOT_FOUND_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 12);
/**
* Incompatible types for argument/result in compute job.
* For example, the one has defined a marshaller for Type A in the compute job
* but on the client side they have passed Type B.
*/
public static final int MARSHALLING_TYPE_MISMATCH_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 13);
/** Compute job cancelled. */
public static final int COMPUTE_JOB_CANCELLED_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 14);
/** Platform compute executor error. */
public static final int COMPUTE_PLATFORM_EXECUTOR_ERR = COMPUTE_ERR_GROUP.registerErrorCode((short) 15);
}
/** Catalog error group. */
@ErrorCodeGroup
public static class Catalog {
/** Catalog error group. */
public static final ErrorGroup CATALOG_ERR_GROUP = registerGroup("CATALOG", (short) 17);
/** Command to the catalog has not passed the validation. See exception message for details. */
public static final int VALIDATION_ERR = CATALOG_ERR_GROUP.registerErrorCode((short) 1);
}
/** Placement driver error group. */
@ErrorCodeGroup
public static class PlacementDriver {
/** Placement driver error group. */
public static final ErrorGroup PLACEMENT_DRIVER_ERR_GROUP = registerGroup("PLACEMENTDRIVER", (short) 18);
/** Primary replica await timeout error. */
public static final int PRIMARY_REPLICA_AWAIT_TIMEOUT_ERR = PLACEMENT_DRIVER_ERR_GROUP.registerErrorCode((short) 1);
/** Primary replica await error. */
public static final int PRIMARY_REPLICA_AWAIT_ERR = PLACEMENT_DRIVER_ERR_GROUP.registerErrorCode((short) 2);
/** Error that occurs if there are no assignments for a group. */
public static final int EMPTY_ASSIGNMENTS_ERR = PLACEMENT_DRIVER_ERR_GROUP.registerErrorCode((short) 3);
}
/** Critical workers error group. */
@ErrorCodeGroup
public static class CriticalWorkers {
/** Critical workers error group. */
public static final ErrorGroup CRITICAL_WORKERS_ERR_GROUP = registerGroup("WORKERS", (short) 19);
/** System worker does not update its heartbeat for a long time. */
public static final int SYSTEM_WORKER_BLOCKED_ERR = CRITICAL_WORKERS_ERR_GROUP.registerErrorCode((short) 1);
/** System-critical operation timed out. */
public static final int SYSTEM_CRITICAL_OPERATION_TIMEOUT_ERR = CRITICAL_WORKERS_ERR_GROUP.registerErrorCode((short) 2);
}
/** Disaster recovery error group. */
@ErrorCodeGroup
public static class DisasterRecovery {
/** Disaster recovery group. */
public static final ErrorGroup RECOVERY_ERR_GROUP = registerGroup("RECOVERY", (short) 20);
/** Partition ID is not in valid range. */
public static final int ILLEGAL_PARTITION_ID_ERR = RECOVERY_ERR_GROUP.registerErrorCode((short) 1);
/** Nodes were not found. */
public static final int NODES_NOT_FOUND_ERR = RECOVERY_ERR_GROUP.registerErrorCode((short) 2);
/** Error while returning partition states. */
public static final int PARTITION_STATE_ERR = RECOVERY_ERR_GROUP.registerErrorCode((short) 3);
/** Error while returning partition states. */
public static final int CLUSTER_NOT_IDLE_ERR = RECOVERY_ERR_GROUP.registerErrorCode((short) 4);
/** Error while restarting the cluster with clean up. */
public static final int RESTART_WITH_CLEAN_UP_ERR = RECOVERY_ERR_GROUP.registerErrorCode((short) 5);
}
/** Embedded API error group. */
@ErrorCodeGroup
public static class Embedded {
/** Embedded API group. */
public static final ErrorGroup EMBEDDED_ERR_GROUP = registerGroup("EMBEDDED", (short) 21);
/** Cluster is not yet initialized. */
public static final int CLUSTER_NOT_INITIALIZED_ERR = EMBEDDED_ERR_GROUP.registerErrorCode((short) 1);
/** Cluster initialization failed. */
public static final int CLUSTER_INIT_FAILED_ERR = EMBEDDED_ERR_GROUP.registerErrorCode((short) 2);
/** Node not started. */
public static final int NODE_NOT_STARTED_ERR = EMBEDDED_ERR_GROUP.registerErrorCode((short) 3);
/** Node start failed.. */
public static final int NODE_START_ERR = EMBEDDED_ERR_GROUP.registerErrorCode((short) 4);
}
/** Marshalling error group. */
@ErrorCodeGroup
public static class Marshalling {
/** Marshalling error group. */
public static final ErrorGroup MARSHALLING_ERR_GROUP = registerGroup("MARSHALLING", (short) 22);
/** Marshalling error. */
public static final int COMMON_ERR = MARSHALLING_ERR_GROUP.registerErrorCode((short) 1);
/** Unsupported object type error. */
public static final int UNSUPPORTED_OBJECT_TYPE_ERR = MARSHALLING_ERR_GROUP.registerErrorCode((short) 2);
/** Unmarshalling error. */
public static final int UNMARSHALLING_ERR = MARSHALLING_ERR_GROUP.registerErrorCode((short) 3);
}
/** REST service error group. */
@ErrorCodeGroup
public static class Rest {
/** REST service error group. */
public static final ErrorGroup REST_ERR_GROUP = registerGroup("REST", (short) 23);
/** Cluster has not yet been initialized or the node is in the process of stopping. */
public static final int CLUSTER_NOT_INIT_ERR = REST_ERR_GROUP.registerErrorCode((short) 1);
}
/** Configuration error group. */
@ErrorCodeGroup
public static class CommonConfiguration {
public static final ErrorGroup COMMON_CONF_ERR_GROUP = registerGroup("COMMONCFG", (short) 24);
/** Configuration apply failed. */
public static final int CONFIGURATION_APPLY_ERR = COMMON_CONF_ERR_GROUP.registerErrorCode((short) 1);
/** Configuration parse error. */
public static final int CONFIGURATION_PARSE_ERR = COMMON_CONF_ERR_GROUP.registerErrorCode((short) 2);
/** Configuration validation error. */
public static final int CONFIGURATION_VALIDATION_ERR = COMMON_CONF_ERR_GROUP.registerErrorCode((short) 3);
}
}
|
openjdk/jmc | 34,185 | application/org.openjdk.jmc.flightrecorder.ui/src/main/java/org/openjdk/jmc/flightrecorder/ui/pages/MethodProfilingPage.java | /*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The contents of this file are subject to the terms of either the Universal Permissive License
* v 1.0 as shown at https://oss.oracle.com/licenses/upl
*
* or the following license:
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.openjdk.jmc.flightrecorder.ui.pages;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.stream.Stream;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.ViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.openjdk.jmc.common.IDisplayable;
import org.openjdk.jmc.common.IMCFrame;
import org.openjdk.jmc.common.IMCStackTrace;
import org.openjdk.jmc.common.IState;
import org.openjdk.jmc.common.IWritableState;
import org.openjdk.jmc.common.item.Aggregators;
import org.openjdk.jmc.common.item.Attribute;
import org.openjdk.jmc.common.item.IAttribute;
import org.openjdk.jmc.common.item.IItem;
import org.openjdk.jmc.common.item.IItemCollection;
import org.openjdk.jmc.common.item.IItemFilter;
import org.openjdk.jmc.common.item.IItemIterable;
import org.openjdk.jmc.common.item.IMemberAccessor;
import org.openjdk.jmc.common.item.IType;
import org.openjdk.jmc.common.item.ItemFilters;
import org.openjdk.jmc.common.item.ItemToolkit;
import org.openjdk.jmc.common.unit.ContentType;
import org.openjdk.jmc.common.unit.IQuantity;
import org.openjdk.jmc.common.unit.IRange;
import org.openjdk.jmc.common.unit.UnitLookup;
import org.openjdk.jmc.flightrecorder.JfrAttributes;
import org.openjdk.jmc.flightrecorder.jdk.JdkAttributes;
import org.openjdk.jmc.flightrecorder.jdk.JdkFilters;
import org.openjdk.jmc.flightrecorder.jdk.JdkFilters.MethodFilter;
import org.openjdk.jmc.flightrecorder.jdk.JdkTypeIDs;
import org.openjdk.jmc.flightrecorder.rules.util.JfrRuleTopics;
import org.openjdk.jmc.flightrecorder.stacktrace.FrameSeparator;
import org.openjdk.jmc.flightrecorder.stacktrace.FrameSeparator.FrameCategorization;
import org.openjdk.jmc.flightrecorder.stacktrace.StacktraceFormatToolkit;
import org.openjdk.jmc.flightrecorder.stacktrace.StacktraceFrame;
import org.openjdk.jmc.flightrecorder.stacktrace.StacktraceModel;
import org.openjdk.jmc.flightrecorder.stacktrace.StacktraceModel.Branch;
import org.openjdk.jmc.flightrecorder.stacktrace.StacktraceModel.Fork;
import org.openjdk.jmc.flightrecorder.stacktrace.tree.AggregatableFrame;
import org.openjdk.jmc.flightrecorder.stacktrace.tree.Node;
import org.openjdk.jmc.flightrecorder.stacktrace.tree.StacktraceTreeModel;
import org.openjdk.jmc.flightrecorder.ui.FlightRecorderUI;
import org.openjdk.jmc.flightrecorder.ui.IDataPageFactory;
import org.openjdk.jmc.flightrecorder.ui.IDisplayablePage;
import org.openjdk.jmc.flightrecorder.ui.IPageContainer;
import org.openjdk.jmc.flightrecorder.ui.IPageDefinition;
import org.openjdk.jmc.flightrecorder.ui.IPageUI;
import org.openjdk.jmc.flightrecorder.ui.StreamModel;
import org.openjdk.jmc.flightrecorder.ui.common.AbstractDataPage;
import org.openjdk.jmc.flightrecorder.ui.common.DataPageToolkit;
import org.openjdk.jmc.flightrecorder.ui.common.FilterComponent;
import org.openjdk.jmc.flightrecorder.ui.common.FlavorSelector;
import org.openjdk.jmc.flightrecorder.ui.common.FlavorSelector.FlavorSelectorState;
import org.openjdk.jmc.flightrecorder.ui.common.ImageConstants;
import org.openjdk.jmc.flightrecorder.ui.common.ItemHistogram;
import org.openjdk.jmc.flightrecorder.ui.common.ItemHistogram.ItemHistogramBuilder;
import org.openjdk.jmc.flightrecorder.ui.messages.internal.Messages;
import org.openjdk.jmc.flightrecorder.ui.pages.internal.MethodWithFrameType;
import org.openjdk.jmc.flightrecorder.ui.pages.internal.MethodWithFrameTypeLabelProvider;
import org.openjdk.jmc.flightrecorder.ui.selection.SelectionStoreActionToolkit;
import org.openjdk.jmc.ui.column.ColumnManager.SelectionState;
import org.openjdk.jmc.ui.column.ColumnMenusFactory;
import org.openjdk.jmc.ui.column.TableSettings;
import org.openjdk.jmc.ui.column.TableSettings.ColumnSettings;
import org.openjdk.jmc.ui.handlers.MCContextMenuManager;
import org.openjdk.jmc.ui.handlers.MethodFormatter;
import org.openjdk.jmc.ui.misc.AbstractStructuredContentProvider;
import org.openjdk.jmc.ui.misc.DisplayToolkit;
import org.openjdk.jmc.ui.misc.PersistableSashForm;
import org.openjdk.jmc.ui.misc.SWTColorToolkit;
public class MethodProfilingPage extends AbstractDataPage {
private static final Color ALTERNATE_COLOR = SWTColorToolkit.getColor(new RGB(255, 255, 240));
private static final String COUNT_IMG_KEY = "countColor"; //$NON-NLS-1$
private static final String SIBLINGS_IMG_KEY = "siblingsColor"; //$NON-NLS-1$
private static final String PERCENTAGE_COL_ID = "HotMethods.Percentage"; //$NON-NLS-1$
private static final Color SIBLINGS_COUNT_COLOR = SWTColorToolkit.getColor(new RGB(170, 250, 170));
private static final Color COUNT_COLOR = SWTColorToolkit.getColor(new RGB(100, 200, 100));
// Same as STACK_TRACE_TOP_METHOD but includes information about the frame type for the sample (and will distinguish methods on this)
private static final IAttribute<MethodWithFrameType> STACK_TRACE_TOP_METHOD_WITH_FRAME_TYPE = new Attribute<MethodWithFrameType>(
"(stackTrace).topMethodOptimization", Messages.MethodProfilingPage_METHOD_TITLE, //$NON-NLS-1$
Messages.MethodProfilingPage_METHOD_DESCRIPTION, new ContentType<MethodWithFrameType>("methodwithframetype", //$NON-NLS-1$
Messages.MethodProfilingPage_METHOD_CONTENT_TYPE_DESCRIPTION)) {
@Override
public <U> IMemberAccessor<MethodWithFrameType, U> customAccessor(IType<U> type) {
final IMemberAccessor<IMCFrame, U> accessor = JdkAttributes.STACK_TRACE_TOP_FRAME.getAccessor(type);
return accessor == null ? null : new IMemberAccessor<MethodWithFrameType, U>() {
@Override
public MethodWithFrameType getMember(U i) {
IMCFrame frame = accessor.getMember(i);
return frame == null ? null : new MethodWithFrameType(frame.getMethod(), frame.getType());
}
};
}
};
private static final Listener PERCENTAGE_BACKGROUND_DRAWER = new Listener() {
@Override
public void handleEvent(Event event) {
StacktraceFrame frame = (StacktraceFrame) event.item.getData();
Fork rootFork = getRootFork(frame.getBranch().getParentFork());
double total;
if (event.index == 2 && (total = rootFork.getItemsInFork()) > 0) { // index == 2 => percentage column
// Draw siblings
Fork parentFork = frame.getBranch().getParentFork();
long forkOffset = parentFork.getItemOffset();
int siblingsStart = (int) Math.floor(event.width * forkOffset / total);
int siblingsWidth = (int) Math.round(event.width * parentFork.getItemsInFork() / total);
event.gc.setBackground(SIBLINGS_COUNT_COLOR);
event.gc.fillRectangle(event.x + siblingsStart, event.y, siblingsWidth, event.height);
// Draw group
double offset = (forkOffset + frame.getBranch().getItemOffsetInFork()) / total;
double fraction = frame.getItemCount() / total;
event.gc.setBackground(COUNT_COLOR);
int startPixel = (int) Math.floor(event.width * offset);
int widthPixel = (int) Math.round(event.width * fraction);
event.gc.fillRectangle(event.x + startPixel, event.y, Math.max(widthPixel, 1), event.height);
event.detail &= ~SWT.BACKGROUND;
}
}
};
private static final Listener SUCCESSOR_PERCENTAGE_BACKGROUND_DRAWER = new Listener() {
@Override
public void handleEvent(Event event) {
SuccessorNode node = (SuccessorNode) event.item.getData();
double total;
if (event.index == 2 && (total = node.model.root.count) > 0) { // index == 2 => percentage column
// Draw siblings
int siblingsStart = 0;
int siblingsWidth = (int) Math.round(event.width * node.count / total);
event.gc.setBackground(SIBLINGS_COUNT_COLOR);
event.gc.fillRectangle(event.x + siblingsStart, event.y, siblingsWidth, event.height);
// Draw group
double fraction = node.count / total;
event.gc.setBackground(COUNT_COLOR);
int startPixel = 0;
int widthPixel = (int) Math.round(event.width * fraction);
event.gc.fillRectangle(event.x + startPixel, event.y, Math.max(widthPixel, 1), event.height);
event.detail &= ~SWT.BACKGROUND;
}
}
};
public static class MethodProfilingPageFactory implements IDataPageFactory {
@Override
public String getName(IState state) {
return Messages.MethodProfilingPage_PAGE_NAME;
}
@Override
public ImageDescriptor getImageDescriptor(IState state) {
return FlightRecorderUI.getDefault().getMCImageDescriptor(ImageConstants.PAGE_METHOD);
}
@Override
public String[] getTopics(IState state) {
return new String[] {JfrRuleTopics.METHOD_PROFILING};
}
@Override
public IDisplayablePage createPage(IPageDefinition dpd, StreamModel items, IPageContainer editor) {
return new MethodProfilingPage(dpd, items, editor);
}
}
private static final IItemFilter TABLE_ITEMS = ItemFilters.type(JdkTypeIDs.EXECUTION_SAMPLE);
private static final ItemHistogramBuilder HOT_METHODS_HISTOGRAM = new ItemHistogramBuilder();
static {
HOT_METHODS_HISTOGRAM.addCountColumn();
HOT_METHODS_HISTOGRAM.addPercentageColumn(PERCENTAGE_COL_ID, Aggregators.count(), "Percentage",
"Sample percentage over total");
}
private class MethodProfilingUi implements IPageUI {
private static final String METHOD_TABLE = "methodTable"; //$NON-NLS-1$
private static final String SASH_ELEMENT = "sash"; //$NON-NLS-1$
private static final String TABLE_ELEMENT = "table"; //$NON-NLS-1$
private static final String METHOD_FORMAT_KEY = "metodFormat"; //$NON-NLS-1$
private final ItemHistogram table;
private final TreeViewer successorTree;
private final TreeViewer predecessorTree;
private final SashForm sash;
private FilterComponent tableFilter;
private FlavorSelector flavorSelector;
private MethodFormatter methodFormatter;
private int[] columnWidths = {650, 80, 120};
MethodProfilingUi(Composite parent, FormToolkit toolkit, IPageContainer pageContainer, IState state) {
Form form = DataPageToolkit.createForm(parent, toolkit, getName(), getIcon());
sash = new SashForm(form.getBody(), SWT.VERTICAL);
toolkit.adapt(sash);
table = HOT_METHODS_HISTOGRAM.buildWithoutBorder(sash, STACK_TRACE_TOP_METHOD_WITH_FRAME_TYPE,
getTableSettings(state.getChild(TABLE_ELEMENT)), new MethodWithFrameTypeLabelProvider());
MCContextMenuManager mm = MCContextMenuManager.create(table.getManager().getViewer().getControl());
ColumnMenusFactory.addDefaultMenus(table.getManager(), mm);
SelectionStoreActionToolkit.addSelectionStoreActions(pageContainer.getSelectionStore(), table,
Messages.FileIOPage_HISTOGRAM_SELECTION, mm);
table.getManager().getViewer().addSelectionChangedListener(e -> updateDetails(e));
table.getManager().getViewer()
.addSelectionChangedListener(e -> pageContainer.showSelection(table.getSelection().getItems()));
tableFilter = FilterComponent.createFilterComponent(table, MethodProfilingPage.this.tableFilter,
getDataSource().getItems().apply(TABLE_ITEMS), pageContainer.getSelectionStore()::getSelections,
this::onTableFilterChange);
mm.add(tableFilter.getShowFilterAction());
mm.add(tableFilter.getShowSearchAction());
tableFilter.loadState(state.getChild(METHOD_TABLE));
methodFormatter = new MethodFormatter(state.getChild(METHOD_FORMAT_KEY), this::refreshTrees);
CTabFolder tabFolder = new CTabFolder(sash, SWT.NONE);
toolkit.adapt(tabFolder);
CTabItem t1 = new CTabItem(tabFolder, SWT.NONE);
t1.setToolTipText(Messages.MethodProfilingPage_PREDECESSORS_DESCRIPTION);
predecessorTree = buildTree(tabFolder, new StacktraceReducedTreeContentProvider());
t1.setText(Messages.PAGES_PREDECESSORS);
t1.setControl(predecessorTree.getControl());
predecessorTree.getControl().addListener(SWT.EraseItem, PERCENTAGE_BACKGROUND_DRAWER);
buildColumn(predecessorTree, Messages.STACKTRACE_VIEW_STACK_TRACE, SWT.NONE, columnWidths[0])
.setLabelProvider(new StackTraceLabelProvider(methodFormatter));
buildColumn(predecessorTree, Messages.STACKTRACE_VIEW_COUNT_COLUMN_NAME, SWT.RIGHT, columnWidths[1])
.setLabelProvider(new CountLabelProvider());
buildColumn(predecessorTree, Messages.STACKTRACE_VIEW_PERCENTAGE_COLUMN_NAME, SWT.RIGHT, columnWidths[2])
.setLabelProvider(new PercentageLabelProvider());
MCContextMenuManager predTreeMenu = MCContextMenuManager.create(predecessorTree.getControl());
predTreeMenu.appendToGroup(MCContextMenuManager.GROUP_VIEWER_SETUP, methodFormatter.createMenu());
CTabItem t2 = new CTabItem(tabFolder, SWT.NONE);
t2.setToolTipText(Messages.MethodProfilingPage_SUCCESSORS_DESCRIPTION);
successorTree = buildTree(tabFolder, new StacktraceTreeContentProvider());
t2.setText(Messages.PAGES_SUCCESSORS);
t2.setControl(successorTree.getControl());
successorTree.getControl().addListener(SWT.EraseItem, SUCCESSOR_PERCENTAGE_BACKGROUND_DRAWER);
successorTree.getControl().addDisposeListener(e -> columnWidths = getColumnWidths(successorTree));
buildColumn(successorTree, Messages.STACKTRACE_VIEW_STACK_TRACE, SWT.NONE, columnWidths[0])
.setLabelProvider(new StackTraceTreeLabelProvider(methodFormatter));
buildColumn(successorTree, Messages.STACKTRACE_VIEW_COUNT_COLUMN_NAME, SWT.RIGHT, columnWidths[1])
.setLabelProvider(new CountTreeLabelProvider());
buildColumn(successorTree, Messages.STACKTRACE_VIEW_PERCENTAGE_COLUMN_NAME, SWT.RIGHT, columnWidths[2])
.setLabelProvider(new PercentageTreeLabelProvider());
MCContextMenuManager succTreeMenu = MCContextMenuManager.create(successorTree.getControl());
succTreeMenu.appendToGroup(MCContextMenuManager.GROUP_VIEWER_SETUP, methodFormatter.createMenu());
tabFolder.setSelection(t1);
PersistableSashForm.loadState(sash, state.getChild(SASH_ELEMENT));
flavorSelector = FlavorSelector.itemsWithTimerange(form, TABLE_ITEMS, getDataSource().getItems(),
pageContainer, this::onInputSelected, flavorSelectorState);
table.getManager().setSelectionState(tableSelection);
addResultActions(form);
}
private void refreshTrees() {
predecessorTree.refresh();
successorTree.refresh();
}
private TreeViewer buildTree(Composite parent, IContentProvider contentProvider) {
TreeViewer treeViewer = new TreeViewer(parent,
SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.BORDER);
treeViewer.setContentProvider(contentProvider);
treeViewer.getTree().setHeaderVisible(true);
treeViewer.getTree().setLinesVisible(true);
return treeViewer;
}
private int[] getColumnWidths(TreeViewer viewer) {
if (!viewer.getControl().isDisposed()) {
return Stream.of(viewer.getTree().getColumns()).mapToInt(TreeColumn::getWidth).toArray();
}
return columnWidths;
}
private ViewerColumn buildColumn(TreeViewer viewer, String text, int style, int width) {
TreeViewerColumn vc = new TreeViewerColumn(viewer, style);
vc.getColumn().setWidth(width);
vc.getColumn().setText(text);
return vc;
}
private void onTableFilterChange(IItemFilter filter) {
tableFilter.filterChangeHelper(filter, table, getDataSource().getItems().apply(TABLE_ITEMS));
MethodProfilingPage.this.tableFilter = filter;
}
@Override
public void saveTo(IWritableState writableState) {
PersistableSashForm.saveState(sash, writableState.createChild(SASH_ELEMENT));
methodFormatter.saveState(writableState.createChild(METHOD_FORMAT_KEY));
saveToLocal();
}
private void saveToLocal() {
tableSelection = table.getManager().getSelectionState();
flavorSelectorState = flavorSelector.getFlavorSelectorState();
}
private void updateDetails(SelectionChangedEvent event) {
IItemCollection items = table.getSelection().getItems();
// Release old model before building the new
predecessorTree.setInput(null);
successorTree.setInput(null);
buildPredecessorTree(items);
buildSuccessorTree(items);
}
private void buildPredecessorTree(IItemCollection items) {
FrameSeparator frameSeparator = new FrameSeparator(FrameCategorization.METHOD, false);
StacktraceModel stacktraceModel = new StacktraceModel(false, frameSeparator, items);
CompletableFuture<StacktraceModel> modelPreparer = getModelPreparer(stacktraceModel, false);
modelPreparer.thenAcceptAsync(this::setModelPredecessor, DisplayToolkit.inDisplayThread())
.exceptionally(MethodProfilingPage::handleModelBuilException);
}
private void setModelPredecessor(StacktraceModel model) {
if (!predecessorTree.getControl().isDisposed()) {
predecessorTree.setInput(model.getRootFork());
}
}
private void buildSuccessorTree(IItemCollection items) {
CompletableFuture<SuccessorTreeModel> modelPreparer = getSuccessorModelPreparer(items);
modelPreparer.thenAcceptAsync(this::setModelSuccessor, DisplayToolkit.inDisplayThread())
.exceptionally(MethodProfilingPage::handleModelBuilException);
}
private void mergeNode(SuccessorTreeModel model, SuccessorNode destNode, Node srcNode) {
destNode.count += (int) srcNode.getCumulativeWeight();
for (Node child : srcNode.getChildren()) {
String key = SuccessorTreeModel.makeKey(child.getFrame());
SuccessorNode existing = destNode.children.putIfAbsent(key, new SuccessorNode(model, destNode, child));
if (existing != null) {
mergeNode(model, existing, child);
}
}
}
private void traverse(Node current, String typeName, String methodName, SuccessorTreeModel model) {
if (methodName.equals(current.getFrame().getMethod().getMethodName())
&& typeName.equals(current.getFrame().getMethod().getType().getFullName())) {
if (model.root == null) {
model.root = new SuccessorNode(model, null, current);
}
mergeNode(model, model.root, current);
}
for (Node child : current.getChildren()) {
traverse(child, typeName, methodName, model);
}
}
private void setModelSuccessor(SuccessorTreeModel model) {
if (model == null) {
return;
}
if (!successorTree.getControl().isDisposed()) {
successorTree.setInput(model);
}
}
private CompletableFuture<StacktraceModel> getModelPreparer(
StacktraceModel model, boolean materializeSelectedBranches) {
return CompletableFuture.supplyAsync(() -> {
Fork root = model.getRootFork();
if (materializeSelectedBranches) {
Branch selectedBranch = getLastSelectedBranch(root);
if (selectedBranch != null) {
selectedBranch.getEndFork();
}
}
return model;
});
}
private CompletableFuture<SuccessorTreeModel> getSuccessorModelPreparer(IItemCollection items) {
return CompletableFuture.supplyAsync(() -> {
IItem execSample = null;
if (items.hasItems()) {
IItemIterable itemIterable = items.iterator().next();
if (itemIterable.hasItems()) {
execSample = itemIterable.iterator().next();
}
}
if (execSample == null) {
return null;
}
@SuppressWarnings("deprecation")
IMemberAccessor<IMCStackTrace, IItem> accessor = ItemToolkit.accessor(JfrAttributes.EVENT_STACKTRACE);
IMCStackTrace stackTrace = accessor.getMember(execSample);
String methodName = null;
String typeName = null;
if (stackTrace != null) {
if (!stackTrace.getFrames().isEmpty()) {
IMCFrame topFrame = stackTrace.getFrames().get(0);
methodName = topFrame.getMethod().getMethodName();
typeName = topFrame.getMethod().getType().getFullName();
}
}
if (methodName == null || typeName == null) {
return null;
}
MethodFilter methodFilter = new JdkFilters.MethodFilter(typeName, methodName);
// Filters event containing the current method
IItemCollection methodEvents = getDataSource().getItems()
.apply(ItemFilters.and(TABLE_ITEMS, methodFilter));
StacktraceTreeModel stacktraceTreeModel = new StacktraceTreeModel(methodEvents);
SuccessorTreeModel model = new SuccessorTreeModel();
traverse(stacktraceTreeModel.getRoot(), typeName, methodName, model);
return model;
});
}
// See JMC-6787
@SuppressWarnings("deprecation")
private Branch getLastSelectedBranch(Fork fromFork) {
Branch lastSelectedBranch = null;
Branch branch = fromFork.getSelectedBranch();
while (branch != null) {
lastSelectedBranch = branch;
branch = branch.getEndFork().getSelectedBranch();
}
return lastSelectedBranch;
}
private void onInputSelected(IItemCollection items, IRange<IQuantity> timeRange) {
}
}
private static TableSettings getTableSettings(IState state) {
if (state == null) {
return new TableSettings(ItemHistogram.COUNT_COL_ID,
Arrays.asList(new ColumnSettings(ItemHistogram.KEY_COL_ID, false, 500, null),
new ColumnSettings(ItemHistogram.COUNT_COL_ID, false, 120, false),
new ColumnSettings(PERCENTAGE_COL_ID, false, 120, false)));
} else {
return new TableSettings(state);
}
}
private static Void handleModelBuilException(Throwable ex) {
FlightRecorderUI.getDefault().getLogger().log(Level.SEVERE, "Failed to build stacktrace view model", ex); //$NON-NLS-1$
return null;
}
private static boolean isFirstInBranchWithSiblings(StacktraceFrame frame) {
return frame.getBranch().getFirstFrame() == frame && frame.getBranch().getParentFork().getBranchCount() > 1;
}
private static boolean isLastFrame(StacktraceFrame frame) {
return frame.getBranch().getLastFrame() == frame && frame.getBranch().getEndFork().getBranchCount() == 0;
}
@Override
public IPageUI display(Composite parent, FormToolkit toolkit, IPageContainer pageContainer, IState state) {
return new MethodProfilingUi(parent, toolkit, pageContainer, state);
}
private IItemFilter tableFilter = null;
private SelectionState tableSelection;
public FlavorSelectorState flavorSelectorState;
public MethodProfilingPage(IPageDefinition dpd, StreamModel items, IPageContainer editor) {
super(dpd, items, editor);
}
@Override
public IItemFilter getDefaultSelectionFilter() {
return TABLE_ITEMS;
}
private static Fork getRootFork(Fork fork) {
while (fork.getParentBranch() != null) {
fork = fork.getParentBranch().getParentFork();
}
return fork;
}
private static class StackTraceLabelProvider extends ColumnLabelProvider {
FrameSeparator frameSeparator;
MethodFormatter methodFormatter;
public StackTraceLabelProvider(MethodFormatter methodFormatter) {
frameSeparator = new FrameSeparator(FrameCategorization.METHOD, false);
this.methodFormatter = methodFormatter;
}
@Override
public String getText(Object element) {
IMCFrame frame = ((StacktraceFrame) element).getFrame();
return getText(frame, frameSeparator);
}
protected String getText(IMCFrame frame, FrameSeparator frameSeparator) {
return StacktraceFormatToolkit.formatFrame(frame, frameSeparator, methodFormatter.showReturnValue(),
methodFormatter.showReturnValuePackage(), methodFormatter.showClassName(),
methodFormatter.showClassPackageName(), methodFormatter.showArguments(),
methodFormatter.showArgumentsPackage());
}
@Override
public Image getImage(Object element) {
StacktraceFrame frame = (StacktraceFrame) element;
FlightRecorderUI plugin = FlightRecorderUI.getDefault();
boolean isFirstInBranch = isFirstInBranchWithSiblings(frame);
if (isFirstInBranch) {
return plugin.getImage(ImageConstants.ICON_ARROW_CURVED_UP);
} else if (isLastFrame(frame)) {
return plugin.getImage(ImageConstants.ICON_ARROW_UP_END);
} else {
return plugin.getImage(ImageConstants.ICON_ARROW_UP);
}
}
@Override
public Color getBackground(Object element) {
int parentCount = 0;
Branch e = ((StacktraceFrame) element).getBranch();
while (e != null) {
e = e.getParentFork().getParentBranch();
parentCount++;
}
return parentCount % 2 == 0 ? null : ALTERNATE_COLOR;
}
}
private static class StackTraceTreeLabelProvider extends StackTraceLabelProvider {
public StackTraceTreeLabelProvider(MethodFormatter methodFormatter) {
super(methodFormatter);
}
@Override
public String getText(Object element) {
IMCFrame frame = ((SuccessorNode) element).frame;
return getText(frame, frameSeparator);
}
@Override
public Image getImage(Object element) {
FlightRecorderUI plugin = FlightRecorderUI.getDefault();
SuccessorNode node = (SuccessorNode) element;
if (isFirstInBranchWithSiblings(node)) {
return plugin.getImage(ImageConstants.ICON_ARROW_CURVED_UP);
} else if (isLastFrame(node)) {
return plugin.getImage(ImageConstants.ICON_ARROW_UP_END);
} else {
return plugin.getImage(ImageConstants.ICON_ARROW_UP);
}
}
private boolean isFirstInBranchWithSiblings(SuccessorNode node) {
SuccessorNode parent = node.parent;
if (parent == null) {
return false;
}
if (node.children.isEmpty()) {
return false;
}
return true;
}
private boolean isLastFrame(SuccessorNode node) {
SuccessorNode parent = node.parent;
if (parent == null) {
return false;
}
SuccessorNode[] children = parent.children.values().toArray(new SuccessorNode[0]);
if (children.length == 0) {
return false;
}
return children[children.length - 1] == node;
}
@Override
public Color getBackground(Object element) {
int parentCount = 0;
SuccessorNode current = ((SuccessorNode) element).parent;
while (current != null) {
current = current.parent;
parentCount++;
}
return parentCount % 2 == 0 ? null : ALTERNATE_COLOR;
}
}
private static class CountLabelProvider extends ColumnLabelProvider {
@Override
public String getText(Object element) {
return Integer.toString(((StacktraceFrame) element).getItemCount());
}
}
private static class CountTreeLabelProvider extends ColumnLabelProvider {
@Override
public String getText(Object element) {
return Integer.toString((int) ((SuccessorNode) element).count);
}
}
private static class PercentageLabelProvider extends ColumnLabelProvider {
@Override
public String getText(Object element) {
StacktraceFrame frame = (StacktraceFrame) element;
int itemCount = frame.getItemCount();
int totalCount = getRootFork(frame.getBranch().getParentFork()).getItemsInFork();
return UnitLookup.PERCENT_UNITY.quantity(itemCount / (double) totalCount).displayUsing(IDisplayable.AUTO);
}
@Override
public String getToolTipText(Object element) {
StacktraceFrame frame = (StacktraceFrame) element;
Fork rootFork = getRootFork(frame.getBranch().getParentFork());
int itemCount = frame.getItemCount();
int totalCount = rootFork.getItemsInFork();
Fork parentFork = frame.getBranch().getParentFork();
int itemsInSiblings = parentFork.getItemsInFork() - frame.getBranch().getFirstFrame().getItemCount();
String frameFraction = UnitLookup.PERCENT_UNITY.quantity(itemCount / (double) totalCount)
.displayUsing(IDisplayable.AUTO);
StringBuilder sb = new StringBuilder("<form>"); //$NON-NLS-1$
sb.append("<li style='image' value='" + COUNT_IMG_KEY + "'><span nowrap='true'>"); //$NON-NLS-1$ //$NON-NLS-2$
sb.append(Messages.stackTraceMessage(itemCount, totalCount, frameFraction));
sb.append("</span></li>"); //$NON-NLS-1$
sb.append("<li style='image' value='" + SIBLINGS_IMG_KEY + "'><span nowrap='true'>"); //$NON-NLS-1$ //$NON-NLS-2$
sb.append(Messages.siblingMessage(itemsInSiblings, parentFork.getBranchCount() - 1));
sb.append("</span></li>"); //$NON-NLS-1$
sb.append("</form>"); //$NON-NLS-1$
return sb.toString();
}
}
private static class PercentageTreeLabelProvider extends ColumnLabelProvider {
@Override
public String getText(Object element) {
SuccessorNode node = (SuccessorNode) element;
int itemCount = node.count;
int totalCount = node.model.root.count;
return UnitLookup.PERCENT_UNITY.quantity(itemCount / (double) totalCount).displayUsing(IDisplayable.AUTO);
}
@Override
public String getToolTipText(Object element) {
SuccessorNode node = (SuccessorNode) element;
int itemCount = node.count;
int totalCount = node.model.root.count;
String frameFraction = UnitLookup.PERCENT_UNITY.quantity(itemCount / (double) totalCount)
.displayUsing(IDisplayable.AUTO);
StringBuilder sb = new StringBuilder("<form>"); //$NON-NLS-1$
sb.append("<li style='image' value='" + COUNT_IMG_KEY + "'><span nowrap='true'>"); //$NON-NLS-1$ //$NON-NLS-2$
sb.append(Messages.stackTraceMessage(itemCount, totalCount, frameFraction));
sb.append("</span></li>"); //$NON-NLS-1$
sb.append("</form>"); //$NON-NLS-1$
return sb.toString();
}
}
private static class StacktraceReducedTreeContentProvider extends AbstractStructuredContentProvider
implements ITreeContentProvider {
@Override
public StacktraceFrame[] getElements(Object inputElement) {
Fork rootFork = (Fork) inputElement;
if (rootFork.getBranchCount() == 1) {
Branch branch = rootFork.getBranch(0);
return Stream
.concat(Stream.concat(Stream.of(branch.getFirstFrame()), Stream.of(branch.getTailFrames())),
Stream.of(branch.getEndFork().getFirstFrames()))
.toArray(StacktraceFrame[]::new);
} else {
return rootFork.getFirstFrames();
}
}
@Override
public boolean hasChildren(Object element) {
StacktraceFrame frame = (StacktraceFrame) element;
return isFirstInBranchWithSiblings(frame) && frame.getBranch().hasTail();
}
@Override
public StacktraceFrame[] getChildren(Object parentElement) {
Stream<StacktraceFrame> children = Stream.empty();
StacktraceFrame frame = (StacktraceFrame) parentElement;
if (isFirstInBranchWithSiblings(frame)) {
children = Stream.concat(Stream.of(frame.getBranch().getTailFrames()),
Stream.of(frame.getBranch().getEndFork().getFirstFrames()));
}
return children.toArray(StacktraceFrame[]::new);
}
@Override
public StacktraceFrame getParent(Object element) {
StacktraceFrame frame = (StacktraceFrame) element;
if (isFirstInBranchWithSiblings(frame) || frame.getBranch().getParentFork().getBranchCount() == 1) {
Branch parentBranch = frame.getBranch().getParentFork().getParentBranch();
return parentBranch == null ? null : parentBranch.getFirstFrame();
} else {
return frame.getBranch().getFirstFrame();
}
}
}
private static class StacktraceTreeContentProvider extends AbstractStructuredContentProvider
implements ITreeContentProvider {
@Override
public SuccessorNode[] getElements(Object inputElement) {
if (inputElement instanceof SuccessorTreeModel) {
return new SuccessorNode[] {((SuccessorTreeModel) inputElement).root};
}
return new SuccessorNode[] {(SuccessorNode) inputElement};
}
@Override
public SuccessorNode[] getChildren(Object inputElement) {
return ((SuccessorNode) inputElement).children.values().toArray(new SuccessorNode[0]);
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public boolean hasChildren(Object element) {
return !((SuccessorNode) element).children.isEmpty();
}
}
private static class SuccessorTreeModel {
SuccessorNode root;
public static String makeKey(IMCFrame frame) {
return frame.getMethod().getType().getFullName() + "::" + frame.getMethod().getMethodName();
}
}
private static class SuccessorNode {
final SuccessorTreeModel model;
final SuccessorNode parent;
final AggregatableFrame frame;
final Map<String, SuccessorNode> children = new HashMap<>();
int count;
SuccessorNode(SuccessorTreeModel model, SuccessorNode parent, Node node) {
this.model = model;
this.parent = parent;
this.frame = node.getFrame();
this.count = (int) node.getCumulativeWeight();
}
}
}
|
googleapis/google-cloud-java | 35,691 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/BatchMigrateResourcesResponse.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/migration_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Response message for
* [MigrationService.BatchMigrateResources][google.cloud.aiplatform.v1beta1.MigrationService.BatchMigrateResources].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse}
*/
public final class BatchMigrateResourcesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse)
BatchMigrateResourcesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use BatchMigrateResourcesResponse.newBuilder() to construct.
private BatchMigrateResourcesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private BatchMigrateResourcesResponse() {
migrateResourceResponses_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new BatchMigrateResourcesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.MigrationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_BatchMigrateResourcesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.MigrationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_BatchMigrateResourcesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse.class,
com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse.Builder.class);
}
public static final int MIGRATE_RESOURCE_RESPONSES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse>
migrateResourceResponses_;
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse>
getMigrateResourceResponsesList() {
return migrateResourceResponses_;
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
@java.lang.Override
public java.util.List<
? extends com.google.cloud.aiplatform.v1beta1.MigrateResourceResponseOrBuilder>
getMigrateResourceResponsesOrBuilderList() {
return migrateResourceResponses_;
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
@java.lang.Override
public int getMigrateResourceResponsesCount() {
return migrateResourceResponses_.size();
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse getMigrateResourceResponses(
int index) {
return migrateResourceResponses_.get(index);
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.MigrateResourceResponseOrBuilder
getMigrateResourceResponsesOrBuilder(int index) {
return migrateResourceResponses_.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 < migrateResourceResponses_.size(); i++) {
output.writeMessage(1, migrateResourceResponses_.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 < migrateResourceResponses_.size(); i++) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(
1, migrateResourceResponses_.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.BatchMigrateResourcesResponse)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse other =
(com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse) obj;
if (!getMigrateResourceResponsesList().equals(other.getMigrateResourceResponsesList()))
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 (getMigrateResourceResponsesCount() > 0) {
hash = (37 * hash) + MIGRATE_RESOURCE_RESPONSES_FIELD_NUMBER;
hash = (53 * hash) + getMigrateResourceResponsesList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse 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.BatchMigrateResourcesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse 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.BatchMigrateResourcesResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse 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.BatchMigrateResourcesResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse 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.BatchMigrateResourcesResponse
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse
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.BatchMigrateResourcesResponse 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.BatchMigrateResourcesResponse 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.BatchMigrateResourcesResponse 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
* [MigrationService.BatchMigrateResources][google.cloud.aiplatform.v1beta1.MigrationService.BatchMigrateResources].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse)
com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.MigrationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_BatchMigrateResourcesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.MigrationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_BatchMigrateResourcesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse.class,
com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse.Builder.class);
}
// Construct using
// com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (migrateResourceResponsesBuilder_ == null) {
migrateResourceResponses_ = java.util.Collections.emptyList();
} else {
migrateResourceResponses_ = null;
migrateResourceResponsesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.aiplatform.v1beta1.MigrationServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_BatchMigrateResourcesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse build() {
com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse buildPartial() {
com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse result =
new com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse result) {
if (migrateResourceResponsesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
migrateResourceResponses_ =
java.util.Collections.unmodifiableList(migrateResourceResponses_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.migrateResourceResponses_ = migrateResourceResponses_;
} else {
result.migrateResourceResponses_ = migrateResourceResponsesBuilder_.build();
}
}
private void buildPartial0(
com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse 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.BatchMigrateResourcesResponse) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse other) {
if (other
== com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse.getDefaultInstance())
return this;
if (migrateResourceResponsesBuilder_ == null) {
if (!other.migrateResourceResponses_.isEmpty()) {
if (migrateResourceResponses_.isEmpty()) {
migrateResourceResponses_ = other.migrateResourceResponses_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureMigrateResourceResponsesIsMutable();
migrateResourceResponses_.addAll(other.migrateResourceResponses_);
}
onChanged();
}
} else {
if (!other.migrateResourceResponses_.isEmpty()) {
if (migrateResourceResponsesBuilder_.isEmpty()) {
migrateResourceResponsesBuilder_.dispose();
migrateResourceResponsesBuilder_ = null;
migrateResourceResponses_ = other.migrateResourceResponses_;
bitField0_ = (bitField0_ & ~0x00000001);
migrateResourceResponsesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getMigrateResourceResponsesFieldBuilder()
: null;
} else {
migrateResourceResponsesBuilder_.addAllMessages(other.migrateResourceResponses_);
}
}
}
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.MigrateResourceResponse m =
input.readMessage(
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.parser(),
extensionRegistry);
if (migrateResourceResponsesBuilder_ == null) {
ensureMigrateResourceResponsesIsMutable();
migrateResourceResponses_.add(m);
} else {
migrateResourceResponsesBuilder_.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.MigrateResourceResponse>
migrateResourceResponses_ = java.util.Collections.emptyList();
private void ensureMigrateResourceResponsesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
migrateResourceResponses_ =
new java.util.ArrayList<com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse>(
migrateResourceResponses_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse,
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.Builder,
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponseOrBuilder>
migrateResourceResponsesBuilder_;
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse>
getMigrateResourceResponsesList() {
if (migrateResourceResponsesBuilder_ == null) {
return java.util.Collections.unmodifiableList(migrateResourceResponses_);
} else {
return migrateResourceResponsesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public int getMigrateResourceResponsesCount() {
if (migrateResourceResponsesBuilder_ == null) {
return migrateResourceResponses_.size();
} else {
return migrateResourceResponsesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse getMigrateResourceResponses(
int index) {
if (migrateResourceResponsesBuilder_ == null) {
return migrateResourceResponses_.get(index);
} else {
return migrateResourceResponsesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public Builder setMigrateResourceResponses(
int index, com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse value) {
if (migrateResourceResponsesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMigrateResourceResponsesIsMutable();
migrateResourceResponses_.set(index, value);
onChanged();
} else {
migrateResourceResponsesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public Builder setMigrateResourceResponses(
int index,
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.Builder builderForValue) {
if (migrateResourceResponsesBuilder_ == null) {
ensureMigrateResourceResponsesIsMutable();
migrateResourceResponses_.set(index, builderForValue.build());
onChanged();
} else {
migrateResourceResponsesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public Builder addMigrateResourceResponses(
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse value) {
if (migrateResourceResponsesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMigrateResourceResponsesIsMutable();
migrateResourceResponses_.add(value);
onChanged();
} else {
migrateResourceResponsesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public Builder addMigrateResourceResponses(
int index, com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse value) {
if (migrateResourceResponsesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureMigrateResourceResponsesIsMutable();
migrateResourceResponses_.add(index, value);
onChanged();
} else {
migrateResourceResponsesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public Builder addMigrateResourceResponses(
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.Builder builderForValue) {
if (migrateResourceResponsesBuilder_ == null) {
ensureMigrateResourceResponsesIsMutable();
migrateResourceResponses_.add(builderForValue.build());
onChanged();
} else {
migrateResourceResponsesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public Builder addMigrateResourceResponses(
int index,
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.Builder builderForValue) {
if (migrateResourceResponsesBuilder_ == null) {
ensureMigrateResourceResponsesIsMutable();
migrateResourceResponses_.add(index, builderForValue.build());
onChanged();
} else {
migrateResourceResponsesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public Builder addAllMigrateResourceResponses(
java.lang.Iterable<? extends com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse>
values) {
if (migrateResourceResponsesBuilder_ == null) {
ensureMigrateResourceResponsesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, migrateResourceResponses_);
onChanged();
} else {
migrateResourceResponsesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public Builder clearMigrateResourceResponses() {
if (migrateResourceResponsesBuilder_ == null) {
migrateResourceResponses_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
migrateResourceResponsesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public Builder removeMigrateResourceResponses(int index) {
if (migrateResourceResponsesBuilder_ == null) {
ensureMigrateResourceResponsesIsMutable();
migrateResourceResponses_.remove(index);
onChanged();
} else {
migrateResourceResponsesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.Builder
getMigrateResourceResponsesBuilder(int index) {
return getMigrateResourceResponsesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.MigrateResourceResponseOrBuilder
getMigrateResourceResponsesOrBuilder(int index) {
if (migrateResourceResponsesBuilder_ == null) {
return migrateResourceResponses_.get(index);
} else {
return migrateResourceResponsesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public java.util.List<
? extends com.google.cloud.aiplatform.v1beta1.MigrateResourceResponseOrBuilder>
getMigrateResourceResponsesOrBuilderList() {
if (migrateResourceResponsesBuilder_ != null) {
return migrateResourceResponsesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(migrateResourceResponses_);
}
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.Builder
addMigrateResourceResponsesBuilder() {
return getMigrateResourceResponsesFieldBuilder()
.addBuilder(
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.getDefaultInstance());
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.Builder
addMigrateResourceResponsesBuilder(int index) {
return getMigrateResourceResponsesFieldBuilder()
.addBuilder(
index,
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.getDefaultInstance());
}
/**
*
*
* <pre>
* Successfully migrated resources.
* </pre>
*
* <code>
* repeated .google.cloud.aiplatform.v1beta1.MigrateResourceResponse migrate_resource_responses = 1;
* </code>
*/
public java.util.List<com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.Builder>
getMigrateResourceResponsesBuilderList() {
return getMigrateResourceResponsesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse,
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.Builder,
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponseOrBuilder>
getMigrateResourceResponsesFieldBuilder() {
if (migrateResourceResponsesBuilder_ == null) {
migrateResourceResponsesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse,
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponse.Builder,
com.google.cloud.aiplatform.v1beta1.MigrateResourceResponseOrBuilder>(
migrateResourceResponses_,
((bitField0_ & 0x00000001) != 0),
getParentForChildren(),
isClean());
migrateResourceResponses_ = null;
}
return migrateResourceResponsesBuilder_;
}
@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.BatchMigrateResourcesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse)
private static final com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse();
}
public static com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<BatchMigrateResourcesResponse> PARSER =
new com.google.protobuf.AbstractParser<BatchMigrateResourcesResponse>() {
@java.lang.Override
public BatchMigrateResourcesResponse 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<BatchMigrateResourcesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<BatchMigrateResourcesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.BatchMigrateResourcesResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/iotdb | 35,729 | iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/exchange/MPPDataExchangeManager.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.iotdb.db.queryengine.execution.exchange;
import org.apache.iotdb.common.rpc.thrift.TEndPoint;
import org.apache.iotdb.common.rpc.thrift.TSStatus;
import org.apache.iotdb.commons.client.IClientManager;
import org.apache.iotdb.commons.client.sync.SyncDataNodeMPPDataExchangeServiceClient;
import org.apache.iotdb.db.queryengine.exception.exchange.GetTsBlockFromClosedOrAbortedChannelException;
import org.apache.iotdb.db.queryengine.execution.driver.DriverContext;
import org.apache.iotdb.db.queryengine.execution.exchange.sink.DownStreamChannelIndex;
import org.apache.iotdb.db.queryengine.execution.exchange.sink.DownStreamChannelLocation;
import org.apache.iotdb.db.queryengine.execution.exchange.sink.ISink;
import org.apache.iotdb.db.queryengine.execution.exchange.sink.ISinkChannel;
import org.apache.iotdb.db.queryengine.execution.exchange.sink.ISinkHandle;
import org.apache.iotdb.db.queryengine.execution.exchange.sink.LocalSinkChannel;
import org.apache.iotdb.db.queryengine.execution.exchange.sink.ShuffleSinkHandle;
import org.apache.iotdb.db.queryengine.execution.exchange.sink.SinkChannel;
import org.apache.iotdb.db.queryengine.execution.exchange.source.ISourceHandle;
import org.apache.iotdb.db.queryengine.execution.exchange.source.LocalSourceHandle;
import org.apache.iotdb.db.queryengine.execution.exchange.source.PipelineSourceHandle;
import org.apache.iotdb.db.queryengine.execution.exchange.source.SourceHandle;
import org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceContext;
import org.apache.iotdb.db.queryengine.execution.memory.LocalMemoryManager;
import org.apache.iotdb.db.queryengine.metric.DataExchangeCostMetricSet;
import org.apache.iotdb.db.queryengine.metric.DataExchangeCountMetricSet;
import org.apache.iotdb.db.utils.SetThreadName;
import org.apache.iotdb.mpp.rpc.thrift.MPPDataExchangeService;
import org.apache.iotdb.mpp.rpc.thrift.TAcknowledgeDataBlockEvent;
import org.apache.iotdb.mpp.rpc.thrift.TCloseSinkChannelEvent;
import org.apache.iotdb.mpp.rpc.thrift.TEndOfDataBlockEvent;
import org.apache.iotdb.mpp.rpc.thrift.TFragmentInstanceId;
import org.apache.iotdb.mpp.rpc.thrift.TGetDataBlockRequest;
import org.apache.iotdb.mpp.rpc.thrift.TGetDataBlockResponse;
import org.apache.iotdb.mpp.rpc.thrift.TNewDataBlockEvent;
import org.apache.iotdb.rpc.TSStatusCode;
import org.apache.commons.lang3.Validate;
import org.apache.thrift.TException;
import org.apache.tsfile.read.common.block.column.TsBlockSerde;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static org.apache.iotdb.db.queryengine.common.DataNodeEndPoints.isSameNode;
import static org.apache.iotdb.db.queryengine.common.FragmentInstanceId.createFullId;
import static org.apache.iotdb.db.queryengine.metric.DataExchangeCostMetricSet.GET_DATA_BLOCK_TASK_SERVER;
import static org.apache.iotdb.db.queryengine.metric.DataExchangeCostMetricSet.ON_ACKNOWLEDGE_DATA_BLOCK_EVENT_TASK_SERVER;
import static org.apache.iotdb.db.queryengine.metric.DataExchangeCostMetricSet.SEND_NEW_DATA_BLOCK_EVENT_TASK_SERVER;
import static org.apache.iotdb.db.queryengine.metric.DataExchangeCountMetricSet.GET_DATA_BLOCK_NUM_SERVER;
import static org.apache.iotdb.db.queryengine.metric.DataExchangeCountMetricSet.ON_ACKNOWLEDGE_DATA_BLOCK_NUM_SERVER;
import static org.apache.iotdb.db.queryengine.metric.DataExchangeCountMetricSet.SEND_NEW_DATA_BLOCK_NUM_SERVER;
public class MPPDataExchangeManager implements IMPPDataExchangeManager {
private static final Logger LOGGER = LoggerFactory.getLogger(MPPDataExchangeManager.class);
// region =========== MPPDataExchangeServiceImpl ===========
/** Handle thrift communications. */
class MPPDataExchangeServiceImpl implements MPPDataExchangeService.Iface {
private final DataExchangeCostMetricSet DATA_EXCHANGE_COST_METRICS =
DataExchangeCostMetricSet.getInstance();
private final DataExchangeCountMetricSet DATA_EXCHANGE_COUNT_METRICS =
DataExchangeCountMetricSet.getInstance();
@Override
public TGetDataBlockResponse getDataBlock(TGetDataBlockRequest req) throws TException {
long startTime = System.nanoTime();
try (SetThreadName fragmentInstanceName =
new SetThreadName(
createFullId(
req.sourceFragmentInstanceId.queryId,
req.sourceFragmentInstanceId.fragmentId,
req.sourceFragmentInstanceId.instanceId))) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"[ProcessGetTsBlockRequest] sequence ID in [{}, {})",
req.getStartSequenceId(),
req.getEndSequenceId());
}
TGetDataBlockResponse resp = new TGetDataBlockResponse(new ArrayList<>());
ISinkHandle sinkHandle = shuffleSinkHandles.get(req.getSourceFragmentInstanceId());
if (sinkHandle == null) {
return resp;
}
// index of the channel must be a SinkChannel
SinkChannel sinkChannel = (SinkChannel) (sinkHandle.getChannel(req.getIndex()));
for (int i = req.getStartSequenceId(); i < req.getEndSequenceId(); i++) {
try {
ByteBuffer serializedTsBlock = sinkChannel.getSerializedTsBlock(i);
resp.addToTsBlocks(serializedTsBlock);
} catch (GetTsBlockFromClosedOrAbortedChannelException e) {
// Return an empty block list to indicate that getting data block failed this time.
// The SourceHandle will deal with this signal depending on its state.
return new TGetDataBlockResponse(new ArrayList<>());
} catch (IllegalStateException | IOException e) {
throw new TException(e);
}
}
return resp;
} finally {
DATA_EXCHANGE_COST_METRICS.recordDataExchangeCost(
GET_DATA_BLOCK_TASK_SERVER, System.nanoTime() - startTime);
DATA_EXCHANGE_COUNT_METRICS.recordDataBlockNum(
GET_DATA_BLOCK_NUM_SERVER, req.getEndSequenceId() - req.getStartSequenceId());
}
}
@Override
public void onAcknowledgeDataBlockEvent(TAcknowledgeDataBlockEvent e) {
long startTime = System.nanoTime();
try (SetThreadName fragmentInstanceName =
new SetThreadName(
createFullId(
e.sourceFragmentInstanceId.queryId,
e.sourceFragmentInstanceId.fragmentId,
e.sourceFragmentInstanceId.instanceId))) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Received AcknowledgeDataBlockEvent for TsBlocks whose sequence ID are in [{}, {}) from {}.",
e.getStartSequenceId(),
e.getEndSequenceId(),
e.getSourceFragmentInstanceId());
}
ISinkHandle sinkHandle = shuffleSinkHandles.get(e.getSourceFragmentInstanceId());
if (sinkHandle == null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"received ACK event but target FragmentInstance[{}] is not found.",
e.getSourceFragmentInstanceId());
}
return;
}
// index of the channel must be a SinkChannel
((SinkChannel) (sinkHandle.getChannel(e.getIndex())))
.acknowledgeTsBlock(e.getStartSequenceId(), e.getEndSequenceId());
} catch (Throwable t) {
LOGGER.warn(
"ack TsBlock [{}, {}) failed.", e.getStartSequenceId(), e.getEndSequenceId(), t);
throw t;
} finally {
DATA_EXCHANGE_COST_METRICS.recordDataExchangeCost(
ON_ACKNOWLEDGE_DATA_BLOCK_EVENT_TASK_SERVER, System.nanoTime() - startTime);
DATA_EXCHANGE_COUNT_METRICS.recordDataBlockNum(
ON_ACKNOWLEDGE_DATA_BLOCK_NUM_SERVER, e.getEndSequenceId() - e.getStartSequenceId());
}
}
@Override
public void onCloseSinkChannelEvent(TCloseSinkChannelEvent e) throws TException {
try (SetThreadName fragmentInstanceName =
new SetThreadName(
createFullId(
e.sourceFragmentInstanceId.queryId,
e.sourceFragmentInstanceId.fragmentId,
e.sourceFragmentInstanceId.instanceId))) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Closed source handle of ShuffleSinkHandle {}, channel index: {}.",
e.getSourceFragmentInstanceId(),
e.getIndex());
}
ISinkHandle sinkHandle = shuffleSinkHandles.get(e.getSourceFragmentInstanceId());
if (sinkHandle == null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"received CloseSinkChannelEvent but target FragmentInstance[{}] is not found.",
e.getSourceFragmentInstanceId());
}
return;
}
sinkHandle.getChannel(e.getIndex()).close();
} catch (Throwable t) {
LOGGER.warn(
"Close channel of ShuffleSinkHandle {}, index {} failed.",
e.getSourceFragmentInstanceId(),
e.getIndex(),
t);
throw t;
}
}
@Override
public void onNewDataBlockEvent(TNewDataBlockEvent e) throws TException {
long startTime = System.nanoTime();
try (SetThreadName fragmentInstanceName =
new SetThreadName(createFullIdFrom(e.targetFragmentInstanceId, e.targetPlanNodeId))) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"New data block event received, for plan node {} of {} from {}.",
e.getTargetPlanNodeId(),
e.getTargetFragmentInstanceId(),
e.getSourceFragmentInstanceId());
}
Map<String, ISourceHandle> sourceHandleMap =
sourceHandles.get(e.getTargetFragmentInstanceId());
SourceHandle sourceHandle =
sourceHandleMap == null
? null
: (SourceHandle) sourceHandleMap.get(e.getTargetPlanNodeId());
if (sourceHandle == null || sourceHandle.isAborted() || sourceHandle.isFinished()) {
// In some scenario, when the SourceHandle sends the data block ACK event, its upstream
// may
// have already been stopped. For example, in the read whit LimitOperator, the downstream
// FragmentInstance may be finished, although the upstream is still working.
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"received NewDataBlockEvent but the downstream FragmentInstance[{}] is not found",
e.getTargetFragmentInstanceId());
}
return;
}
sourceHandle.updatePendingDataBlockInfo(e.getStartSequenceId(), e.getBlockSizes());
} finally {
DATA_EXCHANGE_COST_METRICS.recordDataExchangeCost(
SEND_NEW_DATA_BLOCK_EVENT_TASK_SERVER, System.nanoTime() - startTime);
DATA_EXCHANGE_COUNT_METRICS.recordDataBlockNum(
SEND_NEW_DATA_BLOCK_NUM_SERVER, e.getBlockSizes().size());
}
}
@Override
public void onEndOfDataBlockEvent(TEndOfDataBlockEvent e) throws TException {
try (SetThreadName fragmentInstanceName =
new SetThreadName(createFullIdFrom(e.targetFragmentInstanceId, e.targetPlanNodeId))) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"End of data block event received, for plan node {} of {} from {}.",
e.getTargetPlanNodeId(),
e.getTargetFragmentInstanceId(),
e.getSourceFragmentInstanceId());
}
Map<String, ISourceHandle> sourceHandleMap =
sourceHandles.get(e.getTargetFragmentInstanceId());
SourceHandle sourceHandle =
sourceHandleMap == null
? null
: (SourceHandle) sourceHandleMap.get(e.getTargetPlanNodeId());
if (sourceHandle == null || sourceHandle.isAborted() || sourceHandle.isFinished()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"received onEndOfDataBlockEvent but the downstream FragmentInstance[{}] is not found",
e.getTargetFragmentInstanceId());
}
return;
}
sourceHandle.setNoMoreTsBlocks(e.getLastSequenceId());
}
}
@Override
public TSStatus testConnectionEmptyRPC() throws TException {
return new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode());
}
}
// endregion
// region =========== listener ===========
public interface SourceHandleListener {
void onFinished(ISourceHandle sourceHandle);
void onAborted(ISourceHandle sourceHandle);
void onFailure(ISourceHandle sourceHandle, Throwable t);
}
public interface SinkListener {
void onFinish(ISink sink);
void onEndOfBlocks(ISink sink);
Optional<Throwable> onAborted(ISink sink);
void onFailure(ISink sink, Throwable t);
}
/** Listen to the state changes of a source handle. */
class SourceHandleListenerImpl implements SourceHandleListener {
private final IMPPDataExchangeManagerCallback<Throwable> onFailureCallback;
public SourceHandleListenerImpl(IMPPDataExchangeManagerCallback<Throwable> onFailureCallback) {
this.onFailureCallback = onFailureCallback;
}
@Override
public void onFinished(ISourceHandle sourceHandle) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[ScHListenerOnFinish]");
}
Map<String, ISourceHandle> sourceHandleMap =
sourceHandles.get(sourceHandle.getLocalFragmentInstanceId());
if ((sourceHandleMap == null
|| sourceHandleMap.remove(sourceHandle.getLocalPlanNodeId()) == null)
&& LOGGER.isDebugEnabled()) {
LOGGER.debug("[ScHListenerAlreadyReleased]");
}
if (sourceHandleMap != null && sourceHandleMap.isEmpty()) {
sourceHandles.remove(sourceHandle.getLocalFragmentInstanceId());
}
}
@Override
public void onAborted(ISourceHandle sourceHandle) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[ScHListenerOnAbort]");
}
onFinished(sourceHandle);
}
@Override
public void onFailure(ISourceHandle sourceHandle, Throwable t) {
LOGGER.warn("Source handle failed due to: ", t);
if (onFailureCallback != null) {
onFailureCallback.call(t);
}
}
}
/**
* Listen to the state changes of a source handle of pipeline. Since we register nothing in the
* exchangeManager, so we don't need to remove it too.
*/
static class PipelineSourceHandleListenerImpl implements SourceHandleListener {
private final IMPPDataExchangeManagerCallback<Throwable> onFailureCallback;
public PipelineSourceHandleListenerImpl(
IMPPDataExchangeManagerCallback<Throwable> onFailureCallback) {
this.onFailureCallback = onFailureCallback;
}
@Override
public void onFinished(ISourceHandle sourceHandle) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[ScHListenerOnFinish]");
}
}
@Override
public void onAborted(ISourceHandle sourceHandle) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[ScHListenerOnAbort]");
}
}
@Override
public void onFailure(ISourceHandle sourceHandle, Throwable t) {
LOGGER.warn("Source handle failed due to: ", t);
if (onFailureCallback != null) {
onFailureCallback.call(t);
}
}
}
/** Listen to the state changes of a sink handle. */
class ShuffleSinkListenerImpl implements SinkListener {
private final FragmentInstanceContext context;
private final IMPPDataExchangeManagerCallback<Throwable> onFailureCallback;
public ShuffleSinkListenerImpl(
FragmentInstanceContext context,
IMPPDataExchangeManagerCallback<Throwable> onFailureCallback) {
this.context = context;
this.onFailureCallback = onFailureCallback;
}
@Override
public void onFinish(ISink sink) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[ShuffleSinkHandleListenerOnFinish]");
}
shuffleSinkHandles.remove(sink.getLocalFragmentInstanceId());
context.finished();
}
@Override
public void onEndOfBlocks(ISink sink) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[ShuffleSinkHandleListenerOnEndOfTsBlocks]");
}
context.transitionToFlushing();
}
@Override
public Optional<Throwable> onAborted(ISink sink) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[ShuffleSinkHandleListenerOnAbort]");
}
shuffleSinkHandles.remove(sink.getLocalFragmentInstanceId());
return context.getFailureCause();
}
@Override
public void onFailure(ISink sink, Throwable t) {
// TODO: (xingtanzjr) should we remove the sink from MPPDataExchangeManager ?
LOGGER.warn("Sink failed due to", t);
if (onFailureCallback != null) {
onFailureCallback.call(t);
}
}
}
class ISinkChannelListenerImpl implements SinkListener {
private final TFragmentInstanceId shuffleSinkHandleId;
private final FragmentInstanceContext context;
private final IMPPDataExchangeManagerCallback<Throwable> onFailureCallback;
private final AtomicInteger cnt;
private final AtomicBoolean hasDecremented = new AtomicBoolean(false);
public ISinkChannelListenerImpl(
TFragmentInstanceId localFragmentInstanceId,
FragmentInstanceContext context,
IMPPDataExchangeManagerCallback<Throwable> onFailureCallback,
AtomicInteger cnt) {
this.shuffleSinkHandleId = localFragmentInstanceId;
this.context = context;
this.onFailureCallback = onFailureCallback;
this.cnt = cnt;
}
@Override
public void onFinish(ISink sink) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[SkHListenerOnFinish]");
}
decrementCnt();
}
@Override
public void onEndOfBlocks(ISink sink) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[SkHListenerOnEndOfTsBlocks]");
}
}
@Override
public Optional<Throwable> onAborted(ISink sink) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[SkHListenerOnAbort]");
}
decrementCnt();
return context.getFailureCause();
}
@Override
public void onFailure(ISink sink, Throwable t) {
LOGGER.warn("ISinkChannel failed due to", t);
decrementCnt();
if (onFailureCallback != null) {
onFailureCallback.call(t);
}
}
private void decrementCnt() {
if (hasDecremented.compareAndSet(false, true) && (cnt.decrementAndGet() == 0)) {
closeShuffleSinkHandle();
}
}
private void closeShuffleSinkHandle() {
ISinkHandle sinkHandle = shuffleSinkHandles.remove(shuffleSinkHandleId);
if (sinkHandle != null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Close ShuffleSinkHandle: {}", shuffleSinkHandleId);
}
sinkHandle.close();
}
}
}
/**
* Listen to the state changes of a sink handle of pipeline. And since the finish of pipeline sink
* handle doesn't equal the finish of the whole fragment, therefore we don't need to notify
* fragment context. But if it's aborted or failed, it can lead to the total fail.
*/
static class PipelineSinkListenerImpl implements SinkListener {
private final FragmentInstanceContext context;
private final IMPPDataExchangeManagerCallback<Throwable> onFailureCallback;
public PipelineSinkListenerImpl(
FragmentInstanceContext context,
IMPPDataExchangeManagerCallback<Throwable> onFailureCallback) {
this.context = context;
this.onFailureCallback = onFailureCallback;
}
@Override
public void onFinish(ISink sink) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[SkHListenerOnFinish]");
}
}
@Override
public void onEndOfBlocks(ISink sink) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[SkHListenerOnEndOfTsBlocks]");
}
}
@Override
public Optional<Throwable> onAborted(ISink sink) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[SkHListenerOnAbort]");
}
return context.getFailureCause();
}
@Override
public void onFailure(ISink sink, Throwable t) {
LOGGER.warn("Sink handle failed due to", t);
if (onFailureCallback != null) {
onFailureCallback.call(t);
}
}
}
// endregion
// region =========== MPPDataExchangeManager ===========
private final LocalMemoryManager localMemoryManager;
private final Supplier<TsBlockSerde> tsBlockSerdeFactory;
private final ExecutorService executorService;
private final IClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
mppDataExchangeServiceClientManager;
private final Map<TFragmentInstanceId, Map<String, ISourceHandle>> sourceHandles;
/** Each FI has only one ShuffleSinkHandle. */
private final Map<TFragmentInstanceId, ISinkHandle> shuffleSinkHandles;
private MPPDataExchangeServiceImpl mppDataExchangeService;
public MPPDataExchangeManager(
LocalMemoryManager localMemoryManager,
Supplier<TsBlockSerde> tsBlockSerdeFactory,
ExecutorService executorService,
IClientManager<TEndPoint, SyncDataNodeMPPDataExchangeServiceClient>
mppDataExchangeServiceClientManager) {
this.localMemoryManager = Validate.notNull(localMemoryManager, "localMemoryManager is null.");
this.tsBlockSerdeFactory =
Validate.notNull(tsBlockSerdeFactory, "tsBlockSerdeFactory is null.");
this.executorService = Validate.notNull(executorService, "executorService is null.");
this.mppDataExchangeServiceClientManager =
Validate.notNull(
mppDataExchangeServiceClientManager, "mppDataExchangeServiceClientManager is null.");
sourceHandles = new ConcurrentHashMap<>();
shuffleSinkHandles = new ConcurrentHashMap<>();
}
public MPPDataExchangeServiceImpl getOrCreateMPPDataExchangeServiceImpl() {
if (mppDataExchangeService == null) {
mppDataExchangeService = new MPPDataExchangeServiceImpl();
}
return mppDataExchangeService;
}
public void deRegisterFragmentInstanceFromMemoryPool(
String queryId, String fragmentInstanceId, boolean forceDeregister) {
localMemoryManager
.getQueryPool()
.deRegisterFragmentInstanceFromQueryMemoryMap(queryId, fragmentInstanceId, forceDeregister);
}
public LocalMemoryManager getLocalMemoryManager() {
return localMemoryManager;
}
public int getShuffleSinkHandleSize() {
return shuffleSinkHandles.size();
}
public int getSourceHandleSize() {
// risk of Integer overflow
return sourceHandles.values().stream().mapToInt(Map::size).sum();
}
private synchronized ISinkChannel createLocalSinkChannel(
TFragmentInstanceId localFragmentInstanceId,
TFragmentInstanceId remoteFragmentInstanceId,
String remotePlanNodeId,
String localPlanNodeId,
// TODO: replace with callbacks to decouple MPPDataExchangeManager from
// FragmentInstanceContext
FragmentInstanceContext instanceContext,
AtomicInteger cnt) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Create local sink handle to plan node {} of {} for {}",
remotePlanNodeId,
remoteFragmentInstanceId,
localFragmentInstanceId);
}
SharedTsBlockQueue queue;
Map<String, ISourceHandle> sourceHandleMap = sourceHandles.get(remoteFragmentInstanceId);
LocalSourceHandle localSourceHandle =
sourceHandleMap == null ? null : (LocalSourceHandle) sourceHandleMap.get(remotePlanNodeId);
if (localSourceHandle != null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Get SharedTsBlockQueue from local source handle");
}
queue = localSourceHandle.getSharedTsBlockQueue();
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Create SharedTsBlockQueue");
}
queue =
new SharedTsBlockQueue(
localFragmentInstanceId, localPlanNodeId, localMemoryManager, executorService);
}
return new LocalSinkChannel(
localFragmentInstanceId,
queue,
new ISinkChannelListenerImpl(
localFragmentInstanceId, instanceContext, instanceContext::failed, cnt));
}
/**
* As we know the upstream and downstream node of shared queue, we don't need to put it into the
* sink map.
*/
public ISinkChannel createLocalSinkChannelForPipeline(
DriverContext driverContext, String planNodeId) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Create local sink handle for {}", driverContext.getDriverTaskID());
}
SharedTsBlockQueue queue =
new SharedTsBlockQueue(
driverContext.getDriverTaskID().getFragmentInstanceId().toThrift(),
planNodeId,
localMemoryManager,
executorService);
queue.allowAddingTsBlock();
return new LocalSinkChannel(
queue,
new PipelineSinkListenerImpl(
driverContext.getFragmentInstanceContext(), driverContext::failed));
}
private ISinkChannel createSinkChannel(
TFragmentInstanceId localFragmentInstanceId,
TEndPoint remoteEndpoint,
TFragmentInstanceId remoteFragmentInstanceId,
String remotePlanNodeId,
String localPlanNodeId,
// TODO: replace with callbacks to decouple MPPDataExchangeManager from
// FragmentInstanceContext
FragmentInstanceContext instanceContext,
AtomicInteger cnt) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Create sink handle to plan node {} of {} for {}",
remotePlanNodeId,
remoteFragmentInstanceId,
localFragmentInstanceId);
}
return new SinkChannel(
remoteEndpoint,
remoteFragmentInstanceId,
remotePlanNodeId,
localPlanNodeId,
localFragmentInstanceId,
localMemoryManager,
executorService,
tsBlockSerdeFactory.get(),
new ISinkChannelListenerImpl(
localFragmentInstanceId, instanceContext, instanceContext::failed, cnt),
mppDataExchangeServiceClientManager);
}
@Override
public ISinkHandle createShuffleSinkHandle(
List<DownStreamChannelLocation> downStreamChannelLocationList,
DownStreamChannelIndex downStreamChannelIndex,
ShuffleSinkHandle.ShuffleStrategyEnum shuffleStrategyEnum,
TFragmentInstanceId localFragmentInstanceId,
String localPlanNodeId,
// TODO: replace with callbacks to decouple MPPDataExchangeManager from
// FragmentInstanceContext
FragmentInstanceContext instanceContext) {
if (shuffleSinkHandles.containsKey(localFragmentInstanceId)) {
throw new IllegalStateException(
"ShuffleSinkHandle for " + localFragmentInstanceId + " is in the map.");
}
int channelNum = downStreamChannelLocationList.size();
AtomicInteger cnt = new AtomicInteger(channelNum);
List<ISinkChannel> downStreamChannelList =
downStreamChannelLocationList.stream()
.map(
downStreamChannelLocation ->
createChannelForShuffleSink(
localFragmentInstanceId,
localPlanNodeId,
downStreamChannelLocation,
instanceContext,
cnt))
.collect(Collectors.toList());
ShuffleSinkHandle shuffleSinkHandle =
new ShuffleSinkHandle(
localFragmentInstanceId,
downStreamChannelList,
downStreamChannelIndex,
shuffleStrategyEnum,
new ShuffleSinkListenerImpl(instanceContext, instanceContext::failed));
shuffleSinkHandles.put(localFragmentInstanceId, shuffleSinkHandle);
return shuffleSinkHandle;
}
private ISinkChannel createChannelForShuffleSink(
TFragmentInstanceId localFragmentInstanceId,
String localPlanNodeId,
DownStreamChannelLocation downStreamChannelLocation,
FragmentInstanceContext instanceContext,
AtomicInteger cnt) {
if (isSameNode(downStreamChannelLocation.getRemoteEndpoint())) {
return createLocalSinkChannel(
localFragmentInstanceId,
downStreamChannelLocation.getRemoteFragmentInstanceId(),
downStreamChannelLocation.getRemotePlanNodeId(),
localPlanNodeId,
instanceContext,
cnt);
} else {
return createSinkChannel(
localFragmentInstanceId,
downStreamChannelLocation.getRemoteEndpoint(),
downStreamChannelLocation.getRemoteFragmentInstanceId(),
downStreamChannelLocation.getRemotePlanNodeId(),
localPlanNodeId,
instanceContext,
cnt);
}
}
/**
* As we know the upstream and downstream node of shared queue, we don't need to put it into the
* sourceHandle map.
*/
public ISourceHandle createLocalSourceHandleForPipeline(
SharedTsBlockQueue queue, DriverContext context) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Create local source handle for {}", context.getDriverTaskID());
}
return new PipelineSourceHandle(
queue,
new PipelineSourceHandleListenerImpl(context::failed),
context.getDriverTaskID().toString());
}
public synchronized ISourceHandle createLocalSourceHandleForFragment(
TFragmentInstanceId localFragmentInstanceId,
String localPlanNodeId,
String remotePlanNodeId,
TFragmentInstanceId remoteFragmentInstanceId,
int index,
IMPPDataExchangeManagerCallback<Throwable> onFailureCallback) {
if (sourceHandles.containsKey(localFragmentInstanceId)
&& sourceHandles.get(localFragmentInstanceId).containsKey(localPlanNodeId)) {
throw new IllegalStateException(
"Source handle for plan node "
+ localPlanNodeId
+ " of "
+ localFragmentInstanceId
+ " exists.");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Create local source handle from {} for plan node {} of {}",
remoteFragmentInstanceId,
localPlanNodeId,
localFragmentInstanceId);
}
SharedTsBlockQueue queue;
ISinkHandle sinkHandle = shuffleSinkHandles.get(remoteFragmentInstanceId);
if (sinkHandle != null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Get SharedTsBlockQueue from local sink handle");
}
queue = ((LocalSinkChannel) (sinkHandle.getChannel(index))).getSharedTsBlockQueue();
} else {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Create SharedTsBlockQueue");
}
queue =
new SharedTsBlockQueue(
remoteFragmentInstanceId, remotePlanNodeId, localMemoryManager, executorService);
}
LocalSourceHandle localSourceHandle =
new LocalSourceHandle(
localFragmentInstanceId,
localPlanNodeId,
queue,
new SourceHandleListenerImpl(onFailureCallback));
sourceHandles
.computeIfAbsent(localFragmentInstanceId, key -> new ConcurrentHashMap<>())
.put(localPlanNodeId, localSourceHandle);
return localSourceHandle;
}
@Override
public ISourceHandle createSourceHandle(
TFragmentInstanceId localFragmentInstanceId,
String localPlanNodeId,
int indexOfUpstreamSinkHandle,
TEndPoint remoteEndpoint,
TFragmentInstanceId remoteFragmentInstanceId,
IMPPDataExchangeManagerCallback<Throwable> onFailureCallback) {
Map<String, ISourceHandle> sourceHandleMap = sourceHandles.get(localFragmentInstanceId);
if (sourceHandleMap != null && sourceHandleMap.containsKey(localPlanNodeId)) {
throw new IllegalStateException(
"Source handle for plan node "
+ localPlanNodeId
+ " of "
+ localFragmentInstanceId
+ " exists.");
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"Create source handle from {} for plan node {} of {}",
remoteFragmentInstanceId,
localPlanNodeId,
localFragmentInstanceId);
}
SourceHandle sourceHandle =
new SourceHandle(
remoteEndpoint,
remoteFragmentInstanceId,
localFragmentInstanceId,
localPlanNodeId,
indexOfUpstreamSinkHandle,
localMemoryManager,
executorService,
tsBlockSerdeFactory.get(),
new SourceHandleListenerImpl(onFailureCallback),
mppDataExchangeServiceClientManager);
sourceHandles
.computeIfAbsent(localFragmentInstanceId, key -> new ConcurrentHashMap<>())
.put(localPlanNodeId, sourceHandle);
return sourceHandle;
}
/**
* Release all the related resources, including data blocks that are not yet fetched by downstream
* fragment instances.
*
* <p>This method should be called when a fragment instance finished in an abnormal state.
*/
public void forceDeregisterFragmentInstance(TFragmentInstanceId fragmentInstanceId) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[StartForceReleaseFIDataExchangeResource]");
}
ISink sinkHandle = shuffleSinkHandles.get(fragmentInstanceId);
if (sinkHandle != null) {
sinkHandle.abort();
shuffleSinkHandles.remove(fragmentInstanceId);
}
Map<String, ISourceHandle> planNodeIdToSourceHandle = sourceHandles.get(fragmentInstanceId);
if (planNodeIdToSourceHandle != null) {
for (Entry<String, ISourceHandle> entry : planNodeIdToSourceHandle.entrySet()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[CloseSourceHandle] {}", entry.getKey());
}
entry.getValue().abort();
}
sourceHandles.remove(fragmentInstanceId);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[EndForceReleaseFIDataExchangeResource]");
}
}
/**
* Create FullId with suffix.
*
* @param suffix should be like [PlanNodeId].SourceHandle/SinHandle
*/
public static String createFullIdFrom(TFragmentInstanceId fragmentInstanceId, String suffix) {
return createFullId(
fragmentInstanceId.queryId,
fragmentInstanceId.fragmentId,
fragmentInstanceId.instanceId)
+ "."
+ suffix;
}
// endregion
}
|
googleapis/google-cloud-java | 35,660 | java-contentwarehouse/proto-google-cloud-contentwarehouse-v1/src/main/java/com/google/cloud/contentwarehouse/v1/FetchAclRequest.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/contentwarehouse/v1/document_service_request.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.contentwarehouse.v1;
/**
*
*
* <pre>
* Request message for DocumentService.FetchAcl
* </pre>
*
* Protobuf type {@code google.cloud.contentwarehouse.v1.FetchAclRequest}
*/
public final class FetchAclRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.contentwarehouse.v1.FetchAclRequest)
FetchAclRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use FetchAclRequest.newBuilder() to construct.
private FetchAclRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private FetchAclRequest() {
resource_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new FetchAclRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.contentwarehouse.v1.DocumentServiceRequestProto
.internal_static_google_cloud_contentwarehouse_v1_FetchAclRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.contentwarehouse.v1.DocumentServiceRequestProto
.internal_static_google_cloud_contentwarehouse_v1_FetchAclRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.contentwarehouse.v1.FetchAclRequest.class,
com.google.cloud.contentwarehouse.v1.FetchAclRequest.Builder.class);
}
private int bitField0_;
public static final int RESOURCE_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object resource_ = "";
/**
*
*
* <pre>
* Required. REQUIRED: The resource for which the policy is being requested.
* Format for document:
* projects/{project_number}/locations/{location}/documents/{document_id}.
* Format for collection:
* projects/{project_number}/locations/{location}/collections/{collection_id}.
* Format for project: projects/{project_number}.
* </pre>
*
* <code>string resource = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The resource.
*/
@java.lang.Override
public java.lang.String getResource() {
java.lang.Object ref = resource_;
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();
resource_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. REQUIRED: The resource for which the policy is being requested.
* Format for document:
* projects/{project_number}/locations/{location}/documents/{document_id}.
* Format for collection:
* projects/{project_number}/locations/{location}/collections/{collection_id}.
* Format for project: projects/{project_number}.
* </pre>
*
* <code>string resource = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for resource.
*/
@java.lang.Override
public com.google.protobuf.ByteString getResourceBytes() {
java.lang.Object ref = resource_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resource_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int REQUEST_METADATA_FIELD_NUMBER = 2;
private com.google.cloud.contentwarehouse.v1.RequestMetadata requestMetadata_;
/**
*
*
* <pre>
* The meta information collected about the end user, used to enforce access
* control for the service.
* </pre>
*
* <code>.google.cloud.contentwarehouse.v1.RequestMetadata request_metadata = 2;</code>
*
* @return Whether the requestMetadata field is set.
*/
@java.lang.Override
public boolean hasRequestMetadata() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* The meta information collected about the end user, used to enforce access
* control for the service.
* </pre>
*
* <code>.google.cloud.contentwarehouse.v1.RequestMetadata request_metadata = 2;</code>
*
* @return The requestMetadata.
*/
@java.lang.Override
public com.google.cloud.contentwarehouse.v1.RequestMetadata getRequestMetadata() {
return requestMetadata_ == null
? com.google.cloud.contentwarehouse.v1.RequestMetadata.getDefaultInstance()
: requestMetadata_;
}
/**
*
*
* <pre>
* The meta information collected about the end user, used to enforce access
* control for the service.
* </pre>
*
* <code>.google.cloud.contentwarehouse.v1.RequestMetadata request_metadata = 2;</code>
*/
@java.lang.Override
public com.google.cloud.contentwarehouse.v1.RequestMetadataOrBuilder
getRequestMetadataOrBuilder() {
return requestMetadata_ == null
? com.google.cloud.contentwarehouse.v1.RequestMetadata.getDefaultInstance()
: requestMetadata_;
}
public static final int PROJECT_OWNER_FIELD_NUMBER = 3;
private boolean projectOwner_ = false;
/**
*
*
* <pre>
* For Get Project ACL only. Authorization check for end user will be ignored
* when project_owner=true.
* </pre>
*
* <code>bool project_owner = 3;</code>
*
* @return The projectOwner.
*/
@java.lang.Override
public boolean getProjectOwner() {
return projectOwner_;
}
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(resource_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, resource_);
}
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(2, getRequestMetadata());
}
if (projectOwner_ != false) {
output.writeBool(3, projectOwner_);
}
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(resource_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, resource_);
}
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getRequestMetadata());
}
if (projectOwner_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, projectOwner_);
}
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.contentwarehouse.v1.FetchAclRequest)) {
return super.equals(obj);
}
com.google.cloud.contentwarehouse.v1.FetchAclRequest other =
(com.google.cloud.contentwarehouse.v1.FetchAclRequest) obj;
if (!getResource().equals(other.getResource())) return false;
if (hasRequestMetadata() != other.hasRequestMetadata()) return false;
if (hasRequestMetadata()) {
if (!getRequestMetadata().equals(other.getRequestMetadata())) return false;
}
if (getProjectOwner() != other.getProjectOwner()) 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) + RESOURCE_FIELD_NUMBER;
hash = (53 * hash) + getResource().hashCode();
if (hasRequestMetadata()) {
hash = (37 * hash) + REQUEST_METADATA_FIELD_NUMBER;
hash = (53 * hash) + getRequestMetadata().hashCode();
}
hash = (37 * hash) + PROJECT_OWNER_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getProjectOwner());
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.contentwarehouse.v1.FetchAclRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contentwarehouse.v1.FetchAclRequest 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.contentwarehouse.v1.FetchAclRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contentwarehouse.v1.FetchAclRequest 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.contentwarehouse.v1.FetchAclRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.contentwarehouse.v1.FetchAclRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.contentwarehouse.v1.FetchAclRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.contentwarehouse.v1.FetchAclRequest 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.contentwarehouse.v1.FetchAclRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.contentwarehouse.v1.FetchAclRequest 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.contentwarehouse.v1.FetchAclRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.contentwarehouse.v1.FetchAclRequest 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.contentwarehouse.v1.FetchAclRequest 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 DocumentService.FetchAcl
* </pre>
*
* Protobuf type {@code google.cloud.contentwarehouse.v1.FetchAclRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.contentwarehouse.v1.FetchAclRequest)
com.google.cloud.contentwarehouse.v1.FetchAclRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.contentwarehouse.v1.DocumentServiceRequestProto
.internal_static_google_cloud_contentwarehouse_v1_FetchAclRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.contentwarehouse.v1.DocumentServiceRequestProto
.internal_static_google_cloud_contentwarehouse_v1_FetchAclRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.contentwarehouse.v1.FetchAclRequest.class,
com.google.cloud.contentwarehouse.v1.FetchAclRequest.Builder.class);
}
// Construct using com.google.cloud.contentwarehouse.v1.FetchAclRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getRequestMetadataFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
resource_ = "";
requestMetadata_ = null;
if (requestMetadataBuilder_ != null) {
requestMetadataBuilder_.dispose();
requestMetadataBuilder_ = null;
}
projectOwner_ = false;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.contentwarehouse.v1.DocumentServiceRequestProto
.internal_static_google_cloud_contentwarehouse_v1_FetchAclRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.contentwarehouse.v1.FetchAclRequest getDefaultInstanceForType() {
return com.google.cloud.contentwarehouse.v1.FetchAclRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.contentwarehouse.v1.FetchAclRequest build() {
com.google.cloud.contentwarehouse.v1.FetchAclRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.contentwarehouse.v1.FetchAclRequest buildPartial() {
com.google.cloud.contentwarehouse.v1.FetchAclRequest result =
new com.google.cloud.contentwarehouse.v1.FetchAclRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.contentwarehouse.v1.FetchAclRequest result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.resource_ = resource_;
}
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000002) != 0)) {
result.requestMetadata_ =
requestMetadataBuilder_ == null ? requestMetadata_ : requestMetadataBuilder_.build();
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.projectOwner_ = projectOwner_;
}
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.contentwarehouse.v1.FetchAclRequest) {
return mergeFrom((com.google.cloud.contentwarehouse.v1.FetchAclRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.contentwarehouse.v1.FetchAclRequest other) {
if (other == com.google.cloud.contentwarehouse.v1.FetchAclRequest.getDefaultInstance())
return this;
if (!other.getResource().isEmpty()) {
resource_ = other.resource_;
bitField0_ |= 0x00000001;
onChanged();
}
if (other.hasRequestMetadata()) {
mergeRequestMetadata(other.getRequestMetadata());
}
if (other.getProjectOwner() != false) {
setProjectOwner(other.getProjectOwner());
}
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:
{
resource_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
input.readMessage(getRequestMetadataFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000002;
break;
} // case 18
case 24:
{
projectOwner_ = 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 resource_ = "";
/**
*
*
* <pre>
* Required. REQUIRED: The resource for which the policy is being requested.
* Format for document:
* projects/{project_number}/locations/{location}/documents/{document_id}.
* Format for collection:
* projects/{project_number}/locations/{location}/collections/{collection_id}.
* Format for project: projects/{project_number}.
* </pre>
*
* <code>string resource = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The resource.
*/
public java.lang.String getResource() {
java.lang.Object ref = resource_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
resource_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. REQUIRED: The resource for which the policy is being requested.
* Format for document:
* projects/{project_number}/locations/{location}/documents/{document_id}.
* Format for collection:
* projects/{project_number}/locations/{location}/collections/{collection_id}.
* Format for project: projects/{project_number}.
* </pre>
*
* <code>string resource = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return The bytes for resource.
*/
public com.google.protobuf.ByteString getResourceBytes() {
java.lang.Object ref = resource_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
resource_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. REQUIRED: The resource for which the policy is being requested.
* Format for document:
* projects/{project_number}/locations/{location}/documents/{document_id}.
* Format for collection:
* projects/{project_number}/locations/{location}/collections/{collection_id}.
* Format for project: projects/{project_number}.
* </pre>
*
* <code>string resource = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The resource to set.
* @return This builder for chaining.
*/
public Builder setResource(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
resource_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. REQUIRED: The resource for which the policy is being requested.
* Format for document:
* projects/{project_number}/locations/{location}/documents/{document_id}.
* Format for collection:
* projects/{project_number}/locations/{location}/collections/{collection_id}.
* Format for project: projects/{project_number}.
* </pre>
*
* <code>string resource = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @return This builder for chaining.
*/
public Builder clearResource() {
resource_ = getDefaultInstance().getResource();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. REQUIRED: The resource for which the policy is being requested.
* Format for document:
* projects/{project_number}/locations/{location}/documents/{document_id}.
* Format for collection:
* projects/{project_number}/locations/{location}/collections/{collection_id}.
* Format for project: projects/{project_number}.
* </pre>
*
* <code>string resource = 1 [(.google.api.field_behavior) = REQUIRED];</code>
*
* @param value The bytes for resource to set.
* @return This builder for chaining.
*/
public Builder setResourceBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
resource_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
private com.google.cloud.contentwarehouse.v1.RequestMetadata requestMetadata_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.contentwarehouse.v1.RequestMetadata,
com.google.cloud.contentwarehouse.v1.RequestMetadata.Builder,
com.google.cloud.contentwarehouse.v1.RequestMetadataOrBuilder>
requestMetadataBuilder_;
/**
*
*
* <pre>
* The meta information collected about the end user, used to enforce access
* control for the service.
* </pre>
*
* <code>.google.cloud.contentwarehouse.v1.RequestMetadata request_metadata = 2;</code>
*
* @return Whether the requestMetadata field is set.
*/
public boolean hasRequestMetadata() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* The meta information collected about the end user, used to enforce access
* control for the service.
* </pre>
*
* <code>.google.cloud.contentwarehouse.v1.RequestMetadata request_metadata = 2;</code>
*
* @return The requestMetadata.
*/
public com.google.cloud.contentwarehouse.v1.RequestMetadata getRequestMetadata() {
if (requestMetadataBuilder_ == null) {
return requestMetadata_ == null
? com.google.cloud.contentwarehouse.v1.RequestMetadata.getDefaultInstance()
: requestMetadata_;
} else {
return requestMetadataBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The meta information collected about the end user, used to enforce access
* control for the service.
* </pre>
*
* <code>.google.cloud.contentwarehouse.v1.RequestMetadata request_metadata = 2;</code>
*/
public Builder setRequestMetadata(com.google.cloud.contentwarehouse.v1.RequestMetadata value) {
if (requestMetadataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
requestMetadata_ = value;
} else {
requestMetadataBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The meta information collected about the end user, used to enforce access
* control for the service.
* </pre>
*
* <code>.google.cloud.contentwarehouse.v1.RequestMetadata request_metadata = 2;</code>
*/
public Builder setRequestMetadata(
com.google.cloud.contentwarehouse.v1.RequestMetadata.Builder builderForValue) {
if (requestMetadataBuilder_ == null) {
requestMetadata_ = builderForValue.build();
} else {
requestMetadataBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The meta information collected about the end user, used to enforce access
* control for the service.
* </pre>
*
* <code>.google.cloud.contentwarehouse.v1.RequestMetadata request_metadata = 2;</code>
*/
public Builder mergeRequestMetadata(
com.google.cloud.contentwarehouse.v1.RequestMetadata value) {
if (requestMetadataBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& requestMetadata_ != null
&& requestMetadata_
!= com.google.cloud.contentwarehouse.v1.RequestMetadata.getDefaultInstance()) {
getRequestMetadataBuilder().mergeFrom(value);
} else {
requestMetadata_ = value;
}
} else {
requestMetadataBuilder_.mergeFrom(value);
}
if (requestMetadata_ != null) {
bitField0_ |= 0x00000002;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* The meta information collected about the end user, used to enforce access
* control for the service.
* </pre>
*
* <code>.google.cloud.contentwarehouse.v1.RequestMetadata request_metadata = 2;</code>
*/
public Builder clearRequestMetadata() {
bitField0_ = (bitField0_ & ~0x00000002);
requestMetadata_ = null;
if (requestMetadataBuilder_ != null) {
requestMetadataBuilder_.dispose();
requestMetadataBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The meta information collected about the end user, used to enforce access
* control for the service.
* </pre>
*
* <code>.google.cloud.contentwarehouse.v1.RequestMetadata request_metadata = 2;</code>
*/
public com.google.cloud.contentwarehouse.v1.RequestMetadata.Builder
getRequestMetadataBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getRequestMetadataFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The meta information collected about the end user, used to enforce access
* control for the service.
* </pre>
*
* <code>.google.cloud.contentwarehouse.v1.RequestMetadata request_metadata = 2;</code>
*/
public com.google.cloud.contentwarehouse.v1.RequestMetadataOrBuilder
getRequestMetadataOrBuilder() {
if (requestMetadataBuilder_ != null) {
return requestMetadataBuilder_.getMessageOrBuilder();
} else {
return requestMetadata_ == null
? com.google.cloud.contentwarehouse.v1.RequestMetadata.getDefaultInstance()
: requestMetadata_;
}
}
/**
*
*
* <pre>
* The meta information collected about the end user, used to enforce access
* control for the service.
* </pre>
*
* <code>.google.cloud.contentwarehouse.v1.RequestMetadata request_metadata = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.contentwarehouse.v1.RequestMetadata,
com.google.cloud.contentwarehouse.v1.RequestMetadata.Builder,
com.google.cloud.contentwarehouse.v1.RequestMetadataOrBuilder>
getRequestMetadataFieldBuilder() {
if (requestMetadataBuilder_ == null) {
requestMetadataBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.contentwarehouse.v1.RequestMetadata,
com.google.cloud.contentwarehouse.v1.RequestMetadata.Builder,
com.google.cloud.contentwarehouse.v1.RequestMetadataOrBuilder>(
getRequestMetadata(), getParentForChildren(), isClean());
requestMetadata_ = null;
}
return requestMetadataBuilder_;
}
private boolean projectOwner_;
/**
*
*
* <pre>
* For Get Project ACL only. Authorization check for end user will be ignored
* when project_owner=true.
* </pre>
*
* <code>bool project_owner = 3;</code>
*
* @return The projectOwner.
*/
@java.lang.Override
public boolean getProjectOwner() {
return projectOwner_;
}
/**
*
*
* <pre>
* For Get Project ACL only. Authorization check for end user will be ignored
* when project_owner=true.
* </pre>
*
* <code>bool project_owner = 3;</code>
*
* @param value The projectOwner to set.
* @return This builder for chaining.
*/
public Builder setProjectOwner(boolean value) {
projectOwner_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* For Get Project ACL only. Authorization check for end user will be ignored
* when project_owner=true.
* </pre>
*
* <code>bool project_owner = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearProjectOwner() {
bitField0_ = (bitField0_ & ~0x00000004);
projectOwner_ = 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.contentwarehouse.v1.FetchAclRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.contentwarehouse.v1.FetchAclRequest)
private static final com.google.cloud.contentwarehouse.v1.FetchAclRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.contentwarehouse.v1.FetchAclRequest();
}
public static com.google.cloud.contentwarehouse.v1.FetchAclRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<FetchAclRequest> PARSER =
new com.google.protobuf.AbstractParser<FetchAclRequest>() {
@java.lang.Override
public FetchAclRequest 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<FetchAclRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<FetchAclRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.contentwarehouse.v1.FetchAclRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/derby | 33,280 | java/org.apache.derby.engine/org/apache/derby/impl/sql/execute/ScrollInsensitiveResultSet.java | /*
Derby - Class org.apache.derby.impl.sql.execute.ScrollInsensitiveResultSet
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.derby.impl.sql.execute;
import org.apache.derby.shared.common.sanity.SanityManager;
import org.apache.derby.iapi.sql.execute.CursorResultSet;
import org.apache.derby.iapi.sql.execute.ExecRow;
import org.apache.derby.iapi.sql.execute.NoPutResultSet;
import org.apache.derby.iapi.sql.Activation;
import org.apache.derby.iapi.types.RowLocation;
import org.apache.derby.iapi.types.DataValueDescriptor;
import org.apache.derby.shared.common.error.StandardException;
import org.apache.derby.shared.common.reference.SQLState;
import org.apache.derby.iapi.store.access.BackingStoreHashtable;
import org.apache.derby.iapi.sql.execute.RowChanger;
import org.apache.derby.iapi.types.SQLBoolean;
import org.apache.derby.iapi.types.SQLInteger;
/**
*
* Provide insensitive scrolling functionality for the underlying
* result set. We build a disk backed hash table of rows as the
* user scrolls forward, with the position as the key.
*
* For read-only result sets the hash table will containg the
* following columns:
*<pre>
* +-------------------------------+
* | KEY |
* +-------------------------------+
* | Row |
* +-------------------------------+
*</pre>
* where key is the position of the row in the result set and row is the data.
*
* And for updatable result sets it will contain:
* <pre>
* +-------------------------------+
* | KEY | [0]
* +-------------------------------+
* | RowLocation | [POS_ROWLOCATION]
* +-------------------------------+
* | Deleted | [POS_ROWDELETED]
* +-------------------------------+
* | Updated | [POS_ROWUPDATED]
* +-------------------------------+
* | Row | [extraColumns ... n]
* +-------------------------------+
*</pre>
* where key is the position of the row in the result set, rowLocation is
* the row location of that row in the Heap, Deleted indicates whether the
* row has been deleted, Updated indicates whether the row has been updated,
* and row is the data.
*
*/
public class ScrollInsensitiveResultSet extends NoPutResultSetImpl
implements CursorResultSet
{
/*
** Set in constructor and not altered during life of object.
*/
public NoPutResultSet source;
private int sourceRowWidth;
private BackingStoreHashtable ht;
private ExecRow resultRow;
// Scroll tracking
private int positionInSource;
private int currentPosition;
private int lastPosition;
private boolean seenFirst;
private boolean seenLast;
private boolean beforeFirst = true;
private boolean afterLast;
public int numFromHashTable;
public int numToHashTable;
private long maxRows;
private boolean keepAfterCommit;
/* The hash table will contain a different number of extra columns depending
* on whether the result set is updatable or not.
* extraColumns will contain the number of extra columns on the hash table,
* 1 for read-only result sets and LAST_EXTRA_COLUMN + 1 for updatable
* result sets.
*/
private int extraColumns;
/* positionInHashTable is used for getting a row from the hash table. Prior
* to getting the row, positionInHashTable will be set to the desired KEY.
*/
private SQLInteger positionInHashTable;
/* Reference to the target result set. Target is used for updatable result
* sets in order to keep the target result set on the same row as the
* ScrollInsensitiveResultSet.
*/
private CursorResultSet target;
/* If the last row was fetched from the HashTable, updatable result sets
* need to be positioned in the last fetched row before resuming the
* fetch from core.
*/
private boolean needsRepositioning;
/* Position of the different fields in the hash table row for updatable
* result sets
*/
private static final int POS_ROWLOCATION = 1;
private static final int POS_ROWDELETED = 2;
private static final int POS_ROWUPDATED = 3;
private static final int LAST_EXTRA_COLUMN = 3;
/**
* Constructor for a ScrollInsensitiveResultSet
*
* @param source The NoPutResultSet from which to get rows
* to scroll through
* @param activation The activation for this execution
* @param resultSetNumber The resultSetNumber
* @param sourceRowWidth # of columns in the source row
*
* @exception StandardException on error
*/
public ScrollInsensitiveResultSet(NoPutResultSet source,
Activation activation, int resultSetNumber,
int sourceRowWidth,
double optimizerEstimatedRowCount,
double optimizerEstimatedCost) throws StandardException
{
super(activation, resultSetNumber,
optimizerEstimatedRowCount, optimizerEstimatedCost);
this.source = source;
this.sourceRowWidth = sourceRowWidth;
keepAfterCommit = activation.getResultSetHoldability();
maxRows = activation.getMaxRows();
if (SanityManager.DEBUG)
{
SanityManager.ASSERT(maxRows != -1,
"maxRows not expected to be -1");
}
positionInHashTable = new SQLInteger();
needsRepositioning = false;
if (isForUpdate()) {
target = ((CursorActivation)activation).getTargetResultSet();
extraColumns = LAST_EXTRA_COLUMN + 1;
} else {
target = null;
extraColumns = 1;
}
recordConstructorTime();
}
//
// ResultSet interface (leftover from NoPutResultSet)
//
/**
* open a scan on the source. scan parameters are evaluated
* at each open, so there is probably some way of altering
* their values...
*
* @exception StandardException thrown on failure
*/
public void openCore() throws StandardException
{
beginTime = getCurrentTimeMillis();
if (SanityManager.DEBUG)
SanityManager.ASSERT( ! isOpen, "ScrollInsensitiveResultSet already open");
source.openCore();
isOpen = true;
numOpens++;
/* Create the hash table. We pass
* null in as the row source as we will
* build the hash table on demand as
* the user scrolls.
* The 1st column, the position in the
* scan, will be the key column.
*/
final int[] keyCols = new int[] { 0 };
/* We don't use the optimizer row count for this because it could be
* wildly pessimistic. We only use Hash tables when the optimizer row count
* is within certain bounds. We have no alternative for scrolling insensitive
* cursors so we'll just trust that it will fit.
* We need BackingStoreHashtable to actually go to disk when it doesn't fit.
* This is a known limitation.
*/
ht = new BackingStoreHashtable(getTransactionController(),
null,
keyCols,
false,
-1, // don't trust optimizer row count
HashScanResultSet.DEFAULT_MAX_CAPACITY,
HashScanResultSet.DEFAULT_INITIAL_CAPACITY,
HashScanResultSet.DEFAULT_MAX_CAPACITY,
false,
keepAfterCommit);
// When re-using language result sets (DERBY-827) we need to
// reset some member variables to the value they would have
// had in a newly constructed object.
lastPosition = 0;
needsRepositioning = false;
numFromHashTable = 0;
numToHashTable = 0;
positionInSource = 0;
seenFirst = false;
seenLast = false;
maxRows = activation.getMaxRows();
openTime += getElapsedMillis(beginTime);
setBeforeFirstRow();
}
/**
* reopen a scan on the table. scan parameters are evaluated
* at each open, so there is probably some way of altering
* their values...
*
* @exception StandardException thrown if cursor finished.
*/
public void reopenCore() throws StandardException
{
boolean constantEval = true;
beginTime = getCurrentTimeMillis();
if (SanityManager.DEBUG)
{
SanityManager.ASSERT(isOpen, "ScrollInsensitiveResultSet already open");
SanityManager.THROWASSERT(
"reopenCore() not expected to be called");
}
setBeforeFirstRow();
}
/**
* Returns the row at the absolute position from the query,
* and returns NULL when there is no such position.
* (Negative position means from the end of the result set.)
* Moving the cursor to an invalid position leaves the cursor
* positioned either before the first row (negative position)
* or after the last row (positive position).
* NOTE: An exception will be thrown on 0.
*
* @param row The position.
* @return The row at the absolute position, or NULL if no such position.
*
* @exception StandardException Thrown on failure
* @see org.apache.derby.iapi.sql.Row
*/
public ExecRow getAbsoluteRow(int row) throws StandardException
{
if ( ! isOpen )
{
throw StandardException.newException(SQLState.LANG_RESULT_SET_NOT_OPEN, "absolute");
}
attachStatementContext();
if (SanityManager.DEBUG)
{
if (!isTopResultSet)
{
SanityManager.THROWASSERT(
this + "expected to be the top ResultSet");
}
}
// Absolute 0 is defined to be before first!
if (row == 0)
{
setBeforeFirstRow();
return null;
}
if (seenLast && row > lastPosition) {
return setAfterLastRow();
}
if (row > 0)
{
// position is from the start of the result set
if (row <= positionInSource)
{
// We've already seen the row before
return getRowFromHashTable(row);
}
/* We haven't seen the row yet, scan until we find
* it or we get to the end.
*/
int diff = row - positionInSource;
ExecRow result = null;
while (diff > 0)
{
if ((result = getNextRowFromSource()) != null)
{
diff--;
}
else
{
break;
}
}
if (result != null) {
result = getRowFromHashTable(row);
}
currentRow = result;
return result;
}
else if (row < 0)
{
// position is from the end of the result set
// Get the last row, if we haven't already
if (!seenLast)
{
getLastRow();
}
// Note, for negative values position is from beyond the end
// of the result set, e.g. absolute(-1) points to the last row
int beyondResult = lastPosition + 1;
if (beyondResult + row > 0)
{
// valid row
return getRowFromHashTable(beyondResult + row);
}
else
{
// position before the beginning of the result set
return setBeforeFirstRow();
}
}
currentRow = null;
return null;
}
/**
* Returns the row at the relative position from the current
* cursor position, and returns NULL when there is no such position.
* (Negative position means toward the beginning of the result set.)
* Moving the cursor to an invalid position leaves the cursor
* positioned either before the first row (negative position)
* or after the last row (positive position).
* NOTE: 0 is valid.
* NOTE: An exception is thrown if the cursor is not currently
* positioned on a row.
*
* @param row The position.
* @return The row at the relative position, or NULL if no such position.
*
* @exception StandardException Thrown on failure
* @see org.apache.derby.iapi.sql.Row
*/
public ExecRow getRelativeRow(int row) throws StandardException
{
if ( ! isOpen )
{
throw StandardException.newException(SQLState.LANG_RESULT_SET_NOT_OPEN, "relative");
}
attachStatementContext();
if (SanityManager.DEBUG)
{
if (!isTopResultSet)
{
SanityManager.THROWASSERT(
this + "expected to be the top ResultSet");
}
}
// Return the current row for 0
if (row == 0)
{
if (beforeFirst || afterLast || currentPosition==0) {
return null;
} else {
return getRowFromHashTable(currentPosition);
}
}
else if (row > 0)
{
return getAbsoluteRow(currentPosition + row);
}
else
{
// row < 0
if (currentPosition + row < 0)
{
return setBeforeFirstRow();
}
return getAbsoluteRow(currentPosition + row);
}
}
/**
* Sets the current position to before the first row and returns NULL
* because there is no current row.
*
* @return NULL.
*
* @see org.apache.derby.iapi.sql.Row
*/
public ExecRow setBeforeFirstRow()
{
currentPosition = 0;
beforeFirst = true;
afterLast = false;
currentRow = null;
return null;
}
/**
* Returns the first row from the query, and returns NULL when there
* are no rows.
*
* @return The first row, or NULL if no rows.
*
* @exception StandardException Thrown on failure
* @see org.apache.derby.iapi.sql.Row
*/
public ExecRow getFirstRow()
throws StandardException
{
if ( ! isOpen )
{
throw StandardException.newException(SQLState.LANG_RESULT_SET_NOT_OPEN, "first");
}
/* Get the row from the hash table if
* we have already seen it before.
*/
if (seenFirst)
{
return getRowFromHashTable(1);
}
attachStatementContext();
if (SanityManager.DEBUG)
{
if (!isTopResultSet)
{
SanityManager.THROWASSERT(
this + "expected to be the top ResultSet");
}
}
return getNextRowCore();
}
/**
*
* @exception StandardException thrown on failure
*/
public ExecRow getNextRowCore() throws StandardException
{
if( isXplainOnlyMode() )
return null;
ExecRow result = null;
beginTime = getCurrentTimeMillis();
if (!isOpen)
throw StandardException.newException(SQLState.LANG_RESULT_SET_NOT_OPEN, "next");
if (seenLast && currentPosition == lastPosition) {
return setAfterLastRow();
}
/* Should we get the next row from the source or the hash table? */
if (currentPosition == positionInSource)
{
/* Current position is same as position in source.
* Get row from the source.
*/
result = getNextRowFromSource();
if (result !=null) {
result = getRowFromHashTable(currentPosition);
}
}
else if (currentPosition < positionInSource)
{
/* Current position is before position in source.
* Get row from the hash table.
*/
result = getRowFromHashTable(currentPosition + 1);
}
else
{
result = null;
}
if (result != null)
{
rowsSeen++;
afterLast = false;
}
setCurrentRow(result);
beforeFirst = false;
nextTime += getElapsedMillis(beginTime);
return result;
}
/**
* Returns the previous row from the query, and returns NULL when there
* are no more previous rows.
*
* @return The previous row, or NULL if no more previous rows.
*
* @exception StandardException Thrown on failure
* @see org.apache.derby.iapi.sql.Row
*/
public ExecRow getPreviousRow()
throws StandardException
{
if ( ! isOpen )
{
throw StandardException.newException(SQLState.LANG_RESULT_SET_NOT_OPEN, "previous");
}
if (SanityManager.DEBUG)
{
if (!isTopResultSet)
{
SanityManager.THROWASSERT(
this + "expected to be the top ResultSet");
}
}
/* No row if we are positioned before the first row
* or the result set is empty.
*/
if (beforeFirst || currentPosition == 0)
{
currentRow = null;
return null;
}
// Get the last row, if we are after it
if (afterLast)
{
// Special case for empty tables
if (lastPosition == 0)
{
afterLast = false;
beforeFirst = false;
currentRow = null;
return null;
}
else
{
return getRowFromHashTable(lastPosition);
}
}
// Move back 1
currentPosition--;
if (currentPosition == 0)
{
setBeforeFirstRow();
return null;
}
return getRowFromHashTable(currentPosition);
}
/**
* Returns the last row from the query, and returns NULL when there
* are no rows.
*
* @return The last row, or NULL if no rows.
*
* @exception StandardException Thrown on failure
* @see org.apache.derby.iapi.sql.Row
*/
public ExecRow getLastRow()
throws StandardException
{
if ( ! isOpen )
{
throw StandardException.newException(SQLState.LANG_RESULT_SET_NOT_OPEN, "next");
}
if (!seenLast)
{
attachStatementContext();
if (SanityManager.DEBUG)
{
if (!isTopResultSet)
{
SanityManager.THROWASSERT(
this + "expected to be the top ResultSet");
}
}
/* Scroll to the end, filling the hash table as
* we scroll, and return the last row that we find.
*/
ExecRow result = null;
while ((result = getNextRowFromSource()) != null);
}
if (SanityManager.DEBUG && !seenLast)
{
SanityManager.THROWASSERT(this + "expected to have seen last");
}
beforeFirst = false;
afterLast = false;
// Special case if table is empty
if (lastPosition == 0)
{
currentRow = null;
return null;
}
else
{
return getRowFromHashTable(lastPosition);
}
}
/**
* Sets the current position to after the last row and returns NULL
* because there is no current row.
*
* @return NULL.
*
* @exception StandardException Thrown on failure
* @see org.apache.derby.iapi.sql.Row
*/
public ExecRow setAfterLastRow()
throws StandardException
{
if (! seenLast)
{
getLastRow();
}
if (lastPosition == 0) {
// empty rs special case
currentPosition = 0;
afterLast = false;
} else {
currentPosition = lastPosition + 1;
afterLast = true;
}
beforeFirst = false;
currentRow = null;
return null;
}
/**
* Determine if the cursor is before the first row in the result
* set.
*
* @return true if before the first row, false otherwise. Returns
* false when the result set contains no rows.
* @exception StandardException Thrown on error.
*/
public boolean checkRowPosition(int isType) throws StandardException
{
switch (isType) {
case ISBEFOREFIRST:
if (! beforeFirst)
{
return false;
}
// Spec says to return false if result set is empty
if (seenFirst)
{
return true;
}
else
{
ExecRow firstRow = getFirstRow();
if (firstRow == null)
{
// ResultSet is empty
return false;
}
else
{
// ResultSet is not empty - reset position
getPreviousRow();
return true;
}
}
case ISFIRST:
return (currentPosition == 1);
case ISLAST:
if (beforeFirst || afterLast || currentPosition==0 ||
currentPosition<positionInSource)
{
return false;
}
/* If we have seen the last row, we can tell if we are
* on it by comparing currentPosition with lastPosition.
* Otherwise, we check if there is a next row.
*/
if (seenLast)
{
return (currentPosition == lastPosition);
}
else
{
final int savePosition = currentPosition;
final boolean retval = (getNextRowFromSource() == null);
getRowFromHashTable(savePosition);
return retval;
}
case ISAFTERLAST:
return afterLast;
default:
return false;
}
}
/**
* Returns the row number of the current row. Row
* numbers start from 1 and go to 'n'. Corresponds
* to row numbering used to position current row
* in the result set (as per JDBC).
*
* @return the row number, or 0 if not on a row
*
*/
public int getRowNumber()
{
return currentRow == null ? 0 : currentPosition;
}
/* Get the next row from the source ResultSet tree and insert into the hash table */
private ExecRow getNextRowFromSource() throws StandardException
{
ExecRow sourceRow = null;
ExecRow result = null;
/* Don't give back more rows than requested */
if (maxRows > 0 && maxRows == positionInSource)
{
seenLast = true;
lastPosition = positionInSource;
afterLast = true;
return null;
}
if (needsRepositioning) {
positionInLastFetchedRow();
needsRepositioning = false;
}
sourceRow = source.getNextRowCore();
if (sourceRow != null)
{
seenFirst = true;
beforeFirst = false;
long beginTCTime = getCurrentTimeMillis();
/* If this is the first row from the source then we create a new row
* for use when fetching from the hash table.
*/
if (resultRow == null)
{
resultRow = activation.getExecutionFactory().getValueRow(sourceRowWidth);
}
positionInSource++;
currentPosition = positionInSource;
RowLocation rowLoc = null;
if (source.isForUpdate()) {
rowLoc = ((CursorResultSet)source).getRowLocation();
}
addRowToHashTable(sourceRow, currentPosition, rowLoc, false);
}
// Remember whether or not we're past the end of the table
else
{
if (! seenLast)
{
lastPosition = positionInSource;
}
seenLast = true;
// Special case for empty table (afterLast is never true)
if (positionInSource == 0)
{
afterLast = false;
}
else
{
afterLast = true;
currentPosition = positionInSource + 1;
}
}
return sourceRow;
}
/**
* If the result set has been opened,
* close the open scan.
*
* @exception StandardException thrown on error
*/
public void close() throws StandardException
{
beginTime = getCurrentTimeMillis();
if ( isOpen )
{
currentRow = null;
source.close();
if (ht != null)
{
ht.close();
ht = null;
}
super.close();
}
else
if (SanityManager.DEBUG)
SanityManager.DEBUG("CloseRepeatInfo","Close of ScrollInsensitiveResultSet repeated");
setBeforeFirstRow();
closeTime += getElapsedMillis(beginTime);
}
public void finish() throws StandardException
{
source.finish();
finishAndRTS();
}
/**
* Return the total amount of time spent in this ResultSet
*
* @param type CURRENT_RESULTSET_ONLY - time spent only in this ResultSet
* ENTIRE_RESULTSET_TREE - time spent in this ResultSet and below.
*
* @return long The total amount of time spent (in milliseconds).
*/
public long getTimeSpent(int type)
{
long totTime = constructorTime + openTime + nextTime + closeTime;
if (type == NoPutResultSet.CURRENT_RESULTSET_ONLY)
{
return totTime - source.getTimeSpent(ENTIRE_RESULTSET_TREE);
}
else
{
return totTime;
}
}
//
// CursorResultSet interface
//
/**
* Gets information from its source. We might want
* to have this take a CursorResultSet in its constructor some day,
* instead of doing a cast here?
*
* @see CursorResultSet
*
* @return the row location of the current cursor row.
*
* @exception StandardException thrown on failure
*/
public RowLocation getRowLocation() throws StandardException
{
if (SanityManager.DEBUG)
SanityManager.ASSERT(source instanceof CursorResultSet, "source not CursorResultSet");
return ( (CursorResultSet)source ).getRowLocation();
}
/**
* Gets information from last getNextRow call.
*
* @see CursorResultSet
*
* @return the last row returned.
*/
/* RESOLVE - this should return activation.getCurrentRow(resultSetNumber),
* once there is such a method. (currentRow is redundant)
*/
public ExecRow getCurrentRow() throws StandardException
{
if (isForUpdate() && isDeleted()) {
return null;
} else {
return currentRow;
}
}
//
// class implementation
//
/**
* Add a row to the backing hash table, keyed on position.
* When a row gets updated when using scrollable insensitive updatable
* result sets, the old entry for the row will be deleted from the hash
* table and this method will be called to add the new values for the row
* to the hash table, with the parameter rowUpdated = true so as to mark
* the row as updated. The latter is done in order to implement
* detectability of own changes for result sets of this type.
*
* @param sourceRow The row to add.
* @param position The key
* @param rowLoc The rowLocation of the row to add.
* @param rowUpdated Indicates whether the row has been updated.
*
*/
private void addRowToHashTable(ExecRow sourceRow, int position,
RowLocation rowLoc, boolean rowUpdated)
throws StandardException
{
DataValueDescriptor[] hashRowArray = new
DataValueDescriptor[sourceRowWidth + extraColumns];
// 1st element is the key
hashRowArray[0] = new SQLInteger(position);
if (isForUpdate()) {
hashRowArray[POS_ROWLOCATION] = rowLoc.cloneValue(false);
hashRowArray[POS_ROWDELETED] = new SQLBoolean(false);
hashRowArray[POS_ROWUPDATED] = new SQLBoolean(rowUpdated);
}
/* Copy rest of elements from sourceRow.
* NOTE: We need to clone the source row
* and we do our own cloning since the 1st column
* is not a wrapper.
*/
DataValueDescriptor[] sourceRowArray = sourceRow.getRowArray();
System.arraycopy(sourceRowArray, 0, hashRowArray, extraColumns,
sourceRowArray.length);
ht.putRow(true, hashRowArray, null);
numToHashTable++;
}
/**
* Get the row at the specified position
* from the hash table.
*
* @param position The specified position.
*
* @return The row at that position.
*
* @exception StandardException thrown on failure
*/
private ExecRow getRowFromHashTable(int position)
throws StandardException
{
// Get the row from the hash table
positionInHashTable.setValue(position);
DataValueDescriptor[] hashRowArray = getCurrentRowFromHashtable();
if (SanityManager.DEBUG)
{
SanityManager.ASSERT(hashRowArray != null,
"hashRowArray expected to be non-null");
}
// Copy out the Object[] without the position.
DataValueDescriptor[] resultRowArray = new
DataValueDescriptor[hashRowArray.length - extraColumns];
System.arraycopy(hashRowArray, extraColumns, resultRowArray, 0,
resultRowArray.length);
resultRow.setRowArray(resultRowArray);
// Reset the current position to the user position
currentPosition = position;
numFromHashTable++;
if (resultRow != null)
{
beforeFirst = false;
afterLast = false;
}
if (isForUpdate()) {
RowLocation rowLoc = (RowLocation) hashRowArray[POS_ROWLOCATION];
// Keep source and target with the same currentRow
((NoPutResultSet)target).setCurrentRow(resultRow);
((NoPutResultSet)target).positionScanAtRowLocation(rowLoc);
needsRepositioning = true;
}
setCurrentRow(resultRow);
return resultRow;
}
/**
* Get the row data at the specified position
* from the hash table.
*
* @param position The specified position.
*
* @return The row data at that position.
*
* @exception StandardException thrown on failure
*/
private DataValueDescriptor[] getRowArrayFromHashTable(int position)
throws StandardException
{
positionInHashTable.setValue(position);
final DataValueDescriptor[] hashRowArray = getCurrentRowFromHashtable();
// Copy out the Object[] without the position.
final DataValueDescriptor[] resultRowArray = new
DataValueDescriptor[hashRowArray.length - extraColumns];
System.arraycopy(hashRowArray, extraColumns, resultRowArray, 0,
resultRowArray.length);
return resultRowArray;
}
/**
* Positions the cursor in the last fetched row. This is done before
* navigating to a row that has not previously been fetched, so that
* getNextRowCore() will re-start from where it stopped.
*/
private void positionInLastFetchedRow() throws StandardException {
if (positionInSource > 0) {
positionInHashTable.setValue(positionInSource);
DataValueDescriptor[] hashRowArray = getCurrentRowFromHashtable();
RowLocation rowLoc = (RowLocation) hashRowArray[POS_ROWLOCATION];
((NoPutResultSet)target).positionScanAtRowLocation(rowLoc);
currentPosition = positionInSource;
}
}
/**
* @see NoPutResultSet#updateRow
*
* Sets the updated column of the hash table to true and updates the row
* in the hash table with the new values for the row.
*/
public void updateRow(ExecRow row, RowChanger rowChanger)
throws StandardException {
ProjectRestrictResultSet prRS = null;
if (source instanceof ProjectRestrictResultSet) {
prRS = (ProjectRestrictResultSet)source;
} else if (source instanceof RowCountResultSet) {
// To do any projection in the presence of an intervening
// RowCountResultSet, we get its child.
prRS = ((RowCountResultSet)source).getUnderlyingProjectRestrictRS();
}
positionInHashTable.setValue(currentPosition);
DataValueDescriptor[] hashRowArray = getCurrentRowFromHashtable();
RowLocation rowLoc = (RowLocation) hashRowArray[POS_ROWLOCATION];
// Maps from each selected column to underlying base table column
// number, i.e. as from getBaseProjectMapping if a PRN exists, if not
// we construct one, so we always know where in the hash table a
// modified column will need to go (we do our own projection).
int[] map;
if (prRS != null) {
map = prRS.getBaseProjectMapping();
} else {
// create a natural projection mapping for all columns in SELECT
// list so we can treat the cases of no PRN and PRN the same.
int noOfSelectedColumns =
hashRowArray.length - (LAST_EXTRA_COLUMN+1);
map = new int[noOfSelectedColumns];
// initialize as 1,2,3, .. n which we know is correct since there
// is no underlying PRN.
for (int i=0; i < noOfSelectedColumns; i++) {
map[i] = i+1; // column is 1-based
}
}
// Construct a new row based on the old one and the updated columns
ExecRow newRow = new ValueRow(map.length);
for (int i=0; i < map.length; i++) {
// What index in ExecRow "row" corresponds to this position in the
// hash table, if any?
int rowColumn = rowChanger.findSelectedCol(map[i]);
if (rowColumn > 0) {
// OK, a new value has been supplied, use it
newRow.setColumn(i+1, row.getColumn(rowColumn));
} else {
// No new value, so continue using old one
newRow.setColumn(i+1, hashRowArray[LAST_EXTRA_COLUMN + 1 + i]);
}
}
ht.remove(new SQLInteger(currentPosition));
addRowToHashTable(newRow, currentPosition, rowLoc, true);
// Modify row to refer to data in the BackingStoreHashtable.
// This allows reading of data which goes over multiple pages
// when doing the actual update (LOBs). Putting columns of
// type SQLBinary to disk, has destructive effect on the columns,
// and they need to be re-read. That is the reason this is needed.
DataValueDescriptor[] backedData =
getRowArrayFromHashTable(currentPosition);
for (int i=0; i < map.length; i++) {
// What index in "row" corresponds to this position in the table,
// if any?
int rowColumn = rowChanger.findSelectedCol(map[i]);
if (rowColumn > 0) {
// OK, put the value in the hash table back to row.
row.setColumn(rowColumn, backedData[i]);
}
}
}
/**
* @see NoPutResultSet#markRowAsDeleted
*
* Sets the deleted column of the hash table to true in the current row.
*/
public void markRowAsDeleted() throws StandardException {
positionInHashTable.setValue(currentPosition);
DataValueDescriptor[] hashRowArray = getCurrentRowFromHashtable();
RowLocation rowLoc = (RowLocation) hashRowArray[POS_ROWLOCATION];
ht.remove(new SQLInteger(currentPosition));
((SQLBoolean)hashRowArray[POS_ROWDELETED]).setValue(true);
// Set all columns to NULL, the row is now a placeholder
for (int i=extraColumns; i<hashRowArray.length; i++) {
hashRowArray[i].setToNull();
}
ht.putRow(true, hashRowArray, null);
}
/**
* Returns TRUE if the row was been deleted within the transaction,
* otherwise returns FALSE
*
* @return True if the row has been deleted, otherwise false
*
* @exception StandardException on error
*/
public boolean isDeleted() throws StandardException {
if (currentPosition <= positionInSource && currentPosition > 0) {
positionInHashTable.setValue(currentPosition);
DataValueDescriptor[] hashRowArray = getCurrentRowFromHashtable();
return hashRowArray[POS_ROWDELETED].getBoolean();
}
return false;
}
/**
* Returns TRUE if the row was been updated within the transaction,
* otherwise returns FALSE
*
* @return True if the row has been deleted, otherwise false
*
* @exception StandardException on error
*/
public boolean isUpdated() throws StandardException {
if (currentPosition <= positionInSource && currentPosition > 0) {
positionInHashTable.setValue(currentPosition);
DataValueDescriptor[] hashRowArray = getCurrentRowFromHashtable();
return hashRowArray[POS_ROWUPDATED].getBoolean();
}
return false;
}
public boolean isForUpdate() {
return source.isForUpdate();
}
/** Get the column array from the current position in the hash table */
private DataValueDescriptor[] getCurrentRowFromHashtable()
throws StandardException
{
return unpackHashValue( ht.get(positionInHashTable) );
}
}
|
apache/ofbiz | 35,816 | framework/entityext/src/main/java/org/apache/ofbiz/entityext/synchronization/EntitySyncServices.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.entityext.synchronization;
import static org.apache.ofbiz.base.util.UtilGenerics.checkList;
import java.io.IOException;
import java.net.URL;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.ofbiz.base.util.Debug;
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.UtilURL;
import org.apache.ofbiz.base.util.UtilValidate;
import org.apache.ofbiz.base.util.UtilXml;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.DelegatorFactory;
import org.apache.ofbiz.entity.GenericEntity;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.condition.EntityCondition;
import org.apache.ofbiz.entity.condition.EntityOperator;
import org.apache.ofbiz.entity.model.ModelEntity;
import org.apache.ofbiz.entity.serialize.SerializeException;
import org.apache.ofbiz.entity.serialize.XmlSerializer;
import org.apache.ofbiz.entity.util.EntityQuery;
import org.apache.ofbiz.entityext.synchronization.EntitySyncContext.SyncAbortException;
import org.apache.ofbiz.entityext.synchronization.EntitySyncContext.SyncErrorException;
import org.apache.ofbiz.service.DispatchContext;
import org.apache.ofbiz.service.GenericServiceException;
import org.apache.ofbiz.service.LocalDispatcher;
import org.apache.ofbiz.service.ServiceUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import com.ibm.icu.util.Calendar;
/**
* Entity Engine Sync Services
*/
public class EntitySyncServices {
public static final String module = EntitySyncServices.class.getName();
public static final String resource = "EntityExtUiLabels";
/**
* Run an Entity Sync (checks to see if other already running, etc)
*@param dctx The DispatchContext that this service is operating in
*@param context Map containing the input parameters
*@return Map with the result of the service, the output parameters
*/
public static Map<String, Object> runEntitySync(DispatchContext dctx, Map<String, ? extends Object> context) {
Locale locale = (Locale) context.get("locale");
EntitySyncContext esc = null;
try {
esc = new EntitySyncContext(dctx, context);
if ("Y".equals(esc.entitySync.get("forPullOnly"))) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtCannotDoEntitySyncPush", locale));
}
esc.runPushStartRunning();
// increment starting time to run until now
esc.setSplitStartTime(); // just run this the first time, will be updated between each loop automatically
while (esc.hasMoreTimeToSync()) {
// this will result in lots of log messages, so leaving commented out unless needed/wanted later
// Debug.logInfo("Doing runEntitySync split, currentRunStartTime=" + esc.currentRunStartTime + ", currentRunEndTime=" + esc.currentRunEndTime, module);
esc.totalSplits++;
// tx times are indexed
// keep track of how long these sync runs take and store that info on the history table
// saves info about removed, all entities that don't have no-auto-stamp set, this will be done in the GenericDAO like the stamp sets
// ===== INSERTS =====
ArrayList<GenericValue> valuesToCreate = esc.assembleValuesToCreate();
// ===== UPDATES =====
ArrayList<GenericValue> valuesToStore = esc.assembleValuesToStore();
// ===== DELETES =====
List<GenericEntity> keysToRemove = esc.assembleKeysToRemove();
esc.runPushSendData(valuesToCreate, valuesToStore, keysToRemove);
esc.saveResultsReportedFromDataStore();
esc.advanceRunTimes();
}
esc.saveFinalSyncResults();
} catch (SyncAbortException e) {
return e.returnError(module);
} catch (SyncErrorException e) {
e.saveSyncErrorInfo(esc);
return e.returnError(module);
}
return ServiceUtil.returnSuccess();
}
/**
* Store Entity Sync Data
*@param dctx The DispatchContext that this service is operating in
*@param context Map containing the input parameters
*@return Map with the result of the service, the output parameters
*/
public static Map<String, Object> storeEntitySyncData(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
String overrideDelegatorName = (String) context.get("delegatorName");
Locale locale = (Locale) context.get("locale");
if (UtilValidate.isNotEmpty(overrideDelegatorName)) {
delegator = DelegatorFactory.getDelegator(overrideDelegatorName);
if (delegator == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtCannotFindDelegator", UtilMisc.toMap("overrideDelegatorName", overrideDelegatorName), locale));
}
}
//LocalDispatcher dispatcher = dctx.getDispatcher();
String entitySyncId = (String) context.get("entitySyncId");
// incoming lists will already be sorted by lastUpdatedStamp (or lastCreatedStamp)
List<GenericValue> valuesToCreate = UtilGenerics.cast(context.get("valuesToCreate"));
List<GenericValue> valuesToStore = UtilGenerics.cast(context.get("valuesToStore"));
List<GenericEntity> keysToRemove = UtilGenerics.cast(context.get("keysToRemove"));
if (Debug.infoOn()) Debug.logInfo("Running storeEntitySyncData (" + entitySyncId + ") - [" + valuesToCreate.size() + "] to create; [" + valuesToStore.size() + "] to store; [" + keysToRemove.size() + "] to remove.", module);
try {
long toCreateInserted = 0;
long toCreateUpdated = 0;
long toCreateNotUpdated = 0;
long toStoreInserted = 0;
long toStoreUpdated = 0;
long toStoreNotUpdated = 0;
long toRemoveDeleted = 0;
long toRemoveAlreadyDeleted = 0;
// create all values in the valuesToCreate List; if the value already exists update it, or if exists and was updated more recently than this one dont update it
for (GenericValue valueToCreate : valuesToCreate) {
// to Create check if exists (find by pk), if not insert; if exists check lastUpdatedStamp: if null or before the candidate value insert, otherwise don't insert
// NOTE: use the delegator from this DispatchContext rather than the one named in the GenericValue
// maintain the original timestamps when doing storage of synced data, by default with will update the timestamps to now
valueToCreate.setIsFromEntitySync(true);
// check to make sure all foreign keys are created; if not create dummy values as place holders
valueToCreate.checkFks(true);
GenericValue existingValue = EntityQuery.use(delegator)
.from(valueToCreate.getEntityName())
.where(valueToCreate.getPrimaryKey())
.queryOne();
if (existingValue == null) {
delegator.create(valueToCreate);
toCreateInserted++;
} else {
// if the existing value has a stamp field that is AFTER the stamp on the valueToCreate, don't update it
if (existingValue.get(ModelEntity.STAMP_FIELD) != null && existingValue.getTimestamp(ModelEntity.STAMP_FIELD).after(valueToCreate.getTimestamp(ModelEntity.STAMP_FIELD))) {
toCreateNotUpdated++;
} else {
delegator.store(valueToCreate);
toCreateUpdated++;
}
}
}
// iterate through to store list and store each
for (GenericValue valueToStore : valuesToStore) {
// to store check if exists (find by pk), if not insert; if exists check lastUpdatedStamp: if null or before the candidate value insert, otherwise don't insert
// maintain the original timestamps when doing storage of synced data, by default with will update the timestamps to now
valueToStore.setIsFromEntitySync(true);
// check to make sure all foreign keys are created; if not create dummy values as place holders
valueToStore.checkFks(true);
GenericValue existingValue = EntityQuery.use(delegator)
.from(valueToStore.getEntityName())
.where(valueToStore.getPrimaryKey())
.queryOne();
if (existingValue == null) {
delegator.create(valueToStore);
toStoreInserted++;
} else {
// if the existing value has a stamp field that is AFTER the stamp on the valueToStore, don't update it
if (existingValue.get(ModelEntity.STAMP_FIELD) != null && existingValue.getTimestamp(ModelEntity.STAMP_FIELD).after(valueToStore.getTimestamp(ModelEntity.STAMP_FIELD))) {
toStoreNotUpdated++;
} else {
delegator.store(valueToStore);
toStoreUpdated++;
}
}
}
// iterate through to remove list and remove each
for (GenericEntity pkToRemove : keysToRemove) {
// check to see if it exists, if so remove and count, if not just count already removed
// always do a removeByAnd, if it was a removeByAnd great, if it was a removeByPrimaryKey, this will also work and save us a query
pkToRemove.setIsFromEntitySync(true);
// remove the stamp fields inserted by EntitySyncContext.java at or near line 646
pkToRemove.remove(ModelEntity.STAMP_TX_FIELD);
pkToRemove.remove(ModelEntity.STAMP_FIELD);
pkToRemove.remove(ModelEntity.CREATE_STAMP_TX_FIELD);
pkToRemove.remove(ModelEntity.CREATE_STAMP_FIELD);
int numRemByAnd = delegator.removeByAnd(pkToRemove.getEntityName(), pkToRemove);
if (numRemByAnd == 0) {
toRemoveAlreadyDeleted++;
} else {
toRemoveDeleted++;
}
}
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("toCreateInserted", Long.valueOf(toCreateInserted));
result.put("toCreateUpdated", Long.valueOf(toCreateUpdated));
result.put("toCreateNotUpdated", Long.valueOf(toCreateNotUpdated));
result.put("toStoreInserted", Long.valueOf(toStoreInserted));
result.put("toStoreUpdated", Long.valueOf(toStoreUpdated));
result.put("toStoreNotUpdated", Long.valueOf(toStoreNotUpdated));
result.put("toRemoveDeleted", Long.valueOf(toRemoveDeleted));
result.put("toRemoveAlreadyDeleted", Long.valueOf(toRemoveAlreadyDeleted));
if (Debug.infoOn()) Debug.logInfo("Finisching storeEntitySyncData (" + entitySyncId + ") - [" + keysToRemove.size() + "] to remove. Actually removed: " + toRemoveDeleted + " already removed: " + toRemoveAlreadyDeleted, module);
return result;
} catch (GenericEntityException e) {
Debug.logError(e, "Exception saving Entity Sync Data for entitySyncId [" + entitySyncId + "]: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtExceptionSavingEntitySyncData", UtilMisc.toMap("entitySyncId", entitySyncId, "errorString", e.toString()), locale));
} catch (Throwable t) {
Debug.logError(t, "Error saving Entity Sync Data for entitySyncId [" + entitySyncId + "]: " + t.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtErrorSavingEntitySyncData", UtilMisc.toMap("entitySyncId", entitySyncId, "errorString", t.toString()), locale));
}
}
/**
* Run Pull Entity Sync - Pull From Remote
*@param dctx The DispatchContext that this service is operating in
*@param context Map containing the input parameters
*@return Map with the result of the service, the output parameters
*/
public static Map<String, Object> runPullEntitySync(DispatchContext dctx, Map<String, Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Locale locale = (Locale) context.get("locale");
String entitySyncId = (String) context.get("entitySyncId");
String remotePullAndReportEntitySyncDataName = (String) context.get("remotePullAndReportEntitySyncDataName");
Debug.logInfo("Running runPullEntitySync for entitySyncId=" + context.get("entitySyncId"), module);
// loop until no data is returned to store
boolean gotMoreData = true;
Timestamp startDate = null;
Long toCreateInserted = null;
Long toCreateUpdated = null;
Long toCreateNotUpdated = null;
Long toStoreInserted = null;
Long toStoreUpdated = null;
Long toStoreNotUpdated = null;
Long toRemoveDeleted = null;
Long toRemoveAlreadyDeleted = null;
while (gotMoreData) {
gotMoreData = false;
// call pullAndReportEntitySyncData, initially with no results, then with results from last loop
Map<String, Object> remoteCallContext = new HashMap<String, Object>();
remoteCallContext.put("entitySyncId", entitySyncId);
remoteCallContext.put("delegatorName", context.get("remoteDelegatorName"));
remoteCallContext.put("userLogin", context.get("userLogin"));
remoteCallContext.put("startDate", startDate);
remoteCallContext.put("toCreateInserted", toCreateInserted);
remoteCallContext.put("toCreateUpdated", toCreateUpdated);
remoteCallContext.put("toCreateNotUpdated", toCreateNotUpdated);
remoteCallContext.put("toStoreInserted", toStoreInserted);
remoteCallContext.put("toStoreUpdated", toStoreUpdated);
remoteCallContext.put("toStoreNotUpdated", toStoreNotUpdated);
remoteCallContext.put("toRemoveDeleted", toRemoveDeleted);
remoteCallContext.put("toRemoveAlreadyDeleted", toRemoveAlreadyDeleted);
try {
Map<String, Object> result = dispatcher.runSync(remotePullAndReportEntitySyncDataName, remoteCallContext);
if (ServiceUtil.isError(result)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtErrorCallingRemotePull", UtilMisc.toMap("remotePullAndReportEntitySyncDataName", remotePullAndReportEntitySyncDataName), locale), null, null, result);
}
startDate = (Timestamp) result.get("startDate");
try {
// store data returned, get results (just call storeEntitySyncData locally, get the numbers back and boom shakalaka)
// anything to store locally?
if (startDate != null && (UtilValidate.isNotEmpty(result.get("valuesToCreate")) ||
UtilValidate.isNotEmpty(result.get("valuesToStore")) ||
UtilValidate.isNotEmpty(result.get("keysToRemove")))) {
// yep, we got more data
gotMoreData = true;
// at least one of the is not empty, make sure none of them are null now too...
List<GenericValue> valuesToCreate = checkList(result.get("valuesToCreate"), GenericValue.class);
if (valuesToCreate == null) valuesToCreate = Collections.emptyList();
List<GenericValue> valuesToStore = checkList(result.get("valuesToStore"), GenericValue.class);
if (valuesToStore == null) valuesToStore = Collections.emptyList();
List<GenericEntity> keysToRemove = checkList(result.get("keysToRemove"), GenericEntity.class);
if (keysToRemove == null) keysToRemove = Collections.emptyList();
Map<String, Object> callLocalStoreContext = UtilMisc.toMap("entitySyncId", entitySyncId, "delegatorName", context.get("localDelegatorName"),
"valuesToCreate", valuesToCreate, "valuesToStore", valuesToStore,
"keysToRemove", keysToRemove);
callLocalStoreContext.put("userLogin", context.get("userLogin"));
Map<String, Object> storeResult = dispatcher.runSync("storeEntitySyncData", callLocalStoreContext);
if (ServiceUtil.isError(storeResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtErrorCallingService", locale), null, null, storeResult);
}
// get results for next pass
toCreateInserted = (Long) storeResult.get("toCreateInserted");
toCreateUpdated = (Long) storeResult.get("toCreateUpdated");
toCreateNotUpdated = (Long) storeResult.get("toCreateNotUpdated");
toStoreInserted = (Long) storeResult.get("toStoreInserted");
toStoreUpdated = (Long) storeResult.get("toStoreUpdated");
toStoreNotUpdated = (Long) storeResult.get("toStoreNotUpdated");
toRemoveDeleted = (Long) storeResult.get("toRemoveDeleted");
toRemoveAlreadyDeleted = (Long) storeResult.get("toRemoveAlreadyDeleted");
}
} catch (GenericServiceException e) {
Debug.logError(e, "Error calling service to store data locally: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtErrorCallingService", locale) + e.toString());
}
} catch (GenericServiceException e) {
Debug.logError(e, "Exception calling remote pull and report EntitySync service with name: " + remotePullAndReportEntitySyncDataName + "; " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtErrorCallingRemotePull", UtilMisc.toMap("remotePullAndReportEntitySyncDataName", remotePullAndReportEntitySyncDataName), locale) + e.toString());
} catch (Throwable t) {
Debug.logError(t, "Error calling remote pull and report EntitySync service with name: " + remotePullAndReportEntitySyncDataName + "; " + t.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtErrorCallingRemotePull", UtilMisc.toMap("remotePullAndReportEntitySyncDataName", remotePullAndReportEntitySyncDataName), locale) + t.toString());
}
}
return ServiceUtil.returnSuccess();
}
/**
* Pull and Report Entity Sync Data - Called Remotely to Push Results from last pull, the Pull next set of results.
*@param dctx The DispatchContext that this service is operating in
*@param context Map containing the input parameters
*@return Map with the result of the service, the output parameters
*/
public static Map<String, Object> pullAndReportEntitySyncData(DispatchContext dctx, Map<String, ? extends Object> context) {
EntitySyncContext esc = null;
Locale locale = (Locale) context.get("locale");
try {
esc = new EntitySyncContext(dctx, context);
Debug.logInfo("Doing pullAndReportEntitySyncData for entitySyncId=" + esc.entitySyncId + ", currentRunStartTime=" + esc.currentRunStartTime + ", currentRunEndTime=" + esc.currentRunEndTime, module);
if ("Y".equals(esc.entitySync.get("forPushOnly"))) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtCannotDoEntitySyncPush", locale));
}
// Part 1: if any results are passed, store the results for the given startDate, update EntitySync, etc
// restore info from last pull, or if no results start new run
esc.runPullStartOrRestoreSavedResults();
// increment starting time to run until now
while (esc.hasMoreTimeToSync()) {
// make sure the following message is commented out before commit:
// Debug.logInfo("(loop)Doing pullAndReportEntitySyncData split, currentRunStartTime=" + esc.currentRunStartTime + ", currentRunEndTime=" + esc.currentRunEndTime, module);
esc.totalSplits++;
// tx times are indexed
// keep track of how long these sync runs take and store that info on the history table
// saves info about removed, all entities that don't have no-auto-stamp set, this will be done in the GenericDAO like the stamp sets
// Part 2: get the next set of data for the given entitySyncId
// Part 2a: return it back for storage but leave the EntitySyncHistory without results, and don't update the EntitySync last time
// ===== INSERTS =====
ArrayList<GenericValue> valuesToCreate = esc.assembleValuesToCreate();
// ===== UPDATES =====
ArrayList<GenericValue> valuesToStore = esc.assembleValuesToStore();
// ===== DELETES =====
List<GenericEntity> keysToRemove = esc.assembleKeysToRemove();
esc.setTotalRowCounts(valuesToCreate, valuesToStore, keysToRemove);
if (Debug.infoOn()) Debug.logInfo("Service pullAndReportEntitySyncData returning - [" + valuesToCreate.size() + "] to create; [" + valuesToStore.size() + "] to store; [" + keysToRemove.size() + "] to remove; [" + esc.totalRowsPerSplit + "] total rows per split.", module);
if (esc.totalRowsPerSplit > 0) {
// stop if we found some data, otherwise look and try again
Map<String, Object> result = ServiceUtil.returnSuccess();
result.put("startDate", esc.startDate);
result.put("valuesToCreate", valuesToCreate);
result.put("valuesToStore", valuesToStore);
result.put("keysToRemove", keysToRemove);
return result;
} else {
// save the progress to EntitySync and EntitySyncHistory, and move on...
esc.saveResultsReportedFromDataStore();
esc.advanceRunTimes();
}
}
// if no more results from database to return, save final settings
if (!esc.hasMoreTimeToSync()) {
esc.saveFinalSyncResults();
}
} catch (SyncAbortException e) {
return e.returnError(module);
} catch (SyncErrorException e) {
e.saveSyncErrorInfo(esc);
return e.returnError(module);
}
return ServiceUtil.returnSuccess();
}
public static Map<String, Object> runOfflineEntitySync(DispatchContext dctx, Map<String, ? extends Object> context) {
String fileName = (String) context.get("fileName");
EntitySyncContext esc = null;
long totalRowsExported = 0;
try {
esc = new EntitySyncContext(dctx, context);
Debug.logInfo("Doing runManualEntitySync for entitySyncId=" + esc.entitySyncId + ", currentRunStartTime=" + esc.currentRunStartTime + ", currentRunEndTime=" + esc.currentRunEndTime, module);
Document mainDoc = UtilXml.makeEmptyXmlDocument("xml-entity-synchronization");
Element docElement = mainDoc.getDocumentElement();
docElement.setAttribute("xml:lang", "en-US");
esc.runOfflineStartRunning();
// increment starting time to run until now
esc.setSplitStartTime(); // just run this the first time, will be updated between each loop automatically
while (esc.hasMoreTimeToSync()) {
esc.totalSplits++;
ArrayList<GenericValue> valuesToCreate = esc.assembleValuesToCreate();
ArrayList<GenericValue> valuesToStore = esc.assembleValuesToStore();
List<GenericEntity> keysToRemove = esc.assembleKeysToRemove();
long currentRows = esc.setTotalRowCounts(valuesToCreate, valuesToStore, keysToRemove);
totalRowsExported += currentRows;
if (currentRows > 0) {
// create the XML document
Element syncElement = UtilXml.addChildElement(docElement, "entity-sync", mainDoc);
syncElement.setAttribute("entitySyncId", esc.entitySyncId);
syncElement.setAttribute("lastSuccessfulSynchTime", esc.currentRunEndTime.toString());
// serialize the list data for XML storage
try {
UtilXml.addChildElementValue(syncElement, "values-to-create", XmlSerializer.serialize(valuesToCreate), mainDoc);
UtilXml.addChildElementValue(syncElement, "values-to-store", XmlSerializer.serialize(valuesToStore), mainDoc);
UtilXml.addChildElementValue(syncElement, "keys-to-remove", XmlSerializer.serialize(keysToRemove), mainDoc);
} catch (SerializeException e) {
throw new EntitySyncContext.SyncOtherErrorException("List serialization problem", e);
} catch (IOException e) {
throw new EntitySyncContext.SyncOtherErrorException("XML writing problem", e);
}
}
// update the result info
esc.runSaveOfflineSyncInfo(currentRows);
esc.advanceRunTimes();
}
if (totalRowsExported > 0) {
// check the file name; use a default if none is passed in
if (UtilValidate.isEmpty(fileName)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
fileName = "offline_entitySync-" + esc.entitySyncId + "-" + sdf.format(new Date()) + ".xml";
}
// write the XML file
try {
UtilXml.writeXmlDocument(fileName, mainDoc);
} catch (java.io.FileNotFoundException e) {
throw new EntitySyncContext.SyncOtherErrorException(e);
} catch (java.io.IOException e) {
throw new EntitySyncContext.SyncOtherErrorException(e);
}
} else {
Debug.logInfo("No rows to write; no data exported.", module);
}
// save the final results
esc.saveFinalSyncResults();
} catch (SyncAbortException e) {
return e.returnError(module);
} catch (SyncErrorException e) {
e.saveSyncErrorInfo(esc);
return e.returnError(module);
}
return ServiceUtil.returnSuccess();
}
public static Map<String, Object> loadOfflineSyncData(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String fileName = (String) context.get("xmlFileName");
Locale locale = (Locale) context.get("locale");
URL xmlFile = UtilURL.fromResource(fileName);
if (xmlFile != null) {
Document xmlSyncDoc = null;
try {
xmlSyncDoc = UtilXml.readXmlDocument(xmlFile, false);
} catch (SAXException e) {
Debug.logError(e, module);
} catch (ParserConfigurationException e) {
Debug.logError(e, module);
} catch (IOException e) {
Debug.logError(e, module);
}
if (xmlSyncDoc == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtEntitySyncXMLDocumentIsNotValid", UtilMisc.toMap("fileName", fileName), locale));
}
List<? extends Element> syncElements = UtilXml.childElementList(xmlSyncDoc.getDocumentElement());
if (syncElements != null) {
for (Element entitySync: syncElements) {
String entitySyncId = entitySync.getAttribute("entitySyncId");
String startTime = entitySync.getAttribute("lastSuccessfulSynchTime");
String createString = UtilXml.childElementValue(entitySync, "values-to-create");
String storeString = UtilXml.childElementValue(entitySync, "values-to-store");
String removeString = UtilXml.childElementValue(entitySync, "keys-to-remove");
// de-serialize the value lists
try {
List<GenericValue> valuesToCreate = checkList(XmlSerializer.deserialize(createString, delegator), GenericValue.class);
List<GenericValue> valuesToStore = checkList(XmlSerializer.deserialize(storeString, delegator), GenericValue.class);
List<GenericEntity> keysToRemove = checkList(XmlSerializer.deserialize(removeString, delegator), GenericEntity.class);
Map<String, Object> storeContext = UtilMisc.toMap("entitySyncId", entitySyncId, "valuesToCreate", valuesToCreate,
"valuesToStore", valuesToStore, "keysToRemove", keysToRemove, "userLogin", userLogin);
// store the value(s)
Map<String, Object> storeResult = dispatcher.runSync("storeEntitySyncData", storeContext);
if (ServiceUtil.isError(storeResult)) {
throw new Exception(ServiceUtil.getErrorMessage(storeResult));
}
// TODO create a response document to send back to the initial sync machine
} catch (GenericServiceException gse) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtUnableToLoadXMLDocument", UtilMisc.toMap("entitySyncId", entitySyncId, "startTime", startTime, "errorString", gse.getMessage()), locale));
} catch (Exception e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtUnableToLoadXMLDocument", UtilMisc.toMap("entitySyncId", entitySyncId, "startTime", startTime, "errorString", e.getMessage()), locale));
}
}
}
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtOfflineXMLFileNotFound", UtilMisc.toMap("fileName", fileName), locale));
}
return ServiceUtil.returnSuccess();
}
public static Map<String, Object> updateOfflineEntitySync(DispatchContext dctx, Map<String, Object> context) {
Locale locale = (Locale) context.get("locale");
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtThisServiceIsNotYetImplemented", locale));
}
/**
* Clean EntitySyncRemove Info
*@param dctx The DispatchContext that this service is operating in
*@param context Map containing the input parameters
*@return Map with the result of the service, the output parameters
*/
public static Map<String, Object> cleanSyncRemoveInfo(DispatchContext dctx, Map<String, ? extends Object> context) {
Debug.logInfo("Running cleanSyncRemoveInfo", module);
Delegator delegator = dctx.getDelegator();
Locale locale = (Locale) context.get("locale");
try {
// find the largest keepRemoveInfoHours value on an EntitySyncRemove and kill everything before that, if none found default to 10 days (240 hours)
double keepRemoveInfoHours = 24;
List<GenericValue> entitySyncRemoveList = EntityQuery.use(delegator).from("EntitySync").queryList();
for (GenericValue entitySyncRemove: entitySyncRemoveList) {
Double curKrih = entitySyncRemove.getDouble("keepRemoveInfoHours");
if (curKrih != null) {
double curKrihVal = curKrih.doubleValue();
if (curKrihVal > keepRemoveInfoHours) {
keepRemoveInfoHours = curKrihVal;
}
}
}
int keepSeconds = (int) Math.floor(keepRemoveInfoHours * 3600);
Calendar nowCal = Calendar.getInstance();
nowCal.setTimeInMillis(System.currentTimeMillis());
nowCal.add(Calendar.SECOND, -keepSeconds);
Timestamp keepAfterStamp = new Timestamp(nowCal.getTimeInMillis());
int numRemoved = delegator.removeByCondition("EntitySyncRemove", EntityCondition.makeCondition(ModelEntity.STAMP_TX_FIELD, EntityOperator.LESS_THAN, keepAfterStamp));
Debug.logInfo("In cleanSyncRemoveInfo removed [" + numRemoved + "] values with TX timestamp before [" + keepAfterStamp + "]", module);
return ServiceUtil.returnSuccess();
} catch (GenericEntityException e) {
Debug.logError(e, "Error cleaning out EntitySyncRemove info: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtErrorCleaningEntitySyncRemove", UtilMisc.toMap("errorString", e.toString()), locale));
}
}
}
|
apache/felix-dev | 35,788 | framework/src/main/java/org/apache/felix/framework/cache/BundleArchive.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.framework.cache;
import java.io.*;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.felix.framework.Logger;
import org.apache.felix.framework.util.WeakZipFileFactory;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.connect.ModuleConnector;
import org.osgi.framework.connect.ConnectModule;
/**
* <p>
* This class is a logical abstraction for a bundle archive. This class,
* combined with <tt>BundleCache</tt> and concrete <tt>BundleRevision</tt>
* subclasses, implement the bundle cache for Felix. The bundle archive
* abstracts the actual bundle content into revisions and the revisions
* provide access to the actual bundle content. When a bundle is
* installed it has one revision associated with its content. Updating a
* bundle adds another revision for the updated content. Any number of
* revisions can be associated with a bundle archive. When the bundle
* (or framework) is refreshed, then all old revisions are purged and only
* the most recent revision is maintained.
* </p>
* <p>
* The content associated with a revision can come in many forms, such as
* a standard JAR file or an exploded bundle directory. The bundle archive
* is responsible for creating all revision instances during invocations
* of the <tt>revise()</tt> method call. Internally, it determines the
* concrete type of revision type by examining the location string as an
* URL. Currently, it supports standard JAR files, referenced JAR files,
* and referenced directories. Examples of each type of URL are, respectively:
* </p>
* <ul>
* <li><tt>http://www.foo.com/bundle.jar</tt></li>
* <li><tt>reference:file:/foo/bundle.jar</tt></li>
* <li><tt>reference:file:/foo/bundle/</tt></li>
* </ul>
* <p>
* The "<tt>reference:</tt>" notation signifies that the resource should be
* used "in place", meaning that they will not be copied. For referenced JAR
* files, some resources may still be copied, such as embedded JAR files or
* native libraries, but for referenced exploded bundle directories, nothing
* will be copied. Currently, reference URLs can only refer to "file:" targets.
* </p>
* @see org.apache.felix.framework.cache.BundleCache
**/
public class BundleArchive
{
public static final transient String FILE_PROTOCOL = "file:";
public static final transient String REFERENCE_PROTOCOL = "reference:";
public static final transient String INPUTSTREAM_PROTOCOL = "inputstream:";
private static final transient String BUNDLE_INFO_FILE = "bundle.info";
private static final transient String REVISION_LOCATION_FILE = "revision.location";
private static final transient String REVISION_DIRECTORY = "version";
private static final transient String DATA_DIRECTORY = "data";
private final Logger m_logger;
private final Map<?,?> m_configMap;
private final WeakZipFileFactory m_zipFactory;
private final File m_archiveRootDir;
private long m_id = -1;
private String m_originalLocation = null;
private int m_persistentState = -1;
private int m_startLevel = -1;
private long m_lastModified = -1;
/**
* The refresh count field is used when generating the bundle revision
* directory name where native libraries are extracted. This is necessary
* because Sun's JVM requires a one-to-one mapping between native libraries
* and class loaders where the native library is uniquely identified by its
* absolute path in the file system. This constraint creates a problem when
* a bundle is refreshed, because it gets a new class loader. Using the
* refresh counter to generate the name of the bundle revision directory
* resolves this problem because each time bundle is refresh, the native
* library will have a unique name. As a result of the unique name, the JVM
* will then reload the native library without a problem.
**/
private long m_refreshCount = -1;
private final ModuleConnector m_connector;
// Maps a Long revision number to a BundleRevision.
private final SortedMap<Long, BundleArchiveRevision> m_revisions
= new TreeMap<>();
/**
* <p>
* This constructor is used for creating new archives when a bundle is
* installed into the framework. Each archive receives a logger, a root
* directory, its associated bundle identifier, the associated bundle
* location string, and an input stream from which to read the bundle
* content. The root directory is where any required state can be
* stored. The input stream may be null, in which case the location is
* used as an URL to the bundle content.
* </p>
* @param logger the logger to be used by the archive.
* @param archiveRootDir the archive root directory for storing state.
* @param id the bundle identifier associated with the archive.
* @param location the bundle location string associated with the archive.
* @param is input stream from which to read the bundle content.
* @throws Exception if any error occurs.
**/
public BundleArchive(Logger logger, Map<?,?> configMap, WeakZipFileFactory zipFactory, ModuleConnector
connectFactory,
File archiveRootDir, long id, int startLevel, String location, InputStream is)
throws Exception
{
m_logger = logger;
m_configMap = configMap;
m_zipFactory = zipFactory;
m_archiveRootDir = archiveRootDir;
m_id = id;
if (m_id <= 0)
{
throw new IllegalArgumentException(
"Bundle ID cannot be less than or equal to zero.");
}
m_originalLocation = location;
m_persistentState = Bundle.INSTALLED;
m_startLevel = startLevel;
m_lastModified = System.currentTimeMillis();
m_refreshCount = 0;
m_connector = connectFactory;
// Save state.
initialize();
// Add a revision for the content.
reviseInternal(false, 0L, m_originalLocation, is);
}
/**
* <p>
* This constructor is called when an archive for a bundle is being
* reconstructed when the framework is restarted. Each archive receives
* a logger, a root directory, and its associated bundle identifier.
* The root directory is where any required state can be stored.
* </p>
* @param logger the logger to be used by the archive.
* @param archiveRootDir the archive root directory for storing state.
* @param configMap configMap for BundleArchive
* @throws Exception if any error occurs.
**/
public BundleArchive(Logger logger, Map<?,?> configMap, WeakZipFileFactory zipFactory, ModuleConnector connectFactory,
File archiveRootDir)
throws Exception
{
m_logger = logger;
m_configMap = configMap;
m_zipFactory = zipFactory;
m_archiveRootDir = archiveRootDir;
readBundleInfo();
// Add a revision number for each revision that exists in the file
// system. The file system might contain more than one revision if
// the bundle was updated in a previous session, but the framework
// was not refreshed; this might happen if the framework did not
// exit cleanly. We must add the existing revisions so that
// they can be properly purged.
// Find the existing revision directories, which will be named like:
// "${REVISION_DIRECTORY)${refresh-count}.${revision-number}"
File[] children = m_archiveRootDir.listFiles();
for (File child : children)
{
if (child.getName().startsWith(REVISION_DIRECTORY)
&& BundleCache.getSecureAction().isFileDirectory(child))
{
// Determine the revision number and add it to the revision map.
int idx = child.getName().lastIndexOf('.');
if (idx > 0)
{
Long revNum = Long.decode(child.getName().substring(idx + 1));
m_revisions.put(revNum, null);
}
}
}
if (m_revisions.isEmpty())
{
throw new Exception(
"No valid revisions in bundle archive directory: "
+ archiveRootDir);
}
// Remove the last revision number since the call to reviseInternal()
// will properly add the most recent bundle revision.
// NOTE: We do not actually need to add a real revision object for the
// older revisions since they will be purged immediately on framework
// startup.
Long currentRevNum = m_revisions.lastKey();
m_revisions.remove(currentRevNum);
String location = getRevisionLocation(currentRevNum);
m_connector = connectFactory;
// Add the revision object for the most recent revision.
reviseInternal(true, currentRevNum, location, null);
}
/**
* <p>
* Returns the bundle identifier associated with this archive.
* </p>
* @return the bundle identifier associated with this archive.
* @throws Exception if any error occurs.
**/
public synchronized long getId() throws Exception
{
return m_id;
}
/**
* <p>
* Returns the location string associated with this archive.
* </p>
* @return the location string associated with this archive.
* @throws Exception if any error occurs.
**/
public synchronized String getLocation() throws Exception
{
return m_originalLocation;
}
/**
* <p>
* Returns the persistent state of this archive. The value returned is
* one of the following: <tt>Bundle.INSTALLED</tt>, <tt>Bundle.ACTIVE</tt>,
* or <tt>Bundle.UNINSTALLED</tt>.
* </p>
* @return the persistent state of this archive.
* @throws Exception if any error occurs.
**/
public synchronized int getPersistentState() throws Exception
{
return m_persistentState;
}
/**
* <p>
* Sets the persistent state of this archive. The value is
* one of the following: <tt>Bundle.INSTALLED</tt>, <tt>Bundle.ACTIVE</tt>,
* or <tt>Bundle.UNINSTALLED</tt>.
* </p>
* @param state the persistent state value to set for this archive.
* @throws Exception if any error occurs.
**/
public synchronized void setPersistentState(int state) throws Exception
{
if (m_persistentState != state)
{
m_persistentState = state;
writeBundleInfo();
}
}
/**
* <p>
* Returns the start level of this archive.
* </p>
* @return the start level of this archive.
* @throws Exception if any error occurs.
**/
public synchronized int getStartLevel() throws Exception
{
return m_startLevel;
}
/**
* <p>
* Sets the the start level of this archive this archive.
* </p>
* @param level the start level to set for this archive.
* @throws Exception if any error occurs.
**/
public synchronized void setStartLevel(int level) throws Exception
{
if (m_startLevel != level)
{
m_startLevel = level;
writeBundleInfo();
}
}
/**
* <p>
* Returns the last modification time of this archive.
* </p>
* @return the last modification time of this archive.
* @throws Exception if any error occurs.
**/
public synchronized long getLastModified() throws Exception
{
return m_lastModified;
}
/**
* <p>
* Sets the the last modification time of this archive.
* </p>
* @param lastModified The time of the last modification to set for
* this archive. According to the OSGi specification this time is
* set each time a bundle is installed, updated or uninstalled.
*
* @throws Exception if any error occurs.
**/
public synchronized void setLastModified(long lastModified) throws Exception
{
if (m_lastModified != lastModified)
{
m_lastModified = lastModified;
writeBundleInfo();
}
}
/**
* This utility method is used to retrieve the current refresh
* counter value for the bundle. This value is used when generating
* the bundle revision directory name where native libraries are extracted.
* This is necessary because Sun's JVM requires a one-to-one mapping
* between native libraries and class loaders where the native library
* is uniquely identified by its absolute path in the file system. This
* constraint creates a problem when a bundle is refreshed, because it
* gets a new class loader. Using the refresh counter to generate the name
* of the bundle revision directory resolves this problem because each time
* bundle is refresh, the native library will have a unique name.
* As a result of the unique name, the JVM will then reload the
* native library without a problem.
**/
private long getRefreshCount() throws Exception
{
return m_refreshCount;
}
/**
* This utility method is used to retrieve the current refresh
* counter value for the bundle. This value is used when generating
* the bundle revision directory name where native libraries are extracted.
* This is necessary because Sun's JVM requires a one-to-one mapping
* between native libraries and class loaders where the native library
* is uniquely identified by its absolute path in the file system. This
* constraint creates a problem when a bundle is refreshed, because it
* gets a new class loader. Using the refresh counter to generate the name
* of the bundle revision directory resolves this problem because each time
* bundle is refresh, the native library will have a unique name.
* As a result of the unique name, the JVM will then reload the
* native library without a problem.
**/
private void setRefreshCount(long count)
throws Exception
{
if (m_refreshCount != count)
{
m_refreshCount = count;
writeBundleInfo();
}
}
/**
* <p>
* Returns a <tt>File</tt> object corresponding to the data file
* of the relative path of the specified string.
* </p>
* @return a <tt>File</tt> object corresponding to the specified file name.
* @throws Exception if any error occurs.
**/
public File getDataFile(String fileName) throws Exception
{
// Get bundle data directory.
File dataDir = new File(m_archiveRootDir, DATA_DIRECTORY);
// Create the data directory if necessary.
if (!BundleCache.getSecureAction().fileExists(dataDir) && !BundleCache.getSecureAction().mkdirs(dataDir) && !BundleCache.getSecureAction().fileExists(dataDir))
{
throw new IOException("Unable to create bundle data directory.");
}
File dataFile = new File(dataDir, fileName);
String dataFilePath = BundleCache.getSecureAction().getCanonicalPath(dataFile);
String dataDirPath = BundleCache.getSecureAction().getCanonicalPath(dataDir);
if (!dataFilePath.equals(dataDirPath) && !dataFilePath.startsWith(dataDirPath + File.separatorChar))
{
throw new IllegalArgumentException("The data file must be inside the data dir.");
}
// Return the data file.
return dataFile;
}
/**
* <p>
* Returns the current revision object for the archive.
* </p>
* @return the current revision object for the archive.
**/
public synchronized Long getCurrentRevisionNumber()
{
return (m_revisions.isEmpty()) ? null : m_revisions.lastKey();
}
/**
* <p>
* Returns the current revision object for the archive.
* </p>
* @return the current revision object for the archive.
**/
public synchronized BundleArchiveRevision getCurrentRevision()
{
return (m_revisions.isEmpty()) ? null : m_revisions.get(m_revisions.lastKey());
}
public synchronized boolean isRemovalPending()
{
return (m_revisions.size() > 1);
}
/**
* <p>
* This method adds a revision to the archive using the associated
* location and input stream. If the input stream is null, then the
* location is used a URL to obtain an input stream.
* </p>
* @param location the location string associated with the revision.
* @param is the input stream from which to read the revision.
* @throws Exception if any error occurs.
**/
public synchronized void revise(String location, InputStream is)
throws Exception
{
Long revNum = (m_revisions.isEmpty())
? 0L
: m_revisions.lastKey().longValue() + 1;
reviseInternal(false, revNum, location, is);
}
/**
* Actually adds a revision to the bundle archive. This method is also
* used to reload cached bundles too. The revision is given the specified
* revision number and is read from the input stream if supplied or from
* the location URL if not.
* @param isReload if the bundle is being reloaded or not.
* @param revNum the revision number of the revision.
* @param location the location associated with the revision.
* @param is the input stream from which to read the revision.
* @throws Exception if any error occurs.
*/
private void reviseInternal(
boolean isReload, Long revNum, String location, InputStream is)
throws Exception
{
// If we have an input stream, then we have to use it
// no matter what the update location is, so just ignore
// the update location and set the location to be input
// stream.
if (is != null)
{
location = "inputstream:";
}
// Create a bundle revision for revision number.
BundleArchiveRevision revision = createRevisionFromLocation(location, is, revNum);
if (revision == null)
{
throw new Exception("Unable to revise archive.");
}
if (!isReload)
{
setRevisionLocation(location, revNum);
}
// Add new revision to revision map.
m_revisions.put(revNum, revision);
}
/**
* <p>
* This method undoes the previous revision to the archive; this method will
* remove the latest revision from the archive. This method is only called
* when there are problems during an update after the revision has been
* created, such as errors in the update bundle's manifest. This method
* can only be called if there is more than one revision, otherwise there
* is nothing to undo.
* </p>
* @return true if the undo was a success false if there is no previous revision
* @throws Exception if any error occurs.
*/
public synchronized boolean rollbackRevise() throws Exception
{
// Can only undo the revision if there is more than one.
if (m_revisions.size() <= 1)
{
return false;
}
Long revNum = m_revisions.lastKey();
BundleArchiveRevision revision = m_revisions.remove(revNum);
try
{
revision.close();
}
catch(Exception ex)
{
m_logger.log(Logger.LOG_ERROR, getClass().getName() +
": Unable to dispose latest revision", ex);
}
File revisionDir = new File(m_archiveRootDir, REVISION_DIRECTORY +
getRefreshCount() + "." + revNum.toString());
if (BundleCache.getSecureAction().fileExists(revisionDir))
{
BundleCache.deleteDirectoryTree(revisionDir);
}
return true;
}
private synchronized String getRevisionLocation(Long revNum) throws Exception
{
InputStream is = null;
BufferedReader br = null;
try
{
is = BundleCache.getSecureAction().getInputStream(new File(
new File(m_archiveRootDir, REVISION_DIRECTORY +
getRefreshCount() + "." + revNum.toString()), REVISION_LOCATION_FILE));
br = new BufferedReader(new InputStreamReader(is));
return br.readLine();
}
finally
{
if (br != null) br.close();
if (is != null) is.close();
}
}
private synchronized void setRevisionLocation(String location, Long revNum)
throws Exception
{
// Save current revision location.
OutputStream os = null;
BufferedWriter bw = null;
try
{
os = BundleCache.getSecureAction()
.getOutputStream(new File(
new File(m_archiveRootDir, REVISION_DIRECTORY +
getRefreshCount() + "." + revNum.toString()), REVISION_LOCATION_FILE));
bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write(location, 0, location.length());
}
finally
{
if (bw != null) bw.close();
if (os != null) os.close();
}
}
public synchronized void close()
{
// Get the current revision count.
for (BundleArchiveRevision revision : m_revisions.values())
{
// Dispose of the revision, but this might be null in certain
// circumstances, such as if this bundle archive was created
// for an existing bundle that was updated, but not refreshed
// due to a system crash; see the constructor code for details.
if (revision != null)
{
try
{
revision.close();
}
catch (Exception ex)
{
m_logger.log(
Logger.LOG_ERROR,
"Unable to close revision - "
+ revision.getRevisionRootDir(), ex);
}
}
}
}
/**
* <p>
* This method closes any revisions and deletes the bundle archive directory.
* </p>
* @throws Exception if any error occurs.
**/
public synchronized void closeAndDelete()
{
// Close the revisions and delete the archive directory.
close();
if (!BundleCache.deleteDirectoryTree(m_archiveRootDir))
{
m_logger.log(
Logger.LOG_ERROR,
"Unable to delete archive directory - " + m_archiveRootDir);
}
}
/**
* <p>
* This method removes all old revisions associated with the archive
* and keeps only the current revision.
* </p>
* @throws Exception if any error occurs.
**/
public synchronized void purge() throws Exception
{
// Remember current revision number.
Long currentRevNum = getCurrentRevisionNumber();
// Record whether the current revision has native libraries, which
// we'll use later to determine if we need to rename its directory.
Map<String, String> headers = getCurrentRevision().getManifestHeader();
boolean hasNativeLibs = headers != null && getCurrentRevision().getManifestHeader()
.containsKey(Constants.BUNDLE_NATIVECODE);
// Close all revisions and then delete all but the current revision.
// We don't delete it the current revision, because we want to rename it
// to the new refresh level.
close();
// Delete all old revisions.
long refreshCount = getRefreshCount();
for (Long revNum : m_revisions.keySet())
{
if (!revNum.equals(currentRevNum))
{
File revisionDir = new File(
m_archiveRootDir,
REVISION_DIRECTORY + refreshCount + "." + revNum.toString());
if (BundleCache.getSecureAction().fileExists(revisionDir))
{
BundleCache.deleteDirectoryTree(revisionDir);
}
}
}
// If the revision has native libraries, then rename its directory
// to avoid the issue of being unable to load the same native library
// into two different class loaders.
if (hasNativeLibs)
{
// Increment the refresh count.
setRefreshCount(refreshCount + 1);
// Rename the current revision directory to the new refresh level.
File currentDir = new File(m_archiveRootDir,
REVISION_DIRECTORY + (refreshCount + 1) + "." + currentRevNum.toString());
File revisionDir = new File(m_archiveRootDir,
REVISION_DIRECTORY + refreshCount + "." + currentRevNum.toString());
BundleCache.getSecureAction().renameFile(revisionDir, currentDir);
}
// Clear the revision map since they are all invalid now.
m_revisions.clear();
// Recreate the revision for the current location.
BundleArchiveRevision revision = createRevisionFromLocation(
getRevisionLocation(currentRevNum), null, currentRevNum);
// Add new revision to the revision map.
m_revisions.put(currentRevNum, revision);
}
/**
* <p>
* Initializes the bundle archive object by creating the archive
* root directory and saving the initial state.
* </p>
* @throws Exception if any error occurs.
**/
private void initialize() throws Exception
{
try (OutputStream os = null;
BufferedWriter bw = null)
{
// If the archive directory exists, then we don't
// need to initialize since it has already been done.
if (BundleCache.getSecureAction().fileExists(m_archiveRootDir))
{
return;
}
// Create archive directory, if it does not exist.
if (!BundleCache.getSecureAction().mkdir(m_archiveRootDir))
{
m_logger.log(
Logger.LOG_ERROR,
getClass().getName() + ": Unable to create archive directory.");
throw new IOException("Unable to create archive directory.");
}
writeBundleInfo();
}
}
/**
* <p>
* Creates a revision based on the location string and/or input stream.
* </p>
* @return the location string associated with this archive.
**/
private BundleArchiveRevision createRevisionFromLocation(
String location, InputStream is, Long revNum)
throws Exception
{
// The revision directory is named using the refresh count and
// the revision number. The revision number is an increasing
// counter of the number of times the bundle was revised.
// The refresh count is necessary due to how native libraries
// are handled in Java; needless to say, every time a bundle is
// refreshed we must change the name of its native libraries so
// that we can reload them. Thus, we use the refresh counter as
// a way to change the name of the revision directory to give
// native libraries new absolute names.
File revisionRootDir = new File(m_archiveRootDir,
REVISION_DIRECTORY + getRefreshCount() + "." + revNum.toString());
BundleArchiveRevision result = null;
try
{
// Check if the location string represents a reference URL.
if ((location != null) && location.startsWith(REFERENCE_PROTOCOL))
{
// Reference URLs only support the file protocol.
location = location.substring(REFERENCE_PROTOCOL.length());
if (!location.startsWith(FILE_PROTOCOL))
{
throw new IOException("Reference URLs can only be files: " + location);
}
// Decode any URL escaped sequences.
location = decode(location);
// Make sure the referenced file exists.
File file = new File(location.substring(FILE_PROTOCOL.length()));
if (!BundleCache.getSecureAction().fileExists(file))
{
throw new IOException("Referenced file does not exist: " + file);
}
// If the referenced file is a directory, then create a directory
// revision; otherwise, create a JAR revision with the reference
// flag set to true.
if (BundleCache.getSecureAction().isFileDirectory(file))
{
result = new DirectoryRevision(m_logger, m_configMap,
m_zipFactory, revisionRootDir, location);
}
else
{
result = new JarRevision(m_logger, m_configMap,
m_zipFactory, revisionRootDir, location, true, null);
}
}
else if (location.startsWith(INPUTSTREAM_PROTOCOL))
{
// Assume all input streams point to JAR files.
result = new JarRevision(m_logger, m_configMap,
m_zipFactory, revisionRootDir, location, false, is);
}
else
{
ConnectModule module = m_connector != null ?
m_connector.connect(location).orElse(null) : null;
if (module != null)
{
result = new ConnectRevision(m_logger, m_configMap, m_zipFactory, revisionRootDir, location, module);
}
else
{
// Anything else is assumed to be a URL to a JAR file.
result = new JarRevision(m_logger, m_configMap,
m_zipFactory, revisionRootDir, location, false, null);
}
}
}
catch (Exception ex)
{
if (BundleCache.getSecureAction().fileExists(revisionRootDir))
{
if (!BundleCache.deleteDirectoryTree(revisionRootDir))
{
m_logger.log(
Logger.LOG_ERROR,
getClass().getName()
+ ": Unable to delete revision directory - "
+ revisionRootDir);
}
}
throw ex;
}
return result;
}
// Method from Harmony java.net.URIEncoderDecoder (luni subproject)
// used by URI to decode uri components.
private static String decode(String s) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
ByteArrayOutputStream out = new ByteArrayOutputStream();
for (int i = 0; i < s.length();)
{
char c = s.charAt(i);
if (c == '%')
{
out.reset();
do
{
if ((i + 2) >= s.length())
{
throw new IllegalArgumentException(
"Incomplete % sequence at: " + i);
}
int d1 = Character.digit(s.charAt(i + 1), 16);
int d2 = Character.digit(s.charAt(i + 2), 16);
if ((d1 == -1) || (d2 == -1))
{
throw new IllegalArgumentException("Invalid % sequence ("
+ s.substring(i, i + 3)
+ ") at: " + String.valueOf(i));
}
out.write((byte) ((d1 << 4) + d2));
i += 3;
}
while ((i < s.length()) && (s.charAt(i) == '%'));
result.append(out.toString("UTF-8"));
continue;
}
result.append(c);
i++;
}
return result.toString();
}
private void readBundleInfo() throws Exception
{
File infoFile = new File(m_archiveRootDir, BUNDLE_INFO_FILE);
// Read the bundle start level.
InputStream is = null;
BufferedReader br= null;
try
{
is = BundleCache.getSecureAction()
.getInputStream(infoFile);
br = new BufferedReader(new InputStreamReader(is));
// Read id.
m_id = Long.parseLong(br.readLine());
// Read location.
m_originalLocation = br.readLine();
// Read state.
m_persistentState = Integer.parseInt(br.readLine());
// Read start level.
m_startLevel = Integer.parseInt(br.readLine());
// Read last modified.
m_lastModified = Long.parseLong(br.readLine());
// Read refresh count.
m_refreshCount = Long.parseLong(br.readLine());
}
finally
{
if (br != null) br.close();
if (is != null) is.close();
}
}
private void writeBundleInfo() throws Exception
{
// Write the bundle start level.
OutputStream os = null;
BufferedWriter bw = null;
try
{
os = BundleCache.getSecureAction()
.getOutputStream(new File(m_archiveRootDir, BUNDLE_INFO_FILE));
bw = new BufferedWriter(new OutputStreamWriter(os));
// Write id.
String s = Long.toString(m_id);
bw.write(s, 0, s.length());
bw.newLine();
// Write location.
s = (m_originalLocation == null) ? "" : m_originalLocation;
bw.write(s, 0, s.length());
bw.newLine();
// Write state.
s = Integer.toString(m_persistentState);
bw.write(s, 0, s.length());
bw.newLine();
// Write start level.
s = Integer.toString(m_startLevel);
bw.write(s, 0, s.length());
bw.newLine();
// Write last modified.
s = Long.toString(m_lastModified);
bw.write(s, 0, s.length());
bw.newLine();
// Write refresh count.
s = Long.toString(m_refreshCount);
bw.write(s, 0, s.length());
bw.newLine();
}
catch (IOException ex)
{
m_logger.log(
Logger.LOG_ERROR,
getClass().getName() + ": Unable to cache bundle info - " + ex);
throw ex;
}
finally
{
if (bw != null) bw.close();
if (os != null) os.close();
}
}
}
|
googleapis/google-cloud-java | 35,495 | java-gsuite-addons/proto-google-apps-script-type-protos/src/main/java/com/google/apps/script/type/gmail/UniversalAction.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/script/type/gmail/gmail_addon_manifest.proto
// Protobuf Java Version: 3.25.8
package com.google.apps.script.type.gmail;
/**
*
*
* <pre>
* An action that is always available in the add-on toolbar menu regardless of
* message context.
* </pre>
*
* Protobuf type {@code google.apps.script.type.gmail.UniversalAction}
*/
public final class UniversalAction extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.apps.script.type.gmail.UniversalAction)
UniversalActionOrBuilder {
private static final long serialVersionUID = 0L;
// Use UniversalAction.newBuilder() to construct.
private UniversalAction(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UniversalAction() {
text_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UniversalAction();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.apps.script.type.gmail.GmailAddOnManifestProto
.internal_static_google_apps_script_type_gmail_UniversalAction_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.apps.script.type.gmail.GmailAddOnManifestProto
.internal_static_google_apps_script_type_gmail_UniversalAction_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.apps.script.type.gmail.UniversalAction.class,
com.google.apps.script.type.gmail.UniversalAction.Builder.class);
}
private int actionTypeCase_ = 0;
@SuppressWarnings("serial")
private java.lang.Object actionType_;
public enum ActionTypeCase
implements
com.google.protobuf.Internal.EnumLite,
com.google.protobuf.AbstractMessage.InternalOneOfEnum {
OPEN_LINK(2),
RUN_FUNCTION(3),
ACTIONTYPE_NOT_SET(0);
private final int value;
private ActionTypeCase(int value) {
this.value = value;
}
/**
* @param value The number of the enum to look for.
* @return The enum associated with the given number.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static ActionTypeCase valueOf(int value) {
return forNumber(value);
}
public static ActionTypeCase forNumber(int value) {
switch (value) {
case 2:
return OPEN_LINK;
case 3:
return RUN_FUNCTION;
case 0:
return ACTIONTYPE_NOT_SET;
default:
return null;
}
}
public int getNumber() {
return this.value;
}
};
public ActionTypeCase getActionTypeCase() {
return ActionTypeCase.forNumber(actionTypeCase_);
}
public static final int TEXT_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private volatile java.lang.Object text_ = "";
/**
*
*
* <pre>
* Required. User-visible text describing the action, for example, "Add a new
* contact."
* </pre>
*
* <code>string text = 1;</code>
*
* @return The text.
*/
@java.lang.Override
public java.lang.String getText() {
java.lang.Object ref = text_;
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();
text_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. User-visible text describing the action, for example, "Add a new
* contact."
* </pre>
*
* <code>string text = 1;</code>
*
* @return The bytes for text.
*/
@java.lang.Override
public com.google.protobuf.ByteString getTextBytes() {
java.lang.Object ref = text_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
text_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int OPEN_LINK_FIELD_NUMBER = 2;
/**
*
*
* <pre>
* A link that is opened by Gmail when the user triggers the action.
* </pre>
*
* <code>string open_link = 2;</code>
*
* @return Whether the openLink field is set.
*/
public boolean hasOpenLink() {
return actionTypeCase_ == 2;
}
/**
*
*
* <pre>
* A link that is opened by Gmail when the user triggers the action.
* </pre>
*
* <code>string open_link = 2;</code>
*
* @return The openLink.
*/
public java.lang.String getOpenLink() {
java.lang.Object ref = "";
if (actionTypeCase_ == 2) {
ref = actionType_;
}
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();
if (actionTypeCase_ == 2) {
actionType_ = s;
}
return s;
}
}
/**
*
*
* <pre>
* A link that is opened by Gmail when the user triggers the action.
* </pre>
*
* <code>string open_link = 2;</code>
*
* @return The bytes for openLink.
*/
public com.google.protobuf.ByteString getOpenLinkBytes() {
java.lang.Object ref = "";
if (actionTypeCase_ == 2) {
ref = actionType_;
}
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (actionTypeCase_ == 2) {
actionType_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int RUN_FUNCTION_FIELD_NUMBER = 3;
/**
*
*
* <pre>
* An endpoint that is called when the user triggers the
* action. See the [universal actions
* guide](/gmail/add-ons/how-tos/universal-actions) for details.
* </pre>
*
* <code>string run_function = 3;</code>
*
* @return Whether the runFunction field is set.
*/
public boolean hasRunFunction() {
return actionTypeCase_ == 3;
}
/**
*
*
* <pre>
* An endpoint that is called when the user triggers the
* action. See the [universal actions
* guide](/gmail/add-ons/how-tos/universal-actions) for details.
* </pre>
*
* <code>string run_function = 3;</code>
*
* @return The runFunction.
*/
public java.lang.String getRunFunction() {
java.lang.Object ref = "";
if (actionTypeCase_ == 3) {
ref = actionType_;
}
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();
if (actionTypeCase_ == 3) {
actionType_ = s;
}
return s;
}
}
/**
*
*
* <pre>
* An endpoint that is called when the user triggers the
* action. See the [universal actions
* guide](/gmail/add-ons/how-tos/universal-actions) for details.
* </pre>
*
* <code>string run_function = 3;</code>
*
* @return The bytes for runFunction.
*/
public com.google.protobuf.ByteString getRunFunctionBytes() {
java.lang.Object ref = "";
if (actionTypeCase_ == 3) {
ref = actionType_;
}
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (actionTypeCase_ == 3) {
actionType_ = 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(text_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, text_);
}
if (actionTypeCase_ == 2) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, actionType_);
}
if (actionTypeCase_ == 3) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, actionType_);
}
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(text_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, text_);
}
if (actionTypeCase_ == 2) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, actionType_);
}
if (actionTypeCase_ == 3) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, actionType_);
}
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.script.type.gmail.UniversalAction)) {
return super.equals(obj);
}
com.google.apps.script.type.gmail.UniversalAction other =
(com.google.apps.script.type.gmail.UniversalAction) obj;
if (!getText().equals(other.getText())) return false;
if (!getActionTypeCase().equals(other.getActionTypeCase())) return false;
switch (actionTypeCase_) {
case 2:
if (!getOpenLink().equals(other.getOpenLink())) return false;
break;
case 3:
if (!getRunFunction().equals(other.getRunFunction())) return false;
break;
case 0:
default:
}
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) + TEXT_FIELD_NUMBER;
hash = (53 * hash) + getText().hashCode();
switch (actionTypeCase_) {
case 2:
hash = (37 * hash) + OPEN_LINK_FIELD_NUMBER;
hash = (53 * hash) + getOpenLink().hashCode();
break;
case 3:
hash = (37 * hash) + RUN_FUNCTION_FIELD_NUMBER;
hash = (53 * hash) + getRunFunction().hashCode();
break;
case 0:
default:
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.apps.script.type.gmail.UniversalAction parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.script.type.gmail.UniversalAction 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.script.type.gmail.UniversalAction parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.script.type.gmail.UniversalAction 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.script.type.gmail.UniversalAction parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.apps.script.type.gmail.UniversalAction parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.apps.script.type.gmail.UniversalAction parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.apps.script.type.gmail.UniversalAction 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.script.type.gmail.UniversalAction parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.apps.script.type.gmail.UniversalAction 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.script.type.gmail.UniversalAction parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.apps.script.type.gmail.UniversalAction 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.script.type.gmail.UniversalAction 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>
* An action that is always available in the add-on toolbar menu regardless of
* message context.
* </pre>
*
* Protobuf type {@code google.apps.script.type.gmail.UniversalAction}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.apps.script.type.gmail.UniversalAction)
com.google.apps.script.type.gmail.UniversalActionOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.apps.script.type.gmail.GmailAddOnManifestProto
.internal_static_google_apps_script_type_gmail_UniversalAction_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.apps.script.type.gmail.GmailAddOnManifestProto
.internal_static_google_apps_script_type_gmail_UniversalAction_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.apps.script.type.gmail.UniversalAction.class,
com.google.apps.script.type.gmail.UniversalAction.Builder.class);
}
// Construct using com.google.apps.script.type.gmail.UniversalAction.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
text_ = "";
actionTypeCase_ = 0;
actionType_ = null;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.apps.script.type.gmail.GmailAddOnManifestProto
.internal_static_google_apps_script_type_gmail_UniversalAction_descriptor;
}
@java.lang.Override
public com.google.apps.script.type.gmail.UniversalAction getDefaultInstanceForType() {
return com.google.apps.script.type.gmail.UniversalAction.getDefaultInstance();
}
@java.lang.Override
public com.google.apps.script.type.gmail.UniversalAction build() {
com.google.apps.script.type.gmail.UniversalAction result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.apps.script.type.gmail.UniversalAction buildPartial() {
com.google.apps.script.type.gmail.UniversalAction result =
new com.google.apps.script.type.gmail.UniversalAction(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
buildPartialOneofs(result);
onBuilt();
return result;
}
private void buildPartial0(com.google.apps.script.type.gmail.UniversalAction result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.text_ = text_;
}
}
private void buildPartialOneofs(com.google.apps.script.type.gmail.UniversalAction result) {
result.actionTypeCase_ = actionTypeCase_;
result.actionType_ = this.actionType_;
}
@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.script.type.gmail.UniversalAction) {
return mergeFrom((com.google.apps.script.type.gmail.UniversalAction) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.apps.script.type.gmail.UniversalAction other) {
if (other == com.google.apps.script.type.gmail.UniversalAction.getDefaultInstance())
return this;
if (!other.getText().isEmpty()) {
text_ = other.text_;
bitField0_ |= 0x00000001;
onChanged();
}
switch (other.getActionTypeCase()) {
case OPEN_LINK:
{
actionTypeCase_ = 2;
actionType_ = other.actionType_;
onChanged();
break;
}
case RUN_FUNCTION:
{
actionTypeCase_ = 3;
actionType_ = other.actionType_;
onChanged();
break;
}
case ACTIONTYPE_NOT_SET:
{
break;
}
}
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:
{
text_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000001;
break;
} // case 10
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
actionTypeCase_ = 2;
actionType_ = s;
break;
} // case 18
case 26:
{
java.lang.String s = input.readStringRequireUtf8();
actionTypeCase_ = 3;
actionType_ = s;
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 actionTypeCase_ = 0;
private java.lang.Object actionType_;
public ActionTypeCase getActionTypeCase() {
return ActionTypeCase.forNumber(actionTypeCase_);
}
public Builder clearActionType() {
actionTypeCase_ = 0;
actionType_ = null;
onChanged();
return this;
}
private int bitField0_;
private java.lang.Object text_ = "";
/**
*
*
* <pre>
* Required. User-visible text describing the action, for example, "Add a new
* contact."
* </pre>
*
* <code>string text = 1;</code>
*
* @return The text.
*/
public java.lang.String getText() {
java.lang.Object ref = text_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
text_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. User-visible text describing the action, for example, "Add a new
* contact."
* </pre>
*
* <code>string text = 1;</code>
*
* @return The bytes for text.
*/
public com.google.protobuf.ByteString getTextBytes() {
java.lang.Object ref = text_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
text_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. User-visible text describing the action, for example, "Add a new
* contact."
* </pre>
*
* <code>string text = 1;</code>
*
* @param value The text to set.
* @return This builder for chaining.
*/
public Builder setText(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
text_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. User-visible text describing the action, for example, "Add a new
* contact."
* </pre>
*
* <code>string text = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearText() {
text_ = getDefaultInstance().getText();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. User-visible text describing the action, for example, "Add a new
* contact."
* </pre>
*
* <code>string text = 1;</code>
*
* @param value The bytes for text to set.
* @return This builder for chaining.
*/
public Builder setTextBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
text_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* A link that is opened by Gmail when the user triggers the action.
* </pre>
*
* <code>string open_link = 2;</code>
*
* @return Whether the openLink field is set.
*/
@java.lang.Override
public boolean hasOpenLink() {
return actionTypeCase_ == 2;
}
/**
*
*
* <pre>
* A link that is opened by Gmail when the user triggers the action.
* </pre>
*
* <code>string open_link = 2;</code>
*
* @return The openLink.
*/
@java.lang.Override
public java.lang.String getOpenLink() {
java.lang.Object ref = "";
if (actionTypeCase_ == 2) {
ref = actionType_;
}
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (actionTypeCase_ == 2) {
actionType_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A link that is opened by Gmail when the user triggers the action.
* </pre>
*
* <code>string open_link = 2;</code>
*
* @return The bytes for openLink.
*/
@java.lang.Override
public com.google.protobuf.ByteString getOpenLinkBytes() {
java.lang.Object ref = "";
if (actionTypeCase_ == 2) {
ref = actionType_;
}
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (actionTypeCase_ == 2) {
actionType_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A link that is opened by Gmail when the user triggers the action.
* </pre>
*
* <code>string open_link = 2;</code>
*
* @param value The openLink to set.
* @return This builder for chaining.
*/
public Builder setOpenLink(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
actionTypeCase_ = 2;
actionType_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* A link that is opened by Gmail when the user triggers the action.
* </pre>
*
* <code>string open_link = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearOpenLink() {
if (actionTypeCase_ == 2) {
actionTypeCase_ = 0;
actionType_ = null;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* A link that is opened by Gmail when the user triggers the action.
* </pre>
*
* <code>string open_link = 2;</code>
*
* @param value The bytes for openLink to set.
* @return This builder for chaining.
*/
public Builder setOpenLinkBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
actionTypeCase_ = 2;
actionType_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* An endpoint that is called when the user triggers the
* action. See the [universal actions
* guide](/gmail/add-ons/how-tos/universal-actions) for details.
* </pre>
*
* <code>string run_function = 3;</code>
*
* @return Whether the runFunction field is set.
*/
@java.lang.Override
public boolean hasRunFunction() {
return actionTypeCase_ == 3;
}
/**
*
*
* <pre>
* An endpoint that is called when the user triggers the
* action. See the [universal actions
* guide](/gmail/add-ons/how-tos/universal-actions) for details.
* </pre>
*
* <code>string run_function = 3;</code>
*
* @return The runFunction.
*/
@java.lang.Override
public java.lang.String getRunFunction() {
java.lang.Object ref = "";
if (actionTypeCase_ == 3) {
ref = actionType_;
}
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (actionTypeCase_ == 3) {
actionType_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* An endpoint that is called when the user triggers the
* action. See the [universal actions
* guide](/gmail/add-ons/how-tos/universal-actions) for details.
* </pre>
*
* <code>string run_function = 3;</code>
*
* @return The bytes for runFunction.
*/
@java.lang.Override
public com.google.protobuf.ByteString getRunFunctionBytes() {
java.lang.Object ref = "";
if (actionTypeCase_ == 3) {
ref = actionType_;
}
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
if (actionTypeCase_ == 3) {
actionType_ = b;
}
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* An endpoint that is called when the user triggers the
* action. See the [universal actions
* guide](/gmail/add-ons/how-tos/universal-actions) for details.
* </pre>
*
* <code>string run_function = 3;</code>
*
* @param value The runFunction to set.
* @return This builder for chaining.
*/
public Builder setRunFunction(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
actionTypeCase_ = 3;
actionType_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* An endpoint that is called when the user triggers the
* action. See the [universal actions
* guide](/gmail/add-ons/how-tos/universal-actions) for details.
* </pre>
*
* <code>string run_function = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearRunFunction() {
if (actionTypeCase_ == 3) {
actionTypeCase_ = 0;
actionType_ = null;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* An endpoint that is called when the user triggers the
* action. See the [universal actions
* guide](/gmail/add-ons/how-tos/universal-actions) for details.
* </pre>
*
* <code>string run_function = 3;</code>
*
* @param value The bytes for runFunction to set.
* @return This builder for chaining.
*/
public Builder setRunFunctionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
actionTypeCase_ = 3;
actionType_ = value;
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.script.type.gmail.UniversalAction)
}
// @@protoc_insertion_point(class_scope:google.apps.script.type.gmail.UniversalAction)
private static final com.google.apps.script.type.gmail.UniversalAction DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.apps.script.type.gmail.UniversalAction();
}
public static com.google.apps.script.type.gmail.UniversalAction getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UniversalAction> PARSER =
new com.google.protobuf.AbstractParser<UniversalAction>() {
@java.lang.Override
public UniversalAction 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<UniversalAction> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UniversalAction> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.apps.script.type.gmail.UniversalAction getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,681 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/UpdateIndexEndpointRequest.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/index_endpoint_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Request message for
* [IndexEndpointService.UpdateIndexEndpoint][google.cloud.aiplatform.v1beta1.IndexEndpointService.UpdateIndexEndpoint].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest}
*/
public final class UpdateIndexEndpointRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest)
UpdateIndexEndpointRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateIndexEndpointRequest.newBuilder() to construct.
private UpdateIndexEndpointRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateIndexEndpointRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateIndexEndpointRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.IndexEndpointServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateIndexEndpointRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.IndexEndpointServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateIndexEndpointRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest.class,
com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest.Builder.class);
}
private int bitField0_;
public static final int INDEX_ENDPOINT_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1beta1.IndexEndpoint indexEndpoint_;
/**
*
*
* <pre>
* Required. The IndexEndpoint which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the indexEndpoint field is set.
*/
@java.lang.Override
public boolean hasIndexEndpoint() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The IndexEndpoint which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The indexEndpoint.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.IndexEndpoint getIndexEndpoint() {
return indexEndpoint_ == null
? com.google.cloud.aiplatform.v1beta1.IndexEndpoint.getDefaultInstance()
: indexEndpoint_;
}
/**
*
*
* <pre>
* Required. The IndexEndpoint which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.IndexEndpointOrBuilder getIndexEndpointOrBuilder() {
return indexEndpoint_ == null
? com.google.cloud.aiplatform.v1beta1.IndexEndpoint.getDefaultInstance()
: indexEndpoint_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Required. The update mask applies to the resource. See
* [google.protobuf.FieldMask][google.protobuf.FieldMask].
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The update mask applies to the resource. See
* [google.protobuf.FieldMask][google.protobuf.FieldMask].
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Required. The update mask applies to the resource. See
* [google.protobuf.FieldMask][google.protobuf.FieldMask].
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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, getIndexEndpoint());
}
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, getIndexEndpoint());
}
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.aiplatform.v1beta1.UpdateIndexEndpointRequest)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest other =
(com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest) obj;
if (hasIndexEndpoint() != other.hasIndexEndpoint()) return false;
if (hasIndexEndpoint()) {
if (!getIndexEndpoint().equals(other.getIndexEndpoint())) 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 (hasIndexEndpoint()) {
hash = (37 * hash) + INDEX_ENDPOINT_FIELD_NUMBER;
hash = (53 * hash) + getIndexEndpoint().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.aiplatform.v1beta1.UpdateIndexEndpointRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest 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.UpdateIndexEndpointRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest 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.UpdateIndexEndpointRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest 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.UpdateIndexEndpointRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest 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.UpdateIndexEndpointRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest 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.UpdateIndexEndpointRequest 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.UpdateIndexEndpointRequest 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.UpdateIndexEndpointRequest 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
* [IndexEndpointService.UpdateIndexEndpoint][google.cloud.aiplatform.v1beta1.IndexEndpointService.UpdateIndexEndpoint].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest)
com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.IndexEndpointServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateIndexEndpointRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.IndexEndpointServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateIndexEndpointRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest.class,
com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getIndexEndpointFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
indexEndpoint_ = null;
if (indexEndpointBuilder_ != null) {
indexEndpointBuilder_.dispose();
indexEndpointBuilder_ = 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.aiplatform.v1beta1.IndexEndpointServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateIndexEndpointRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest build() {
com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest buildPartial() {
com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest result =
new com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.indexEndpoint_ =
indexEndpointBuilder_ == null ? indexEndpoint_ : indexEndpointBuilder_.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.aiplatform.v1beta1.UpdateIndexEndpointRequest) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest other) {
if (other
== com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest.getDefaultInstance())
return this;
if (other.hasIndexEndpoint()) {
mergeIndexEndpoint(other.getIndexEndpoint());
}
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(getIndexEndpointFieldBuilder().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.aiplatform.v1beta1.IndexEndpoint indexEndpoint_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.IndexEndpoint,
com.google.cloud.aiplatform.v1beta1.IndexEndpoint.Builder,
com.google.cloud.aiplatform.v1beta1.IndexEndpointOrBuilder>
indexEndpointBuilder_;
/**
*
*
* <pre>
* Required. The IndexEndpoint which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the indexEndpoint field is set.
*/
public boolean hasIndexEndpoint() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The IndexEndpoint which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The indexEndpoint.
*/
public com.google.cloud.aiplatform.v1beta1.IndexEndpoint getIndexEndpoint() {
if (indexEndpointBuilder_ == null) {
return indexEndpoint_ == null
? com.google.cloud.aiplatform.v1beta1.IndexEndpoint.getDefaultInstance()
: indexEndpoint_;
} else {
return indexEndpointBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The IndexEndpoint which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setIndexEndpoint(com.google.cloud.aiplatform.v1beta1.IndexEndpoint value) {
if (indexEndpointBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
indexEndpoint_ = value;
} else {
indexEndpointBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The IndexEndpoint which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setIndexEndpoint(
com.google.cloud.aiplatform.v1beta1.IndexEndpoint.Builder builderForValue) {
if (indexEndpointBuilder_ == null) {
indexEndpoint_ = builderForValue.build();
} else {
indexEndpointBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The IndexEndpoint which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeIndexEndpoint(com.google.cloud.aiplatform.v1beta1.IndexEndpoint value) {
if (indexEndpointBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& indexEndpoint_ != null
&& indexEndpoint_
!= com.google.cloud.aiplatform.v1beta1.IndexEndpoint.getDefaultInstance()) {
getIndexEndpointBuilder().mergeFrom(value);
} else {
indexEndpoint_ = value;
}
} else {
indexEndpointBuilder_.mergeFrom(value);
}
if (indexEndpoint_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The IndexEndpoint which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearIndexEndpoint() {
bitField0_ = (bitField0_ & ~0x00000001);
indexEndpoint_ = null;
if (indexEndpointBuilder_ != null) {
indexEndpointBuilder_.dispose();
indexEndpointBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The IndexEndpoint which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.IndexEndpoint.Builder getIndexEndpointBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getIndexEndpointFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The IndexEndpoint which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.IndexEndpointOrBuilder getIndexEndpointOrBuilder() {
if (indexEndpointBuilder_ != null) {
return indexEndpointBuilder_.getMessageOrBuilder();
} else {
return indexEndpoint_ == null
? com.google.cloud.aiplatform.v1beta1.IndexEndpoint.getDefaultInstance()
: indexEndpoint_;
}
}
/**
*
*
* <pre>
* Required. The IndexEndpoint which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.IndexEndpoint index_endpoint = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.IndexEndpoint,
com.google.cloud.aiplatform.v1beta1.IndexEndpoint.Builder,
com.google.cloud.aiplatform.v1beta1.IndexEndpointOrBuilder>
getIndexEndpointFieldBuilder() {
if (indexEndpointBuilder_ == null) {
indexEndpointBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.IndexEndpoint,
com.google.cloud.aiplatform.v1beta1.IndexEndpoint.Builder,
com.google.cloud.aiplatform.v1beta1.IndexEndpointOrBuilder>(
getIndexEndpoint(), getParentForChildren(), isClean());
indexEndpoint_ = null;
}
return indexEndpointBuilder_;
}
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>
* Required. The update mask applies to the resource. See
* [google.protobuf.FieldMask][google.protobuf.FieldMask].
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Required. The update mask applies to the resource. See
* [google.protobuf.FieldMask][google.protobuf.FieldMask].
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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>
* Required. The update mask applies to the resource. See
* [google.protobuf.FieldMask][google.protobuf.FieldMask].
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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>
* Required. The update mask applies to the resource. See
* [google.protobuf.FieldMask][google.protobuf.FieldMask].
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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>
* Required. The update mask applies to the resource. See
* [google.protobuf.FieldMask][google.protobuf.FieldMask].
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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>
* Required. The update mask applies to the resource. See
* [google.protobuf.FieldMask][google.protobuf.FieldMask].
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The update mask applies to the resource. See
* [google.protobuf.FieldMask][google.protobuf.FieldMask].
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The update mask applies to the resource. See
* [google.protobuf.FieldMask][google.protobuf.FieldMask].
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Required. The update mask applies to the resource. See
* [google.protobuf.FieldMask][google.protobuf.FieldMask].
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = REQUIRED];
* </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.aiplatform.v1beta1.UpdateIndexEndpointRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest)
private static final com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest();
}
public static com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateIndexEndpointRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateIndexEndpointRequest>() {
@java.lang.Override
public UpdateIndexEndpointRequest 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<UpdateIndexEndpointRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateIndexEndpointRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.UpdateIndexEndpointRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,849 | java-discoveryengine/grpc-google-cloud-discoveryengine-v1beta/src/main/java/com/google/cloud/discoveryengine/v1beta/UserEventServiceGrpc.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.discoveryengine.v1beta;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
*
*
* <pre>
* Service for ingesting end user actions on a website to Discovery Engine API.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: google/cloud/discoveryengine/v1beta/user_event_service.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class UserEventServiceGrpc {
private UserEventServiceGrpc() {}
public static final java.lang.String SERVICE_NAME =
"google.cloud.discoveryengine.v1beta.UserEventService";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest,
com.google.cloud.discoveryengine.v1beta.UserEvent>
getWriteUserEventMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "WriteUserEvent",
requestType = com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest.class,
responseType = com.google.cloud.discoveryengine.v1beta.UserEvent.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest,
com.google.cloud.discoveryengine.v1beta.UserEvent>
getWriteUserEventMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest,
com.google.cloud.discoveryengine.v1beta.UserEvent>
getWriteUserEventMethod;
if ((getWriteUserEventMethod = UserEventServiceGrpc.getWriteUserEventMethod) == null) {
synchronized (UserEventServiceGrpc.class) {
if ((getWriteUserEventMethod = UserEventServiceGrpc.getWriteUserEventMethod) == null) {
UserEventServiceGrpc.getWriteUserEventMethod =
getWriteUserEventMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest,
com.google.cloud.discoveryengine.v1beta.UserEvent>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "WriteUserEvent"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.discoveryengine.v1beta.UserEvent
.getDefaultInstance()))
.setSchemaDescriptor(
new UserEventServiceMethodDescriptorSupplier("WriteUserEvent"))
.build();
}
}
}
return getWriteUserEventMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest, com.google.api.HttpBody>
getCollectUserEventMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "CollectUserEvent",
requestType = com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest.class,
responseType = com.google.api.HttpBody.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest, com.google.api.HttpBody>
getCollectUserEventMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest,
com.google.api.HttpBody>
getCollectUserEventMethod;
if ((getCollectUserEventMethod = UserEventServiceGrpc.getCollectUserEventMethod) == null) {
synchronized (UserEventServiceGrpc.class) {
if ((getCollectUserEventMethod = UserEventServiceGrpc.getCollectUserEventMethod) == null) {
UserEventServiceGrpc.getCollectUserEventMethod =
getCollectUserEventMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest,
com.google.api.HttpBody>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "CollectUserEvent"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.api.HttpBody.getDefaultInstance()))
.setSchemaDescriptor(
new UserEventServiceMethodDescriptorSupplier("CollectUserEvent"))
.build();
}
}
}
return getCollectUserEventMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest,
com.google.longrunning.Operation>
getPurgeUserEventsMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "PurgeUserEvents",
requestType = com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest.class,
responseType = com.google.longrunning.Operation.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest,
com.google.longrunning.Operation>
getPurgeUserEventsMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest,
com.google.longrunning.Operation>
getPurgeUserEventsMethod;
if ((getPurgeUserEventsMethod = UserEventServiceGrpc.getPurgeUserEventsMethod) == null) {
synchronized (UserEventServiceGrpc.class) {
if ((getPurgeUserEventsMethod = UserEventServiceGrpc.getPurgeUserEventsMethod) == null) {
UserEventServiceGrpc.getPurgeUserEventsMethod =
getPurgeUserEventsMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest,
com.google.longrunning.Operation>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "PurgeUserEvents"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.longrunning.Operation.getDefaultInstance()))
.setSchemaDescriptor(
new UserEventServiceMethodDescriptorSupplier("PurgeUserEvents"))
.build();
}
}
}
return getPurgeUserEventsMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest,
com.google.longrunning.Operation>
getImportUserEventsMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "ImportUserEvents",
requestType = com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest.class,
responseType = com.google.longrunning.Operation.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest,
com.google.longrunning.Operation>
getImportUserEventsMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest,
com.google.longrunning.Operation>
getImportUserEventsMethod;
if ((getImportUserEventsMethod = UserEventServiceGrpc.getImportUserEventsMethod) == null) {
synchronized (UserEventServiceGrpc.class) {
if ((getImportUserEventsMethod = UserEventServiceGrpc.getImportUserEventsMethod) == null) {
UserEventServiceGrpc.getImportUserEventsMethod =
getImportUserEventsMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest,
com.google.longrunning.Operation>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "ImportUserEvents"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.longrunning.Operation.getDefaultInstance()))
.setSchemaDescriptor(
new UserEventServiceMethodDescriptorSupplier("ImportUserEvents"))
.build();
}
}
}
return getImportUserEventsMethod;
}
/** Creates a new async stub that supports all call types for the service */
public static UserEventServiceStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<UserEventServiceStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<UserEventServiceStub>() {
@java.lang.Override
public UserEventServiceStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new UserEventServiceStub(channel, callOptions);
}
};
return UserEventServiceStub.newStub(factory, channel);
}
/** Creates a new blocking-style stub that supports all types of calls on the service */
public static UserEventServiceBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<UserEventServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<UserEventServiceBlockingV2Stub>() {
@java.lang.Override
public UserEventServiceBlockingV2Stub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new UserEventServiceBlockingV2Stub(channel, callOptions);
}
};
return UserEventServiceBlockingV2Stub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static UserEventServiceBlockingStub newBlockingStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<UserEventServiceBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<UserEventServiceBlockingStub>() {
@java.lang.Override
public UserEventServiceBlockingStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new UserEventServiceBlockingStub(channel, callOptions);
}
};
return UserEventServiceBlockingStub.newStub(factory, channel);
}
/** Creates a new ListenableFuture-style stub that supports unary calls on the service */
public static UserEventServiceFutureStub newFutureStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<UserEventServiceFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<UserEventServiceFutureStub>() {
@java.lang.Override
public UserEventServiceFutureStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new UserEventServiceFutureStub(channel, callOptions);
}
};
return UserEventServiceFutureStub.newStub(factory, channel);
}
/**
*
*
* <pre>
* Service for ingesting end user actions on a website to Discovery Engine API.
* </pre>
*/
public interface AsyncService {
/**
*
*
* <pre>
* Writes a single user event.
* </pre>
*/
default void writeUserEvent(
com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.discoveryengine.v1beta.UserEvent>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getWriteUserEventMethod(), responseObserver);
}
/**
*
*
* <pre>
* Writes a single user event from the browser. This uses a GET request to
* due to browser restriction of POST-ing to a third-party domain.
* This method is used only by the Discovery Engine API JavaScript pixel and
* Google Tag Manager. Users should not call this method directly.
* </pre>
*/
default void collectUserEvent(
com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest request,
io.grpc.stub.StreamObserver<com.google.api.HttpBody> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getCollectUserEventMethod(), responseObserver);
}
/**
*
*
* <pre>
* Deletes permanently all user events specified by the filter provided.
* Depending on the number of events specified by the filter, this operation
* could take hours or days to complete. To test a filter, use the list
* command first.
* </pre>
*/
default void purgeUserEvents(
com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getPurgeUserEventsMethod(), responseObserver);
}
/**
*
*
* <pre>
* Bulk import of user events. Request processing might be
* synchronous. Events that already exist are skipped.
* Use this method for backfilling historical user events.
* Operation.response is of type ImportResponse. Note that it is
* possible for a subset of the items to be successfully inserted.
* Operation.metadata is of type ImportMetadata.
* </pre>
*/
default void importUserEvents(
com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getImportUserEventsMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service UserEventService.
*
* <pre>
* Service for ingesting end user actions on a website to Discovery Engine API.
* </pre>
*/
public abstract static class UserEventServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override
public final io.grpc.ServerServiceDefinition bindService() {
return UserEventServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service UserEventService.
*
* <pre>
* Service for ingesting end user actions on a website to Discovery Engine API.
* </pre>
*/
public static final class UserEventServiceStub
extends io.grpc.stub.AbstractAsyncStub<UserEventServiceStub> {
private UserEventServiceStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected UserEventServiceStub build(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new UserEventServiceStub(channel, callOptions);
}
/**
*
*
* <pre>
* Writes a single user event.
* </pre>
*/
public void writeUserEvent(
com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.discoveryengine.v1beta.UserEvent>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getWriteUserEventMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Writes a single user event from the browser. This uses a GET request to
* due to browser restriction of POST-ing to a third-party domain.
* This method is used only by the Discovery Engine API JavaScript pixel and
* Google Tag Manager. Users should not call this method directly.
* </pre>
*/
public void collectUserEvent(
com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest request,
io.grpc.stub.StreamObserver<com.google.api.HttpBody> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getCollectUserEventMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Deletes permanently all user events specified by the filter provided.
* Depending on the number of events specified by the filter, this operation
* could take hours or days to complete. To test a filter, use the list
* command first.
* </pre>
*/
public void purgeUserEvents(
com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getPurgeUserEventsMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Bulk import of user events. Request processing might be
* synchronous. Events that already exist are skipped.
* Use this method for backfilling historical user events.
* Operation.response is of type ImportResponse. Note that it is
* possible for a subset of the items to be successfully inserted.
* Operation.metadata is of type ImportMetadata.
* </pre>
*/
public void importUserEvents(
com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getImportUserEventsMethod(), getCallOptions()),
request,
responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service UserEventService.
*
* <pre>
* Service for ingesting end user actions on a website to Discovery Engine API.
* </pre>
*/
public static final class UserEventServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<UserEventServiceBlockingV2Stub> {
private UserEventServiceBlockingV2Stub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected UserEventServiceBlockingV2Stub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new UserEventServiceBlockingV2Stub(channel, callOptions);
}
/**
*
*
* <pre>
* Writes a single user event.
* </pre>
*/
public com.google.cloud.discoveryengine.v1beta.UserEvent writeUserEvent(
com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getWriteUserEventMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Writes a single user event from the browser. This uses a GET request to
* due to browser restriction of POST-ing to a third-party domain.
* This method is used only by the Discovery Engine API JavaScript pixel and
* Google Tag Manager. Users should not call this method directly.
* </pre>
*/
public com.google.api.HttpBody collectUserEvent(
com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCollectUserEventMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Deletes permanently all user events specified by the filter provided.
* Depending on the number of events specified by the filter, this operation
* could take hours or days to complete. To test a filter, use the list
* command first.
* </pre>
*/
public com.google.longrunning.Operation purgeUserEvents(
com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getPurgeUserEventsMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Bulk import of user events. Request processing might be
* synchronous. Events that already exist are skipped.
* Use this method for backfilling historical user events.
* Operation.response is of type ImportResponse. Note that it is
* possible for a subset of the items to be successfully inserted.
* Operation.metadata is of type ImportMetadata.
* </pre>
*/
public com.google.longrunning.Operation importUserEvents(
com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getImportUserEventsMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do limited synchronous rpc calls to service UserEventService.
*
* <pre>
* Service for ingesting end user actions on a website to Discovery Engine API.
* </pre>
*/
public static final class UserEventServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<UserEventServiceBlockingStub> {
private UserEventServiceBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected UserEventServiceBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new UserEventServiceBlockingStub(channel, callOptions);
}
/**
*
*
* <pre>
* Writes a single user event.
* </pre>
*/
public com.google.cloud.discoveryengine.v1beta.UserEvent writeUserEvent(
com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getWriteUserEventMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Writes a single user event from the browser. This uses a GET request to
* due to browser restriction of POST-ing to a third-party domain.
* This method is used only by the Discovery Engine API JavaScript pixel and
* Google Tag Manager. Users should not call this method directly.
* </pre>
*/
public com.google.api.HttpBody collectUserEvent(
com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCollectUserEventMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Deletes permanently all user events specified by the filter provided.
* Depending on the number of events specified by the filter, this operation
* could take hours or days to complete. To test a filter, use the list
* command first.
* </pre>
*/
public com.google.longrunning.Operation purgeUserEvents(
com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getPurgeUserEventsMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Bulk import of user events. Request processing might be
* synchronous. Events that already exist are skipped.
* Use this method for backfilling historical user events.
* Operation.response is of type ImportResponse. Note that it is
* possible for a subset of the items to be successfully inserted.
* Operation.metadata is of type ImportMetadata.
* </pre>
*/
public com.google.longrunning.Operation importUserEvents(
com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getImportUserEventsMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service UserEventService.
*
* <pre>
* Service for ingesting end user actions on a website to Discovery Engine API.
* </pre>
*/
public static final class UserEventServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<UserEventServiceFutureStub> {
private UserEventServiceFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected UserEventServiceFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new UserEventServiceFutureStub(channel, callOptions);
}
/**
*
*
* <pre>
* Writes a single user event.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.discoveryengine.v1beta.UserEvent>
writeUserEvent(com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getWriteUserEventMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Writes a single user event from the browser. This uses a GET request to
* due to browser restriction of POST-ing to a third-party domain.
* This method is used only by the Discovery Engine API JavaScript pixel and
* Google Tag Manager. Users should not call this method directly.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.api.HttpBody>
collectUserEvent(com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getCollectUserEventMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Deletes permanently all user events specified by the filter provided.
* Depending on the number of events specified by the filter, this operation
* could take hours or days to complete. To test a filter, use the list
* command first.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation>
purgeUserEvents(com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getPurgeUserEventsMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Bulk import of user events. Request processing might be
* synchronous. Events that already exist are skipped.
* Use this method for backfilling historical user events.
* Operation.response is of type ImportResponse. Note that it is
* possible for a subset of the items to be successfully inserted.
* Operation.metadata is of type ImportMetadata.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation>
importUserEvents(com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getImportUserEventsMethod(), getCallOptions()), request);
}
}
private static final int METHODID_WRITE_USER_EVENT = 0;
private static final int METHODID_COLLECT_USER_EVENT = 1;
private static final int METHODID_PURGE_USER_EVENTS = 2;
private static final int METHODID_IMPORT_USER_EVENTS = 3;
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_WRITE_USER_EVENT:
serviceImpl.writeUserEvent(
(com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest) request,
(io.grpc.stub.StreamObserver<com.google.cloud.discoveryengine.v1beta.UserEvent>)
responseObserver);
break;
case METHODID_COLLECT_USER_EVENT:
serviceImpl.collectUserEvent(
(com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest) request,
(io.grpc.stub.StreamObserver<com.google.api.HttpBody>) responseObserver);
break;
case METHODID_PURGE_USER_EVENTS:
serviceImpl.purgeUserEvents(
(com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest) request,
(io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver);
break;
case METHODID_IMPORT_USER_EVENTS:
serviceImpl.importUserEvents(
(com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest) 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(
getWriteUserEventMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.discoveryengine.v1beta.WriteUserEventRequest,
com.google.cloud.discoveryengine.v1beta.UserEvent>(
service, METHODID_WRITE_USER_EVENT)))
.addMethod(
getCollectUserEventMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.discoveryengine.v1beta.CollectUserEventRequest,
com.google.api.HttpBody>(service, METHODID_COLLECT_USER_EVENT)))
.addMethod(
getPurgeUserEventsMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.discoveryengine.v1beta.PurgeUserEventsRequest,
com.google.longrunning.Operation>(service, METHODID_PURGE_USER_EVENTS)))
.addMethod(
getImportUserEventsMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.discoveryengine.v1beta.ImportUserEventsRequest,
com.google.longrunning.Operation>(service, METHODID_IMPORT_USER_EVENTS)))
.build();
}
private abstract static class UserEventServiceBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier,
io.grpc.protobuf.ProtoServiceDescriptorSupplier {
UserEventServiceBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.google.cloud.discoveryengine.v1beta.UserEventServiceProto.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("UserEventService");
}
}
private static final class UserEventServiceFileDescriptorSupplier
extends UserEventServiceBaseDescriptorSupplier {
UserEventServiceFileDescriptorSupplier() {}
}
private static final class UserEventServiceMethodDescriptorSupplier
extends UserEventServiceBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final java.lang.String methodName;
UserEventServiceMethodDescriptorSupplier(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 (UserEventServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor =
result =
io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new UserEventServiceFileDescriptorSupplier())
.addMethod(getWriteUserEventMethod())
.addMethod(getCollectUserEventMethod())
.addMethod(getPurgeUserEventsMethod())
.addMethod(getImportUserEventsMethod())
.build();
}
}
}
return result;
}
}
|
googleapis/google-cloud-java | 35,838 | java-networkconnectivity/grpc-google-cloud-networkconnectivity-v1/src/main/java/com/google/cloud/networkconnectivity/v1/PolicyBasedRoutingServiceGrpc.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.networkconnectivity.v1;
import static io.grpc.MethodDescriptor.generateFullMethodName;
/**
*
*
* <pre>
* Policy-Based Routing allows GCP customers to specify flexibile routing
* policies for Layer 4 traffic traversing through the connected service.
* </pre>
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler",
comments = "Source: google/cloud/networkconnectivity/v1/policy_based_routing.proto")
@io.grpc.stub.annotations.GrpcGenerated
public final class PolicyBasedRoutingServiceGrpc {
private PolicyBasedRoutingServiceGrpc() {}
public static final java.lang.String SERVICE_NAME =
"google.cloud.networkconnectivity.v1.PolicyBasedRoutingService";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest,
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse>
getListPolicyBasedRoutesMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "ListPolicyBasedRoutes",
requestType = com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest.class,
responseType = com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest,
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse>
getListPolicyBasedRoutesMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest,
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse>
getListPolicyBasedRoutesMethod;
if ((getListPolicyBasedRoutesMethod =
PolicyBasedRoutingServiceGrpc.getListPolicyBasedRoutesMethod)
== null) {
synchronized (PolicyBasedRoutingServiceGrpc.class) {
if ((getListPolicyBasedRoutesMethod =
PolicyBasedRoutingServiceGrpc.getListPolicyBasedRoutesMethod)
== null) {
PolicyBasedRoutingServiceGrpc.getListPolicyBasedRoutesMethod =
getListPolicyBasedRoutesMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest,
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
generateFullMethodName(SERVICE_NAME, "ListPolicyBasedRoutes"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse
.getDefaultInstance()))
.setSchemaDescriptor(
new PolicyBasedRoutingServiceMethodDescriptorSupplier(
"ListPolicyBasedRoutes"))
.build();
}
}
}
return getListPolicyBasedRoutesMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest,
com.google.cloud.networkconnectivity.v1.PolicyBasedRoute>
getGetPolicyBasedRouteMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "GetPolicyBasedRoute",
requestType = com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest.class,
responseType = com.google.cloud.networkconnectivity.v1.PolicyBasedRoute.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest,
com.google.cloud.networkconnectivity.v1.PolicyBasedRoute>
getGetPolicyBasedRouteMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest,
com.google.cloud.networkconnectivity.v1.PolicyBasedRoute>
getGetPolicyBasedRouteMethod;
if ((getGetPolicyBasedRouteMethod = PolicyBasedRoutingServiceGrpc.getGetPolicyBasedRouteMethod)
== null) {
synchronized (PolicyBasedRoutingServiceGrpc.class) {
if ((getGetPolicyBasedRouteMethod =
PolicyBasedRoutingServiceGrpc.getGetPolicyBasedRouteMethod)
== null) {
PolicyBasedRoutingServiceGrpc.getGetPolicyBasedRouteMethod =
getGetPolicyBasedRouteMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest,
com.google.cloud.networkconnectivity.v1.PolicyBasedRoute>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
generateFullMethodName(SERVICE_NAME, "GetPolicyBasedRoute"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.networkconnectivity.v1.PolicyBasedRoute
.getDefaultInstance()))
.setSchemaDescriptor(
new PolicyBasedRoutingServiceMethodDescriptorSupplier(
"GetPolicyBasedRoute"))
.build();
}
}
}
return getGetPolicyBasedRouteMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest,
com.google.longrunning.Operation>
getCreatePolicyBasedRouteMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "CreatePolicyBasedRoute",
requestType = com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest.class,
responseType = com.google.longrunning.Operation.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest,
com.google.longrunning.Operation>
getCreatePolicyBasedRouteMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest,
com.google.longrunning.Operation>
getCreatePolicyBasedRouteMethod;
if ((getCreatePolicyBasedRouteMethod =
PolicyBasedRoutingServiceGrpc.getCreatePolicyBasedRouteMethod)
== null) {
synchronized (PolicyBasedRoutingServiceGrpc.class) {
if ((getCreatePolicyBasedRouteMethod =
PolicyBasedRoutingServiceGrpc.getCreatePolicyBasedRouteMethod)
== null) {
PolicyBasedRoutingServiceGrpc.getCreatePolicyBasedRouteMethod =
getCreatePolicyBasedRouteMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest,
com.google.longrunning.Operation>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
generateFullMethodName(SERVICE_NAME, "CreatePolicyBasedRoute"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.longrunning.Operation.getDefaultInstance()))
.setSchemaDescriptor(
new PolicyBasedRoutingServiceMethodDescriptorSupplier(
"CreatePolicyBasedRoute"))
.build();
}
}
}
return getCreatePolicyBasedRouteMethod;
}
private static volatile io.grpc.MethodDescriptor<
com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest,
com.google.longrunning.Operation>
getDeletePolicyBasedRouteMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "DeletePolicyBasedRoute",
requestType = com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest.class,
responseType = com.google.longrunning.Operation.class,
methodType = io.grpc.MethodDescriptor.MethodType.UNARY)
public static io.grpc.MethodDescriptor<
com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest,
com.google.longrunning.Operation>
getDeletePolicyBasedRouteMethod() {
io.grpc.MethodDescriptor<
com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest,
com.google.longrunning.Operation>
getDeletePolicyBasedRouteMethod;
if ((getDeletePolicyBasedRouteMethod =
PolicyBasedRoutingServiceGrpc.getDeletePolicyBasedRouteMethod)
== null) {
synchronized (PolicyBasedRoutingServiceGrpc.class) {
if ((getDeletePolicyBasedRouteMethod =
PolicyBasedRoutingServiceGrpc.getDeletePolicyBasedRouteMethod)
== null) {
PolicyBasedRoutingServiceGrpc.getDeletePolicyBasedRouteMethod =
getDeletePolicyBasedRouteMethod =
io.grpc.MethodDescriptor
.<com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest,
com.google.longrunning.Operation>
newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(
generateFullMethodName(SERVICE_NAME, "DeletePolicyBasedRoute"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest
.getDefaultInstance()))
.setResponseMarshaller(
io.grpc.protobuf.ProtoUtils.marshaller(
com.google.longrunning.Operation.getDefaultInstance()))
.setSchemaDescriptor(
new PolicyBasedRoutingServiceMethodDescriptorSupplier(
"DeletePolicyBasedRoute"))
.build();
}
}
}
return getDeletePolicyBasedRouteMethod;
}
/** Creates a new async stub that supports all call types for the service */
public static PolicyBasedRoutingServiceStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<PolicyBasedRoutingServiceStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<PolicyBasedRoutingServiceStub>() {
@java.lang.Override
public PolicyBasedRoutingServiceStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PolicyBasedRoutingServiceStub(channel, callOptions);
}
};
return PolicyBasedRoutingServiceStub.newStub(factory, channel);
}
/** Creates a new blocking-style stub that supports all types of calls on the service */
public static PolicyBasedRoutingServiceBlockingV2Stub newBlockingV2Stub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<PolicyBasedRoutingServiceBlockingV2Stub> factory =
new io.grpc.stub.AbstractStub.StubFactory<PolicyBasedRoutingServiceBlockingV2Stub>() {
@java.lang.Override
public PolicyBasedRoutingServiceBlockingV2Stub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PolicyBasedRoutingServiceBlockingV2Stub(channel, callOptions);
}
};
return PolicyBasedRoutingServiceBlockingV2Stub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static PolicyBasedRoutingServiceBlockingStub newBlockingStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<PolicyBasedRoutingServiceBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<PolicyBasedRoutingServiceBlockingStub>() {
@java.lang.Override
public PolicyBasedRoutingServiceBlockingStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PolicyBasedRoutingServiceBlockingStub(channel, callOptions);
}
};
return PolicyBasedRoutingServiceBlockingStub.newStub(factory, channel);
}
/** Creates a new ListenableFuture-style stub that supports unary calls on the service */
public static PolicyBasedRoutingServiceFutureStub newFutureStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<PolicyBasedRoutingServiceFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<PolicyBasedRoutingServiceFutureStub>() {
@java.lang.Override
public PolicyBasedRoutingServiceFutureStub newStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PolicyBasedRoutingServiceFutureStub(channel, callOptions);
}
};
return PolicyBasedRoutingServiceFutureStub.newStub(factory, channel);
}
/**
*
*
* <pre>
* Policy-Based Routing allows GCP customers to specify flexibile routing
* policies for Layer 4 traffic traversing through the connected service.
* </pre>
*/
public interface AsyncService {
/**
*
*
* <pre>
* Lists policy-based routes in a given project and location.
* </pre>
*/
default void listPolicyBasedRoutes(
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest request,
io.grpc.stub.StreamObserver<
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getListPolicyBasedRoutesMethod(), responseObserver);
}
/**
*
*
* <pre>
* Gets details of a single policy-based route.
* </pre>
*/
default void getPolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.networkconnectivity.v1.PolicyBasedRoute>
responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getGetPolicyBasedRouteMethod(), responseObserver);
}
/**
*
*
* <pre>
* Creates a new policy-based route in a given project and location.
* </pre>
*/
default void createPolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getCreatePolicyBasedRouteMethod(), responseObserver);
}
/**
*
*
* <pre>
* Deletes a single policy-based route.
* </pre>
*/
default void deletePolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall(
getDeletePolicyBasedRouteMethod(), responseObserver);
}
}
/**
* Base class for the server implementation of the service PolicyBasedRoutingService.
*
* <pre>
* Policy-Based Routing allows GCP customers to specify flexibile routing
* policies for Layer 4 traffic traversing through the connected service.
* </pre>
*/
public abstract static class PolicyBasedRoutingServiceImplBase
implements io.grpc.BindableService, AsyncService {
@java.lang.Override
public final io.grpc.ServerServiceDefinition bindService() {
return PolicyBasedRoutingServiceGrpc.bindService(this);
}
}
/**
* A stub to allow clients to do asynchronous rpc calls to service PolicyBasedRoutingService.
*
* <pre>
* Policy-Based Routing allows GCP customers to specify flexibile routing
* policies for Layer 4 traffic traversing through the connected service.
* </pre>
*/
public static final class PolicyBasedRoutingServiceStub
extends io.grpc.stub.AbstractAsyncStub<PolicyBasedRoutingServiceStub> {
private PolicyBasedRoutingServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected PolicyBasedRoutingServiceStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PolicyBasedRoutingServiceStub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists policy-based routes in a given project and location.
* </pre>
*/
public void listPolicyBasedRoutes(
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest request,
io.grpc.stub.StreamObserver<
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getListPolicyBasedRoutesMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Gets details of a single policy-based route.
* </pre>
*/
public void getPolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest request,
io.grpc.stub.StreamObserver<com.google.cloud.networkconnectivity.v1.PolicyBasedRoute>
responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getGetPolicyBasedRouteMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Creates a new policy-based route in a given project and location.
* </pre>
*/
public void createPolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getCreatePolicyBasedRouteMethod(), getCallOptions()),
request,
responseObserver);
}
/**
*
*
* <pre>
* Deletes a single policy-based route.
* </pre>
*/
public void deletePolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest request,
io.grpc.stub.StreamObserver<com.google.longrunning.Operation> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getDeletePolicyBasedRouteMethod(), getCallOptions()),
request,
responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service PolicyBasedRoutingService.
*
* <pre>
* Policy-Based Routing allows GCP customers to specify flexibile routing
* policies for Layer 4 traffic traversing through the connected service.
* </pre>
*/
public static final class PolicyBasedRoutingServiceBlockingV2Stub
extends io.grpc.stub.AbstractBlockingStub<PolicyBasedRoutingServiceBlockingV2Stub> {
private PolicyBasedRoutingServiceBlockingV2Stub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected PolicyBasedRoutingServiceBlockingV2Stub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PolicyBasedRoutingServiceBlockingV2Stub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists policy-based routes in a given project and location.
* </pre>
*/
public com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse
listPolicyBasedRoutes(
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListPolicyBasedRoutesMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Gets details of a single policy-based route.
* </pre>
*/
public com.google.cloud.networkconnectivity.v1.PolicyBasedRoute getPolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetPolicyBasedRouteMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Creates a new policy-based route in a given project and location.
* </pre>
*/
public com.google.longrunning.Operation createPolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCreatePolicyBasedRouteMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Deletes a single policy-based route.
* </pre>
*/
public com.google.longrunning.Operation deletePolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeletePolicyBasedRouteMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do limited synchronous rpc calls to service
* PolicyBasedRoutingService.
*
* <pre>
* Policy-Based Routing allows GCP customers to specify flexibile routing
* policies for Layer 4 traffic traversing through the connected service.
* </pre>
*/
public static final class PolicyBasedRoutingServiceBlockingStub
extends io.grpc.stub.AbstractBlockingStub<PolicyBasedRoutingServiceBlockingStub> {
private PolicyBasedRoutingServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected PolicyBasedRoutingServiceBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PolicyBasedRoutingServiceBlockingStub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists policy-based routes in a given project and location.
* </pre>
*/
public com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse
listPolicyBasedRoutes(
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getListPolicyBasedRoutesMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Gets details of a single policy-based route.
* </pre>
*/
public com.google.cloud.networkconnectivity.v1.PolicyBasedRoute getPolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getGetPolicyBasedRouteMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Creates a new policy-based route in a given project and location.
* </pre>
*/
public com.google.longrunning.Operation createPolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getCreatePolicyBasedRouteMethod(), getCallOptions(), request);
}
/**
*
*
* <pre>
* Deletes a single policy-based route.
* </pre>
*/
public com.google.longrunning.Operation deletePolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest request) {
return io.grpc.stub.ClientCalls.blockingUnaryCall(
getChannel(), getDeletePolicyBasedRouteMethod(), getCallOptions(), request);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service
* PolicyBasedRoutingService.
*
* <pre>
* Policy-Based Routing allows GCP customers to specify flexibile routing
* policies for Layer 4 traffic traversing through the connected service.
* </pre>
*/
public static final class PolicyBasedRoutingServiceFutureStub
extends io.grpc.stub.AbstractFutureStub<PolicyBasedRoutingServiceFutureStub> {
private PolicyBasedRoutingServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected PolicyBasedRoutingServiceFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new PolicyBasedRoutingServiceFutureStub(channel, callOptions);
}
/**
*
*
* <pre>
* Lists policy-based routes in a given project and location.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse>
listPolicyBasedRoutes(
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getListPolicyBasedRoutesMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Gets details of a single policy-based route.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<
com.google.cloud.networkconnectivity.v1.PolicyBasedRoute>
getPolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getGetPolicyBasedRouteMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Creates a new policy-based route in a given project and location.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation>
createPolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getCreatePolicyBasedRouteMethod(), getCallOptions()), request);
}
/**
*
*
* <pre>
* Deletes a single policy-based route.
* </pre>
*/
public com.google.common.util.concurrent.ListenableFuture<com.google.longrunning.Operation>
deletePolicyBasedRoute(
com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest request) {
return io.grpc.stub.ClientCalls.futureUnaryCall(
getChannel().newCall(getDeletePolicyBasedRouteMethod(), getCallOptions()), request);
}
}
private static final int METHODID_LIST_POLICY_BASED_ROUTES = 0;
private static final int METHODID_GET_POLICY_BASED_ROUTE = 1;
private static final int METHODID_CREATE_POLICY_BASED_ROUTE = 2;
private static final int METHODID_DELETE_POLICY_BASED_ROUTE = 3;
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_POLICY_BASED_ROUTES:
serviceImpl.listPolicyBasedRoutes(
(com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest) request,
(io.grpc.stub.StreamObserver<
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse>)
responseObserver);
break;
case METHODID_GET_POLICY_BASED_ROUTE:
serviceImpl.getPolicyBasedRoute(
(com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest) request,
(io.grpc.stub.StreamObserver<
com.google.cloud.networkconnectivity.v1.PolicyBasedRoute>)
responseObserver);
break;
case METHODID_CREATE_POLICY_BASED_ROUTE:
serviceImpl.createPolicyBasedRoute(
(com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest) request,
(io.grpc.stub.StreamObserver<com.google.longrunning.Operation>) responseObserver);
break;
case METHODID_DELETE_POLICY_BASED_ROUTE:
serviceImpl.deletePolicyBasedRoute(
(com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest) 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(
getListPolicyBasedRoutesMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesRequest,
com.google.cloud.networkconnectivity.v1.ListPolicyBasedRoutesResponse>(
service, METHODID_LIST_POLICY_BASED_ROUTES)))
.addMethod(
getGetPolicyBasedRouteMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.networkconnectivity.v1.GetPolicyBasedRouteRequest,
com.google.cloud.networkconnectivity.v1.PolicyBasedRoute>(
service, METHODID_GET_POLICY_BASED_ROUTE)))
.addMethod(
getCreatePolicyBasedRouteMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.networkconnectivity.v1.CreatePolicyBasedRouteRequest,
com.google.longrunning.Operation>(service, METHODID_CREATE_POLICY_BASED_ROUTE)))
.addMethod(
getDeletePolicyBasedRouteMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
com.google.cloud.networkconnectivity.v1.DeletePolicyBasedRouteRequest,
com.google.longrunning.Operation>(service, METHODID_DELETE_POLICY_BASED_ROUTE)))
.build();
}
private abstract static class PolicyBasedRoutingServiceBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoFileDescriptorSupplier,
io.grpc.protobuf.ProtoServiceDescriptorSupplier {
PolicyBasedRoutingServiceBaseDescriptorSupplier() {}
@java.lang.Override
public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() {
return com.google.cloud.networkconnectivity.v1.PolicyBasedRoutingProto.getDescriptor();
}
@java.lang.Override
public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() {
return getFileDescriptor().findServiceByName("PolicyBasedRoutingService");
}
}
private static final class PolicyBasedRoutingServiceFileDescriptorSupplier
extends PolicyBasedRoutingServiceBaseDescriptorSupplier {
PolicyBasedRoutingServiceFileDescriptorSupplier() {}
}
private static final class PolicyBasedRoutingServiceMethodDescriptorSupplier
extends PolicyBasedRoutingServiceBaseDescriptorSupplier
implements io.grpc.protobuf.ProtoMethodDescriptorSupplier {
private final java.lang.String methodName;
PolicyBasedRoutingServiceMethodDescriptorSupplier(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 (PolicyBasedRoutingServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor =
result =
io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.setSchemaDescriptor(new PolicyBasedRoutingServiceFileDescriptorSupplier())
.addMethod(getListPolicyBasedRoutesMethod())
.addMethod(getGetPolicyBasedRouteMethod())
.addMethod(getCreatePolicyBasedRouteMethod())
.addMethod(getDeletePolicyBasedRouteMethod())
.build();
}
}
}
return result;
}
}
|
oracle/nosql | 35,923 | kvmain/src/main/java/oracle/kv/impl/admin/plan/TopoTaskGenerator.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.admin.plan;
import static oracle.kv.impl.topo.Datacenter.MASTER_AFFINITY;
import static oracle.kv.impl.topo.Datacenter.NO_MASTER_AFFINITY;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
import oracle.kv.impl.admin.Admin;
import oracle.kv.impl.admin.AdminServiceParams;
import oracle.kv.impl.admin.CommandResult;
import oracle.kv.impl.admin.param.AdminParams;
import oracle.kv.impl.admin.param.GlobalParams;
import oracle.kv.impl.admin.param.Parameters;
import oracle.kv.impl.admin.param.RepNodeParams;
import oracle.kv.impl.admin.param.SecurityParams;
import oracle.kv.impl.admin.plan.task.AddPartitions;
import oracle.kv.impl.admin.plan.task.BroadcastMetadata;
import oracle.kv.impl.admin.plan.task.BroadcastTopo;
import oracle.kv.impl.admin.plan.task.CheckRNMemorySettings;
import oracle.kv.impl.admin.plan.task.DeployNewARB;
import oracle.kv.impl.admin.plan.task.DeployNewRN;
import oracle.kv.impl.admin.plan.task.DeployShard;
import oracle.kv.impl.admin.plan.task.MigratePartition;
import oracle.kv.impl.admin.plan.task.NewArbNodeParameters;
import oracle.kv.impl.admin.plan.task.NewNthANParameters;
import oracle.kv.impl.admin.plan.task.NewNthRNParameters;
import oracle.kv.impl.admin.plan.task.NewRepNodeParameters;
import oracle.kv.impl.admin.plan.task.ParallelBundle;
import oracle.kv.impl.admin.plan.task.RelocateAN;
import oracle.kv.impl.admin.plan.task.RelocateRN;
import oracle.kv.impl.admin.plan.task.RemoveAN;
import oracle.kv.impl.admin.plan.task.RemoveRepNode;
import oracle.kv.impl.admin.plan.task.RemoveShard;
import oracle.kv.impl.admin.plan.task.Task;
import oracle.kv.impl.admin.plan.task.UpdateAdminParams;
import oracle.kv.impl.admin.plan.task.UpdateDatacenter.UpdateDatacenterV2;
import oracle.kv.impl.admin.plan.task.UpdateHelperHostV2;
import oracle.kv.impl.admin.plan.task.UpdateNthANHelperHost;
import oracle.kv.impl.admin.plan.task.UpdateNthRNHelperHost;
import oracle.kv.impl.admin.plan.task.UpdateRepNodeParams;
import oracle.kv.impl.admin.plan.task.Utils;
import oracle.kv.impl.admin.plan.task.WaitForAdminState;
import oracle.kv.impl.admin.plan.task.WaitForNodeState;
import oracle.kv.impl.admin.plan.task.WriteNewParams;
import oracle.kv.impl.admin.topo.TopologyCandidate;
import oracle.kv.impl.admin.topo.TopologyDiff;
import oracle.kv.impl.admin.topo.TopologyDiff.RelocatedAN;
import oracle.kv.impl.admin.topo.TopologyDiff.RelocatedPartition;
import oracle.kv.impl.admin.topo.TopologyDiff.RelocatedRN;
import oracle.kv.impl.admin.topo.TopologyDiff.ShardChange;
import oracle.kv.impl.fault.CommandFaultException;
import oracle.kv.impl.metadata.Metadata.MetadataType;
import oracle.kv.impl.param.ParameterMap;
import oracle.kv.impl.security.metadata.SecurityMetadata;
import oracle.kv.impl.security.util.SecurityUtils;
import oracle.kv.impl.topo.AdminId;
import oracle.kv.impl.topo.ArbNode;
import oracle.kv.impl.topo.ArbNodeId;
import oracle.kv.impl.topo.Datacenter;
import oracle.kv.impl.topo.DatacenterId;
import oracle.kv.impl.topo.DatacenterType;
import oracle.kv.impl.topo.RepGroup;
import oracle.kv.impl.topo.RepGroupId;
import oracle.kv.impl.topo.RepNode;
import oracle.kv.impl.topo.RepNodeId;
import oracle.kv.impl.topo.StorageNode;
import oracle.kv.impl.topo.StorageNodeId;
import oracle.kv.impl.topo.Topology;
import oracle.kv.impl.util.ConfigurableService.ServiceStatus;
import oracle.kv.impl.util.server.LoggerUtils;
import oracle.kv.util.ErrorMessage;
/**
* Populate the target plan with the sequence of tasks and the new param
* instances required to move from the current to a new target topology.
*/
class TopoTaskGenerator {
/* This plan will be populated with tasks by the generator. */
private final DeployTopoPlan plan;
private final TopologyCandidate candidate;
private final Logger logger;
private final TopologyDiff diff;
private final Set<DatacenterId> offlineZones;
private final RepGroupId failedShard;
TopoTaskGenerator(DeployTopoPlan plan,
Topology source,
TopologyCandidate candidate,
AdminServiceParams adminServiceParams,
Set<DatacenterId> offlineZones,
RepGroupId failedShard) {
this.plan = plan;
this.candidate = candidate;
logger = LoggerUtils.getLogger(this.getClass(), adminServiceParams);
diff = new TopologyDiff(source, null, candidate,
plan.getAdmin().getCurrentParameters(),
true /* validate */,
!offlineZones.isEmpty() /* forFailover */);
logger.fine(() -> "task generator sees diff of " + diff.display(true));
this.offlineZones = offlineZones;
this.failedShard = failedShard;
}
/**
* Compare the source and the candidate topologies, and generate tasks that
* will make the required changes.
*
* Note that the new repGroupIds in the candidate topology cannot be taken
* verbatim. The topology class maintains a sequence used to create ids for
* topology components; one cannot specify the id value for a new
* component. Since we want to provide some independence between the
* candidate topology and the topology deployment -- we don't want to
* require that components be created in precisely some order to mimic
* the candidate -- we refer to the shards by ordinal value. That is,
* we refer to the first, second, third, etc shard.
*
* The task generator puts the new shards into a list, and generates the
* tasks with a plan shard index that is the order from that list. The
* DeployTopoPlan will create and maintain a list of newly generated
* repgroup/shard ids, and generated tasks will use their ordinal value,
* as indicated by the planShardIdx and to find the true repgroup id
* to use.
*/
void generate() {
/*
* If -failed-shard option is specified then it is important to
* check if it is same as -failed-shard option specified at
* topology remove-shard before proceeding further.
*
* If removedShards from topology diff is greater than one or
* empty then remove shard operation was not run before and
* some other elasticity operation leading to removing of none
* or two or more shards, we should not proceed in this scenario
* with -failed-shard option specified.
*/
if (failedShard != null) {
Set<RepGroupId> removedShards = diff.getRemovedShards();
if (removedShards.size() > 1 ||
removedShards.isEmpty() ||
!failedShard.equals(removedShards.iterator().next())) {
final String msg =
"The shard specified with the -failed-shard option " +
"for plan deploy-topology (" + failedShard + ") " +
"does not match the shards specified for removal " +
"with topology remove-shard or topology contract (" +
(removedShards.isEmpty() ? "None" : removedShards) + ").";
throw new CommandFaultException(
msg, new IllegalStateException(msg),
ErrorMessage.NOSQL_5200, CommandResult.NO_CLEANUP_JOBS);
}
}
makeDatacenterUpdates();
if (diff.getRemovedShards().isEmpty()) {
/*
* Execute the RN relocations before creating new RNs, so that a
* given SN does not become temporarily over capacity, or end up
* housing two RNs in the same mount point. RNs relocation occurs
* at this point only when no shard will be removed. The extra
* available SNs are not from removed shards.
*/
makeRelocatedRNTasks();
makeRelocatedANTasks();
makeCreateRNandARBTasks();
makeRemoveANTasks();
makeRemoveRNTasks();
} else {
makeCreateRNandARBTasks();
}
/*
* Broadcast all of the above topo changes now so any migrations run
* smoothly
*
* We need not broadcast topo changes to the RN's of failed shard
*/
plan.addTask(new BroadcastTopo(plan, failedShard));
/*
* Load current security metadata, may be null if it has not been
* initialized.
*/
SecurityMetadata secMd = getSecurityMetadata();
/*
* Update security metadata with Kerberos configuration information if
* store is secured and enabled Kerberos.
*/
secMd = updateWithKerberosInfo(secMd);
/*
* Since all RNs are expected to be active now, broadcast the security
* metadata to them, so that the login authentication is able to work.
*/
plan.addTask(new BroadcastMetadata<>(plan, secMd));
makePartitionTasks();
/* Execute remove shards after the partitions migration task */
if (makeRemoveShardTasks()) {
/*
* Relocate RNs at this point when there are removed shards. Because
* removed shards release some SNs.
*/
makeRelocatedRNTasks();
makeRelocatedANTasks();
}
/* Broadcast topology At the end of deploy topo plan */
plan.addTask(new BroadcastTopo(plan));
}
/*
* Adds tasks related to changes in zones.
*/
private void makeDatacenterUpdates() {
/*
* This method only checks for changes in primary and secondary zones.
* If more zone types are created, this will have to change.
*/
assert DatacenterType.VALUES_COUNT == 2;
final Topology target = candidate.getTopology();
/*
* Do the primary zones first, then secondary to avoid leaving a store
* with no primary zone.
*/
for (Datacenter dc : target.getDatacenterMap().getAll()) {
if (dc.getDatacenterType().isPrimary()) {
makeDatacenterUpdates(target, dc);
}
}
for (Datacenter dc : target.getDatacenterMap().getAll()) {
if (dc.getDatacenterType().isSecondary()) {
makeDatacenterUpdates(target, dc);
}
}
}
private void makeDatacenterUpdates(Topology target, Datacenter dc) {
final DatacenterId dcId = dc.getResourceId();
/*
* Add a task to check to see if the zone attributes are up to date.
* Add the task unconditionally, so it's checked at plan execution
* time.
*/
plan.addTask(new UpdateDatacenterV2(plan, dcId, dc.getRepFactor(),
dc.getDatacenterType(),
dc.getAllowArbiters(),
dc.getMasterAffinity()));
/*
* Set new value of je.rep.node.priority for RN when master affinity is
* changed. The change has two steps:
* 1. WriteNewParams task writes the new value for node priority
* 2. NewRepNodeParameters task refresh the changed value for RepNode
*/
if (diff.affinityChanged(dcId)) {
boolean masterAffinity = dc.getMasterAffinity();
Parameters params = plan.getAdmin().getCurrentParameters();
final Topology current = plan.getAdmin().getCurrentTopology();
Set<RepNodeId> rnIds = current.getRepNodeIds(dcId);
/* Add tasks to change node priority for RepNodes */
for (RepNodeId rnId : rnIds) {
RepNodeParams rnp = params.get(rnId);
ParameterMap pMap = rnp.getMap();
if (masterAffinity) {
rnp.setJENodePriority(MASTER_AFFINITY);
} else {
rnp.setJENodePriority(NO_MASTER_AFFINITY);
}
ParameterMap filtered = pMap.readOnlyFilter();
StorageNodeId snId = current.get(rnId).getStorageNodeId();
/*
* Add task to write the new value for parameter
* je.rep.node.priority
*/
plan.addTask(new WriteNewParams(plan, filtered, rnId, snId,
false));
/*
* Add task to refresh parameter je.rep.node.priority in RepNode
*/
plan.addTask(new NewRepNodeParameters(plan, rnId));
}
}
/* If the type did not change we are done */
if (!diff.typeChanged(dcId)) {
return;
}
/* Propogate information about the zone type change */
plan.addTask(new BroadcastTopo(plan));
/*
* If the zone type changed then add tasks to change and restart
* the Admins and RNs in the zone.
*
* If the zone is offline, then only update the admin database, and
* don't attempt to update its Admins or RNs. Those changes should be
* done using repair topology after the zone comes back online and
* those services, and the SNA, are accessible again.
*/
final boolean zoneIsOffline = offlineZones.contains(dc.getResourceId());
/*
* Add change Admin tasks. Must be done serially in case admins are
* being restarted.
*/
final Parameters parameters = plan.getAdmin().getCurrentParameters();
for (AdminParams ap : parameters.getAdminParams()) {
final StorageNode sn =
target.getStorageNodeMap().get(ap.getStorageNodeId());
if (sn == null) {
final String msg =
"Inconsistency between the parameters and the " +
"topology, " + ap.getStorageNodeId() + " was not " +
"found in parameters";
throw new CommandFaultException(
msg, new IllegalStateException(msg),
ErrorMessage.NOSQL_5400, CommandResult.TOPO_PLAN_REPAIR);
}
if (sn.getDatacenterId().equals(dcId)) {
final AdminId adminId = ap.getAdminId();
plan.addTask(new UpdateAdminParams(plan, adminId,
zoneIsOffline));
/*
* If this is an online primary Admin, wait for it to
* restart before proceeding
*/
if (!zoneIsOffline && dc.getDatacenterType().isPrimary()) {
plan.addTask(
new WaitForAdminState(plan, ap.getStorageNodeId(),
adminId, ServiceStatus.RUNNING));
}
}
}
/*
* Add change RN tasks. We can safely change one RN per
* shard in parallel. This is to avoid the newly switched over
* nodes from becoming masters by outnumbering the existing
* nodes in the quorum.
*/
final int rf = dc.getRepFactor();
final ParallelBundle[] updateTasks = new ParallelBundle[rf];
final ParallelBundle[] waitTasks = new ParallelBundle[rf];
for (int i = 0; i < rf; i++) {
updateTasks[i] = new ParallelBundle();
waitTasks[i] = new ParallelBundle();
}
/*
* Use the current topology when mapping over RNs to update. If an RN
* is not deployed yet, then it doesn't need updating
*/
final Topology currentTopo = plan.getAdmin().getCurrentTopology();
for (RepGroup rg: currentTopo.getRepGroupMap().getAll()) {
int i = 0;
for (RepNode rn: rg.getRepNodes()) {
final StorageNode sn =
rn.getStorageNodeId().getComponent(target);
if (sn.getDatacenterId().equals(dcId)) {
final RepNodeId rnId = rn.getResourceId();
updateTasks[i].addTask(new UpdateRepNodeParams(plan, rnId,
zoneIsOffline,
false, false));
/*
* If this is an online primary node, add a task to wait
* for it to restart.
*/
if (!zoneIsOffline && dc.getDatacenterType().isPrimary()) {
waitTasks[i].addTask(
new WaitForNodeState(plan, rnId,
ServiceStatus.RUNNING));
}
i++;
}
}
}
for (int i = 0; i < rf; i++) {
plan.addTask(updateTasks[i]);
plan.addTask(waitTasks[i]);
}
}
private boolean makeRemoveShardTasks() {
makeRemoveANTasks();
/* Get the list of to be removed shards */
Set<RepGroupId> removedShards = diff.getRemovedShards();
/* Return false when no shard to be removed */
if (removedShards.isEmpty()) {
return false;
}
/* Firstly, remove all RepNodes under the to-be-removed shards */
final Topology currentTopo = plan.getAdmin().getCurrentTopology();
ParallelBundle bundle = new ParallelBundle();
for (RepGroupId rgId : removedShards) {
RepGroup rg = currentTopo.get(rgId);
for (RepNode rn : rg.getRepNodes()) {
Task t = new RemoveRepNode(plan, rn.getResourceId(),
failedShard != null);
bundle.addTask(t);
}
}
plan.addTask(bundle);
/* Add remove shard tasks for all to be removed shards */
for (RepGroupId rgId : removedShards) {
plan.addTask(new RemoveShard(plan, rgId));
/* Broadcast topology as shards are removed */
plan.addTask(new BroadcastTopo(plan));
}
return true;
}
/**
* Create tasks to execute all the RN and AN creations.
*/
private void makeCreateRNandARBTasks() {
Topology target = candidate.getTopology();
/* These are the brand new shards */
List<RepGroupId> newShards = diff.getNewShards();
for (int planShardIdx = 0;
planShardIdx < newShards.size();
planShardIdx++) {
RepGroupId candidateShard = newShards.get(planShardIdx);
ShardChange change = diff.getShardChange(candidateShard);
String snSetDescription = change.getSNSetDescription(target);
/* We wouldn't expect a brand new shard to host old RNs. */
if (change.getRelocatedRNs().size() > 0) {
final String msg =
"New shard " + candidateShard + " to be deployed on " +
snSetDescription + ", should not host existing RNs " +
change.getRelocatedRNs();
throw new CommandFaultException(
msg, new IllegalStateException(msg),
ErrorMessage.NOSQL_5200, CommandResult.NO_CLEANUP_JOBS);
}
if (change.getRelocatedANs().size() > 0) {
final String msg =
"New shard " + candidateShard + " to be deployed on " +
snSetDescription + ", should not host existing ANs " +
change.getRelocatedANs();
throw new CommandFaultException(
msg, new IllegalStateException(msg),
ErrorMessage.NOSQL_5200, CommandResult.NO_CLEANUP_JOBS);
}
/* Make the shard. */
plan.addTask(new DeployShard(plan,
planShardIdx,
snSetDescription));
/* Make all the new RNs that will go on this new shard */
/*
* Create the first RN in a primary datacenter first, so it can be
* the self-electing node and can act as the helper for the
* remaining nodes, including any non-electable ones
*/
final List<RepNodeId> newRnIds =
new ArrayList<>(change.getNewRNs());
for (final Iterator<RepNodeId> i = newRnIds.iterator();
i.hasNext(); ) {
final RepNodeId rnId = i.next();
final Datacenter dc = target.getDatacenter(rnId);
if (dc.getDatacenterType().isPrimary()) {
i.remove();
newRnIds.add(0, rnId);
break;
}
}
for (final RepNodeId proposedRNId : newRnIds) {
RepNode rn = target.get(proposedRNId);
plan.addTask(new DeployNewRN(plan,
rn.getStorageNodeId(),
planShardIdx,
diff.getStorageDir(proposedRNId),
diff.getRNLogDir(proposedRNId)));
}
/* Add new arbiter nodes. */
for (final ArbNodeId proposedARBId : change.getNewANs()) {
ArbNode arb = target.get(proposedARBId);
plan.addTask(new DeployNewARB(plan,
arb.getStorageNodeId(),
planShardIdx));
}
/*
* After the RNs have been created and stored in the topology
* update their helper hosts.
*/
for (int i = 0; i < change.getNewRNs().size(); i++) {
plan.addTask(new UpdateNthRNHelperHost(plan, planShardIdx, i));
plan.addTask(new NewNthRNParameters(plan, planShardIdx, i));
}
/*
* After the ANs have been created and stored in the topology
* update their helper hosts.
*/
for (int i = 0; i < change.getNewANs().size(); i++) {
plan.addTask(new UpdateNthANHelperHost(plan, planShardIdx, i));
plan.addTask(new NewNthANParameters(plan, planShardIdx, i));
}
}
/* These are the shards that existed before, but have new RNs */
for (Map.Entry<RepGroupId, ShardChange> change :
diff.getChangedShards().entrySet()) {
RepGroupId rgId = change.getKey();
if (newShards.contains(rgId)) {
continue;
}
/* The removed shard has no new RN, so filter out it */
RepGroup rg = target.get(rgId);
if (rg == null) {
continue;
}
/* Make all the new RNs that will go on this new shard */
for (RepNodeId proposedRNId : change.getValue().getNewRNs()) {
RepNode rn = target.get(proposedRNId);
plan.addTask(new DeployNewRN(plan,
rn.getStorageNodeId(),
rgId,
diff.getStorageDir(proposedRNId),
diff.getRNLogDir(proposedRNId)));
}
/* Make all the new ANs that will go on this new shard */
for (ArbNodeId proposedANId : change.getValue().getNewANs()) {
ArbNode an = target.get(proposedANId);
plan.addTask(new DeployNewARB(plan,
an.getStorageNodeId(),
rgId));
}
/*
* After the new RNs have been created and stored in the topology
* update the helper hosts for all the RNs in the shard, including
* the ones that existed before.
*/
makeUpdateHelperParamsTasks(rgId);
}
}
/**
* Create tasks to move an RN from one SN to another.
* The relocation requires three actions that must seen atomic:
* 1. updating kvstore metadata (topology, params(disable bit, helper
* hosts for the target RN and all other members of the HA group) and
* broadcast it to all members of the shard. This requires an Admin rep
* group quorum
* 2. updating JE HA rep group metadata (groupDB) and share this with all
* members of the JE HA group. This requires a shard master and
* quorum. Since we are in the business of actively shutting down one of
* the members of the shard, this is clearly a moment of vulnerability
* 3. Moving the environment data to the new SN
* 4. Delete the old environment from the old SN
*
* Once (1) and (2) are done, the change is logically committed. (1) and
* (2) can fail due to lack of write availability. The RN is unavailable
* from (1) to the end of (3). There are a number of options that can short
* these periods of unavailability, but none that can remove it entirely.
*
* One option for making the time from 1->3 shorter is to reach into the JE
* network backup layer that is the foundation of NetworkRestore, in order
* to reduce the amount of time used by (3) to transfer data to the new SN.
* Another option that would make the period from 1-> 2 less
* vulnerable to lack of quorum is to be able to do writes with a less than
* quorum number of acks, which is a pending JE HA feature.
*
* Both options lessen but do not remove the unavailability periods and the
* possibility that the changes must be reverse. RelocateRN embodies step
* 1 and 2 and attempt to clean up if either step fails.
*/
private void makeRelocatedRNTasks() {
Set<StorageNodeId> sourceSNs = new HashSet<>();
for (Map.Entry<RepGroupId, ShardChange> change :
diff.getChangedShards().entrySet()) {
for (RelocatedRN reloc : change.getValue().getRelocatedRNs()) {
RepNodeId rnId = reloc.getRnId();
StorageNodeId oldSNId = reloc.getOldSNId();
StorageNodeId newSNId = reloc.getNewSNId();
/*
* Stop the RN, update its params and topo, update the helper
* host param for all members of the group, update its HA group
* address, redeploy it on the new SN, and delete the RN from
* the original SN once the new RN has come up, and is
* consistent with the master. Also ask the original SN to
* delete the files from the environment.
*/
plan.addTask(new RelocateRN(plan, oldSNId, newSNId, rnId,
diff.getStorageDir(rnId),
diff.getRNLogDir(rnId)));
sourceSNs.add(oldSNId);
}
/*
* SNs that were previously over capacity and have lost an RN may
* now be able to increase the per-RN memory settings. Check
* all the source SNs.
*/
for (StorageNodeId snId : sourceSNs) {
plan.addTask(new CheckRNMemorySettings(plan, snId));
}
}
}
private void makeRelocatedANTasks() {
for (Map.Entry<RepGroupId, ShardChange> change :
diff.getChangedShards().entrySet()) {
boolean addedTask = false;
RepGroupId rgId = change.getKey();
for (RelocatedAN reloc : change.getValue().getRelocatedANs()) {
ArbNodeId anId = reloc.getArbId();
StorageNodeId oldSNId = reloc.getOldSNId();
StorageNodeId newSNId = reloc.getNewSNId();
/*
* Stop the AN, update its params and topo, update the helper
* host parameters in the SN configuration for all members
* of the group, update its HA group
* address, redeploy it on the new SN, and delete the AN from
* the original SN once the new AN has come up.
* Also ask the original SN to delete the files from
* the environment.
*/
plan.addTask(new RelocateAN(plan, oldSNId, newSNId, anId));
addedTask = true;
}
if (addedTask) {
/*
* After the new ANs have been relocated the topology
* update the helper hosts for all the RNs in the shard.
*/
makeUpdateHelperParamsTasks(rgId);
}
}
}
private void makeRemoveANTasks() {
for (Map.Entry<RepGroupId, ShardChange> change :
diff.getChangedShards().entrySet()) {
boolean addedTask = false;
RepGroupId rgId = change.getKey();
for (ArbNodeId anId : change.getValue().getRemovedANs()) {
/*
* Stop the AN, update its params and topo, update the helper
* host parameters in the SN configuration for all members
* of the group, update its HA group address.
*/
plan.addTask(new RemoveAN(plan, anId));
addedTask = true;
}
if (addedTask) {
/*
* After the new ANs have been removed the topology
* update the helper hosts for all the RNs in the shard.
*/
makeUpdateHelperParamsTasks(rgId);
}
}
}
private void makeRemoveRNTasks() {
for (final Entry<RepGroupId, ShardChange> entry :
diff.getChangedShards().entrySet())
{
final RepGroupId rgId = entry.getKey();
final ShardChange change = entry.getValue();
boolean addedTask = false;
for (final RepNodeId rnId : change.getRemovedRNs()) {
plan.addTask(new RemoveRepNode(plan, rnId, false));
addedTask = true;
}
if (addedTask) {
/*
* After RNs have been removed, update helper hosts for all RNs
* in the shard
*/
makeUpdateHelperParamsTasks(rgId);
}
}
}
/**
* Partition related tasks. For a brand new deployment, add all the
* partitions. For redistributions, generate one task per migrated
* partition.
*/
private void makePartitionTasks() {
/* Brand new deployment -- only create new partitions, no migrations. */
if (diff.getNumCreatedPartitions() > 0) {
List<RepGroupId> newShards = diff.getNewShards();
/*
* If the topology build was not completed there may not yet be any
* shards.
*/
if (newShards.isEmpty()) {
return;
}
List<Integer> partitionCount = new ArrayList<>(newShards.size());
for (RepGroupId rgId : newShards) {
ShardChange change = diff.getShardChange(rgId);
int newParts = change.getNumNewPartitions();
partitionCount.add(newParts);
}
plan.addTask(new AddPartitions(plan, partitionCount,
diff.getNumCreatedPartitions()));
return;
}
if (diff.getChangedShards().isEmpty()) {
return;
}
/* A redistribution. Run all partition migrations in parallel. */
final ParallelBundle bundle = new ParallelBundle();
for (Map.Entry<RepGroupId,ShardChange> entry :
diff.getChangedShards().entrySet()){
RepGroupId targetRGId = entry.getKey();
List<RelocatedPartition> pChanges =
entry.getValue().getMigrations();
for(RelocatedPartition pt : pChanges) {
Task t = new MigratePartition(plan,
pt.getSourceShard(),
targetRGId,
pt.getPartitionId(),
failedShard);
bundle.addTask(t);
}
}
plan.addTask(bundle);
}
private void makeUpdateHelperParamsTasks(RepGroupId rgId)
{
Topology target = candidate.getTopology();
/*
* Filter out the removed shard, because no need to update parameters
* for removed shard
*/
if (target.get(rgId) == null) {
return;
}
for (RepNode member : target.get(rgId).getRepNodes()) {
RepNodeId rnId = member.getResourceId();
plan.addTask(new UpdateHelperHostV2(plan, rnId, rgId));
if (!offlineZones.contains(target.getDatacenterId(rnId))) {
plan.addTask(new NewRepNodeParameters(plan, rnId));
}
}
for (ArbNode member : target.get(rgId).getArbNodes()) {
ArbNodeId anId = member.getResourceId();
plan.addTask(new UpdateHelperHostV2(plan, anId, rgId));
if (!offlineZones.contains(target.getDatacenterId(anId))) {
plan.addTask(new NewArbNodeParameters(plan, anId));
}
}
}
/**
* Return current security metadata stored on admin, may be null if security
* metadata has not been initialized.
*/
private SecurityMetadata getSecurityMetadata() {
final Admin admin = plan.getAdmin();
return admin.getMetadata(SecurityMetadata.class, MetadataType.SECURITY);
}
/**
* Attempt to store Kerberos configuration information in security metadata
* if current store enabled security and configured Kerberos as user
* external authentication method.
*
* @return security metadata after updated Kerberos info.
*/
private SecurityMetadata updateWithKerberosInfo(SecurityMetadata md) {
final AdminServiceParams adminParams = plan.getAdmin().getParams();
final SecurityParams securityParams = adminParams.getSecurityParams();
if (!securityParams.isSecure()) {
return md;
}
final GlobalParams globalParams = adminParams.getGlobalParams();
if (SecurityUtils.hasKerberos(
globalParams.getUserExternalAuthMethods())) {
try {
Utils.storeKerberosInfo(plan, md, logger);
} catch (Exception e) {
throw new IllegalStateException(
"Unexpected error occur while storing Kerberos " +
"principal in metadata: " + e.getMessage(),
e);
}
}
return md;
}
}
|
googleapis/google-cloud-java | 35,590 | java-notebooks/proto-google-cloud-notebooks-v2/src/main/java/com/google/cloud/notebooks/v2/CheckInstanceUpgradabilityResponse.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/v2/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.notebooks.v2;
/**
*
*
* <pre>
* Response for checking if a notebook instance is upgradeable.
* </pre>
*
* Protobuf type {@code google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse}
*/
public final class CheckInstanceUpgradabilityResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse)
CheckInstanceUpgradabilityResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use CheckInstanceUpgradabilityResponse.newBuilder() to construct.
private CheckInstanceUpgradabilityResponse(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private CheckInstanceUpgradabilityResponse() {
upgradeVersion_ = "";
upgradeInfo_ = "";
upgradeImage_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new CheckInstanceUpgradabilityResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.notebooks.v2.ServiceProto
.internal_static_google_cloud_notebooks_v2_CheckInstanceUpgradabilityResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.notebooks.v2.ServiceProto
.internal_static_google_cloud_notebooks_v2_CheckInstanceUpgradabilityResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse.class,
com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse.Builder.class);
}
public static final int UPGRADEABLE_FIELD_NUMBER = 1;
private boolean upgradeable_ = false;
/**
*
*
* <pre>
* If an instance is upgradeable.
* </pre>
*
* <code>bool upgradeable = 1;</code>
*
* @return The upgradeable.
*/
@java.lang.Override
public boolean getUpgradeable() {
return upgradeable_;
}
public static final int UPGRADE_VERSION_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object upgradeVersion_ = "";
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @return The upgradeVersion.
*/
@java.lang.Override
public java.lang.String getUpgradeVersion() {
java.lang.Object ref = upgradeVersion_;
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();
upgradeVersion_ = s;
return s;
}
}
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @return The bytes for upgradeVersion.
*/
@java.lang.Override
public com.google.protobuf.ByteString getUpgradeVersionBytes() {
java.lang.Object ref = upgradeVersion_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
upgradeVersion_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int UPGRADE_INFO_FIELD_NUMBER = 3;
@SuppressWarnings("serial")
private volatile java.lang.Object upgradeInfo_ = "";
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @return The upgradeInfo.
*/
@java.lang.Override
public java.lang.String getUpgradeInfo() {
java.lang.Object ref = upgradeInfo_;
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();
upgradeInfo_ = s;
return s;
}
}
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @return The bytes for upgradeInfo.
*/
@java.lang.Override
public com.google.protobuf.ByteString getUpgradeInfoBytes() {
java.lang.Object ref = upgradeInfo_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
upgradeInfo_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int UPGRADE_IMAGE_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object upgradeImage_ = "";
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @return The upgradeImage.
*/
@java.lang.Override
public java.lang.String getUpgradeImage() {
java.lang.Object ref = upgradeImage_;
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();
upgradeImage_ = s;
return s;
}
}
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @return The bytes for upgradeImage.
*/
@java.lang.Override
public com.google.protobuf.ByteString getUpgradeImageBytes() {
java.lang.Object ref = upgradeImage_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
upgradeImage_ = 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 (upgradeable_ != false) {
output.writeBool(1, upgradeable_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(upgradeVersion_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, upgradeVersion_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(upgradeInfo_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, upgradeInfo_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(upgradeImage_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, upgradeImage_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (upgradeable_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(1, upgradeable_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(upgradeVersion_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, upgradeVersion_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(upgradeInfo_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, upgradeInfo_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(upgradeImage_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, upgradeImage_);
}
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.v2.CheckInstanceUpgradabilityResponse)) {
return super.equals(obj);
}
com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse other =
(com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse) obj;
if (getUpgradeable() != other.getUpgradeable()) return false;
if (!getUpgradeVersion().equals(other.getUpgradeVersion())) return false;
if (!getUpgradeInfo().equals(other.getUpgradeInfo())) return false;
if (!getUpgradeImage().equals(other.getUpgradeImage())) 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) + UPGRADEABLE_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getUpgradeable());
hash = (37 * hash) + UPGRADE_VERSION_FIELD_NUMBER;
hash = (53 * hash) + getUpgradeVersion().hashCode();
hash = (37 * hash) + UPGRADE_INFO_FIELD_NUMBER;
hash = (53 * hash) + getUpgradeInfo().hashCode();
hash = (37 * hash) + UPGRADE_IMAGE_FIELD_NUMBER;
hash = (53 * hash) + getUpgradeImage().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse 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.v2.CheckInstanceUpgradabilityResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse 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.v2.CheckInstanceUpgradabilityResponse parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse 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.v2.CheckInstanceUpgradabilityResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse 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.v2.CheckInstanceUpgradabilityResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse 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.v2.CheckInstanceUpgradabilityResponse 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 checking if a notebook instance is upgradeable.
* </pre>
*
* Protobuf type {@code google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse)
com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.notebooks.v2.ServiceProto
.internal_static_google_cloud_notebooks_v2_CheckInstanceUpgradabilityResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.notebooks.v2.ServiceProto
.internal_static_google_cloud_notebooks_v2_CheckInstanceUpgradabilityResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse.class,
com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse.Builder.class);
}
// Construct using com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
upgradeable_ = false;
upgradeVersion_ = "";
upgradeInfo_ = "";
upgradeImage_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.notebooks.v2.ServiceProto
.internal_static_google_cloud_notebooks_v2_CheckInstanceUpgradabilityResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse
getDefaultInstanceForType() {
return com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse build() {
com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse buildPartial() {
com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse result =
new com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.upgradeable_ = upgradeable_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.upgradeVersion_ = upgradeVersion_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.upgradeInfo_ = upgradeInfo_;
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.upgradeImage_ = upgradeImage_;
}
}
@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.v2.CheckInstanceUpgradabilityResponse) {
return mergeFrom((com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse other) {
if (other
== com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse.getDefaultInstance())
return this;
if (other.getUpgradeable() != false) {
setUpgradeable(other.getUpgradeable());
}
if (!other.getUpgradeVersion().isEmpty()) {
upgradeVersion_ = other.upgradeVersion_;
bitField0_ |= 0x00000002;
onChanged();
}
if (!other.getUpgradeInfo().isEmpty()) {
upgradeInfo_ = other.upgradeInfo_;
bitField0_ |= 0x00000004;
onChanged();
}
if (!other.getUpgradeImage().isEmpty()) {
upgradeImage_ = other.upgradeImage_;
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 8:
{
upgradeable_ = input.readBool();
bitField0_ |= 0x00000001;
break;
} // case 8
case 18:
{
upgradeVersion_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000002;
break;
} // case 18
case 26:
{
upgradeInfo_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
upgradeImage_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
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 boolean upgradeable_;
/**
*
*
* <pre>
* If an instance is upgradeable.
* </pre>
*
* <code>bool upgradeable = 1;</code>
*
* @return The upgradeable.
*/
@java.lang.Override
public boolean getUpgradeable() {
return upgradeable_;
}
/**
*
*
* <pre>
* If an instance is upgradeable.
* </pre>
*
* <code>bool upgradeable = 1;</code>
*
* @param value The upgradeable to set.
* @return This builder for chaining.
*/
public Builder setUpgradeable(boolean value) {
upgradeable_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* If an instance is upgradeable.
* </pre>
*
* <code>bool upgradeable = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearUpgradeable() {
bitField0_ = (bitField0_ & ~0x00000001);
upgradeable_ = false;
onChanged();
return this;
}
private java.lang.Object upgradeVersion_ = "";
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @return The upgradeVersion.
*/
public java.lang.String getUpgradeVersion() {
java.lang.Object ref = upgradeVersion_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
upgradeVersion_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @return The bytes for upgradeVersion.
*/
public com.google.protobuf.ByteString getUpgradeVersionBytes() {
java.lang.Object ref = upgradeVersion_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
upgradeVersion_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @param value The upgradeVersion to set.
* @return This builder for chaining.
*/
public Builder setUpgradeVersion(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
upgradeVersion_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @return This builder for chaining.
*/
public Builder clearUpgradeVersion() {
upgradeVersion_ = getDefaultInstance().getUpgradeVersion();
bitField0_ = (bitField0_ & ~0x00000002);
onChanged();
return this;
}
/**
*
*
* <pre>
* The version this instance will be upgraded to if calling the upgrade
* endpoint. This field will only be populated if field upgradeable is true.
* </pre>
*
* <code>string upgrade_version = 2;</code>
*
* @param value The bytes for upgradeVersion to set.
* @return This builder for chaining.
*/
public Builder setUpgradeVersionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
upgradeVersion_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
private java.lang.Object upgradeInfo_ = "";
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @return The upgradeInfo.
*/
public java.lang.String getUpgradeInfo() {
java.lang.Object ref = upgradeInfo_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
upgradeInfo_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @return The bytes for upgradeInfo.
*/
public com.google.protobuf.ByteString getUpgradeInfoBytes() {
java.lang.Object ref = upgradeInfo_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
upgradeInfo_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @param value The upgradeInfo to set.
* @return This builder for chaining.
*/
public Builder setUpgradeInfo(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
upgradeInfo_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @return This builder for chaining.
*/
public Builder clearUpgradeInfo() {
upgradeInfo_ = getDefaultInstance().getUpgradeInfo();
bitField0_ = (bitField0_ & ~0x00000004);
onChanged();
return this;
}
/**
*
*
* <pre>
* Additional information about upgrade.
* </pre>
*
* <code>string upgrade_info = 3;</code>
*
* @param value The bytes for upgradeInfo to set.
* @return This builder for chaining.
*/
public Builder setUpgradeInfoBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
upgradeInfo_ = value;
bitField0_ |= 0x00000004;
onChanged();
return this;
}
private java.lang.Object upgradeImage_ = "";
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @return The upgradeImage.
*/
public java.lang.String getUpgradeImage() {
java.lang.Object ref = upgradeImage_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
upgradeImage_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @return The bytes for upgradeImage.
*/
public com.google.protobuf.ByteString getUpgradeImageBytes() {
java.lang.Object ref = upgradeImage_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
upgradeImage_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @param value The upgradeImage to set.
* @return This builder for chaining.
*/
public Builder setUpgradeImage(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
upgradeImage_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearUpgradeImage() {
upgradeImage_ = getDefaultInstance().getUpgradeImage();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* The new image self link this instance will be upgraded to if calling the
* upgrade endpoint. This field will only be populated if field upgradeable
* is true.
* </pre>
*
* <code>string upgrade_image = 4;</code>
*
* @param value The bytes for upgradeImage to set.
* @return This builder for chaining.
*/
public Builder setUpgradeImageBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
upgradeImage_ = 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.notebooks.v2.CheckInstanceUpgradabilityResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse)
private static final com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse();
}
public static com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<CheckInstanceUpgradabilityResponse> PARSER =
new com.google.protobuf.AbstractParser<CheckInstanceUpgradabilityResponse>() {
@java.lang.Override
public CheckInstanceUpgradabilityResponse 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<CheckInstanceUpgradabilityResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<CheckInstanceUpgradabilityResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.notebooks.v2.CheckInstanceUpgradabilityResponse
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,611 | java-vpcaccess/proto-google-cloud-vpcaccess-v1/src/main/java/com/google/cloud/vpcaccess/v1/ListConnectorsResponse.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/vpcaccess/v1/vpc_access.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.vpcaccess.v1;
/**
*
*
* <pre>
* Response for listing Serverless VPC Access connectors.
* </pre>
*
* Protobuf type {@code google.cloud.vpcaccess.v1.ListConnectorsResponse}
*/
public final class ListConnectorsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.vpcaccess.v1.ListConnectorsResponse)
ListConnectorsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListConnectorsResponse.newBuilder() to construct.
private ListConnectorsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListConnectorsResponse() {
connectors_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListConnectorsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vpcaccess.v1.VpcAccessProto
.internal_static_google_cloud_vpcaccess_v1_ListConnectorsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vpcaccess.v1.VpcAccessProto
.internal_static_google_cloud_vpcaccess_v1_ListConnectorsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vpcaccess.v1.ListConnectorsResponse.class,
com.google.cloud.vpcaccess.v1.ListConnectorsResponse.Builder.class);
}
public static final int CONNECTORS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.vpcaccess.v1.Connector> connectors_;
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.vpcaccess.v1.Connector> getConnectorsList() {
return connectors_;
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.vpcaccess.v1.ConnectorOrBuilder>
getConnectorsOrBuilderList() {
return connectors_;
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
@java.lang.Override
public int getConnectorsCount() {
return connectors_.size();
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
@java.lang.Override
public com.google.cloud.vpcaccess.v1.Connector getConnectors(int index) {
return connectors_.get(index);
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
@java.lang.Override
public com.google.cloud.vpcaccess.v1.ConnectorOrBuilder getConnectorsOrBuilder(int index) {
return connectors_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Continuation 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>
* Continuation 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 < connectors_.size(); i++) {
output.writeMessage(1, connectors_.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 < connectors_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, connectors_.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.vpcaccess.v1.ListConnectorsResponse)) {
return super.equals(obj);
}
com.google.cloud.vpcaccess.v1.ListConnectorsResponse other =
(com.google.cloud.vpcaccess.v1.ListConnectorsResponse) obj;
if (!getConnectorsList().equals(other.getConnectorsList())) 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 (getConnectorsCount() > 0) {
hash = (37 * hash) + CONNECTORS_FIELD_NUMBER;
hash = (53 * hash) + getConnectorsList().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.vpcaccess.v1.ListConnectorsResponse parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vpcaccess.v1.ListConnectorsResponse 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.vpcaccess.v1.ListConnectorsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vpcaccess.v1.ListConnectorsResponse 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.vpcaccess.v1.ListConnectorsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.vpcaccess.v1.ListConnectorsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.vpcaccess.v1.ListConnectorsResponse parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vpcaccess.v1.ListConnectorsResponse 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.vpcaccess.v1.ListConnectorsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.vpcaccess.v1.ListConnectorsResponse 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.vpcaccess.v1.ListConnectorsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.vpcaccess.v1.ListConnectorsResponse 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.vpcaccess.v1.ListConnectorsResponse 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 listing Serverless VPC Access connectors.
* </pre>
*
* Protobuf type {@code google.cloud.vpcaccess.v1.ListConnectorsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.vpcaccess.v1.ListConnectorsResponse)
com.google.cloud.vpcaccess.v1.ListConnectorsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.vpcaccess.v1.VpcAccessProto
.internal_static_google_cloud_vpcaccess_v1_ListConnectorsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.vpcaccess.v1.VpcAccessProto
.internal_static_google_cloud_vpcaccess_v1_ListConnectorsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.vpcaccess.v1.ListConnectorsResponse.class,
com.google.cloud.vpcaccess.v1.ListConnectorsResponse.Builder.class);
}
// Construct using com.google.cloud.vpcaccess.v1.ListConnectorsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (connectorsBuilder_ == null) {
connectors_ = java.util.Collections.emptyList();
} else {
connectors_ = null;
connectorsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.vpcaccess.v1.VpcAccessProto
.internal_static_google_cloud_vpcaccess_v1_ListConnectorsResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.vpcaccess.v1.ListConnectorsResponse getDefaultInstanceForType() {
return com.google.cloud.vpcaccess.v1.ListConnectorsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.vpcaccess.v1.ListConnectorsResponse build() {
com.google.cloud.vpcaccess.v1.ListConnectorsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.vpcaccess.v1.ListConnectorsResponse buildPartial() {
com.google.cloud.vpcaccess.v1.ListConnectorsResponse result =
new com.google.cloud.vpcaccess.v1.ListConnectorsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.vpcaccess.v1.ListConnectorsResponse result) {
if (connectorsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
connectors_ = java.util.Collections.unmodifiableList(connectors_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.connectors_ = connectors_;
} else {
result.connectors_ = connectorsBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.vpcaccess.v1.ListConnectorsResponse 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.vpcaccess.v1.ListConnectorsResponse) {
return mergeFrom((com.google.cloud.vpcaccess.v1.ListConnectorsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.vpcaccess.v1.ListConnectorsResponse other) {
if (other == com.google.cloud.vpcaccess.v1.ListConnectorsResponse.getDefaultInstance())
return this;
if (connectorsBuilder_ == null) {
if (!other.connectors_.isEmpty()) {
if (connectors_.isEmpty()) {
connectors_ = other.connectors_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureConnectorsIsMutable();
connectors_.addAll(other.connectors_);
}
onChanged();
}
} else {
if (!other.connectors_.isEmpty()) {
if (connectorsBuilder_.isEmpty()) {
connectorsBuilder_.dispose();
connectorsBuilder_ = null;
connectors_ = other.connectors_;
bitField0_ = (bitField0_ & ~0x00000001);
connectorsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getConnectorsFieldBuilder()
: null;
} else {
connectorsBuilder_.addAllMessages(other.connectors_);
}
}
}
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.vpcaccess.v1.Connector m =
input.readMessage(
com.google.cloud.vpcaccess.v1.Connector.parser(), extensionRegistry);
if (connectorsBuilder_ == null) {
ensureConnectorsIsMutable();
connectors_.add(m);
} else {
connectorsBuilder_.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.vpcaccess.v1.Connector> connectors_ =
java.util.Collections.emptyList();
private void ensureConnectorsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
connectors_ = new java.util.ArrayList<com.google.cloud.vpcaccess.v1.Connector>(connectors_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vpcaccess.v1.Connector,
com.google.cloud.vpcaccess.v1.Connector.Builder,
com.google.cloud.vpcaccess.v1.ConnectorOrBuilder>
connectorsBuilder_;
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public java.util.List<com.google.cloud.vpcaccess.v1.Connector> getConnectorsList() {
if (connectorsBuilder_ == null) {
return java.util.Collections.unmodifiableList(connectors_);
} else {
return connectorsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public int getConnectorsCount() {
if (connectorsBuilder_ == null) {
return connectors_.size();
} else {
return connectorsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public com.google.cloud.vpcaccess.v1.Connector getConnectors(int index) {
if (connectorsBuilder_ == null) {
return connectors_.get(index);
} else {
return connectorsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public Builder setConnectors(int index, com.google.cloud.vpcaccess.v1.Connector value) {
if (connectorsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureConnectorsIsMutable();
connectors_.set(index, value);
onChanged();
} else {
connectorsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public Builder setConnectors(
int index, com.google.cloud.vpcaccess.v1.Connector.Builder builderForValue) {
if (connectorsBuilder_ == null) {
ensureConnectorsIsMutable();
connectors_.set(index, builderForValue.build());
onChanged();
} else {
connectorsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public Builder addConnectors(com.google.cloud.vpcaccess.v1.Connector value) {
if (connectorsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureConnectorsIsMutable();
connectors_.add(value);
onChanged();
} else {
connectorsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public Builder addConnectors(int index, com.google.cloud.vpcaccess.v1.Connector value) {
if (connectorsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureConnectorsIsMutable();
connectors_.add(index, value);
onChanged();
} else {
connectorsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public Builder addConnectors(com.google.cloud.vpcaccess.v1.Connector.Builder builderForValue) {
if (connectorsBuilder_ == null) {
ensureConnectorsIsMutable();
connectors_.add(builderForValue.build());
onChanged();
} else {
connectorsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public Builder addConnectors(
int index, com.google.cloud.vpcaccess.v1.Connector.Builder builderForValue) {
if (connectorsBuilder_ == null) {
ensureConnectorsIsMutable();
connectors_.add(index, builderForValue.build());
onChanged();
} else {
connectorsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public Builder addAllConnectors(
java.lang.Iterable<? extends com.google.cloud.vpcaccess.v1.Connector> values) {
if (connectorsBuilder_ == null) {
ensureConnectorsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, connectors_);
onChanged();
} else {
connectorsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public Builder clearConnectors() {
if (connectorsBuilder_ == null) {
connectors_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
connectorsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public Builder removeConnectors(int index) {
if (connectorsBuilder_ == null) {
ensureConnectorsIsMutable();
connectors_.remove(index);
onChanged();
} else {
connectorsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public com.google.cloud.vpcaccess.v1.Connector.Builder getConnectorsBuilder(int index) {
return getConnectorsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public com.google.cloud.vpcaccess.v1.ConnectorOrBuilder getConnectorsOrBuilder(int index) {
if (connectorsBuilder_ == null) {
return connectors_.get(index);
} else {
return connectorsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public java.util.List<? extends com.google.cloud.vpcaccess.v1.ConnectorOrBuilder>
getConnectorsOrBuilderList() {
if (connectorsBuilder_ != null) {
return connectorsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(connectors_);
}
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public com.google.cloud.vpcaccess.v1.Connector.Builder addConnectorsBuilder() {
return getConnectorsFieldBuilder()
.addBuilder(com.google.cloud.vpcaccess.v1.Connector.getDefaultInstance());
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public com.google.cloud.vpcaccess.v1.Connector.Builder addConnectorsBuilder(int index) {
return getConnectorsFieldBuilder()
.addBuilder(index, com.google.cloud.vpcaccess.v1.Connector.getDefaultInstance());
}
/**
*
*
* <pre>
* List of Serverless VPC Access connectors.
* </pre>
*
* <code>repeated .google.cloud.vpcaccess.v1.Connector connectors = 1;</code>
*/
public java.util.List<com.google.cloud.vpcaccess.v1.Connector.Builder>
getConnectorsBuilderList() {
return getConnectorsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vpcaccess.v1.Connector,
com.google.cloud.vpcaccess.v1.Connector.Builder,
com.google.cloud.vpcaccess.v1.ConnectorOrBuilder>
getConnectorsFieldBuilder() {
if (connectorsBuilder_ == null) {
connectorsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.vpcaccess.v1.Connector,
com.google.cloud.vpcaccess.v1.Connector.Builder,
com.google.cloud.vpcaccess.v1.ConnectorOrBuilder>(
connectors_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
connectors_ = null;
}
return connectorsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* Continuation 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>
* Continuation 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>
* Continuation 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>
* Continuation 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>
* Continuation 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.cloud.vpcaccess.v1.ListConnectorsResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.vpcaccess.v1.ListConnectorsResponse)
private static final com.google.cloud.vpcaccess.v1.ListConnectorsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.vpcaccess.v1.ListConnectorsResponse();
}
public static com.google.cloud.vpcaccess.v1.ListConnectorsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListConnectorsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListConnectorsResponse>() {
@java.lang.Override
public ListConnectorsResponse 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<ListConnectorsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListConnectorsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.vpcaccess.v1.ListConnectorsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/harmony | 35,633 | classlib/modules/luni/src/test/api/common/org/apache/harmony/luni/tests/java/net/ServerSocketTest.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.luni.tests.java.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.BindException;
import java.net.ConnectException;
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.net.SocketImpl;
import java.net.SocketImplFactory;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;
import org.apache.harmony.luni.net.PlainServerSocketImpl;
import tests.support.Support_Configuration;
import tests.support.Support_Exec;
public class ServerSocketTest extends SocketTestCase {
boolean interrupted;
ServerSocket s;
Socket sconn;
Thread t;
static class SSClient implements Runnable {
Socket cs;
int port;
public SSClient(int prt) {
port = prt;
}
public void run() {
try {
// Go to sleep so the server can setup and wait for connection
Thread.sleep(1000);
cs = new Socket(InetAddress.getLocalHost().getHostName(), port);
// Sleep again to allow server side processing. Thread is
// stopped by server.
Thread.sleep(10000);
} catch (InterruptedException e) {
return;
} catch (Throwable e) {
System.out
.println("Error establishing client: " + e.toString());
} finally {
try {
if (cs != null)
cs.close();
} catch (Exception e) {
}
}
}
}
/**
* @tests java.net.ServerSocket#ServerSocket()
*/
public void test_Constructor() {
// Test for method java.net.ServerSocket(int)
assertTrue("Used during tests", true);
}
/**
* @tests java.net.ServerSocket#ServerSocket(int)
*/
public void test_ConstructorI() {
// Test for method java.net.ServerSocket(int)
assertTrue("Used during tests", true);
}
/**
* @tests java.net.ServerSocket#ServerSocket(int)
*/
public void test_ConstructorI_SocksSet() throws IOException {
// Harmony-623 regression test
ServerSocket ss = null;
Properties props = (Properties) System.getProperties().clone();
try {
System.setProperty("socksProxyHost", "127.0.0.1");
System.setProperty("socksProxyPort", "12345");
ss = new ServerSocket(0);
} finally {
System.setProperties(props);
if (null != ss) {
ss.close();
}
}
}
/**
* @tests java.net.ServerSocket#ServerSocket(int, int)
*/
public void test_ConstructorII() throws IOException {
try {
s = new ServerSocket(0, 10);
s.setSoTimeout(2000);
startClient(s.getLocalPort());
sconn = s.accept();
} catch (InterruptedIOException e) {
return;
}
ServerSocket s1 = new ServerSocket(0);
try {
try {
ServerSocket s2 = new ServerSocket(s1.getLocalPort());
s2.close();
fail("Was able to create two serversockets on same port");
} catch (BindException e) {
// Expected
}
} finally {
s1.close();
}
s1 = new ServerSocket(0);
int allocatedPort = s1.getLocalPort();
s1.close();
s1 = new ServerSocket(allocatedPort);
s1.close();
}
/**
* @tests java.net.ServerSocket#ServerSocket(int, int, java.net.InetAddress)
*/
public void test_ConstructorIILjava_net_InetAddress()
throws UnknownHostException, IOException {
s = new ServerSocket(0, 10, InetAddress.getLocalHost());
try {
s.setSoTimeout(5000);
startClient(s.getLocalPort());
sconn = s.accept();
assertNotNull("Was unable to accept connection", sconn);
sconn.close();
} finally {
s.close();
}
}
/**
* @tests java.net.ServerSocket#accept()
*/
public void test_accept() throws IOException {
s = new ServerSocket(0);
try {
s.setSoTimeout(5000);
startClient(s.getLocalPort());
sconn = s.accept();
int localPort1 = s.getLocalPort();
int localPort2 = sconn.getLocalPort();
sconn.close();
assertEquals("Bad local port value", localPort1, localPort2);
} finally {
s.close();
}
try {
interrupted = false;
final ServerSocket ss = new ServerSocket(0);
ss.setSoTimeout(12000);
Runnable runnable = new Runnable() {
public void run() {
try {
ss.accept();
} catch (InterruptedIOException e) {
interrupted = true;
} catch (IOException e) {
}
}
};
Thread thread = new Thread(runnable, "ServerSocket.accept");
thread.start();
try {
do {
Thread.sleep(500);
} while (!thread.isAlive());
} catch (InterruptedException e) {
}
ss.close();
int c = 0;
do {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
if (interrupted) {
fail("accept interrupted");
}
if (++c > 4) {
fail("accept call did not exit");
}
} while (thread.isAlive());
interrupted = false;
ServerSocket ss2 = new ServerSocket(0);
ss2.setSoTimeout(500);
Date start = new Date();
try {
ss2.accept();
} catch (InterruptedIOException e) {
interrupted = true;
}
assertTrue("accept not interrupted", interrupted);
Date finish = new Date();
int delay = (int) (finish.getTime() - start.getTime());
assertTrue("timeout too soon: " + delay + " " + start.getTime()
+ " " + finish.getTime(), delay >= 490);
ss2.close();
} catch (IOException e) {
fail("Unexpected IOException : " + e.getMessage());
}
}
/**
* @tests java.net.ServerSocket#close()
*/
public void test_close() throws IOException {
try {
s = new ServerSocket(0);
try {
s.close();
s.accept();
fail("Close test failed");
} catch (SocketException e) {
// expected;
}
} finally {
s.close();
}
}
/**
* @tests java.net.ServerSocket#getInetAddress()
*/
public void test_getInetAddress() throws IOException {
InetAddress addr = InetAddress.getLocalHost();
s = new ServerSocket(0, 10, addr);
try {
assertEquals("Returned incorrect InetAdrees", addr, s
.getInetAddress());
} finally {
s.close();
}
}
/**
* @tests java.net.ServerSocket#getLocalPort()
*/
public void test_getLocalPort() throws IOException {
// Try a specific port number, but don't complain if we don't get it
int portNumber = 63024; // I made this up
try {
try {
s = new ServerSocket(portNumber);
} catch (BindException e) {
// we could not get the port, give up
return;
}
assertEquals("Returned incorrect port", portNumber, s
.getLocalPort());
} finally {
s.close();
}
}
/**
* @tests java.net.ServerSocket#getSoTimeout()
*/
public void test_getSoTimeout() throws IOException {
s = new ServerSocket(0);
try {
s.setSoTimeout(100);
assertEquals("Returned incorrect sotimeout", 100, s.getSoTimeout());
} finally {
s.close();
}
}
/**
* @tests java.net.ServerSocket#setSocketFactory(java.net.SocketImplFactory)
*/
public void test_setSocketFactoryLjava_net_SocketImplFactory()
throws IOException {
SocketImplFactory factory = new MockSocketImplFactory();
// Should not throw SocketException when set DatagramSocketImplFactory
// for the first time.
ServerSocket.setSocketFactory(factory);
try {
ServerSocket.setSocketFactory(null);
fail("Should throw SocketException");
} catch (SocketException e) {
// Expected
}
try {
ServerSocket.setSocketFactory(factory);
fail("Should throw SocketException");
} catch (SocketException e) {
// Expected
}
}
private static class MockSocketImplFactory implements SocketImplFactory {
public SocketImpl createSocketImpl() {
return new PlainServerSocketImpl();
}
}
/**
* @tests java.net.ServerSocket#setSoTimeout(int)
*/
public void test_setSoTimeoutI() throws IOException {
// Timeout should trigger and throw InterruptedIOException
try {
s = new ServerSocket(0);
s.setSoTimeout(100);
s.accept();
} catch (InterruptedIOException e) {
assertEquals("Set incorrect sotimeout", 100, s.getSoTimeout());
return;
}
// Timeout should not trigger in this case
s = new ServerSocket(0);
startClient(s.getLocalPort());
s.setSoTimeout(10000);
sconn = s.accept();
}
/**
* @tests java.net.ServerSocket#toString()
*/
public void test_toString() throws Exception {
s = new ServerSocket(0);
try {
int portNumber = s.getLocalPort();
assertEquals("ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport="
+ portNumber + "]", s.toString());
} finally {
s.close();
}
}
/**
* @tests java.net.ServerSocket#bind(java.net.SocketAddress)
*/
public void test_bindLjava_net_SocketAddress() throws IOException {
class mySocketAddress extends SocketAddress {
public mySocketAddress() {
}
}
// create servers socket, bind it and then validate basic state
ServerSocket theSocket = new ServerSocket();
InetSocketAddress theAddress = new InetSocketAddress(InetAddress
.getLocalHost(), 0);
theSocket.bind(theAddress);
int portNumber = theSocket.getLocalPort();
assertTrue(
"Returned incorrect InetSocketAddress(2):"
+ theSocket.getLocalSocketAddress().toString()
+ "Expected: "
+ (new InetSocketAddress(InetAddress.getLocalHost(),
portNumber)).toString(), theSocket
.getLocalSocketAddress().equals(
new InetSocketAddress(InetAddress
.getLocalHost(), portNumber)));
assertTrue("Server socket not bound when it should be:", theSocket
.isBound());
// now make sure that it is actually bound and listening on the
// address we provided
Socket clientSocket = new Socket();
InetSocketAddress clAddress = new InetSocketAddress(InetAddress
.getLocalHost(), portNumber);
clientSocket.connect(clAddress);
Socket servSock = theSocket.accept();
assertEquals(clAddress, clientSocket.getRemoteSocketAddress());
theSocket.close();
servSock.close();
clientSocket.close();
// validate we can specify null for the address in the bind and all
// goes ok
theSocket = new ServerSocket();
theSocket.bind(null);
theSocket.close();
// Address that we have already bound to
theSocket = new ServerSocket();
ServerSocket theSocket2 = new ServerSocket();
try {
theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
theSocket.bind(theAddress);
SocketAddress localAddress = theSocket.getLocalSocketAddress();
theSocket2.bind(localAddress);
fail("No exception binding to address that is not available");
} catch (IOException ex) {
}
theSocket.close();
theSocket2.close();
// validate we get io address when we try to bind to address we
// cannot bind to
theSocket = new ServerSocket();
try {
theSocket.bind(new InetSocketAddress(InetAddress
.getByAddress(Support_Configuration.nonLocalAddressBytes),
0));
fail("No exception was thrown when binding to bad address");
} catch (IOException ex) {
}
theSocket.close();
// now validate case where we pass in an unsupported subclass of
// SocketAddress
theSocket = new ServerSocket();
try {
theSocket.bind(new mySocketAddress());
fail("No exception when binding using unsupported SocketAddress subclass");
} catch (IllegalArgumentException ex) {
}
theSocket.close();
}
/**
* @tests java.net.ServerSocket#bind(java.net.SocketAddress,int)
*/
public void test_bindLjava_net_SocketAddressI() throws IOException {
class mySocketAddress extends SocketAddress {
public mySocketAddress() {
}
}
// create servers socket, bind it and then validate basic state
ServerSocket theSocket = new ServerSocket();
InetSocketAddress theAddress = new InetSocketAddress(InetAddress
.getLocalHost(), 0);
theSocket.bind(theAddress, 5);
int portNumber = theSocket.getLocalPort();
assertTrue(
"Returned incorrect InetSocketAddress(2):"
+ theSocket.getLocalSocketAddress().toString()
+ "Expected: "
+ (new InetSocketAddress(InetAddress.getLocalHost(),
portNumber)).toString(), theSocket
.getLocalSocketAddress().equals(
new InetSocketAddress(InetAddress
.getLocalHost(), portNumber)));
assertTrue("Server socket not bound when it should be:", theSocket
.isBound());
// now make sure that it is actually bound and listening on the
// address we provided
SocketAddress localAddress = theSocket.getLocalSocketAddress();
Socket clientSocket = new Socket();
clientSocket.connect(localAddress);
Socket servSock = theSocket.accept();
assertTrue(clientSocket.getRemoteSocketAddress().equals(localAddress));
theSocket.close();
servSock.close();
clientSocket.close();
// validate we can specify null for the address in the bind and all
// goes ok
theSocket = new ServerSocket();
theSocket.bind(null, 5);
theSocket.close();
// Address that we have already bound to
theSocket = new ServerSocket();
ServerSocket theSocket2 = new ServerSocket();
try {
theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
theSocket.bind(theAddress, 5);
SocketAddress inuseAddress = theSocket.getLocalSocketAddress();
theSocket2.bind(inuseAddress, 5);
fail("No exception binding to address that is not available");
} catch (IOException ex) {
// expected
}
theSocket.close();
theSocket2.close();
// validate we get ioException when we try to bind to address we
// cannot bind to
theSocket = new ServerSocket();
try {
theSocket.bind(new InetSocketAddress(InetAddress
.getByAddress(Support_Configuration.nonLocalAddressBytes),
0), 5);
fail("No exception was thrown when binding to bad address");
} catch (IOException ex) {
}
theSocket.close();
// now validate case where we pass in an unsupported subclass of
// SocketAddress
theSocket = new ServerSocket();
try {
theSocket.bind(new mySocketAddress(), 5);
fail("Binding using unsupported SocketAddress subclass should have thrown exception");
} catch (IllegalArgumentException ex) {
}
theSocket.close();
// now validate that backlog is respected. We have to do a test that
// checks if it is a least a certain number as some platforms make
// it higher than we request. Unfortunately non-server versions of
// windows artificially limit the backlog to 5 and 5 is the
// historical default so it is not a great test.
theSocket = new ServerSocket();
theAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
theSocket.bind(theAddress, 4);
localAddress = theSocket.getLocalSocketAddress();
Socket theSockets[] = new Socket[4];
int i = 0;
try {
for (i = 0; i < 4; i++) {
theSockets[i] = new Socket();
theSockets[i].connect(localAddress);
}
} catch (ConnectException ex) {
fail("Backlog does not seem to be respected in bind:" + i + ":"
+ ex.toString());
}
for (i = 0; i < 4; i++) {
theSockets[i].close();
}
theSocket.close();
servSock.close();
}
/**
* @tests java.net.ServerSocket#getLocalSocketAddress()
*/
public void test_getLocalSocketAddress() throws Exception {
// set up server connect and then validate that we get the right
// response for the local address
ServerSocket theSocket = new ServerSocket(0, 5, InetAddress
.getLocalHost());
int portNumber = theSocket.getLocalPort();
assertTrue("Returned incorrect InetSocketAddress(1):"
+ theSocket.getLocalSocketAddress().toString()
+ "Expected: "
+ (new InetSocketAddress(InetAddress.getLocalHost(),
portNumber)).toString(), theSocket
.getLocalSocketAddress().equals(
new InetSocketAddress(InetAddress.getLocalHost(),
portNumber)));
theSocket.close();
// now create a socket that is not bound and validate we get the
// right answer
theSocket = new ServerSocket();
assertNull(
"Returned incorrect InetSocketAddress -unbound socket- Expected null",
theSocket.getLocalSocketAddress());
// now bind the socket and make sure we get the right answer
theSocket
.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
int localPort = theSocket.getLocalPort();
assertEquals("Returned incorrect InetSocketAddress(2):", theSocket
.getLocalSocketAddress(), new InetSocketAddress(InetAddress
.getLocalHost(), localPort));
theSocket.close();
}
/**
* @tests java.net.ServerSocket#isBound()
*/
public void test_isBound() throws IOException {
InetAddress addr = InetAddress.getLocalHost();
ServerSocket serverSocket = new ServerSocket();
assertFalse("Socket indicated bound when it should be (1)",
serverSocket.isBound());
// now bind and validate bound ok
serverSocket.bind(new InetSocketAddress(addr, 0));
assertTrue("Socket indicated not bound when it should be (1)",
serverSocket.isBound());
serverSocket.close();
// now do with some of the other constructors
serverSocket = new ServerSocket(0);
assertTrue("Socket indicated not bound when it should be (2)",
serverSocket.isBound());
serverSocket.close();
serverSocket = new ServerSocket(0, 5, addr);
assertTrue("Socket indicated not bound when it should be (3)",
serverSocket.isBound());
serverSocket.close();
serverSocket = new ServerSocket(0, 5);
assertTrue("Socket indicated not bound when it should be (4)",
serverSocket.isBound());
serverSocket.close();
}
/**
* @tests java.net.ServerSocket#isClosed()
*/
public void test_isClosed() throws IOException {
InetAddress addr = InetAddress.getLocalHost();
ServerSocket serverSocket = new ServerSocket(0, 5, addr);
// validate isClosed returns expected values
assertFalse("Socket should indicate it is not closed(1):", serverSocket
.isClosed());
serverSocket.close();
assertTrue("Socket should indicate it is closed(1):", serverSocket
.isClosed());
// now do with some of the other constructors
serverSocket = new ServerSocket(0);
assertFalse("Socket should indicate it is not closed(1):", serverSocket
.isClosed());
serverSocket.close();
assertTrue("Socket should indicate it is closed(1):", serverSocket
.isClosed());
serverSocket = new ServerSocket(0, 5, addr);
assertFalse("Socket should indicate it is not closed(1):", serverSocket
.isClosed());
serverSocket.close();
assertTrue("Socket should indicate it is closed(1):", serverSocket
.isClosed());
serverSocket = new ServerSocket(0, 5);
assertFalse("Socket should indicate it is not closed(1):", serverSocket
.isClosed());
serverSocket.close();
assertTrue("Socket should indicate it is closed(1):", serverSocket
.isClosed());
}
/*
* Regression HARMONY-6090
*/
public void test_defaultValueReuseAddress() throws Exception {
String platform = System.getProperty("os.name").toLowerCase(Locale.US);
if (!platform.startsWith("windows")) {
// on Unix
assertTrue(new ServerSocket().getReuseAddress());
assertTrue(new ServerSocket(0).getReuseAddress());
assertTrue(new ServerSocket(0, 50).getReuseAddress());
assertTrue(new ServerSocket(0, 50, InetAddress.getLocalHost()).getReuseAddress());
} else {
// on Windows
assertFalse(new ServerSocket().getReuseAddress());
assertFalse(new ServerSocket(0).getReuseAddress());
assertFalse(new ServerSocket(0, 50).getReuseAddress());
assertFalse(new ServerSocket(0, 50, InetAddress.getLocalHost()).getReuseAddress());
}
}
/**
* @tests java.net.ServerSocket#setReuseAddress(boolean)
*/
public void test_setReuseAddressZ() {
try {
// set up server and connect
InetSocketAddress anyAddress = new InetSocketAddress(InetAddress
.getLocalHost(), 0);
ServerSocket serverSocket = new ServerSocket();
serverSocket.setReuseAddress(false);
serverSocket.bind(anyAddress);
SocketAddress theAddress = serverSocket.getLocalSocketAddress();
// make a connection to the server, then close the server
Socket theSocket = new Socket();
theSocket.connect(theAddress);
Socket stillActiveSocket = serverSocket.accept();
serverSocket.close();
// now try to rebind the server which should fail with
// setReuseAddress to false. On windows platforms the bind is
// allowed even then reUseAddress is false so our test uses
// the platform to determine what the expected result is.
String platform = System.getProperty("os.name");
try {
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(false);
serverSocket.bind(theAddress);
if ((!platform.startsWith("Windows"))) {
fail("No exception when setReuseAddress is false and we bind:"
+ theAddress.toString());
}
} catch (IOException ex) {
if (platform.startsWith("Windows")) {
fail("Got unexpected exception when binding with setReuseAddress false on windows platform:"
+ theAddress.toString() + ":" + ex.toString());
}
}
stillActiveSocket.close();
theSocket.close();
// now test case were we set it to true
anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(anyAddress);
theAddress = serverSocket.getLocalSocketAddress();
// make a connection to the server, then close the server
theSocket = new Socket();
theSocket.connect(theAddress);
stillActiveSocket = serverSocket.accept();
serverSocket.close();
// now try to rebind the server which should pass with
// setReuseAddress to true
try {
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.bind(theAddress);
} catch (IOException ex) {
fail("Unexpected exception when setReuseAddress is true and we bind:"
+ theAddress.toString() + ":" + ex.toString());
}
stillActiveSocket.close();
theSocket.close();
ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
// now test default case were we expect this to work regardless of
// the value set
anyAddress = new InetSocketAddress(InetAddress.getLocalHost(), 0);
serverSocket = new ServerSocket();
serverSocket.bind(anyAddress);
theAddress = serverSocket.getLocalSocketAddress();
// make a connection to the server, then close the server
theSocket = new Socket();
theSocket.connect(theAddress);
stillActiveSocket = serverSocket.accept();
serverSocket.close();
// now try to rebind the server which should pass
try {
serverSocket = new ServerSocket();
serverSocket.bind(theAddress);
} catch (IOException ex) {
fail("Unexpected exception when setReuseAddress is the default case and we bind:"
+ theAddress.toString() + ":" + ex.toString());
}
stillActiveSocket.close();
theSocket.close();
ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
} catch (Exception e) {
handleException(e, SO_REUSEADDR);
}
}
/**
* @tests java.net.ServerSocket#getReuseAddress()
*/
public void test_getReuseAddress() {
try {
ServerSocket theSocket = new ServerSocket();
theSocket.setReuseAddress(true);
assertTrue("getReuseAddress false when it should be true",
theSocket.getReuseAddress());
theSocket.setReuseAddress(false);
assertFalse("getReuseAddress true when it should be False",
theSocket.getReuseAddress());
ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_REUSEADDR);
} catch (Exception e) {
handleException(e, SO_REUSEADDR);
}
}
/**
* @tests java.net.ServerSocket#setReceiveBufferSize(int)
*/
public void test_setReceiveBufferSizeI() {
try {
// now validate case where we try to set to 0
ServerSocket theSocket = new ServerSocket();
try {
theSocket.setReceiveBufferSize(0);
fail("No exception when receive buffer size set to 0");
} catch (IllegalArgumentException ex) {
}
theSocket.close();
// now validate case where we try to set to a negative value
theSocket = new ServerSocket();
try {
theSocket.setReceiveBufferSize(-1000);
fail("No exception when receive buffer size set to -1000");
} catch (IllegalArgumentException ex) {
}
theSocket.close();
// now just try to set a good value to make sure it is set and there
// are not exceptions
theSocket = new ServerSocket();
theSocket.setReceiveBufferSize(1000);
theSocket.close();
ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
} catch (Exception e) {
handleException(e, SO_RCVBUF);
}
}
/*
* @tests java.net.ServerSocket#getReceiveBufferSize()
*/
public void test_getReceiveBufferSize() {
try {
ServerSocket theSocket = new ServerSocket();
// since the value returned is not necessary what we set we are
// limited in what we can test
// just validate that it is not 0 or negative
assertFalse("get Buffer size returns 0:", 0 == theSocket
.getReceiveBufferSize());
assertFalse("get Buffer size returns a negative value:",
0 > theSocket.getReceiveBufferSize());
ensureExceptionThrownIfOptionIsUnsupportedOnOS(SO_RCVBUF);
} catch (Exception e) {
handleException(e, SO_RCVBUF);
}
}
/**
* @tests java.net.ServerSocket#getChannel()
*/
public void test_getChannel() throws Exception {
assertNull(new ServerSocket().getChannel());
}
/*
* @tests java.net.ServerSocket#setPerformancePreference()
*/
public void test_setPerformancePreference_Int_Int_Int() throws Exception {
ServerSocket theSocket = new ServerSocket();
theSocket.setPerformancePreferences(1, 1, 1);
}
/**
* Sets up the fixture, for example, open a network connection. This method
* is called before a test is executed.
*/
protected void setUp() {
}
/**
* Tears down the fixture, for example, close a network connection. This
* method is called after a test is executed.
*/
protected void tearDown() {
try {
if (s != null)
s.close();
if (sconn != null)
sconn.close();
if (t != null)
t.interrupt();
} catch (Exception e) {
}
}
/**
* Sets up the fixture, for example, open a network connection. This method
* is called before a test is executed.
*/
protected void startClient(int port) {
t = new Thread(new SSClient(port), "SSClient");
t.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Exception during startClinet()" + e.toString());
}
}
/**
* @tests java.net.ServerSocket#implAccept
*/
public void test_implAcceptLjava_net_Socket() throws Exception {
// regression test for Harmony-1235
try {
new MockServerSocket().mockImplAccept(new MockSocket(
new MockSocketImpl()));
} catch (SocketException e) {
// expected
}
}
/**
* Regression for HARMONY-3265
* @throws Exception
*/
public void test_ServerSocket_init() throws Exception {
String[] args = new String[]{"org.apache.harmony.luni.tests.java.net.TestServerSocketInit"};
Support_Exec.execJava(args, null, true);
}
static class MockSocketImpl extends SocketImpl {
protected void create(boolean arg0) throws IOException {
// empty
}
protected void connect(String arg0, int arg1) throws IOException {
// empty
}
protected void connect(InetAddress arg0, int arg1) throws IOException {
// empty
}
protected void connect(SocketAddress arg0, int arg1) throws IOException {
// empty
}
protected void bind(InetAddress arg0, int arg1) throws IOException {
// empty
}
protected void listen(int arg0) throws IOException {
// empty
}
protected void accept(SocketImpl arg0) throws IOException {
// empty
}
protected InputStream getInputStream() throws IOException {
return null;
}
protected OutputStream getOutputStream() throws IOException {
return null;
}
protected int available() throws IOException {
return 0;
}
protected void close() throws IOException {
// empty
}
protected void sendUrgentData(int arg0) throws IOException {
// empty
}
public void setOption(int arg0, Object arg1) throws SocketException {
// empty
}
public Object getOption(int arg0) throws SocketException {
return null;
}
}
static class MockSocket extends Socket {
public MockSocket(SocketImpl impl) throws SocketException {
super(impl);
}
}
static class MockServerSocket extends ServerSocket {
public MockServerSocket() throws Exception {
super();
}
public void mockImplAccept(Socket s) throws Exception {
super.implAccept(s);
}
}
}
|
google/j2objc | 35,942 | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UTS46.java | /* GENERATED SOURCE. DO NOT MODIFY. */
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
/*
*******************************************************************************
* Copyright (C) 2010-2014, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
*/
package android.icu.impl;
import java.util.EnumSet;
import android.icu.lang.UCharacter;
import android.icu.lang.UCharacterCategory;
import android.icu.lang.UCharacterDirection;
import android.icu.lang.UScript;
import android.icu.text.IDNA;
import android.icu.text.Normalizer2;
import android.icu.text.StringPrepParseException;
import android.icu.util.ICUException;
// Note about tests for IDNA.Error.DOMAIN_NAME_TOO_LONG:
//
// The domain name length limit is 255 octets in an internal DNS representation
// where the last ("root") label is the empty label
// represented by length byte 0 alone.
// In a conventional string, this translates to 253 characters, or 254
// if there is a trailing dot for the root label.
/**
* UTS #46 (IDNA2008) implementation.
* @author Markus Scherer
* @hide Only a subset of ICU is exposed in Android
*/
public final class UTS46 extends IDNA {
public UTS46(int options) {
this.options=options;
}
@Override
public StringBuilder labelToASCII(CharSequence label, StringBuilder dest, Info info) {
return process(label, true, true, dest, info);
}
@Override
public StringBuilder labelToUnicode(CharSequence label, StringBuilder dest, Info info) {
return process(label, true, false, dest, info);
}
@Override
public StringBuilder nameToASCII(CharSequence name, StringBuilder dest, Info info) {
process(name, false, true, dest, info);
if( dest.length()>=254 && !info.getErrors().contains(Error.DOMAIN_NAME_TOO_LONG) &&
isASCIIString(dest) &&
(dest.length()>254 || dest.charAt(253)!='.')
) {
addError(info, Error.DOMAIN_NAME_TOO_LONG);
}
return dest;
}
@Override
public StringBuilder nameToUnicode(CharSequence name, StringBuilder dest, Info info) {
return process(name, false, false, dest, info);
}
private static final Normalizer2 uts46Norm2=
Normalizer2.getInstance(null, "uts46", Normalizer2.Mode.COMPOSE); // uts46.nrm
final int options;
// Severe errors which usually result in a U+FFFD replacement character in the result string.
private static final EnumSet<Error> severeErrors=EnumSet.of(
Error.LEADING_COMBINING_MARK,
Error.DISALLOWED,
Error.PUNYCODE,
Error.LABEL_HAS_DOT,
Error.INVALID_ACE_LABEL);
private static boolean
isASCIIString(CharSequence dest) {
int length=dest.length();
for(int i=0; i<length; ++i) {
if(dest.charAt(i)>0x7f) {
return false;
}
}
return true;
}
// UTS #46 data for ASCII characters.
// The normalizer (using uts46.nrm) maps uppercase ASCII letters to lowercase
// and passes through all other ASCII characters.
// If USE_STD3_RULES is set, then non-LDH characters are disallowed
// using this data.
// The ASCII fastpath also uses this data.
// Values: -1=disallowed 0==valid 1==mapped (lowercase)
private static final byte asciiData[]={
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
// 002D..002E; valid # HYPHEN-MINUS..FULL STOP
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, -1,
// 0030..0039; valid # DIGIT ZERO..DIGIT NINE
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1,
// 0041..005A; mapped # LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER Z
-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1,
// 0061..007A; valid # LATIN SMALL LETTER A..LATIN SMALL LETTER Z
-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1
};
private StringBuilder
process(CharSequence src,
boolean isLabel, boolean toASCII,
StringBuilder dest,
Info info) {
// uts46Norm2.normalize() would do all of this error checking and setup,
// but with the ASCII fastpath we do not always call it, and do not
// call it first.
if(dest==src) {
throw new IllegalArgumentException();
}
// Arguments are fine, reset output values.
dest.delete(0, 0x7fffffff);
resetInfo(info);
int srcLength=src.length();
if(srcLength==0) {
addError(info, Error.EMPTY_LABEL);
return dest;
}
// ASCII fastpath
boolean disallowNonLDHDot=(options&USE_STD3_RULES)!=0;
int labelStart=0;
int i;
for(i=0;; ++i) {
if(i==srcLength) {
if(toASCII) {
if((i-labelStart)>63) {
addLabelError(info, Error.LABEL_TOO_LONG);
}
// There is a trailing dot if labelStart==i.
if(!isLabel && i>=254 && (i>254 || labelStart<i)) {
addError(info, Error.DOMAIN_NAME_TOO_LONG);
}
}
promoteAndResetLabelErrors(info);
return dest;
}
char c=src.charAt(i);
if(c>0x7f) {
break;
}
int cData=asciiData[c];
if(cData>0) {
dest.append((char)(c+0x20)); // Lowercase an uppercase ASCII letter.
} else if(cData<0 && disallowNonLDHDot) {
break; // Replacing with U+FFFD can be complicated for toASCII.
} else {
dest.append(c);
if(c=='-') { // hyphen
if(i==(labelStart+3) && src.charAt(i-1)=='-') {
// "??--..." is Punycode or forbidden.
++i; // '-' was copied to dest already
break;
}
if(i==labelStart) {
// label starts with "-"
addLabelError(info, Error.LEADING_HYPHEN);
}
if((i+1)==srcLength || src.charAt(i+1)=='.') {
// label ends with "-"
addLabelError(info, Error.TRAILING_HYPHEN);
}
} else if(c=='.') { // dot
if(isLabel) {
// Replacing with U+FFFD can be complicated for toASCII.
++i; // '.' was copied to dest already
break;
}
if(i==labelStart) {
addLabelError(info, Error.EMPTY_LABEL);
}
if(toASCII && (i-labelStart)>63) {
addLabelError(info, Error.LABEL_TOO_LONG);
}
promoteAndResetLabelErrors(info);
labelStart=i+1;
}
}
}
promoteAndResetLabelErrors(info);
processUnicode(src, labelStart, i, isLabel, toASCII, dest, info);
if( isBiDi(info) && !hasCertainErrors(info, severeErrors) &&
(!isOkBiDi(info) || (labelStart>0 && !isASCIIOkBiDi(dest, labelStart)))
) {
addError(info, Error.BIDI);
}
return dest;
}
private StringBuilder
processUnicode(CharSequence src,
int labelStart, int mappingStart,
boolean isLabel, boolean toASCII,
StringBuilder dest,
Info info) {
if(mappingStart==0) {
uts46Norm2.normalize(src, dest);
} else {
uts46Norm2.normalizeSecondAndAppend(dest, src.subSequence(mappingStart, src.length()));
}
boolean doMapDevChars=
toASCII ? (options&NONTRANSITIONAL_TO_ASCII)==0 :
(options&NONTRANSITIONAL_TO_UNICODE)==0;
int destLength=dest.length();
int labelLimit=labelStart;
while(labelLimit<destLength) {
char c=dest.charAt(labelLimit);
if(c=='.' && !isLabel) {
int labelLength=labelLimit-labelStart;
int newLength=processLabel(dest, labelStart, labelLength,
toASCII, info);
promoteAndResetLabelErrors(info);
destLength+=newLength-labelLength;
labelLimit=labelStart+=newLength+1;
} else if(0xdf<=c && c<=0x200d && (c==0xdf || c==0x3c2 || c>=0x200c)) {
setTransitionalDifferent(info);
if(doMapDevChars) {
destLength=mapDevChars(dest, labelStart, labelLimit);
// Do not increment labelLimit in case c was removed.
// All deviation characters have been mapped, no need to check for them again.
doMapDevChars=false;
} else {
++labelLimit;
}
} else {
++labelLimit;
}
}
// Permit an empty label at the end (0<labelStart==labelLimit==destLength is ok)
// but not an empty label elsewhere nor a completely empty domain name.
// processLabel() sets UIDNA_ERROR_EMPTY_LABEL when labelLength==0.
if(0==labelStart || labelStart<labelLimit) {
processLabel(dest, labelStart, labelLimit-labelStart, toASCII, info);
promoteAndResetLabelErrors(info);
}
return dest;
}
// returns the new dest.length()
private int
mapDevChars(StringBuilder dest, int labelStart, int mappingStart) {
int length=dest.length();
boolean didMapDevChars=false;
for(int i=mappingStart; i<length;) {
char c=dest.charAt(i);
switch(c) {
case 0xdf:
// Map sharp s to ss.
didMapDevChars=true;
dest.setCharAt(i++, 's');
dest.insert(i++, 's');
++length;
break;
case 0x3c2: // Map final sigma to nonfinal sigma.
didMapDevChars=true;
dest.setCharAt(i++, '\u03c3');
break;
case 0x200c: // Ignore/remove ZWNJ.
case 0x200d: // Ignore/remove ZWJ.
didMapDevChars=true;
dest.delete(i, i+1);
--length;
break;
default:
++i;
break;
}
}
if(didMapDevChars) {
// Mapping deviation characters might have resulted in an un-NFC string.
// We could use either the NFC or the UTS #46 normalizer.
// By using the UTS #46 normalizer again, we avoid having to load a second .nrm data file.
String normalized=uts46Norm2.normalize(dest.subSequence(labelStart, dest.length()));
dest.replace(labelStart, 0x7fffffff, normalized);
return dest.length();
}
return length;
}
// Some non-ASCII characters are equivalent to sequences with
// non-LDH ASCII characters. To find them:
// grep disallowed_STD3_valid IdnaMappingTable.txt (or uts46.txt)
private static boolean
isNonASCIIDisallowedSTD3Valid(int c) {
return c==0x2260 || c==0x226E || c==0x226F;
}
// Replace the label in dest with the label string, if the label was modified.
// If label==dest then the label was modified in-place and labelLength
// is the new label length, different from label.length().
// If label!=dest then labelLength==label.length().
// Returns labelLength (= the new label length).
private static int
replaceLabel(StringBuilder dest, int destLabelStart, int destLabelLength,
CharSequence label, int labelLength) {
if(label!=dest) {
dest.delete(destLabelStart, destLabelStart+destLabelLength).insert(destLabelStart, label);
// or dest.replace(destLabelStart, destLabelStart+destLabelLength, label.toString());
// which would create a String rather than moving characters in the StringBuilder.
}
return labelLength;
}
// returns the new label length
private int
processLabel(StringBuilder dest,
int labelStart, int labelLength,
boolean toASCII,
Info info) {
StringBuilder fromPunycode;
StringBuilder labelString;
int destLabelStart=labelStart;
int destLabelLength=labelLength;
boolean wasPunycode;
if( labelLength>=4 &&
dest.charAt(labelStart)=='x' && dest.charAt(labelStart+1)=='n' &&
dest.charAt(labelStart+2)=='-' && dest.charAt(labelStart+3)=='-'
) {
// Label starts with "xn--", try to un-Punycode it.
wasPunycode=true;
try {
fromPunycode=Punycode.decode(dest.subSequence(labelStart+4, labelStart+labelLength), null);
} catch (StringPrepParseException e) {
addLabelError(info, Error.PUNYCODE);
return markBadACELabel(dest, labelStart, labelLength, toASCII, info);
}
// Check for NFC, and for characters that are not
// valid or deviation characters according to the normalizer.
// If there is something wrong, then the string will change.
// Note that the normalizer passes through non-LDH ASCII and deviation characters.
// Deviation characters are ok in Punycode even in transitional processing.
// In the code further below, if we find non-LDH ASCII and we have UIDNA_USE_STD3_RULES
// then we will set UIDNA_ERROR_INVALID_ACE_LABEL there too.
boolean isValid=uts46Norm2.isNormalized(fromPunycode);
if(!isValid) {
addLabelError(info, Error.INVALID_ACE_LABEL);
return markBadACELabel(dest, labelStart, labelLength, toASCII, info);
}
labelString=fromPunycode;
labelStart=0;
labelLength=fromPunycode.length();
} else {
wasPunycode=false;
labelString=dest;
}
// Validity check
if(labelLength==0) {
addLabelError(info, Error.EMPTY_LABEL);
return replaceLabel(dest, destLabelStart, destLabelLength, labelString, labelLength);
}
// labelLength>0
if(labelLength>=4 && labelString.charAt(labelStart+2)=='-' && labelString.charAt(labelStart+3)=='-') {
// label starts with "??--"
addLabelError(info, Error.HYPHEN_3_4);
}
if(labelString.charAt(labelStart)=='-') {
// label starts with "-"
addLabelError(info, Error.LEADING_HYPHEN);
}
if(labelString.charAt(labelStart+labelLength-1)=='-') {
// label ends with "-"
addLabelError(info, Error.TRAILING_HYPHEN);
}
// If the label was not a Punycode label, then it was the result of
// mapping, normalization and label segmentation.
// If the label was in Punycode, then we mapped it again above
// and checked its validity.
// Now we handle the STD3 restriction to LDH characters (if set)
// and we look for U+FFFD which indicates disallowed characters
// in a non-Punycode label or U+FFFD itself in a Punycode label.
// We also check for dots which can come from the input to a single-label function.
// Ok to cast away const because we own the UnicodeString.
int i=labelStart;
int limit=labelStart+labelLength;
char oredChars=0;
// If we enforce STD3 rules, then ASCII characters other than LDH and dot are disallowed.
boolean disallowNonLDHDot=(options&USE_STD3_RULES)!=0;
do {
char c=labelString.charAt(i);
if(c<=0x7f) {
if(c=='.') {
addLabelError(info, Error.LABEL_HAS_DOT);
labelString.setCharAt(i, '\ufffd');
} else if(disallowNonLDHDot && asciiData[c]<0) {
addLabelError(info, Error.DISALLOWED);
labelString.setCharAt(i, '\ufffd');
}
} else {
oredChars|=c;
if(disallowNonLDHDot && isNonASCIIDisallowedSTD3Valid(c)) {
addLabelError(info, Error.DISALLOWED);
labelString.setCharAt(i, '\ufffd');
} else if(c==0xfffd) {
addLabelError(info, Error.DISALLOWED);
}
}
++i;
} while(i<limit);
// Check for a leading combining mark after other validity checks
// so that we don't report IDNA.Error.DISALLOWED for the U+FFFD from here.
int c;
// "Unsafe" is ok because unpaired surrogates were mapped to U+FFFD.
c=labelString.codePointAt(labelStart);
if((U_GET_GC_MASK(c)&U_GC_M_MASK)!=0) {
addLabelError(info, Error.LEADING_COMBINING_MARK);
labelString.setCharAt(labelStart, '\ufffd');
if(c>0xffff) {
// Remove c's trail surrogate.
labelString.deleteCharAt(labelStart+1);
--labelLength;
if(labelString==dest) {
--destLabelLength;
}
}
}
if(!hasCertainLabelErrors(info, severeErrors)) {
// Do contextual checks only if we do not have U+FFFD from a severe error
// because U+FFFD can make these checks fail.
if((options&CHECK_BIDI)!=0 && (!isBiDi(info) || isOkBiDi(info))) {
checkLabelBiDi(labelString, labelStart, labelLength, info);
}
if( (options&CHECK_CONTEXTJ)!=0 && (oredChars&0x200c)==0x200c &&
!isLabelOkContextJ(labelString, labelStart, labelLength)
) {
addLabelError(info, Error.CONTEXTJ);
}
if((options&CHECK_CONTEXTO)!=0 && oredChars>=0xb7) {
checkLabelContextO(labelString, labelStart, labelLength, info);
}
if(toASCII) {
if(wasPunycode) {
// Leave a Punycode label unchanged if it has no severe errors.
if(destLabelLength>63) {
addLabelError(info, Error.LABEL_TOO_LONG);
}
return destLabelLength;
} else if(oredChars>=0x80) {
// Contains non-ASCII characters.
StringBuilder punycode;
try {
punycode=Punycode.encode(labelString.subSequence(labelStart, labelStart+labelLength), null);
} catch (StringPrepParseException e) {
throw new ICUException(e); // unexpected
}
punycode.insert(0, "xn--");
if(punycode.length()>63) {
addLabelError(info, Error.LABEL_TOO_LONG);
}
return replaceLabel(dest, destLabelStart, destLabelLength,
punycode, punycode.length());
} else {
// all-ASCII label
if(labelLength>63) {
addLabelError(info, Error.LABEL_TOO_LONG);
}
}
}
} else {
// If a Punycode label has severe errors,
// then leave it but make sure it does not look valid.
if(wasPunycode) {
addLabelError(info, Error.INVALID_ACE_LABEL);
return markBadACELabel(dest, destLabelStart, destLabelLength, toASCII, info);
}
}
return replaceLabel(dest, destLabelStart, destLabelLength, labelString, labelLength);
}
private int
markBadACELabel(StringBuilder dest,
int labelStart, int labelLength,
boolean toASCII, Info info) {
boolean disallowNonLDHDot=(options&USE_STD3_RULES)!=0;
boolean isASCII=true;
boolean onlyLDH=true;
int i=labelStart+4; // After the initial "xn--".
int limit=labelStart+labelLength;
do {
char c=dest.charAt(i);
if(c<=0x7f) {
if(c=='.') {
addLabelError(info, Error.LABEL_HAS_DOT);
dest.setCharAt(i, '\ufffd');
isASCII=onlyLDH=false;
} else if(asciiData[c]<0) {
onlyLDH=false;
if(disallowNonLDHDot) {
dest.setCharAt(i, '\ufffd');
isASCII=false;
}
}
} else {
isASCII=onlyLDH=false;
}
} while(++i<limit);
if(onlyLDH) {
dest.insert(labelStart+labelLength, '\ufffd');
++labelLength;
} else {
if(toASCII && isASCII && labelLength>63) {
addLabelError(info, Error.LABEL_TOO_LONG);
}
}
return labelLength;
}
private static final int L_MASK=U_MASK(UCharacterDirection.LEFT_TO_RIGHT);
private static final int R_AL_MASK=
U_MASK(UCharacterDirection.RIGHT_TO_LEFT)|
U_MASK(UCharacterDirection.RIGHT_TO_LEFT_ARABIC);
private static final int L_R_AL_MASK=L_MASK|R_AL_MASK;
private static final int R_AL_AN_MASK=R_AL_MASK|U_MASK(UCharacterDirection.ARABIC_NUMBER);
private static final int EN_AN_MASK=
U_MASK(UCharacterDirection.EUROPEAN_NUMBER)|
U_MASK(UCharacterDirection.ARABIC_NUMBER);
private static final int R_AL_EN_AN_MASK=R_AL_MASK|EN_AN_MASK;
private static final int L_EN_MASK=L_MASK|U_MASK(UCharacterDirection.EUROPEAN_NUMBER);
private static final int ES_CS_ET_ON_BN_NSM_MASK=
U_MASK(UCharacterDirection.EUROPEAN_NUMBER_SEPARATOR)|
U_MASK(UCharacterDirection.COMMON_NUMBER_SEPARATOR)|
U_MASK(UCharacterDirection.EUROPEAN_NUMBER_TERMINATOR)|
U_MASK(UCharacterDirection.OTHER_NEUTRAL)|
U_MASK(UCharacterDirection.BOUNDARY_NEUTRAL)|
U_MASK(UCharacterDirection.DIR_NON_SPACING_MARK);
private static final int L_EN_ES_CS_ET_ON_BN_NSM_MASK=L_EN_MASK|ES_CS_ET_ON_BN_NSM_MASK;
private static final int R_AL_AN_EN_ES_CS_ET_ON_BN_NSM_MASK=R_AL_MASK|EN_AN_MASK|ES_CS_ET_ON_BN_NSM_MASK;
// We scan the whole label and check both for whether it contains RTL characters
// and whether it passes the BiDi Rule.
// In a BiDi domain name, all labels must pass the BiDi Rule, but we might find
// that a domain name is a BiDi domain name (has an RTL label) only after
// processing several earlier labels.
private void
checkLabelBiDi(CharSequence label, int labelStart, int labelLength, Info info) {
// IDNA2008 BiDi rule
// Get the directionality of the first character.
int c;
int i=labelStart;
c=Character.codePointAt(label, i);
i+=Character.charCount(c);
int firstMask=U_MASK(UBiDiProps.INSTANCE.getClass(c));
// 1. The first character must be a character with BIDI property L, R
// or AL. If it has the R or AL property, it is an RTL label; if it
// has the L property, it is an LTR label.
if((firstMask&~L_R_AL_MASK)!=0) {
setNotOkBiDi(info);
}
// Get the directionality of the last non-NSM character.
int lastMask;
int labelLimit=labelStart+labelLength;
for(;;) {
if(i>=labelLimit) {
lastMask=firstMask;
break;
}
c=Character.codePointBefore(label, labelLimit);
labelLimit-=Character.charCount(c);
int dir=UBiDiProps.INSTANCE.getClass(c);
if(dir!=UCharacterDirection.DIR_NON_SPACING_MARK) {
lastMask=U_MASK(dir);
break;
}
}
// 3. In an RTL label, the end of the label must be a character with
// BIDI property R, AL, EN or AN, followed by zero or more
// characters with BIDI property NSM.
// 6. In an LTR label, the end of the label must be a character with
// BIDI property L or EN, followed by zero or more characters with
// BIDI property NSM.
if( (firstMask&L_MASK)!=0 ?
(lastMask&~L_EN_MASK)!=0 :
(lastMask&~R_AL_EN_AN_MASK)!=0
) {
setNotOkBiDi(info);
}
// Get the directionalities of the intervening characters.
int mask=0;
while(i<labelLimit) {
c=Character.codePointAt(label, i);
i+=Character.charCount(c);
mask|=U_MASK(UBiDiProps.INSTANCE.getClass(c));
}
if((firstMask&L_MASK)!=0) {
// 5. In an LTR label, only characters with the BIDI properties L, EN,
// ES, CS, ET, ON, BN and NSM are allowed.
if((mask&~L_EN_ES_CS_ET_ON_BN_NSM_MASK)!=0) {
setNotOkBiDi(info);
}
} else {
// 2. In an RTL label, only characters with the BIDI properties R, AL,
// AN, EN, ES, CS, ET, ON, BN and NSM are allowed.
if((mask&~R_AL_AN_EN_ES_CS_ET_ON_BN_NSM_MASK)!=0) {
setNotOkBiDi(info);
}
// 4. In an RTL label, if an EN is present, no AN may be present, and
// vice versa.
if((mask&EN_AN_MASK)==EN_AN_MASK) {
setNotOkBiDi(info);
}
}
// An RTL label is a label that contains at least one character of type
// R, AL or AN. [...]
// A "BIDI domain name" is a domain name that contains at least one RTL
// label. [...]
// The following rule, consisting of six conditions, applies to labels
// in BIDI domain names.
if(((firstMask|mask|lastMask)&R_AL_AN_MASK)!=0) {
setBiDi(info);
}
}
// Special code for the ASCII prefix of a BiDi domain name.
// The ASCII prefix is all-LTR.
// IDNA2008 BiDi rule, parts relevant to ASCII labels:
// 1. The first character must be a character with BIDI property L [...]
// 5. In an LTR label, only characters with the BIDI properties L, EN,
// ES, CS, ET, ON, BN and NSM are allowed.
// 6. In an LTR label, the end of the label must be a character with
// BIDI property L or EN [...]
// UTF-16 version, called for mapped ASCII prefix.
// Cannot contain uppercase A-Z.
// s[length-1] must be the trailing dot.
private static boolean
isASCIIOkBiDi(CharSequence s, int length) {
int labelStart=0;
for(int i=0; i<length; ++i) {
char c=s.charAt(i);
if(c=='.') { // dot
if(i>labelStart) {
c=s.charAt(i-1);
if(!('a'<=c && c<='z') && !('0'<=c && c<='9')) {
// Last character in the label is not an L or EN.
return false;
}
}
labelStart=i+1;
} else if(i==labelStart) {
if(!('a'<=c && c<='z')) {
// First character in the label is not an L.
return false;
}
} else {
if(c<=0x20 && (c>=0x1c || (9<=c && c<=0xd))) {
// Intermediate character in the label is a B, S or WS.
return false;
}
}
}
return true;
}
private boolean
isLabelOkContextJ(CharSequence label, int labelStart, int labelLength) {
// [IDNA2008-Tables]
// 200C..200D ; CONTEXTJ # ZERO WIDTH NON-JOINER..ZERO WIDTH JOINER
int labelLimit=labelStart+labelLength;
for(int i=labelStart; i<labelLimit; ++i) {
if(label.charAt(i)==0x200c) {
// Appendix A.1. ZERO WIDTH NON-JOINER
// Rule Set:
// False;
// If Canonical_Combining_Class(Before(cp)) .eq. Virama Then True;
// If RegExpMatch((Joining_Type:{L,D})(Joining_Type:T)*\u200C
// (Joining_Type:T)*(Joining_Type:{R,D})) Then True;
if(i==labelStart) {
return false;
}
int c;
int j=i;
c=Character.codePointBefore(label, j);
j-=Character.charCount(c);
if(uts46Norm2.getCombiningClass(c)==9) {
continue;
}
// check precontext (Joining_Type:{L,D})(Joining_Type:T)*
for(;;) {
/* UJoiningType */ int type=UBiDiProps.INSTANCE.getJoiningType(c);
if(type==UCharacter.JoiningType.TRANSPARENT) {
if(j==0) {
return false;
}
c=Character.codePointBefore(label, j);
j-=Character.charCount(c);
} else if(type==UCharacter.JoiningType.LEFT_JOINING || type==UCharacter.JoiningType.DUAL_JOINING) {
break; // precontext fulfilled
} else {
return false;
}
}
// check postcontext (Joining_Type:T)*(Joining_Type:{R,D})
for(j=i+1;;) {
if(j==labelLimit) {
return false;
}
c=Character.codePointAt(label, j);
j+=Character.charCount(c);
/* UJoiningType */ int type=UBiDiProps.INSTANCE.getJoiningType(c);
if(type==UCharacter.JoiningType.TRANSPARENT) {
// just skip this character
} else if(type==UCharacter.JoiningType.RIGHT_JOINING || type==UCharacter.JoiningType.DUAL_JOINING) {
break; // postcontext fulfilled
} else {
return false;
}
}
} else if(label.charAt(i)==0x200d) {
// Appendix A.2. ZERO WIDTH JOINER (U+200D)
// Rule Set:
// False;
// If Canonical_Combining_Class(Before(cp)) .eq. Virama Then True;
if(i==labelStart) {
return false;
}
int c=Character.codePointBefore(label, i);
if(uts46Norm2.getCombiningClass(c)!=9) {
return false;
}
}
}
return true;
}
private void
checkLabelContextO(CharSequence label, int labelStart, int labelLength, Info info) {
int labelEnd=labelStart+labelLength-1; // inclusive
int arabicDigits=0; // -1 for 066x, +1 for 06Fx
for(int i=labelStart; i<=labelEnd; ++i) {
int c=label.charAt(i);
if(c<0xb7) {
// ASCII fastpath
} else if(c<=0x6f9) {
if(c==0xb7) {
// Appendix A.3. MIDDLE DOT (U+00B7)
// Rule Set:
// False;
// If Before(cp) .eq. U+006C And
// After(cp) .eq. U+006C Then True;
if(!(labelStart<i && label.charAt(i-1)=='l' &&
i<labelEnd && label.charAt(i+1)=='l')) {
addLabelError(info, Error.CONTEXTO_PUNCTUATION);
}
} else if(c==0x375) {
// Appendix A.4. GREEK LOWER NUMERAL SIGN (KERAIA) (U+0375)
// Rule Set:
// False;
// If Script(After(cp)) .eq. Greek Then True;
if(!(i<labelEnd &&
UScript.GREEK==UScript.getScript(Character.codePointAt(label, i+1)))) {
addLabelError(info, Error.CONTEXTO_PUNCTUATION);
}
} else if(c==0x5f3 || c==0x5f4) {
// Appendix A.5. HEBREW PUNCTUATION GERESH (U+05F3)
// Rule Set:
// False;
// If Script(Before(cp)) .eq. Hebrew Then True;
//
// Appendix A.6. HEBREW PUNCTUATION GERSHAYIM (U+05F4)
// Rule Set:
// False;
// If Script(Before(cp)) .eq. Hebrew Then True;
if(!(labelStart<i &&
UScript.HEBREW==UScript.getScript(Character.codePointBefore(label, i)))) {
addLabelError(info, Error.CONTEXTO_PUNCTUATION);
}
} else if(0x660<=c /* && c<=0x6f9 */) {
// Appendix A.8. ARABIC-INDIC DIGITS (0660..0669)
// Rule Set:
// True;
// For All Characters:
// If cp .in. 06F0..06F9 Then False;
// End For;
//
// Appendix A.9. EXTENDED ARABIC-INDIC DIGITS (06F0..06F9)
// Rule Set:
// True;
// For All Characters:
// If cp .in. 0660..0669 Then False;
// End For;
if(c<=0x669) {
if(arabicDigits>0) {
addLabelError(info, Error.CONTEXTO_DIGITS);
}
arabicDigits=-1;
} else if(0x6f0<=c) {
if(arabicDigits<0) {
addLabelError(info, Error.CONTEXTO_DIGITS);
}
arabicDigits=1;
}
}
} else if(c==0x30fb) {
// Appendix A.7. KATAKANA MIDDLE DOT (U+30FB)
// Rule Set:
// False;
// For All Characters:
// If Script(cp) .in. {Hiragana, Katakana, Han} Then True;
// End For;
for(int j=labelStart;; j+=Character.charCount(c)) {
if(j>labelEnd) {
addLabelError(info, Error.CONTEXTO_PUNCTUATION);
break;
}
c=Character.codePointAt(label, j);
int script=UScript.getScript(c);
if(script==UScript.HIRAGANA || script==UScript.KATAKANA || script==UScript.HAN) {
break;
}
}
}
}
}
// TODO: make public(?) -- in C, these are public in uchar.h
private static int U_MASK(int x) {
return 1<<x;
}
private static int U_GET_GC_MASK(int c) {
return (1<<UCharacter.getType(c));
}
private static int U_GC_M_MASK=
U_MASK(UCharacterCategory.NON_SPACING_MARK)|
U_MASK(UCharacterCategory.ENCLOSING_MARK)|
U_MASK(UCharacterCategory.COMBINING_SPACING_MARK);
}
|
apache/harmony | 35,430 | classlib/modules/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/rowset/RowSetMetaDataImplTest.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.sql.tests.javax.sql.rowset;
import java.io.Serializable;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import javax.sql.rowset.RowSetMetaDataImpl;
import org.apache.harmony.testframework.serialization.SerializationTest;
import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* Test class for javax.sql.rowset.RowSetMetaDataImpl
*
*/
public class RowSetMetaDataImplTest extends TestCase {
private static RowSetMetaDataImpl metaDataImpl = null;
/**
* This comparator is designed for RowSetMetaDataImpl objects whose colCount
* has already been set. Other objects may fail when using it.
*/
private final static SerializableAssert ROWSET_METADATA_COMPARATOR = new SerializableAssert() {
public void assertDeserialized(Serializable initial,
Serializable deserialized) {
try {
RowSetMetaDataImpl initialImpl = (RowSetMetaDataImpl) initial;
RowSetMetaDataImpl deserializedImpl = (RowSetMetaDataImpl) deserialized;
Assert.assertEquals(initialImpl.getColumnCount(),
deserializedImpl.getColumnCount());
Assert.assertEquals(initialImpl.getColumnType(1),
deserializedImpl.getColumnType(1));
} catch (SQLException e) {
fail();
}
}
};
/**
* @tests javax.sql.rowset.RowSetMetaDataImpl#RowSetMetaDataImpl()
*/
public void test_Constructor() {
assertNotNull(metaDataImpl);
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#getColumnCount()}
*/
public void test_getColumnCount() throws SQLException {
assertEquals(0, metaDataImpl.getColumnCount());
try {
metaDataImpl.isAutoIncrement(1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(4);
assertEquals(4, metaDataImpl.getColumnCount());
assertFalse(metaDataImpl.isAutoIncrement(4));
metaDataImpl.setColumnCount(Integer.MAX_VALUE);
assertFalse(metaDataImpl.isAutoIncrement(4));
// assertEquals(Integer.MAX_VALUE, metaDataImpl.getColumnCount());
// RI throws ArrayIndexOutOfBoundsException here, which is a RI's bug
try {
metaDataImpl.isAutoIncrement(5);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setColumnCount(int)}
*/
public void test_setColumnCountI() throws SQLException {
try {
metaDataImpl.setColumnCount(-1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
try {
metaDataImpl.setColumnCount(0);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(18);
assertEquals(18, metaDataImpl.getColumnCount());
metaDataImpl.setAutoIncrement(1, true);
assertTrue(metaDataImpl.isAutoIncrement(1));
// original records have been overwritten
metaDataImpl.setColumnCount(19);
assertEquals(19, metaDataImpl.getColumnCount());
assertFalse(metaDataImpl.isAutoIncrement(1));
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#getCatalogName(int)}
*/
public void test_getCatalogNameI() throws SQLException {
try {
metaDataImpl.getCatalogName(1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(2);
assertEquals("", metaDataImpl.getCatalogName(1));
metaDataImpl.setCatalogName(1, "catalog");
assertEquals("catalog", metaDataImpl.getCatalogName(1));
metaDataImpl.setCatalogName(1, null);
assertEquals("", metaDataImpl.getCatalogName(1));
try {
metaDataImpl.getCatalogName(Integer.MIN_VALUE);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#getColumnClassName(int)}
*/
public void test_getColumnClassNameI() throws SQLException {
try {
metaDataImpl.getColumnClassName(1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(12);
assertEquals("java.lang.String", metaDataImpl.getColumnClassName(12));
metaDataImpl.setColumnTypeName(12, null);
assertEquals("java.lang.String", metaDataImpl.getColumnClassName(12));
metaDataImpl.setColumnType(12, Types.BLOB);
assertEquals("[B", metaDataImpl.getColumnClassName(12));
metaDataImpl.setColumnType(12, Types.FLOAT);
assertEquals("java.lang.Double", metaDataImpl.getColumnClassName(12));
metaDataImpl.setColumnType(12, Types.BIGINT);
assertEquals("java.lang.Long", metaDataImpl.getColumnClassName(12));
metaDataImpl.setColumnType(12, Types.BIT);
assertEquals("java.lang.Boolean", metaDataImpl.getColumnClassName(12));
metaDataImpl.setColumnType(12, Types.DECIMAL);
assertEquals("java.math.BigDecimal", metaDataImpl
.getColumnClassName(12));
metaDataImpl.setColumnType(12, Types.TINYINT);
assertEquals("java.lang.Byte", metaDataImpl.getColumnClassName(12));
try {
metaDataImpl.getColumnClassName(0);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#getColumnDisplaySize(int)}
*/
public void test_getColumnDisplaySizeI() throws SQLException {
try {
metaDataImpl.getColumnDisplaySize(1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(2);
assertEquals(0, metaDataImpl.getColumnDisplaySize(1));
metaDataImpl.setColumnDisplaySize(1, 4);
assertEquals(4, metaDataImpl.getColumnDisplaySize(1));
try {
metaDataImpl.getColumnDisplaySize(-32);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#getColumnLabel(int)}
*/
public void test_getColumnLabelI() throws SQLException {
try {
metaDataImpl.getColumnLabel(1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(3);
assertNull(metaDataImpl.getColumnLabel(1));
metaDataImpl.setColumnLabel(1, null);
assertEquals("", metaDataImpl.getColumnLabel(1));
metaDataImpl.setColumnLabel(1, "err");
assertEquals("err", metaDataImpl.getColumnLabel(1));
try {
metaDataImpl.getColumnLabel(11);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#getColumnName(int)}
*/
public void test_getColumnNameI() throws SQLException {
try {
metaDataImpl.getColumnName(1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(13);
assertNull(metaDataImpl.getColumnName(12));
metaDataImpl.setColumnName(12, null);
assertEquals("", metaDataImpl.getColumnName(12));
metaDataImpl.setColumnName(12, "ColumnName");
assertEquals("ColumnName", metaDataImpl.getColumnName(12));
try {
metaDataImpl.getColumnName(0);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#getColumnType(int)}
*/
public void test_getColumnTypeI() throws SQLException {
try {
metaDataImpl.getColumnType(1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(13);
metaDataImpl.setColumnType(13, Types.ARRAY);
assertEquals(Types.ARRAY, metaDataImpl.getColumnType(13));
try {
metaDataImpl.getColumnType(14);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#getColumnTypeName(int)}
*/
public void test_getColumnTypeNameI() throws SQLException {
try {
metaDataImpl.getColumnTypeName(223);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(21);
metaDataImpl.setColumnType(14, Types.BIGINT);
metaDataImpl.setColumnTypeName(14, null);
assertEquals("", metaDataImpl.getColumnTypeName(14));
metaDataImpl.setColumnTypeName(14, "haha");
assertEquals("haha", metaDataImpl.getColumnTypeName(14));
try {
metaDataImpl.getColumnTypeName(22);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#getPrecision(int)}
*/
public void test_getPrecisionI() throws SQLException {
try {
metaDataImpl.getPrecision(2);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(1);
assertEquals(0, metaDataImpl.getPrecision(1));
metaDataImpl.setPrecision(1, Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, metaDataImpl.getPrecision(1));
try {
metaDataImpl.getPrecision(3);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#getSchemaName(int)}
*/
public void test_getScaleI() throws SQLException {
try {
metaDataImpl.getScale(1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(2);
assertEquals(0, metaDataImpl.getScale(2));
metaDataImpl.setScale(2, Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, metaDataImpl.getScale(2));
try {
metaDataImpl.getScale(3);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#getSchemaName(int)}
*/
public void test_getSchemaNameI() throws SQLException {
try {
metaDataImpl.getSchemaName(352);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(67);
metaDataImpl.setSchemaName(67, null);
assertEquals("", metaDataImpl.getSchemaName(67));
metaDataImpl.setSchemaName(67, "a \u0053");
assertEquals("a S", metaDataImpl.getSchemaName(67));
try {
metaDataImpl.getSchemaName(Integer.MIN_VALUE);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#getTableName(int)}
*/
public void test_getTableNameI() throws SQLException {
try {
metaDataImpl.getTableName(2);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(2);
assertEquals("", metaDataImpl.getTableName(1));
assertEquals("", metaDataImpl.getTableName(2));
metaDataImpl.setTableName(1, "tableName");
assertEquals("tableName", metaDataImpl.getTableName(1));
assertEquals("", metaDataImpl.getTableName(2));
try {
metaDataImpl.getTableName(Integer.MIN_VALUE);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#isAutoIncrement(int)}
*/
public void test_isAutoIncrementI() throws SQLException {
try {
metaDataImpl.isAutoIncrement(1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(3);
assertFalse(metaDataImpl.isAutoIncrement(1));
assertFalse(metaDataImpl.isAutoIncrement(3));
metaDataImpl.setAutoIncrement(3, true);
assertTrue(metaDataImpl.isAutoIncrement(3));
try {
metaDataImpl.isAutoIncrement(-1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
try {
metaDataImpl.isAutoIncrement(4);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#isCaseSensitive(int)}
*/
public void test_isCaseSensitiveI() throws SQLException {
metaDataImpl.setColumnCount(5);
assertFalse(metaDataImpl.isCaseSensitive(2));
assertFalse(metaDataImpl.isCaseSensitive(5));
metaDataImpl.setCaseSensitive(2, true);
assertTrue(metaDataImpl.isCaseSensitive(2));
metaDataImpl.setCaseSensitive(2, false);
assertFalse(metaDataImpl.isCaseSensitive(2));
try {
metaDataImpl.isCaseSensitive(0);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
try {
metaDataImpl.isCaseSensitive(6);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#isCurrency(int)}
*/
public void test_isCurrencyI() throws SQLException {
try {
metaDataImpl.isCurrency(1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(5);
assertFalse(metaDataImpl.isCurrency(1));
metaDataImpl.setCurrency(1, true);
assertTrue(metaDataImpl.isCurrency(1));
metaDataImpl.setCurrency(1, true);
assertTrue(metaDataImpl.isCurrency(1));
try {
metaDataImpl.isCurrency(0);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(6);
assertFalse(metaDataImpl.isCurrency(1));
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#isNullable(int)}
*/
public void test_isNullableI() throws SQLException {
try {
metaDataImpl.isNullable(1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(2);
assertEquals(ResultSetMetaData.columnNoNulls, metaDataImpl
.isNullable(1));
metaDataImpl.setNullable(1, ResultSetMetaData.columnNullableUnknown);
assertEquals(ResultSetMetaData.columnNullableUnknown, metaDataImpl
.isNullable(1));
try {
metaDataImpl.isNullable(3);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#isReadOnly(int)}
*/
public void test_isReadOnlyI() throws SQLException {
try {
metaDataImpl.isReadOnly(1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(11);
assertFalse(metaDataImpl.isReadOnly(1));
assertFalse(metaDataImpl.isReadOnly(11));
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#isWritable(int)}
*/
public void test_isWritableI() throws SQLException {
try {
metaDataImpl.isWritable(3);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(3);
assertTrue(metaDataImpl.isWritable(1));
assertTrue(metaDataImpl.isWritable(3));
assertFalse(metaDataImpl.isReadOnly(3));
try {
metaDataImpl.isWritable(4);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#isDefinitelyWritable(int)}
*/
public void test_isDefinitelyWritableI() throws SQLException {
metaDataImpl.setColumnCount(2);
assertTrue(metaDataImpl.isDefinitelyWritable(1));
assertTrue(metaDataImpl.isDefinitelyWritable(2));
// RI fails here, which does not comply to the spec
try {
metaDataImpl.isDefinitelyWritable(-1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#isSearchable(int)}
*/
public void test_isSearchableI() throws SQLException {
try {
metaDataImpl.isSearchable(Integer.MAX_VALUE);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(1);
assertFalse(metaDataImpl.isSearchable(1));
metaDataImpl.setSearchable(1, true);
assertTrue(metaDataImpl.isSearchable(1));
metaDataImpl.setSearchable(1, false);
assertFalse(metaDataImpl.isSearchable(1));
try {
metaDataImpl.isSearchable(2);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#isSigned(int)}
*/
public void test_isSignedI() throws SQLException {
try {
metaDataImpl.isSigned(2);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(35);
assertFalse(metaDataImpl.isSigned(35));
metaDataImpl.setSigned(35, true);
assertTrue(metaDataImpl.isSigned(35));
metaDataImpl.setSigned(35, false);
assertFalse(metaDataImpl.isSigned(35));
try {
metaDataImpl.isSigned(36);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setAutoIncrement(int, boolean)}
*/
public void test_setAutoIncrementIZ() throws SQLException {
try {
metaDataImpl.setAutoIncrement(1, true);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(2);
assertFalse(metaDataImpl.isAutoIncrement(1));
metaDataImpl.setAutoIncrement(1, false);
assertFalse(metaDataImpl.isAutoIncrement(1));
metaDataImpl.setAutoIncrement(1, true);
assertTrue(metaDataImpl.isAutoIncrement(1));
try {
metaDataImpl.setAutoIncrement(-1, false);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setCaseSensitive(int, boolean)}
*/
public void test_setCaseSensitiveIZ() throws SQLException {
try {
metaDataImpl.setCaseSensitive(2, false);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(9);
assertFalse(metaDataImpl.isCaseSensitive(9));
metaDataImpl.setCaseSensitive(9, false);
assertFalse(metaDataImpl.isCaseSensitive(9));
metaDataImpl.setCaseSensitive(9, true);
assertTrue(metaDataImpl.isCaseSensitive(9));
metaDataImpl.setAutoIncrement(9, false);
assertTrue(metaDataImpl.isCaseSensitive(9));
try {
metaDataImpl.setCaseSensitive(10, true);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setCatalogName(int, String)}
*/
public void test_setCatalogNameILjava_lang_String() throws SQLException {
try {
metaDataImpl.setCatalogName(1, "test");
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(1);
metaDataImpl.setCatalogName(1, "AbC");
assertEquals("AbC", metaDataImpl.getCatalogName(1));
metaDataImpl.setCatalogName(1, null);
assertEquals("", metaDataImpl.getCatalogName(1));
try {
metaDataImpl.setCatalogName(10, null);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setColumnDisplaySize(int, int)}
*/
public void test_setColumnDisplaySizeII() throws SQLException {
try {
metaDataImpl.setColumnDisplaySize(1, 2);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(1);
assertEquals(0, metaDataImpl.getColumnDisplaySize(1));
metaDataImpl.setColumnDisplaySize(1, Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, metaDataImpl.getColumnDisplaySize(1));
try {
metaDataImpl.setColumnDisplaySize(2, 0);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
try {
metaDataImpl.setColumnDisplaySize(2, Integer.MIN_VALUE);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setColumnName(int, String)}
*/
public void test_setColumnNameILjava_lang_String() throws SQLException {
try {
metaDataImpl.setColumnName(1, null);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(4);
assertNull(metaDataImpl.getColumnName(1));
metaDataImpl.setColumnName(1, "ate dsW");
assertEquals("ate dsW", metaDataImpl.getColumnName(1));
metaDataImpl.setColumnName(1, null);
assertEquals("", metaDataImpl.getColumnName(1));
try {
metaDataImpl.setColumnName(5, "exception");
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setColumnLabel(int, String)}
*/
public void test_setColumnLabelILjava_lang_String() throws SQLException {
try {
metaDataImpl.setColumnLabel(1, null);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(3);
assertNull(metaDataImpl.getColumnLabel(3));
metaDataImpl.setColumnLabel(3, null);
assertEquals("", metaDataImpl.getColumnLabel(3));
try {
metaDataImpl.setColumnLabel(4, "exception");
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setColumnType(int, int)}
*/
public void test_setColumnTypeII() throws SQLException {
try {
metaDataImpl.setColumnType(1, Types.BIGINT);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(2);
assertEquals(0, metaDataImpl.getColumnType(1));
metaDataImpl.setColumnType(1, Types.CLOB);
assertEquals(Types.CLOB, metaDataImpl.getColumnType(1));
metaDataImpl.setColumnType(1, Types.BOOLEAN);
assertEquals(Types.BOOLEAN, metaDataImpl.getColumnType(1));
try {
metaDataImpl.setColumnType(1, 66);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
try {
metaDataImpl.setColumnType(3, 58);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
try {
metaDataImpl.setColumnType(2, 59);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setColumnTypeName(int, String)}
*/
public void test_setColumnTypeNameILjava_lang_String() throws SQLException {
try {
metaDataImpl.setColumnTypeName(1, "aa");
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(2);
assertNull(metaDataImpl.getColumnTypeName(2));
metaDataImpl.setColumnTypeName(2, null);
assertEquals("", metaDataImpl.getColumnTypeName(2));
metaDataImpl.setColumnTypeName(2, "");
assertEquals("", metaDataImpl.getColumnTypeName(2));
metaDataImpl.setColumnTypeName(2, "java.lang.String");
assertEquals(0, metaDataImpl.getColumnType(2));
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setCurrency(int, boolean)}
*/
public void test_setCurrencyIZ() throws SQLException {
try {
metaDataImpl.setCurrency(12, false);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(7);
assertFalse(metaDataImpl.isCurrency(4));
metaDataImpl.setCurrency(4, false);
assertFalse(metaDataImpl.isCurrency(4));
metaDataImpl.setCurrency(4, true);
assertTrue(metaDataImpl.isCurrency(4));
try {
metaDataImpl.setCurrency(8, true);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setNullable(int, int)}
*/
public void test_setNullableII() throws SQLException {
try {
metaDataImpl.setNullable(21, 1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(1);
assertEquals(0, metaDataImpl.isNullable(1));
metaDataImpl.setNullable(1, ResultSetMetaData.columnNullable);
assertEquals(ResultSetMetaData.columnNullable, metaDataImpl
.isNullable(1));
try {
metaDataImpl
.setNullable(2, ResultSetMetaData.columnNullableUnknown);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
try {
metaDataImpl.setNullable(2, 3);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setPrecision(int, int)}
*/
public void test_setPrecisionII() throws SQLException {
try {
metaDataImpl.setPrecision(12, 1);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(1);
metaDataImpl.setPrecision(1, 0);
assertEquals(0, metaDataImpl.getPrecision(1));
try {
metaDataImpl.setPrecision(12, Integer.MIN_VALUE);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setScale(int, int)}
*/
public void test_setScaleII() throws SQLException {
try {
metaDataImpl.setScale(34, 5);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(1);
metaDataImpl.setScale(1, 252);
assertEquals(252, metaDataImpl.getScale(1));
try {
metaDataImpl.setScale(1, -23);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
try {
metaDataImpl.setScale(2, Integer.MIN_VALUE);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setSchemaName(int, String)}
*/
public void test_setSchemaNameILjava_lang_String() throws SQLException {
try {
metaDataImpl.setSchemaName(-12, "asw");
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(7);
assertEquals("", metaDataImpl.getSchemaName(3));
metaDataImpl.setSchemaName(3, "schema name");
assertEquals("schema name", metaDataImpl.getSchemaName(3));
metaDataImpl.setSchemaName(3, null);
assertEquals("", metaDataImpl.getSchemaName(3));
try {
metaDataImpl.setSchemaName(Integer.MIN_VALUE, null);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setSearchable(int, boolean)}
*/
public void test_setSearchableIZ() throws SQLException {
try {
metaDataImpl.setSearchable(-22, true);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(8);
assertFalse(metaDataImpl.isSearchable(2));
metaDataImpl.setSearchable(2, true);
assertTrue(metaDataImpl.isSearchable(2));
metaDataImpl.setSearchable(2, false);
assertFalse(metaDataImpl.isSearchable(2));
try {
metaDataImpl.setSearchable(Integer.MIN_VALUE, true);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setSigned(int, boolean)}
*/
public void test_setSignedIZ() throws SQLException {
try {
metaDataImpl.setSigned(34, true);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(12);
assertFalse(metaDataImpl.isSigned(12));
metaDataImpl.setSigned(12, true);
assertTrue(metaDataImpl.isSigned(12));
metaDataImpl.setSigned(12, false);
assertFalse(metaDataImpl.isSigned(12));
try {
metaDataImpl.setSigned(0, true);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests {@link javax.sql.rowset.RowSetMetaDataImpl#setTableName(int, String)}
*/
public void test_setTableNameILjava_lang_String() throws SQLException {
try {
metaDataImpl.setTableName(34, null);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
metaDataImpl.setColumnCount(2);
metaDataImpl.setTableName(2, "test");
assertEquals("test", metaDataImpl.getTableName(2));
metaDataImpl.setTableName(2, null);
assertEquals("", metaDataImpl.getTableName(2));
try {
metaDataImpl.setTableName(-3, null);
fail("should throw SQLException");
} catch (SQLException e) {
// expected
}
}
/**
* @tests serialization/deserialization.
*/
public void test_serialization_self() throws Exception {
RowSetMetaDataImpl impl = new RowSetMetaDataImpl();
impl.setColumnCount(1);
impl.setColumnType(1, Types.CHAR);
SerializationTest.verifySelf(impl, ROWSET_METADATA_COMPARATOR);
}
/**
* @tests serialization/deserialization compatibility with RI.
*/
public void test_serialization_compatibility() throws Exception {
RowSetMetaDataImpl impl = new RowSetMetaDataImpl();
impl.setColumnCount(2);
impl.setColumnType(1, Types.ARRAY);
impl.setColumnType(2, Types.BIGINT);
SerializationTest.verifyGolden(this, impl, ROWSET_METADATA_COMPARATOR);
}
@Override
protected void setUp() throws Exception {
super.setUp();
metaDataImpl = new RowSetMetaDataImpl();
}
@Override
protected void tearDown() throws Exception {
metaDataImpl = null;
super.tearDown();
}
}
|
apache/tomcat | 35,786 | java/org/apache/tomcat/dbcp/dbcp2/DelegatingDatabaseMetaData.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.dbcp.dbcp2;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.RowIdLifetime;
import java.sql.SQLException;
import java.util.Objects;
import java.util.concurrent.Callable;
/**
* <p>
* A base delegating implementation of {@link DatabaseMetaData}.
* </p>
* <p>
* Methods that create {@link ResultSet} objects are wrapped to create {@link DelegatingResultSet} objects and the remaining methods simply call the
* corresponding method on the "delegate" provided in the constructor.
* </p>
*
* @since 2.0
*/
public class DelegatingDatabaseMetaData implements DatabaseMetaData {
/** My delegate {@link DatabaseMetaData} */
private final DatabaseMetaData databaseMetaData;
/** The connection that created me. **/
private final DelegatingConnection<?> connection;
/**
* Constructs a new instance for the given delegating connection and database meta data.
*
* @param connection the delegating connection
* @param databaseMetaData the database meta data
*/
public DelegatingDatabaseMetaData(final DelegatingConnection<?> connection, final DatabaseMetaData databaseMetaData) {
this.connection = Objects.requireNonNull(connection, "connection");
this.databaseMetaData = Objects.requireNonNull(databaseMetaData, "databaseMetaData");
}
@Override
public boolean allProceduresAreCallable() throws SQLException {
return getB(databaseMetaData::allProceduresAreCallable);
}
@Override
public boolean allTablesAreSelectable() throws SQLException {
return getB(databaseMetaData::allTablesAreSelectable);
}
@Override
public boolean autoCommitFailureClosesAllResultSets() throws SQLException {
return getB(databaseMetaData::autoCommitFailureClosesAllResultSets);
}
@Override
public boolean dataDefinitionCausesTransactionCommit() throws SQLException {
return getB(databaseMetaData::dataDefinitionCausesTransactionCommit);
}
@Override
public boolean dataDefinitionIgnoredInTransactions() throws SQLException {
return getB(databaseMetaData::dataDefinitionIgnoredInTransactions);
}
@Override
public boolean deletesAreDetected(final int type) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.deletesAreDetected(type)));
}
@Override
public boolean doesMaxRowSizeIncludeBlobs() throws SQLException {
return getB(databaseMetaData::doesMaxRowSizeIncludeBlobs);
}
@Override
public boolean generatedKeyAlwaysReturned() throws SQLException {
connection.checkOpen();
return getB(() -> Boolean.valueOf(Jdbc41Bridge.generatedKeyAlwaysReturned(databaseMetaData)));
}
private <T> T get(final Callable<T> s) throws SQLException {
return get(s, null);
}
private <T> T get(final Callable<T> s, final T defaultValue) throws SQLException {
try {
return s.call();
} catch (final Exception e) {
if (e instanceof SQLException) {
handleException((SQLException) e);
}
return defaultValue;
}
}
@Override
public ResultSet getAttributes(final String catalog, final String schemaPattern, final String typeNamePattern, final String attributeNamePattern)
throws SQLException {
return getRS(() -> databaseMetaData.getAttributes(catalog, schemaPattern, typeNamePattern, attributeNamePattern));
}
private boolean getB(final Callable<Boolean> s) throws SQLException {
return get(s, Boolean.FALSE).booleanValue();
}
@Override
public ResultSet getBestRowIdentifier(final String catalog, final String schema, final String table, final int scope, final boolean nullable)
throws SQLException {
return getRS(() -> databaseMetaData.getBestRowIdentifier(catalog, schema, table, scope, nullable));
}
@Override
public ResultSet getCatalogs() throws SQLException {
return getRS(databaseMetaData::getCatalogs);
}
@Override
public String getCatalogSeparator() throws SQLException {
return get(databaseMetaData::getCatalogSeparator);
}
@Override
public String getCatalogTerm() throws SQLException {
return get(databaseMetaData::getCatalogTerm);
}
@Override
public ResultSet getClientInfoProperties() throws SQLException {
return getRS(databaseMetaData::getClientInfoProperties);
}
@Override
public ResultSet getColumnPrivileges(final String catalog, final String schema, final String table, final String columnNamePattern) throws SQLException {
return getRS(() -> databaseMetaData.getColumnPrivileges(catalog, schema, table, columnNamePattern));
}
@Override
public ResultSet getColumns(final String catalog, final String schemaPattern, final String tableNamePattern, final String columnNamePattern)
throws SQLException {
return getRS(() -> databaseMetaData.getColumns(catalog, schemaPattern, tableNamePattern, columnNamePattern));
}
@Override
public Connection getConnection() throws SQLException {
return connection;
}
@Override
public ResultSet getCrossReference(final String parentCatalog, final String parentSchema, final String parentTable, final String foreignCatalog,
final String foreignSchema, final String foreignTable) throws SQLException {
return getRS(() -> databaseMetaData.getCrossReference(parentCatalog, parentSchema, parentTable, foreignCatalog, foreignSchema, foreignTable));
}
@Override
public int getDatabaseMajorVersion() throws SQLException {
return getI(databaseMetaData::getDatabaseMajorVersion);
}
@Override
public int getDatabaseMinorVersion() throws SQLException {
return getI(databaseMetaData::getDatabaseMinorVersion);
}
@Override
public String getDatabaseProductName() throws SQLException {
return get(databaseMetaData::getDatabaseProductName);
}
@Override
public String getDatabaseProductVersion() throws SQLException {
return get(databaseMetaData::getDatabaseProductVersion);
}
@Override
public int getDefaultTransactionIsolation() throws SQLException {
return getI(databaseMetaData::getDefaultTransactionIsolation);
}
/**
* Gets the underlying database meta data.
*
* @return The underlying database meta data.
*/
public DatabaseMetaData getDelegate() {
return databaseMetaData;
}
@Override
public int getDriverMajorVersion() {
return databaseMetaData.getDriverMajorVersion();
}
@Override
public int getDriverMinorVersion() {
return databaseMetaData.getDriverMinorVersion();
}
@Override
public String getDriverName() throws SQLException {
return get(databaseMetaData::getDriverName);
}
@Override
public String getDriverVersion() throws SQLException {
return get(databaseMetaData::getDriverVersion);
}
@Override
public ResultSet getExportedKeys(final String catalog, final String schema, final String table) throws SQLException {
return getRS(() -> databaseMetaData.getExportedKeys(catalog, schema, table));
}
@Override
public String getExtraNameCharacters() throws SQLException {
return get(databaseMetaData::getExtraNameCharacters);
}
@Override
public ResultSet getFunctionColumns(final String catalog, final String schemaPattern, final String functionNamePattern, final String columnNamePattern)
throws SQLException {
return getRS(() -> databaseMetaData.getFunctionColumns(catalog, schemaPattern, functionNamePattern, columnNamePattern));
}
@Override
public ResultSet getFunctions(final String catalog, final String schemaPattern, final String functionNamePattern) throws SQLException {
return getRS(() -> databaseMetaData.getFunctions(catalog, schemaPattern, functionNamePattern));
}
private int getI(final Callable<Integer> s) throws SQLException {
return get(s, Integer.valueOf(0)).intValue();
}
@Override
public String getIdentifierQuoteString() throws SQLException {
return get(databaseMetaData::getIdentifierQuoteString);
}
@Override
public ResultSet getImportedKeys(final String catalog, final String schema, final String table) throws SQLException {
return getRS(() -> databaseMetaData.getImportedKeys(catalog, schema, table));
}
@Override
public ResultSet getIndexInfo(final String catalog, final String schema, final String table, final boolean unique, final boolean approximate)
throws SQLException {
return getRS(() -> databaseMetaData.getIndexInfo(catalog, schema, table, unique, approximate));
}
/**
* If my underlying {@link ResultSet} is not a {@code DelegatingResultSet}, returns it, otherwise recursively invokes this method on my delegate.
* <p>
* Hence this method will return the first delegate that is not a {@code DelegatingResultSet}, or {@code null} when no non-{@code DelegatingResultSet}
* delegate can be found by traversing this chain.
* </p>
* <p>
* This method is useful when you may have nested {@code DelegatingResultSet}s, and you want to make sure to obtain a "genuine" {@link ResultSet}.
* </p>
*
* @return the innermost database meta data.
*/
public DatabaseMetaData getInnermostDelegate() {
DatabaseMetaData m = databaseMetaData;
while (m instanceof DelegatingDatabaseMetaData) {
m = ((DelegatingDatabaseMetaData) m).getDelegate();
if (this == m) {
return null;
}
}
return m;
}
@Override
public int getJDBCMajorVersion() throws SQLException {
return getI(databaseMetaData::getJDBCMajorVersion);
}
@Override
public int getJDBCMinorVersion() throws SQLException {
return getI(databaseMetaData::getJDBCMinorVersion);
}
private long getL(final Callable<Long> s) throws SQLException {
return get(s, Long.valueOf(0)).longValue();
}
@Override
public int getMaxBinaryLiteralLength() throws SQLException {
return getI(databaseMetaData::getMaxBinaryLiteralLength);
}
@Override
public int getMaxCatalogNameLength() throws SQLException {
return getI(databaseMetaData::getMaxCatalogNameLength);
}
@Override
public int getMaxCharLiteralLength() throws SQLException {
return getI(databaseMetaData::getMaxCharLiteralLength);
}
@Override
public int getMaxColumnNameLength() throws SQLException {
return getI(databaseMetaData::getMaxColumnNameLength);
}
@Override
public int getMaxColumnsInGroupBy() throws SQLException {
return getI(databaseMetaData::getMaxColumnsInGroupBy);
}
@Override
public int getMaxColumnsInIndex() throws SQLException {
return getI(databaseMetaData::getMaxColumnsInIndex);
}
@Override
public int getMaxColumnsInOrderBy() throws SQLException {
return getI(databaseMetaData::getMaxColumnsInOrderBy);
}
@Override
public int getMaxColumnsInSelect() throws SQLException {
return getI(databaseMetaData::getMaxColumnsInSelect);
}
@Override
public int getMaxColumnsInTable() throws SQLException {
return getI(databaseMetaData::getMaxColumnsInTable);
}
@Override
public int getMaxConnections() throws SQLException {
return getI(databaseMetaData::getMaxConnections);
}
@Override
public int getMaxCursorNameLength() throws SQLException {
return getI(databaseMetaData::getMaxCursorNameLength);
}
@Override
public int getMaxIndexLength() throws SQLException {
return getI(databaseMetaData::getMaxIndexLength);
}
/**
* @since 2.5.0
*/
@Override
public long getMaxLogicalLobSize() throws SQLException {
return getL(databaseMetaData::getMaxLogicalLobSize);
}
@Override
public int getMaxProcedureNameLength() throws SQLException {
return getI(databaseMetaData::getMaxProcedureNameLength);
}
@Override
public int getMaxRowSize() throws SQLException {
return getI(databaseMetaData::getMaxRowSize);
}
@Override
public int getMaxSchemaNameLength() throws SQLException {
return getI(databaseMetaData::getMaxSchemaNameLength);
}
@Override
public int getMaxStatementLength() throws SQLException {
return getI(databaseMetaData::getMaxStatementLength);
}
@Override
public int getMaxStatements() throws SQLException {
return getI(databaseMetaData::getMaxStatements);
}
@Override
public int getMaxTableNameLength() throws SQLException {
return getI(databaseMetaData::getMaxTableNameLength);
}
@Override
public int getMaxTablesInSelect() throws SQLException {
return getI(databaseMetaData::getMaxTablesInSelect);
}
@Override
public int getMaxUserNameLength() throws SQLException {
return getI(databaseMetaData::getMaxUserNameLength);
}
@Override
public String getNumericFunctions() throws SQLException {
return get(databaseMetaData::getNumericFunctions);
}
@Override
public ResultSet getPrimaryKeys(final String catalog, final String schema, final String table) throws SQLException {
return getRS(() -> databaseMetaData.getPrimaryKeys(catalog, schema, table));
}
@Override
public ResultSet getProcedureColumns(final String catalog, final String schemaPattern, final String procedureNamePattern, final String columnNamePattern)
throws SQLException {
return getRS(() -> databaseMetaData.getProcedureColumns(catalog, schemaPattern, procedureNamePattern, columnNamePattern));
}
@Override
public ResultSet getProcedures(final String catalog, final String schemaPattern, final String procedureNamePattern) throws SQLException {
return getRS(() -> databaseMetaData.getProcedures(catalog, schemaPattern, procedureNamePattern));
}
@Override
public String getProcedureTerm() throws SQLException {
return get(databaseMetaData::getProcedureTerm);
}
@Override
public ResultSet getPseudoColumns(final String catalog, final String schemaPattern, final String tableNamePattern, final String columnNamePattern)
throws SQLException {
return getRS(() -> Jdbc41Bridge.getPseudoColumns(databaseMetaData, catalog, schemaPattern, tableNamePattern, columnNamePattern));
}
@Override
public int getResultSetHoldability() throws SQLException {
return getI(databaseMetaData::getResultSetHoldability);
}
@Override
public RowIdLifetime getRowIdLifetime() throws SQLException {
return get(databaseMetaData::getRowIdLifetime);
}
private ResultSet getRS(final Callable<ResultSet> s) throws SQLException {
connection.checkOpen();
return DelegatingResultSet.wrapResultSet(connection, get(s));
}
@Override
public ResultSet getSchemas() throws SQLException {
return getRS(databaseMetaData::getSchemas);
}
@Override
public ResultSet getSchemas(final String catalog, final String schemaPattern) throws SQLException {
return getRS(() -> databaseMetaData.getSchemas(catalog, schemaPattern));
}
@Override
public String getSchemaTerm() throws SQLException {
return get(databaseMetaData::getSchemaTerm);
}
@Override
public String getSearchStringEscape() throws SQLException {
return get(databaseMetaData::getSearchStringEscape);
}
@Override
public String getSQLKeywords() throws SQLException {
return get(databaseMetaData::getSQLKeywords);
}
@Override
public int getSQLStateType() throws SQLException {
return getI(databaseMetaData::getSQLStateType);
}
@Override
public String getStringFunctions() throws SQLException {
return get(databaseMetaData::getStringFunctions);
}
@Override
public ResultSet getSuperTables(final String catalog, final String schemaPattern, final String tableNamePattern) throws SQLException {
return getRS(() -> databaseMetaData.getSuperTables(catalog, schemaPattern, tableNamePattern));
}
@Override
public ResultSet getSuperTypes(final String catalog, final String schemaPattern, final String typeNamePattern) throws SQLException {
return getRS(() -> databaseMetaData.getSuperTypes(catalog, schemaPattern, typeNamePattern));
}
@Override
public String getSystemFunctions() throws SQLException {
return get(databaseMetaData::getSystemFunctions);
}
@Override
public ResultSet getTablePrivileges(final String catalog, final String schemaPattern, final String tableNamePattern) throws SQLException {
return getRS(() -> databaseMetaData.getTablePrivileges(catalog, schemaPattern, tableNamePattern));
}
@Override
public ResultSet getTables(final String catalog, final String schemaPattern, final String tableNamePattern, final String[] types) throws SQLException {
return getRS(() -> databaseMetaData.getTables(catalog, schemaPattern, tableNamePattern, types));
}
@Override
public ResultSet getTableTypes() throws SQLException {
return getRS(databaseMetaData::getTableTypes);
}
@Override
public String getTimeDateFunctions() throws SQLException {
return get(databaseMetaData::getTimeDateFunctions);
}
@Override
public ResultSet getTypeInfo() throws SQLException {
return getRS(databaseMetaData::getTypeInfo);
}
@Override
public ResultSet getUDTs(final String catalog, final String schemaPattern, final String typeNamePattern, final int[] types) throws SQLException {
return getRS(() -> databaseMetaData.getUDTs(catalog, schemaPattern, typeNamePattern, types));
}
@Override
public String getURL() throws SQLException {
return get(databaseMetaData::getURL);
}
@Override
public String getUserName() throws SQLException {
return get(databaseMetaData::getUserName);
}
@Override
public ResultSet getVersionColumns(final String catalog, final String schema, final String table) throws SQLException {
return getRS(() -> databaseMetaData.getVersionColumns(catalog, schema, table));
}
/**
* Delegates to the connection's {@link DelegatingConnection#handleException(SQLException)}.
*
* @param e the exception to throw or delegate.
* @throws SQLException the exception to throw.
*/
protected void handleException(final SQLException e) throws SQLException {
if (connection == null) {
throw e;
}
connection.handleException(e);
}
@Override
public boolean insertsAreDetected(final int type) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.insertsAreDetected(type)));
}
@Override
public boolean isCatalogAtStart() throws SQLException {
return getB(databaseMetaData::isCatalogAtStart);
}
@Override
public boolean isReadOnly() throws SQLException {
return getB(databaseMetaData::isReadOnly);
}
@Override
public boolean isWrapperFor(final Class<?> iface) throws SQLException {
if (iface.isAssignableFrom(getClass())) {
return true;
}
if (iface.isAssignableFrom(databaseMetaData.getClass())) {
return true;
}
return databaseMetaData.isWrapperFor(iface);
}
@Override
public boolean locatorsUpdateCopy() throws SQLException {
return getB(databaseMetaData::locatorsUpdateCopy);
}
@Override
public boolean nullPlusNonNullIsNull() throws SQLException {
return getB(databaseMetaData::nullPlusNonNullIsNull);
}
@Override
public boolean nullsAreSortedAtEnd() throws SQLException {
return getB(databaseMetaData::nullsAreSortedAtEnd);
}
@Override
public boolean nullsAreSortedAtStart() throws SQLException {
return getB(databaseMetaData::nullsAreSortedAtStart);
}
@Override
public boolean nullsAreSortedHigh() throws SQLException {
return getB(databaseMetaData::nullsAreSortedHigh);
}
@Override
public boolean nullsAreSortedLow() throws SQLException {
return getB(databaseMetaData::nullsAreSortedLow);
}
@Override
public boolean othersDeletesAreVisible(final int type) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.othersDeletesAreVisible(type)));
}
@Override
public boolean othersInsertsAreVisible(final int type) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.othersInsertsAreVisible(type)));
}
@Override
public boolean othersUpdatesAreVisible(final int type) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.othersUpdatesAreVisible(type)));
}
@Override
public boolean ownDeletesAreVisible(final int type) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.ownDeletesAreVisible(type)));
}
@Override
public boolean ownInsertsAreVisible(final int type) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.ownInsertsAreVisible(type)));
}
@Override
public boolean ownUpdatesAreVisible(final int type) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.ownUpdatesAreVisible(type)));
}
@Override
public boolean storesLowerCaseIdentifiers() throws SQLException {
return getB(databaseMetaData::storesLowerCaseIdentifiers);
}
@Override
public boolean storesLowerCaseQuotedIdentifiers() throws SQLException {
return getB(databaseMetaData::storesLowerCaseQuotedIdentifiers);
}
@Override
public boolean storesMixedCaseIdentifiers() throws SQLException {
return getB(databaseMetaData::storesMixedCaseIdentifiers);
}
@Override
public boolean storesMixedCaseQuotedIdentifiers() throws SQLException {
return getB(databaseMetaData::storesMixedCaseQuotedIdentifiers);
}
@Override
public boolean storesUpperCaseIdentifiers() throws SQLException {
return getB(databaseMetaData::storesUpperCaseIdentifiers);
}
@Override
public boolean storesUpperCaseQuotedIdentifiers() throws SQLException {
return getB(databaseMetaData::storesUpperCaseQuotedIdentifiers);
}
@Override
public boolean supportsAlterTableWithAddColumn() throws SQLException {
return getB(databaseMetaData::supportsAlterTableWithAddColumn);
}
@Override
public boolean supportsAlterTableWithDropColumn() throws SQLException {
return getB(databaseMetaData::supportsAlterTableWithDropColumn);
}
@Override
public boolean supportsANSI92EntryLevelSQL() throws SQLException {
return getB(databaseMetaData::supportsANSI92EntryLevelSQL);
}
@Override
public boolean supportsANSI92FullSQL() throws SQLException {
return getB(databaseMetaData::supportsANSI92FullSQL);
}
@Override
public boolean supportsANSI92IntermediateSQL() throws SQLException {
return getB(databaseMetaData::supportsANSI92IntermediateSQL);
}
@Override
public boolean supportsBatchUpdates() throws SQLException {
return getB(databaseMetaData::supportsBatchUpdates);
}
@Override
public boolean supportsCatalogsInDataManipulation() throws SQLException {
return getB(databaseMetaData::supportsCatalogsInDataManipulation);
}
@Override
public boolean supportsCatalogsInIndexDefinitions() throws SQLException {
return getB(databaseMetaData::supportsCatalogsInIndexDefinitions);
}
@Override
public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException {
return getB(databaseMetaData::supportsCatalogsInPrivilegeDefinitions);
}
@Override
public boolean supportsCatalogsInProcedureCalls() throws SQLException {
return getB(databaseMetaData::supportsCatalogsInProcedureCalls);
}
@Override
public boolean supportsCatalogsInTableDefinitions() throws SQLException {
return getB(databaseMetaData::supportsCatalogsInTableDefinitions);
}
@Override
public boolean supportsColumnAliasing() throws SQLException {
return getB(databaseMetaData::supportsColumnAliasing);
}
@Override
public boolean supportsConvert() throws SQLException {
return getB(databaseMetaData::supportsConvert);
}
@Override
public boolean supportsConvert(final int fromType, final int toType) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.supportsConvert(fromType, toType)));
}
@Override
public boolean supportsCoreSQLGrammar() throws SQLException {
return getB(databaseMetaData::supportsCoreSQLGrammar);
}
@Override
public boolean supportsCorrelatedSubqueries() throws SQLException {
return getB(databaseMetaData::supportsCorrelatedSubqueries);
}
@Override
public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException {
return getB(databaseMetaData::supportsDataDefinitionAndDataManipulationTransactions);
}
@Override
public boolean supportsDataManipulationTransactionsOnly() throws SQLException {
return getB(databaseMetaData::supportsDataManipulationTransactionsOnly);
}
@Override
public boolean supportsDifferentTableCorrelationNames() throws SQLException {
return getB(databaseMetaData::supportsDifferentTableCorrelationNames);
}
@Override
public boolean supportsExpressionsInOrderBy() throws SQLException {
return getB(databaseMetaData::supportsExpressionsInOrderBy);
}
@Override
public boolean supportsExtendedSQLGrammar() throws SQLException {
return getB(databaseMetaData::supportsExtendedSQLGrammar);
}
@Override
public boolean supportsFullOuterJoins() throws SQLException {
return getB(databaseMetaData::supportsFullOuterJoins);
}
@Override
public boolean supportsGetGeneratedKeys() throws SQLException {
return getB(databaseMetaData::supportsGetGeneratedKeys);
}
@Override
public boolean supportsGroupBy() throws SQLException {
return getB(databaseMetaData::supportsGroupBy);
}
@Override
public boolean supportsGroupByBeyondSelect() throws SQLException {
return getB(databaseMetaData::supportsGroupByBeyondSelect);
}
@Override
public boolean supportsGroupByUnrelated() throws SQLException {
return getB(databaseMetaData::supportsGroupByUnrelated);
}
@Override
public boolean supportsIntegrityEnhancementFacility() throws SQLException {
return getB(databaseMetaData::supportsIntegrityEnhancementFacility);
}
@Override
public boolean supportsLikeEscapeClause() throws SQLException {
return getB(databaseMetaData::supportsLikeEscapeClause);
}
@Override
public boolean supportsLimitedOuterJoins() throws SQLException {
return getB(databaseMetaData::supportsLimitedOuterJoins);
}
@Override
public boolean supportsMinimumSQLGrammar() throws SQLException {
return getB(databaseMetaData::supportsMinimumSQLGrammar);
}
@Override
public boolean supportsMixedCaseIdentifiers() throws SQLException {
return getB(databaseMetaData::supportsMixedCaseIdentifiers);
}
@Override
public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException {
return getB(databaseMetaData::supportsMixedCaseQuotedIdentifiers);
}
@Override
public boolean supportsMultipleOpenResults() throws SQLException {
return getB(databaseMetaData::supportsMultipleOpenResults);
}
@Override
public boolean supportsMultipleResultSets() throws SQLException {
return getB(databaseMetaData::supportsMultipleResultSets);
}
@Override
public boolean supportsMultipleTransactions() throws SQLException {
return getB(databaseMetaData::supportsMultipleTransactions);
}
@Override
public boolean supportsNamedParameters() throws SQLException {
return getB(databaseMetaData::supportsNamedParameters);
}
@Override
public boolean supportsNonNullableColumns() throws SQLException {
return getB(databaseMetaData::supportsNonNullableColumns);
}
@Override
public boolean supportsOpenCursorsAcrossCommit() throws SQLException {
return getB(databaseMetaData::supportsOpenCursorsAcrossCommit);
}
@Override
public boolean supportsOpenCursorsAcrossRollback() throws SQLException {
return getB(databaseMetaData::supportsOpenCursorsAcrossRollback);
}
@Override
public boolean supportsOpenStatementsAcrossCommit() throws SQLException {
return getB(databaseMetaData::supportsOpenStatementsAcrossCommit);
}
@Override
public boolean supportsOpenStatementsAcrossRollback() throws SQLException {
return getB(databaseMetaData::supportsOpenStatementsAcrossRollback);
}
@Override
public boolean supportsOrderByUnrelated() throws SQLException {
return getB(databaseMetaData::supportsOrderByUnrelated);
}
@Override
public boolean supportsOuterJoins() throws SQLException {
return getB(databaseMetaData::supportsOuterJoins);
}
@Override
public boolean supportsPositionedDelete() throws SQLException {
return getB(databaseMetaData::supportsPositionedDelete);
}
@Override
public boolean supportsPositionedUpdate() throws SQLException {
return getB(databaseMetaData::supportsPositionedUpdate);
}
/**
* @since 2.5.0
*/
@Override
public boolean supportsRefCursors() throws SQLException {
return getB(databaseMetaData::supportsRefCursors);
}
@Override
public boolean supportsResultSetConcurrency(final int type, final int concurrency) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.supportsResultSetConcurrency(type, concurrency)));
}
@Override
public boolean supportsResultSetHoldability(final int holdability) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.supportsResultSetHoldability(holdability)));
}
@Override
public boolean supportsResultSetType(final int type) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.supportsResultSetType(type)));
}
@Override
public boolean supportsSavepoints() throws SQLException {
return getB(databaseMetaData::supportsSavepoints);
}
@Override
public boolean supportsSchemasInDataManipulation() throws SQLException {
return getB(databaseMetaData::supportsSchemasInDataManipulation);
}
@Override
public boolean supportsSchemasInIndexDefinitions() throws SQLException {
return getB(databaseMetaData::supportsSchemasInIndexDefinitions);
}
@Override
public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException {
return getB(databaseMetaData::supportsSchemasInPrivilegeDefinitions);
}
@Override
public boolean supportsSchemasInProcedureCalls() throws SQLException {
return getB(databaseMetaData::supportsSchemasInProcedureCalls);
}
@Override
public boolean supportsSchemasInTableDefinitions() throws SQLException {
return getB(databaseMetaData::supportsSchemasInTableDefinitions);
}
@Override
public boolean supportsSelectForUpdate() throws SQLException {
return getB(databaseMetaData::supportsSelectForUpdate);
}
@Override
public boolean supportsStatementPooling() throws SQLException {
return getB(databaseMetaData::supportsStatementPooling);
}
@Override
public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException {
return getB(databaseMetaData::supportsStoredFunctionsUsingCallSyntax);
}
@Override
public boolean supportsStoredProcedures() throws SQLException {
return getB(databaseMetaData::supportsStoredProcedures);
}
@Override
public boolean supportsSubqueriesInComparisons() throws SQLException {
return getB(databaseMetaData::supportsSubqueriesInComparisons);
}
@Override
public boolean supportsSubqueriesInExists() throws SQLException {
return getB(databaseMetaData::supportsSubqueriesInExists);
}
@Override
public boolean supportsSubqueriesInIns() throws SQLException {
return getB(databaseMetaData::supportsSubqueriesInIns);
}
@Override
public boolean supportsSubqueriesInQuantifieds() throws SQLException {
return getB(databaseMetaData::supportsSubqueriesInQuantifieds);
}
@Override
public boolean supportsTableCorrelationNames() throws SQLException {
return getB(databaseMetaData::supportsTableCorrelationNames);
}
@Override
public boolean supportsTransactionIsolationLevel(final int level) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.supportsTransactionIsolationLevel(level)));
}
@Override
public boolean supportsTransactions() throws SQLException {
return getB(databaseMetaData::supportsTransactions);
}
@Override
public boolean supportsUnion() throws SQLException {
return getB(databaseMetaData::supportsUnion);
}
@Override
public boolean supportsUnionAll() throws SQLException {
return getB(databaseMetaData::supportsUnionAll);
}
@Override
public <T> T unwrap(final Class<T> iface) throws SQLException {
if (iface.isAssignableFrom(getClass())) {
return iface.cast(this);
}
if (iface.isAssignableFrom(databaseMetaData.getClass())) {
return iface.cast(databaseMetaData);
}
return databaseMetaData.unwrap(iface);
}
@Override
public boolean updatesAreDetected(final int type) throws SQLException {
return getB(() -> Boolean.valueOf(databaseMetaData.updatesAreDetected(type)));
}
@Override
public boolean usesLocalFilePerTable() throws SQLException {
return getB(databaseMetaData::usesLocalFilePerTable);
}
@Override
public boolean usesLocalFiles() throws SQLException {
return getB(databaseMetaData::usesLocalFiles);
}
}
|
googleapis/google-cloud-java | 35,654 | java-aiplatform/proto-google-cloud-aiplatform-v1beta1/src/main/java/com/google/cloud/aiplatform/v1beta1/UpdateExampleStoreRequest.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/example_store_service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.aiplatform.v1beta1;
/**
*
*
* <pre>
* Request message for
* [ExampleStoreService.UpdateExampleStore][google.cloud.aiplatform.v1beta1.ExampleStoreService.UpdateExampleStore].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest}
*/
public final class UpdateExampleStoreRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest)
UpdateExampleStoreRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use UpdateExampleStoreRequest.newBuilder() to construct.
private UpdateExampleStoreRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private UpdateExampleStoreRequest() {}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new UpdateExampleStoreRequest();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.ExampleStoreServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateExampleStoreRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.ExampleStoreServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateExampleStoreRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest.class,
com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest.Builder.class);
}
private int bitField0_;
public static final int EXAMPLE_STORE_FIELD_NUMBER = 1;
private com.google.cloud.aiplatform.v1beta1.ExampleStore exampleStore_;
/**
*
*
* <pre>
* Required. The Example Store which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.ExampleStore example_store = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the exampleStore field is set.
*/
@java.lang.Override
public boolean hasExampleStore() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The Example Store which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.ExampleStore example_store = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The exampleStore.
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ExampleStore getExampleStore() {
return exampleStore_ == null
? com.google.cloud.aiplatform.v1beta1.ExampleStore.getDefaultInstance()
: exampleStore_;
}
/**
*
*
* <pre>
* Required. The Example Store which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.ExampleStore example_store = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.ExampleStoreOrBuilder getExampleStoreOrBuilder() {
return exampleStore_ == null
? com.google.cloud.aiplatform.v1beta1.ExampleStore.getDefaultInstance()
: exampleStore_;
}
public static final int UPDATE_MASK_FIELD_NUMBER = 2;
private com.google.protobuf.FieldMask updateMask_;
/**
*
*
* <pre>
* Optional. Mask specifying which fields to update.
* Supported fields:
*
* * `display_name`
* * `description`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the updateMask field is set.
*/
@java.lang.Override
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Optional. Mask specifying which fields to update.
* Supported fields:
*
* * `display_name`
* * `description`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The updateMask.
*/
@java.lang.Override
public com.google.protobuf.FieldMask getUpdateMask() {
return updateMask_ == null ? com.google.protobuf.FieldMask.getDefaultInstance() : updateMask_;
}
/**
*
*
* <pre>
* Optional. Mask specifying which fields to update.
* Supported fields:
*
* * `display_name`
* * `description`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </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, getExampleStore());
}
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, getExampleStore());
}
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.aiplatform.v1beta1.UpdateExampleStoreRequest)) {
return super.equals(obj);
}
com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest other =
(com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest) obj;
if (hasExampleStore() != other.hasExampleStore()) return false;
if (hasExampleStore()) {
if (!getExampleStore().equals(other.getExampleStore())) 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 (hasExampleStore()) {
hash = (37 * hash) + EXAMPLE_STORE_FIELD_NUMBER;
hash = (53 * hash) + getExampleStore().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.aiplatform.v1beta1.UpdateExampleStoreRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest 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.UpdateExampleStoreRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest 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.UpdateExampleStoreRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest 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.UpdateExampleStoreRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest 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.UpdateExampleStoreRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest 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.UpdateExampleStoreRequest 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.UpdateExampleStoreRequest 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.UpdateExampleStoreRequest 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
* [ExampleStoreService.UpdateExampleStore][google.cloud.aiplatform.v1beta1.ExampleStoreService.UpdateExampleStore].
* </pre>
*
* Protobuf type {@code google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest)
com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.aiplatform.v1beta1.ExampleStoreServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateExampleStoreRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.aiplatform.v1beta1.ExampleStoreServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateExampleStoreRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest.class,
com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest.Builder.class);
}
// Construct using com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getExampleStoreFieldBuilder();
getUpdateMaskFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
exampleStore_ = null;
if (exampleStoreBuilder_ != null) {
exampleStoreBuilder_.dispose();
exampleStoreBuilder_ = 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.aiplatform.v1beta1.ExampleStoreServiceProto
.internal_static_google_cloud_aiplatform_v1beta1_UpdateExampleStoreRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest
getDefaultInstanceForType() {
return com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest build() {
com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest buildPartial() {
com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest result =
new com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(
com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest result) {
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.exampleStore_ =
exampleStoreBuilder_ == null ? exampleStore_ : exampleStoreBuilder_.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.aiplatform.v1beta1.UpdateExampleStoreRequest) {
return mergeFrom((com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest other) {
if (other
== com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest.getDefaultInstance())
return this;
if (other.hasExampleStore()) {
mergeExampleStore(other.getExampleStore());
}
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(getExampleStoreFieldBuilder().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.aiplatform.v1beta1.ExampleStore exampleStore_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.ExampleStore,
com.google.cloud.aiplatform.v1beta1.ExampleStore.Builder,
com.google.cloud.aiplatform.v1beta1.ExampleStoreOrBuilder>
exampleStoreBuilder_;
/**
*
*
* <pre>
* Required. The Example Store which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.ExampleStore example_store = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return Whether the exampleStore field is set.
*/
public boolean hasExampleStore() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Required. The Example Store which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.ExampleStore example_store = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*
* @return The exampleStore.
*/
public com.google.cloud.aiplatform.v1beta1.ExampleStore getExampleStore() {
if (exampleStoreBuilder_ == null) {
return exampleStore_ == null
? com.google.cloud.aiplatform.v1beta1.ExampleStore.getDefaultInstance()
: exampleStore_;
} else {
return exampleStoreBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Required. The Example Store which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.ExampleStore example_store = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setExampleStore(com.google.cloud.aiplatform.v1beta1.ExampleStore value) {
if (exampleStoreBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
exampleStore_ = value;
} else {
exampleStoreBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The Example Store which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.ExampleStore example_store = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder setExampleStore(
com.google.cloud.aiplatform.v1beta1.ExampleStore.Builder builderForValue) {
if (exampleStoreBuilder_ == null) {
exampleStore_ = builderForValue.build();
} else {
exampleStoreBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The Example Store which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.ExampleStore example_store = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder mergeExampleStore(com.google.cloud.aiplatform.v1beta1.ExampleStore value) {
if (exampleStoreBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)
&& exampleStore_ != null
&& exampleStore_
!= com.google.cloud.aiplatform.v1beta1.ExampleStore.getDefaultInstance()) {
getExampleStoreBuilder().mergeFrom(value);
} else {
exampleStore_ = value;
}
} else {
exampleStoreBuilder_.mergeFrom(value);
}
if (exampleStore_ != null) {
bitField0_ |= 0x00000001;
onChanged();
}
return this;
}
/**
*
*
* <pre>
* Required. The Example Store which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.ExampleStore example_store = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public Builder clearExampleStore() {
bitField0_ = (bitField0_ & ~0x00000001);
exampleStore_ = null;
if (exampleStoreBuilder_ != null) {
exampleStoreBuilder_.dispose();
exampleStoreBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The Example Store which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.ExampleStore example_store = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.ExampleStore.Builder getExampleStoreBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getExampleStoreFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Required. The Example Store which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.ExampleStore example_store = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
public com.google.cloud.aiplatform.v1beta1.ExampleStoreOrBuilder getExampleStoreOrBuilder() {
if (exampleStoreBuilder_ != null) {
return exampleStoreBuilder_.getMessageOrBuilder();
} else {
return exampleStore_ == null
? com.google.cloud.aiplatform.v1beta1.ExampleStore.getDefaultInstance()
: exampleStore_;
}
}
/**
*
*
* <pre>
* Required. The Example Store which replaces the resource on the server.
* </pre>
*
* <code>
* .google.cloud.aiplatform.v1beta1.ExampleStore example_store = 1 [(.google.api.field_behavior) = REQUIRED];
* </code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.ExampleStore,
com.google.cloud.aiplatform.v1beta1.ExampleStore.Builder,
com.google.cloud.aiplatform.v1beta1.ExampleStoreOrBuilder>
getExampleStoreFieldBuilder() {
if (exampleStoreBuilder_ == null) {
exampleStoreBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.aiplatform.v1beta1.ExampleStore,
com.google.cloud.aiplatform.v1beta1.ExampleStore.Builder,
com.google.cloud.aiplatform.v1beta1.ExampleStoreOrBuilder>(
getExampleStore(), getParentForChildren(), isClean());
exampleStore_ = null;
}
return exampleStoreBuilder_;
}
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>
* Optional. Mask specifying which fields to update.
* Supported fields:
*
* * `display_name`
* * `description`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return Whether the updateMask field is set.
*/
public boolean hasUpdateMask() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Optional. Mask specifying which fields to update.
* Supported fields:
*
* * `display_name`
* * `description`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </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>
* Optional. Mask specifying which fields to update.
* Supported fields:
*
* * `display_name`
* * `description`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </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>
* Optional. Mask specifying which fields to update.
* Supported fields:
*
* * `display_name`
* * `description`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </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>
* Optional. Mask specifying which fields to update.
* Supported fields:
*
* * `display_name`
* * `description`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </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>
* Optional. Mask specifying which fields to update.
* Supported fields:
*
* * `display_name`
* * `description`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public Builder clearUpdateMask() {
bitField0_ = (bitField0_ & ~0x00000002);
updateMask_ = null;
if (updateMaskBuilder_ != null) {
updateMaskBuilder_.dispose();
updateMaskBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Mask specifying which fields to update.
* Supported fields:
*
* * `display_name`
* * `description`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.protobuf.FieldMask.Builder getUpdateMaskBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getUpdateMaskFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Optional. Mask specifying which fields to update.
* Supported fields:
*
* * `display_name`
* * `description`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*/
public com.google.protobuf.FieldMaskOrBuilder getUpdateMaskOrBuilder() {
if (updateMaskBuilder_ != null) {
return updateMaskBuilder_.getMessageOrBuilder();
} else {
return updateMask_ == null
? com.google.protobuf.FieldMask.getDefaultInstance()
: updateMask_;
}
}
/**
*
*
* <pre>
* Optional. Mask specifying which fields to update.
* Supported fields:
*
* * `display_name`
* * `description`
* </pre>
*
* <code>.google.protobuf.FieldMask update_mask = 2 [(.google.api.field_behavior) = OPTIONAL];
* </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.aiplatform.v1beta1.UpdateExampleStoreRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest)
private static final com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest();
}
public static com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<UpdateExampleStoreRequest> PARSER =
new com.google.protobuf.AbstractParser<UpdateExampleStoreRequest>() {
@java.lang.Override
public UpdateExampleStoreRequest 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<UpdateExampleStoreRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<UpdateExampleStoreRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.aiplatform.v1beta1.UpdateExampleStoreRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
apache/jena | 35,957 | jena-permissions/src/main/java/org/apache/jena/permissions/model/impl/SecuredSeqImpl.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.jena.permissions.model.impl;
import java.util.function.Predicate;
import org.apache.jena.graph.Triple;
import org.apache.jena.permissions.SecurityEvaluator;
import org.apache.jena.permissions.impl.ItemHolder;
import org.apache.jena.permissions.impl.SecuredItemInvoker;
import org.apache.jena.permissions.model.SecuredAlt;
import org.apache.jena.permissions.model.SecuredBag;
import org.apache.jena.permissions.model.SecuredLiteral;
import org.apache.jena.permissions.model.SecuredModel;
import org.apache.jena.permissions.model.SecuredRDFNode;
import org.apache.jena.permissions.model.SecuredResource;
import org.apache.jena.permissions.model.SecuredSeq;
import org.apache.jena.rdf.model.Alt;
import org.apache.jena.rdf.model.Bag;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.ResourceFactory;
import org.apache.jena.rdf.model.Seq;
import org.apache.jena.rdf.model.SeqIndexBoundsException;
import org.apache.jena.rdf.model.Statement;
import org.apache.jena.shared.AddDeniedException;
import org.apache.jena.shared.AuthenticationRequiredException;
import org.apache.jena.shared.DeleteDeniedException;
import org.apache.jena.shared.ReadDeniedException;
import org.apache.jena.shared.UpdateDeniedException;
import org.apache.jena.util.iterator.ExtendedIterator;
import org.apache.jena.vocabulary.RDF;
/**
* Implementation of SecuredSeq to be used by a SecuredItemInvoker proxy.
*
* Sequence may have breaks in the order.
* http://www.w3.org/TR/2004/REC-rdf-mt-20040210/#Containers
*
*/
@SuppressWarnings("all")
public class SecuredSeqImpl extends SecuredContainerImpl implements SecuredSeq {
/**
* A filter that returns objects that have an ordinal predicate and match the
* node in the constructor.
*
*/
private class RDFNodeFilter implements Predicate<Statement> {
private final RDFNode n;
/**
* Constructor.
*
* @param n the node to match.
*/
public RDFNodeFilter(final RDFNode n) {
this.n = n;
}
@Override
public boolean test(final Statement o) {
return (o.getPredicate().getOrdinal() != 0) && n.equals(o.getObject());
}
}
/**
* get a SecuredSeq.
*
* @param securedModel The secured model that provides the security context
* @param seq The Seq to secure.
* @return the SecuredSeq
*/
public static SecuredSeq getInstance(final SecuredModel securedModel, final Seq seq) {
if (securedModel == null) {
throw new IllegalArgumentException("Secured securedModel may not be null");
}
if (seq == null) {
throw new IllegalArgumentException("Seq may not be null");
}
final ItemHolder<Seq, SecuredSeq> holder = new ItemHolder<>(seq);
final SecuredSeqImpl checker = new SecuredSeqImpl(securedModel, holder);
// if we are going to create a duplicate proxy, just return this
// one.
if (seq instanceof SecuredSeq) {
if (checker.isEquivalent((SecuredSeq) seq)) {
return (SecuredSeq) seq;
}
}
return holder.setSecuredItem(new SecuredItemInvoker(seq.getClass(), checker));
}
// the item holder that contains this SecuredSeq.
private final ItemHolder<? extends Seq, ? extends SecuredSeq> holder;
/**
* Constructor.
*
* @param securedModel The secured model that provides the security context
* @param holder The item holder that will contain this SecuredSeq.
*/
protected SecuredSeqImpl(final SecuredModel securedModel,
final ItemHolder<? extends Seq, ? extends SecuredSeq> holder) {
super(securedModel, holder);
this.holder = holder;
}
/**
* @sec.graph Update
* @sec.triple Create SecTriple( this, RDF.li(1), o )
* @throws UpdateDeniedException
* @throws DeleteDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public Seq add(int index, boolean o) {
return add(index, asObject(o));
}
/**
* @sec.graph Update
* @sec.triple Create SecTriple( this, RDF.li(1), o )
* @throws UpdateDeniedException
* @throws DeleteDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public Seq add(int index, long o) {
return add(index, asObject(o));
}
/**
* @sec.graph Update
* @sec.triple Create SecTriple( this, RDF.li(1), o )
* @throws UpdateDeniedException
* @throws DeleteDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public Seq add(int index, char o) {
return add(index, asObject(o));
}
/**
* @sec.graph Update
* @sec.triple Create SecTriple( this, RDF.li(1), o )
* @throws UpdateDeniedException
* @throws DeleteDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public Seq add(int index, float o) {
return add(index, asObject(o));
}
/**
* @sec.graph Update
* @sec.triple Create SecTriple( this, RDF.li(1), o )
* @throws UpdateDeniedException
* @throws DeleteDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public Seq add(int index, double o) {
return add(index, asObject(o));
}
/**
* @sec.graph Update
* @sec.triple Create SecTriple( this, RDF.li(1), o )
* @throws UpdateDeniedException
* @throws DeleteDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public Seq add(int index, Object o) {
return add(index, asObject(o));
}
/**
* @sec.graph Update
* @sec.triple Create SecTriple( this, RDF.li(1), o )
* @throws UpdateDeniedException
* @throws DeleteDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public Seq add(int index, String o) {
return add(index, o, "");
}
/**
* @sec.graph Update
* @sec.triple Create SecTriple( this, RDF.li(1), o )
* @throws UpdateDeniedException
* @throws DeleteDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public Seq add(final int index, final RDFNode o)
throws UpdateDeniedException, AddDeniedException, AuthenticationRequiredException {
checkUpdate();
checkCreate(index, o);
holder.getBaseItem().add(index, o);
return holder.getSecuredItem();
}
/**
* @sec.graph Update
* @sec.triple Create SecTriple( this, RDF.li(1), o )
* @throws UpdateDeniedException
* @throws DeleteDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public Seq add(final int index, final String o, final String l)
throws UpdateDeniedException, AddDeniedException, AuthenticationRequiredException {
return add(index, holder.getBaseItem().getModel().createLiteral(o, l));
}
/**
* Verifies that a node with the specified index can be created.
*
* @param index the index to check
* @param n the RDFNode to to check.
*/
private void checkCreate(final int index, final RDFNode n) {
checkCreate(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), n.asNode()));
}
/**
* Gets the index of the node in the container.
*
* @param n the node to look for
* @return the statement containing the node or {@code null} if none was found.
*/
private Statement containerIndexOf(final RDFNode n) {
final ExtendedIterator<Statement> iter = listProperties().filterKeep(new RDFNodeFilter(n));
try {
if (iter.hasNext()) {
return iter.next();
}
return null;
} finally {
iter.close();
}
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredAlt getAlt(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final Alt a = holder.getBaseItem().getAlt(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), a.asNode()));
return SecuredAltImpl.getInstance(getModel(), a);
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredBag getBag(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final Bag b = holder.getBaseItem().getBag(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), b.asNode()));
return SecuredBagImpl.getInstance(getModel(), b);
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public boolean getBoolean(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final boolean retval = holder.getBaseItem().getBoolean(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), asObject(retval).asNode()));
return retval;
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public byte getByte(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final byte retval = holder.getBaseItem().getByte(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), asObject(retval).asNode()));
return retval;
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public char getChar(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final char retval = holder.getBaseItem().getChar(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), asObject(retval).asNode()));
return retval;
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public double getDouble(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final double retval = holder.getBaseItem().getDouble(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), asObject(retval).asNode()));
return retval;
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public float getFloat(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final float retval = holder.getBaseItem().getFloat(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), asObject(retval).asNode()));
return retval;
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public int getInt(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final int retval = holder.getBaseItem().getInt(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), asObject(retval).asNode()));
return retval;
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public String getLanguage(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final Literal literal = holder.getBaseItem().getLiteral(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), literal.asNode()));
return literal.getLanguage();
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredLiteral getLiteral(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final Literal literal = holder.getBaseItem().getLiteral(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), literal.asNode()));
return SecuredLiteralImpl.getInstance(getModel(), literal);
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public long getLong(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final long retval = holder.getBaseItem().getLong(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), asObject(retval).asNode()));
return retval;
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredRDFNode getObject(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final RDFNode retval = holder.getBaseItem().getObject(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), retval.asNode()));
return SecuredRDFNodeImpl.getInstance(getModel(), retval);
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredResource getResource(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final Resource retval = holder.getBaseItem().getResource(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), retval.asNode()));
return SecuredResourceImpl.getInstance(getModel(), retval);
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredSeq getSeq(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final Seq retval = holder.getBaseItem().getSeq(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), retval.asNode()));
return SecuredSeqImpl.getInstance(getModel(), retval);
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public short getShort(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final short retval = holder.getBaseItem().getShort(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(),
ResourceFactory.createTypedLiteral(retval).asNode()));
return retval;
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then SeqIndexBoundsException is
* thrown
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public String getString(final int index) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final String retval = holder.getBaseItem().getString(index);
checkRead(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(),
ResourceFactory.createTypedLiteral(retval).asNode()));
return retval;
}
throw new SeqIndexBoundsException(index, 0);
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then 0 is returned
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public int indexOf(final boolean o) throws ReadDeniedException, AuthenticationRequiredException {
return indexOf(asObject(o));
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then 0 is returned
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public int indexOf(final char o) throws ReadDeniedException, AuthenticationRequiredException {
return indexOf(asObject(o));
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then 0 is returned
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public int indexOf(final double o) throws ReadDeniedException, AuthenticationRequiredException {
return indexOf(asObject(o));
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then 0 is returned
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public int indexOf(final float o) throws ReadDeniedException, AuthenticationRequiredException {
return indexOf(asObject(o));
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then 0 is returned
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public int indexOf(final long o) throws ReadDeniedException, AuthenticationRequiredException {
return indexOf(asObject(o));
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then 0 is returned
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public int indexOf(final Object o) throws ReadDeniedException, AuthenticationRequiredException {
return indexOf(asObject(o));
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then 0 is returned
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public int indexOf(final RDFNode o) throws ReadDeniedException, AuthenticationRequiredException {
if (checkSoftRead()) {
final Statement stmt = containerIndexOf(o);
if (stmt != null) {
checkRead(stmt);
return stmt.getPredicate().getOrdinal();
}
}
return 0;
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then 0 is returned
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public int indexOf(final String o) throws ReadDeniedException, AuthenticationRequiredException {
return indexOf(asLiteral(o, ""));
}
/**
* @sec.graph Read if {@link SecurityEvaluator#isHardReadError()} is true and
* the user does not have read access then 0 is returned
* @sec.triple Read SecTriple( this, RDF.li(1), o )
* @throws ReadDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public int indexOf(final String o, final String l) throws ReadDeniedException, AuthenticationRequiredException {
return indexOf(asLiteral(o, l));
}
/**
* @sec.graph Update
* @sec.triple Delete SecTriple( this, RDF.li(1), o )
* @sec.triple Update Triples after index
* @throws UpdateDeniedException
* @throws DeleteDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredSeq remove(final int index)
throws UpdateDeniedException, DeleteDeniedException, AuthenticationRequiredException {
checkUpdate();
final RDFNode rdfNode = holder.getBaseItem().getObject(index);
if (rdfNode != null) {
checkDelete(Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), rdfNode.asNode()));
holder.getBaseItem().remove(index);
}
return holder.getSecuredItem();
}
/**
* @sec.graph Update
* @sec.triple Update SecTriple( this, RDF.li(index), old ) SecTriple( this,
* RDF.li(index), o )
* @throws UpdateDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredSeq set(final int index, final boolean o)
throws UpdateDeniedException, AddDeniedException, AuthenticationRequiredException {
return set(index, ResourceFactory.createTypedLiteral(o));
}
/**
* @sec.graph Update
* @sec.triple Update SecTriple( this, RDF.li(index), old ) SecTriple( this,
* RDF.li(index), o )
* @throws UpdateDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredSeq set(final int index, final char o)
throws UpdateDeniedException, AddDeniedException, AuthenticationRequiredException {
return set(index, ResourceFactory.createTypedLiteral(o));
}
/**
* @sec.graph Update
* @sec.triple Update SecTriple( this, RDF.li(index), old ) SecTriple( this,
* RDF.li(index), o )
* @throws UpdateDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredSeq set(final int index, final double o)
throws UpdateDeniedException, AddDeniedException, AuthenticationRequiredException {
return set(index, ResourceFactory.createTypedLiteral(o));
}
/**
* @sec.graph Update
* @sec.triple Update SecTriple( this, RDF.li(index), old ) SecTriple( this,
* RDF.li(index), o )
* @throws UpdateDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredSeq set(final int index, final float o)
throws UpdateDeniedException, AddDeniedException, AuthenticationRequiredException {
return set(index, ResourceFactory.createTypedLiteral(o));
}
/**
* @sec.graph Update
* @sec.triple Update SecTriple( this, RDF.li(index), old ) SecTriple( this,
* RDF.li(index), o )
* @throws UpdateDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredSeq set(final int index, final long o)
throws UpdateDeniedException, AddDeniedException, AuthenticationRequiredException {
return set(index, ResourceFactory.createTypedLiteral(o));
}
/**
* @sec.graph Update
* @sec.triple Update SecTriple( this, RDF.li(index), old ) SecTriple( this,
* RDF.li(index), o )
* @throws UpdateDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredSeq set(final int index, final Object o)
throws UpdateDeniedException, AddDeniedException, AuthenticationRequiredException {
return set(index, asObject(o));
}
/**
* @sec.graph Update
* @sec.triple Update SecTriple( this, RDF.li(index), old ) SecTriple( this,
* RDF.li(index), o )
* @throws UpdateDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredSeq set(final int index, final RDFNode o)
throws UpdateDeniedException, AddDeniedException, AuthenticationRequiredException {
checkUpdate();
final Triple t2 = Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), o.asNode());
final RDFNode rdfNode = holder.getBaseItem().getObject(index);
final Triple t1 = Triple.create(holder.getBaseItem().asNode(), RDF.li(index).asNode(), rdfNode.asNode());
checkUpdate(t1, t2);
holder.getBaseItem().set(index, o);
return holder.getSecuredItem();
}
/**
* @sec.graph Update
* @sec.triple Update SecTriple( this, RDF.li(index), old ) SecTriple( this,
* RDF.li(index), o )
* @throws UpdateDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredSeq set(final int index, final String o)
throws UpdateDeniedException, AddDeniedException, AuthenticationRequiredException {
return set(index, asLiteral(o, ""));
}
/**
* @sec.graph Update
* @sec.triple Update SecTriple( this, RDF.li(index), old ) SecTriple( this,
* RDF.li(index), o )
* @throws UpdateDeniedException
* @throws AuthenticationRequiredException if user is not authenticated and is
* required to be.
*/
@Override
public SecuredSeq set(final int index, final String o, final String l)
throws UpdateDeniedException, AddDeniedException, AuthenticationRequiredException {
return set(index, asLiteral(o, l));
}
}
|
googleapis/google-cloud-java | 35,608 | java-modelarmor/google-cloud-modelarmor/src/test/java/com/google/cloud/modelarmor/v1beta/ModelArmorClientHttpJsonTest.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.modelarmor.v1beta;
import static com.google.cloud.modelarmor.v1beta.ModelArmorClient.ListLocationsPagedResponse;
import static com.google.cloud.modelarmor.v1beta.ModelArmorClient.ListTemplatesPagedResponse;
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.location.GetLocationRequest;
import com.google.cloud.location.ListLocationsRequest;
import com.google.cloud.location.ListLocationsResponse;
import com.google.cloud.location.Location;
import com.google.cloud.modelarmor.v1beta.stub.HttpJsonModelArmorStub;
import com.google.common.collect.Lists;
import com.google.protobuf.Any;
import com.google.protobuf.Empty;
import com.google.protobuf.FieldMask;
import com.google.protobuf.Timestamp;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
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 ModelArmorClientHttpJsonTest {
private static MockHttpService mockService;
private static ModelArmorClient client;
@BeforeClass
public static void startStaticServer() throws IOException {
mockService =
new MockHttpService(
HttpJsonModelArmorStub.getMethodDescriptors(), ModelArmorSettings.getDefaultEndpoint());
ModelArmorSettings settings =
ModelArmorSettings.newHttpJsonBuilder()
.setTransportChannelProvider(
ModelArmorSettings.defaultHttpJsonTransportProviderBuilder()
.setHttpTransport(mockService)
.build())
.setCredentialsProvider(NoCredentialsProvider.create())
.build();
client = ModelArmorClient.create(settings);
}
@AfterClass
public static void stopServer() {
client.close();
}
@Before
public void setUp() {}
@After
public void tearDown() throws Exception {
mockService.reset();
}
@Test
public void listTemplatesTest() throws Exception {
Template responsesElement = Template.newBuilder().build();
ListTemplatesResponse expectedResponse =
ListTemplatesResponse.newBuilder()
.setNextPageToken("")
.addAllTemplates(Arrays.asList(responsesElement))
.build();
mockService.addResponse(expectedResponse);
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
ListTemplatesPagedResponse pagedListResponse = client.listTemplates(parent);
List<Template> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getTemplatesList().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 listTemplatesExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
client.listTemplates(parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listTemplatesTest2() throws Exception {
Template responsesElement = Template.newBuilder().build();
ListTemplatesResponse expectedResponse =
ListTemplatesResponse.newBuilder()
.setNextPageToken("")
.addAllTemplates(Arrays.asList(responsesElement))
.build();
mockService.addResponse(expectedResponse);
String parent = "projects/project-5833/locations/location-5833";
ListTemplatesPagedResponse pagedListResponse = client.listTemplates(parent);
List<Template> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getTemplatesList().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 listTemplatesExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String parent = "projects/project-5833/locations/location-5833";
client.listTemplates(parent);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getTemplateTest() throws Exception {
Template expectedResponse =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
TemplateName name = TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]");
Template actualResponse = client.getTemplate(name);
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 getTemplateExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
TemplateName name = TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]");
client.getTemplate(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getTemplateTest2() throws Exception {
Template expectedResponse =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
String name = "projects/project-127/locations/location-127/templates/template-127";
Template actualResponse = client.getTemplate(name);
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 getTemplateExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String name = "projects/project-127/locations/location-127/templates/template-127";
client.getTemplate(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void createTemplateTest() throws Exception {
Template expectedResponse =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
Template template = Template.newBuilder().build();
String templateId = "templateId1304010549";
Template actualResponse = client.createTemplate(parent, template, templateId);
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 createTemplateExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
LocationName parent = LocationName.of("[PROJECT]", "[LOCATION]");
Template template = Template.newBuilder().build();
String templateId = "templateId1304010549";
client.createTemplate(parent, template, templateId);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void createTemplateTest2() throws Exception {
Template expectedResponse =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
String parent = "projects/project-5833/locations/location-5833";
Template template = Template.newBuilder().build();
String templateId = "templateId1304010549";
Template actualResponse = client.createTemplate(parent, template, templateId);
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 createTemplateExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String parent = "projects/project-5833/locations/location-5833";
Template template = Template.newBuilder().build();
String templateId = "templateId1304010549";
client.createTemplate(parent, template, templateId);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updateTemplateTest() throws Exception {
Template expectedResponse =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
Template template =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
Template actualResponse = client.updateTemplate(template, updateMask);
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 updateTemplateExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
Template template =
Template.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.putAllLabels(new HashMap<String, String>())
.setFilterConfig(FilterConfig.newBuilder().build())
.setTemplateMetadata(Template.TemplateMetadata.newBuilder().build())
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
client.updateTemplate(template, updateMask);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void deleteTemplateTest() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
mockService.addResponse(expectedResponse);
TemplateName name = TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]");
client.deleteTemplate(name);
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 deleteTemplateExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
TemplateName name = TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]");
client.deleteTemplate(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void deleteTemplateTest2() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
mockService.addResponse(expectedResponse);
String name = "projects/project-127/locations/location-127/templates/template-127";
client.deleteTemplate(name);
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 deleteTemplateExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String name = "projects/project-127/locations/location-127/templates/template-127";
client.deleteTemplate(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getFloorSettingTest() throws Exception {
FloorSetting expectedResponse =
FloorSetting.newBuilder()
.setName(FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.setFilterConfig(FilterConfig.newBuilder().build())
.setEnableFloorSettingEnforcement(true)
.addAllIntegratedServices(new ArrayList<FloorSetting.IntegratedService>())
.setAiPlatformFloorSetting(AiPlatformFloorSetting.newBuilder().build())
.setFloorSettingMetadata(FloorSetting.FloorSettingMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
FloorSettingName name = FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]");
FloorSetting actualResponse = client.getFloorSetting(name);
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 getFloorSettingExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
FloorSettingName name = FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]");
client.getFloorSetting(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getFloorSettingTest2() throws Exception {
FloorSetting expectedResponse =
FloorSetting.newBuilder()
.setName(FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.setFilterConfig(FilterConfig.newBuilder().build())
.setEnableFloorSettingEnforcement(true)
.addAllIntegratedServices(new ArrayList<FloorSetting.IntegratedService>())
.setAiPlatformFloorSetting(AiPlatformFloorSetting.newBuilder().build())
.setFloorSettingMetadata(FloorSetting.FloorSettingMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
String name = "projects/project-535/locations/location-535/floorSetting";
FloorSetting actualResponse = client.getFloorSetting(name);
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 getFloorSettingExceptionTest2() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
String name = "projects/project-535/locations/location-535/floorSetting";
client.getFloorSetting(name);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void updateFloorSettingTest() throws Exception {
FloorSetting expectedResponse =
FloorSetting.newBuilder()
.setName(FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.setFilterConfig(FilterConfig.newBuilder().build())
.setEnableFloorSettingEnforcement(true)
.addAllIntegratedServices(new ArrayList<FloorSetting.IntegratedService>())
.setAiPlatformFloorSetting(AiPlatformFloorSetting.newBuilder().build())
.setFloorSettingMetadata(FloorSetting.FloorSettingMetadata.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
FloorSetting floorSetting =
FloorSetting.newBuilder()
.setName(FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.setFilterConfig(FilterConfig.newBuilder().build())
.setEnableFloorSettingEnforcement(true)
.addAllIntegratedServices(new ArrayList<FloorSetting.IntegratedService>())
.setAiPlatformFloorSetting(AiPlatformFloorSetting.newBuilder().build())
.setFloorSettingMetadata(FloorSetting.FloorSettingMetadata.newBuilder().build())
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
FloorSetting actualResponse = client.updateFloorSetting(floorSetting, updateMask);
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 updateFloorSettingExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
FloorSetting floorSetting =
FloorSetting.newBuilder()
.setName(FloorSettingName.ofProjectLocationName("[PROJECT]", "[LOCATION]").toString())
.setCreateTime(Timestamp.newBuilder().build())
.setUpdateTime(Timestamp.newBuilder().build())
.setFilterConfig(FilterConfig.newBuilder().build())
.setEnableFloorSettingEnforcement(true)
.addAllIntegratedServices(new ArrayList<FloorSetting.IntegratedService>())
.setAiPlatformFloorSetting(AiPlatformFloorSetting.newBuilder().build())
.setFloorSettingMetadata(FloorSetting.FloorSettingMetadata.newBuilder().build())
.build();
FieldMask updateMask = FieldMask.newBuilder().build();
client.updateFloorSetting(floorSetting, updateMask);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void sanitizeUserPromptTest() throws Exception {
SanitizeUserPromptResponse expectedResponse =
SanitizeUserPromptResponse.newBuilder()
.setSanitizationResult(SanitizationResult.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
SanitizeUserPromptRequest request =
SanitizeUserPromptRequest.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setUserPromptData(DataItem.newBuilder().build())
.setMultiLanguageDetectionMetadata(MultiLanguageDetectionMetadata.newBuilder().build())
.build();
SanitizeUserPromptResponse actualResponse = client.sanitizeUserPrompt(request);
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 sanitizeUserPromptExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
SanitizeUserPromptRequest request =
SanitizeUserPromptRequest.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setUserPromptData(DataItem.newBuilder().build())
.setMultiLanguageDetectionMetadata(
MultiLanguageDetectionMetadata.newBuilder().build())
.build();
client.sanitizeUserPrompt(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void sanitizeModelResponseTest() throws Exception {
SanitizeModelResponseResponse expectedResponse =
SanitizeModelResponseResponse.newBuilder()
.setSanitizationResult(SanitizationResult.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
SanitizeModelResponseRequest request =
SanitizeModelResponseRequest.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setModelResponseData(DataItem.newBuilder().build())
.setUserPrompt("userPrompt1504308495")
.setMultiLanguageDetectionMetadata(MultiLanguageDetectionMetadata.newBuilder().build())
.build();
SanitizeModelResponseResponse actualResponse = client.sanitizeModelResponse(request);
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 sanitizeModelResponseExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
SanitizeModelResponseRequest request =
SanitizeModelResponseRequest.newBuilder()
.setName(TemplateName.of("[PROJECT]", "[LOCATION]", "[TEMPLATE]").toString())
.setModelResponseData(DataItem.newBuilder().build())
.setUserPrompt("userPrompt1504308495")
.setMultiLanguageDetectionMetadata(
MultiLanguageDetectionMetadata.newBuilder().build())
.build();
client.sanitizeModelResponse(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void listLocationsTest() throws Exception {
Location responsesElement = Location.newBuilder().build();
ListLocationsResponse expectedResponse =
ListLocationsResponse.newBuilder()
.setNextPageToken("")
.addAllLocations(Arrays.asList(responsesElement))
.build();
mockService.addResponse(expectedResponse);
ListLocationsRequest request =
ListLocationsRequest.newBuilder()
.setName("projects/project-3664")
.setFilter("filter-1274492040")
.setPageSize(883849137)
.setPageToken("pageToken873572522")
.build();
ListLocationsPagedResponse pagedListResponse = client.listLocations(request);
List<Location> resources = Lists.newArrayList(pagedListResponse.iterateAll());
Assert.assertEquals(1, resources.size());
Assert.assertEquals(expectedResponse.getLocationsList().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 listLocationsExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
ListLocationsRequest request =
ListLocationsRequest.newBuilder()
.setName("projects/project-3664")
.setFilter("filter-1274492040")
.setPageSize(883849137)
.setPageToken("pageToken873572522")
.build();
client.listLocations(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
@Test
public void getLocationTest() throws Exception {
Location expectedResponse =
Location.newBuilder()
.setName("name3373707")
.setLocationId("locationId1541836720")
.setDisplayName("displayName1714148973")
.putAllLabels(new HashMap<String, String>())
.setMetadata(Any.newBuilder().build())
.build();
mockService.addResponse(expectedResponse);
GetLocationRequest request =
GetLocationRequest.newBuilder()
.setName("projects/project-9062/locations/location-9062")
.build();
Location actualResponse = client.getLocation(request);
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 getLocationExceptionTest() throws Exception {
ApiException exception =
ApiExceptionFactory.createException(
new Exception(), FakeStatusCode.of(StatusCode.Code.INVALID_ARGUMENT), false);
mockService.addException(exception);
try {
GetLocationRequest request =
GetLocationRequest.newBuilder()
.setName("projects/project-9062/locations/location-9062")
.build();
client.getLocation(request);
Assert.fail("No exception raised");
} catch (InvalidArgumentException e) {
// Expected exception.
}
}
}
|
googleapis/google-cloud-java | 35,599 | java-alloydb/proto-google-cloud-alloydb-v1alpha/src/main/java/com/google/cloud/alloydb/v1alpha/SslConfig.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/alloydb/v1alpha/resources.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.alloydb.v1alpha;
/**
*
*
* <pre>
* SSL configuration.
* </pre>
*
* Protobuf type {@code google.cloud.alloydb.v1alpha.SslConfig}
*/
public final class SslConfig extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.alloydb.v1alpha.SslConfig)
SslConfigOrBuilder {
private static final long serialVersionUID = 0L;
// Use SslConfig.newBuilder() to construct.
private SslConfig(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private SslConfig() {
sslMode_ = 0;
caSource_ = 0;
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new SslConfig();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.alloydb.v1alpha.ResourcesProto
.internal_static_google_cloud_alloydb_v1alpha_SslConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.alloydb.v1alpha.ResourcesProto
.internal_static_google_cloud_alloydb_v1alpha_SslConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.alloydb.v1alpha.SslConfig.class,
com.google.cloud.alloydb.v1alpha.SslConfig.Builder.class);
}
/**
*
*
* <pre>
* SSL mode options.
* </pre>
*
* Protobuf enum {@code google.cloud.alloydb.v1alpha.SslConfig.SslMode}
*/
public enum SslMode implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* SSL mode is not specified. Defaults to ENCRYPTED_ONLY.
* </pre>
*
* <code>SSL_MODE_UNSPECIFIED = 0;</code>
*/
SSL_MODE_UNSPECIFIED(0),
/**
*
*
* <pre>
* SSL connections are optional. CA verification not enforced.
* </pre>
*
* <code>SSL_MODE_ALLOW = 1 [deprecated = true];</code>
*/
@java.lang.Deprecated
SSL_MODE_ALLOW(1),
/**
*
*
* <pre>
* SSL connections are required. CA verification not enforced.
* Clients may use locally self-signed certificates (default psql client
* behavior).
* </pre>
*
* <code>SSL_MODE_REQUIRE = 2 [deprecated = true];</code>
*/
@java.lang.Deprecated
SSL_MODE_REQUIRE(2),
/**
*
*
* <pre>
* SSL connections are required. CA verification enforced.
* Clients must have certificates signed by a Cluster CA, for example, using
* GenerateClientCertificate.
* </pre>
*
* <code>SSL_MODE_VERIFY_CA = 3 [deprecated = true];</code>
*/
@java.lang.Deprecated
SSL_MODE_VERIFY_CA(3),
/**
*
*
* <pre>
* SSL connections are optional. CA verification not enforced.
* </pre>
*
* <code>ALLOW_UNENCRYPTED_AND_ENCRYPTED = 4;</code>
*/
ALLOW_UNENCRYPTED_AND_ENCRYPTED(4),
/**
*
*
* <pre>
* SSL connections are required. CA verification not enforced.
* </pre>
*
* <code>ENCRYPTED_ONLY = 5;</code>
*/
ENCRYPTED_ONLY(5),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* SSL mode is not specified. Defaults to ENCRYPTED_ONLY.
* </pre>
*
* <code>SSL_MODE_UNSPECIFIED = 0;</code>
*/
public static final int SSL_MODE_UNSPECIFIED_VALUE = 0;
/**
*
*
* <pre>
* SSL connections are optional. CA verification not enforced.
* </pre>
*
* <code>SSL_MODE_ALLOW = 1 [deprecated = true];</code>
*/
@java.lang.Deprecated public static final int SSL_MODE_ALLOW_VALUE = 1;
/**
*
*
* <pre>
* SSL connections are required. CA verification not enforced.
* Clients may use locally self-signed certificates (default psql client
* behavior).
* </pre>
*
* <code>SSL_MODE_REQUIRE = 2 [deprecated = true];</code>
*/
@java.lang.Deprecated public static final int SSL_MODE_REQUIRE_VALUE = 2;
/**
*
*
* <pre>
* SSL connections are required. CA verification enforced.
* Clients must have certificates signed by a Cluster CA, for example, using
* GenerateClientCertificate.
* </pre>
*
* <code>SSL_MODE_VERIFY_CA = 3 [deprecated = true];</code>
*/
@java.lang.Deprecated public static final int SSL_MODE_VERIFY_CA_VALUE = 3;
/**
*
*
* <pre>
* SSL connections are optional. CA verification not enforced.
* </pre>
*
* <code>ALLOW_UNENCRYPTED_AND_ENCRYPTED = 4;</code>
*/
public static final int ALLOW_UNENCRYPTED_AND_ENCRYPTED_VALUE = 4;
/**
*
*
* <pre>
* SSL connections are required. CA verification not enforced.
* </pre>
*
* <code>ENCRYPTED_ONLY = 5;</code>
*/
public static final int ENCRYPTED_ONLY_VALUE = 5;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static SslMode valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static SslMode forNumber(int value) {
switch (value) {
case 0:
return SSL_MODE_UNSPECIFIED;
case 1:
return SSL_MODE_ALLOW;
case 2:
return SSL_MODE_REQUIRE;
case 3:
return SSL_MODE_VERIFY_CA;
case 4:
return ALLOW_UNENCRYPTED_AND_ENCRYPTED;
case 5:
return ENCRYPTED_ONLY;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<SslMode> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<SslMode> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<SslMode>() {
public SslMode findValueByNumber(int number) {
return SslMode.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
return com.google.cloud.alloydb.v1alpha.SslConfig.getDescriptor().getEnumTypes().get(0);
}
private static final SslMode[] VALUES = values();
public static SslMode valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private SslMode(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.cloud.alloydb.v1alpha.SslConfig.SslMode)
}
/**
*
*
* <pre>
* Certificate Authority (CA) source for SSL/TLS certificates.
* </pre>
*
* Protobuf enum {@code google.cloud.alloydb.v1alpha.SslConfig.CaSource}
*/
public enum CaSource implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* Certificate Authority (CA) source not specified. Defaults to
* CA_SOURCE_MANAGED.
* </pre>
*
* <code>CA_SOURCE_UNSPECIFIED = 0;</code>
*/
CA_SOURCE_UNSPECIFIED(0),
/**
*
*
* <pre>
* Certificate Authority (CA) managed by the AlloyDB Cluster.
* </pre>
*
* <code>CA_SOURCE_MANAGED = 1;</code>
*/
CA_SOURCE_MANAGED(1),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* Certificate Authority (CA) source not specified. Defaults to
* CA_SOURCE_MANAGED.
* </pre>
*
* <code>CA_SOURCE_UNSPECIFIED = 0;</code>
*/
public static final int CA_SOURCE_UNSPECIFIED_VALUE = 0;
/**
*
*
* <pre>
* Certificate Authority (CA) managed by the AlloyDB Cluster.
* </pre>
*
* <code>CA_SOURCE_MANAGED = 1;</code>
*/
public static final int CA_SOURCE_MANAGED_VALUE = 1;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static CaSource valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static CaSource forNumber(int value) {
switch (value) {
case 0:
return CA_SOURCE_UNSPECIFIED;
case 1:
return CA_SOURCE_MANAGED;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<CaSource> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<CaSource> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<CaSource>() {
public CaSource findValueByNumber(int number) {
return CaSource.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
return com.google.cloud.alloydb.v1alpha.SslConfig.getDescriptor().getEnumTypes().get(1);
}
private static final CaSource[] VALUES = values();
public static CaSource valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private CaSource(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.cloud.alloydb.v1alpha.SslConfig.CaSource)
}
public static final int SSL_MODE_FIELD_NUMBER = 1;
private int sslMode_ = 0;
/**
*
*
* <pre>
* Optional. SSL mode. Specifies client-server SSL/TLS connection behavior.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.SslMode ssl_mode = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The enum numeric value on the wire for sslMode.
*/
@java.lang.Override
public int getSslModeValue() {
return sslMode_;
}
/**
*
*
* <pre>
* Optional. SSL mode. Specifies client-server SSL/TLS connection behavior.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.SslMode ssl_mode = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The sslMode.
*/
@java.lang.Override
public com.google.cloud.alloydb.v1alpha.SslConfig.SslMode getSslMode() {
com.google.cloud.alloydb.v1alpha.SslConfig.SslMode result =
com.google.cloud.alloydb.v1alpha.SslConfig.SslMode.forNumber(sslMode_);
return result == null
? com.google.cloud.alloydb.v1alpha.SslConfig.SslMode.UNRECOGNIZED
: result;
}
public static final int CA_SOURCE_FIELD_NUMBER = 2;
private int caSource_ = 0;
/**
*
*
* <pre>
* Optional. Certificate Authority (CA) source. Only CA_SOURCE_MANAGED is
* supported currently, and is the default value.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.CaSource ca_source = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The enum numeric value on the wire for caSource.
*/
@java.lang.Override
public int getCaSourceValue() {
return caSource_;
}
/**
*
*
* <pre>
* Optional. Certificate Authority (CA) source. Only CA_SOURCE_MANAGED is
* supported currently, and is the default value.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.CaSource ca_source = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The caSource.
*/
@java.lang.Override
public com.google.cloud.alloydb.v1alpha.SslConfig.CaSource getCaSource() {
com.google.cloud.alloydb.v1alpha.SslConfig.CaSource result =
com.google.cloud.alloydb.v1alpha.SslConfig.CaSource.forNumber(caSource_);
return result == null
? com.google.cloud.alloydb.v1alpha.SslConfig.CaSource.UNRECOGNIZED
: result;
}
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 (sslMode_
!= com.google.cloud.alloydb.v1alpha.SslConfig.SslMode.SSL_MODE_UNSPECIFIED.getNumber()) {
output.writeEnum(1, sslMode_);
}
if (caSource_
!= com.google.cloud.alloydb.v1alpha.SslConfig.CaSource.CA_SOURCE_UNSPECIFIED.getNumber()) {
output.writeEnum(2, caSource_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (sslMode_
!= com.google.cloud.alloydb.v1alpha.SslConfig.SslMode.SSL_MODE_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(1, sslMode_);
}
if (caSource_
!= com.google.cloud.alloydb.v1alpha.SslConfig.CaSource.CA_SOURCE_UNSPECIFIED.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, caSource_);
}
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.alloydb.v1alpha.SslConfig)) {
return super.equals(obj);
}
com.google.cloud.alloydb.v1alpha.SslConfig other =
(com.google.cloud.alloydb.v1alpha.SslConfig) obj;
if (sslMode_ != other.sslMode_) return false;
if (caSource_ != other.caSource_) 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) + SSL_MODE_FIELD_NUMBER;
hash = (53 * hash) + sslMode_;
hash = (37 * hash) + CA_SOURCE_FIELD_NUMBER;
hash = (53 * hash) + caSource_;
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.alloydb.v1alpha.SslConfig parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.alloydb.v1alpha.SslConfig 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.alloydb.v1alpha.SslConfig parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.alloydb.v1alpha.SslConfig 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.alloydb.v1alpha.SslConfig parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.alloydb.v1alpha.SslConfig parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.alloydb.v1alpha.SslConfig parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.alloydb.v1alpha.SslConfig 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.alloydb.v1alpha.SslConfig parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.alloydb.v1alpha.SslConfig 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.alloydb.v1alpha.SslConfig parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.alloydb.v1alpha.SslConfig 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.alloydb.v1alpha.SslConfig 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>
* SSL configuration.
* </pre>
*
* Protobuf type {@code google.cloud.alloydb.v1alpha.SslConfig}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.alloydb.v1alpha.SslConfig)
com.google.cloud.alloydb.v1alpha.SslConfigOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.alloydb.v1alpha.ResourcesProto
.internal_static_google_cloud_alloydb_v1alpha_SslConfig_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.alloydb.v1alpha.ResourcesProto
.internal_static_google_cloud_alloydb_v1alpha_SslConfig_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.alloydb.v1alpha.SslConfig.class,
com.google.cloud.alloydb.v1alpha.SslConfig.Builder.class);
}
// Construct using com.google.cloud.alloydb.v1alpha.SslConfig.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
sslMode_ = 0;
caSource_ = 0;
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.alloydb.v1alpha.ResourcesProto
.internal_static_google_cloud_alloydb_v1alpha_SslConfig_descriptor;
}
@java.lang.Override
public com.google.cloud.alloydb.v1alpha.SslConfig getDefaultInstanceForType() {
return com.google.cloud.alloydb.v1alpha.SslConfig.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.alloydb.v1alpha.SslConfig build() {
com.google.cloud.alloydb.v1alpha.SslConfig result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.alloydb.v1alpha.SslConfig buildPartial() {
com.google.cloud.alloydb.v1alpha.SslConfig result =
new com.google.cloud.alloydb.v1alpha.SslConfig(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.cloud.alloydb.v1alpha.SslConfig result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.sslMode_ = sslMode_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.caSource_ = caSource_;
}
}
@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.alloydb.v1alpha.SslConfig) {
return mergeFrom((com.google.cloud.alloydb.v1alpha.SslConfig) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.alloydb.v1alpha.SslConfig other) {
if (other == com.google.cloud.alloydb.v1alpha.SslConfig.getDefaultInstance()) return this;
if (other.sslMode_ != 0) {
setSslModeValue(other.getSslModeValue());
}
if (other.caSource_ != 0) {
setCaSourceValue(other.getCaSourceValue());
}
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 8:
{
sslMode_ = input.readEnum();
bitField0_ |= 0x00000001;
break;
} // case 8
case 16:
{
caSource_ = input.readEnum();
bitField0_ |= 0x00000002;
break;
} // case 16
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 int sslMode_ = 0;
/**
*
*
* <pre>
* Optional. SSL mode. Specifies client-server SSL/TLS connection behavior.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.SslMode ssl_mode = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The enum numeric value on the wire for sslMode.
*/
@java.lang.Override
public int getSslModeValue() {
return sslMode_;
}
/**
*
*
* <pre>
* Optional. SSL mode. Specifies client-server SSL/TLS connection behavior.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.SslMode ssl_mode = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The enum numeric value on the wire for sslMode to set.
* @return This builder for chaining.
*/
public Builder setSslModeValue(int value) {
sslMode_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. SSL mode. Specifies client-server SSL/TLS connection behavior.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.SslMode ssl_mode = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The sslMode.
*/
@java.lang.Override
public com.google.cloud.alloydb.v1alpha.SslConfig.SslMode getSslMode() {
com.google.cloud.alloydb.v1alpha.SslConfig.SslMode result =
com.google.cloud.alloydb.v1alpha.SslConfig.SslMode.forNumber(sslMode_);
return result == null
? com.google.cloud.alloydb.v1alpha.SslConfig.SslMode.UNRECOGNIZED
: result;
}
/**
*
*
* <pre>
* Optional. SSL mode. Specifies client-server SSL/TLS connection behavior.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.SslMode ssl_mode = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The sslMode to set.
* @return This builder for chaining.
*/
public Builder setSslMode(com.google.cloud.alloydb.v1alpha.SslConfig.SslMode value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
sslMode_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. SSL mode. Specifies client-server SSL/TLS connection behavior.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.SslMode ssl_mode = 1 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearSslMode() {
bitField0_ = (bitField0_ & ~0x00000001);
sslMode_ = 0;
onChanged();
return this;
}
private int caSource_ = 0;
/**
*
*
* <pre>
* Optional. Certificate Authority (CA) source. Only CA_SOURCE_MANAGED is
* supported currently, and is the default value.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.CaSource ca_source = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The enum numeric value on the wire for caSource.
*/
@java.lang.Override
public int getCaSourceValue() {
return caSource_;
}
/**
*
*
* <pre>
* Optional. Certificate Authority (CA) source. Only CA_SOURCE_MANAGED is
* supported currently, and is the default value.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.CaSource ca_source = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The enum numeric value on the wire for caSource to set.
* @return This builder for chaining.
*/
public Builder setCaSourceValue(int value) {
caSource_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Certificate Authority (CA) source. Only CA_SOURCE_MANAGED is
* supported currently, and is the default value.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.CaSource ca_source = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return The caSource.
*/
@java.lang.Override
public com.google.cloud.alloydb.v1alpha.SslConfig.CaSource getCaSource() {
com.google.cloud.alloydb.v1alpha.SslConfig.CaSource result =
com.google.cloud.alloydb.v1alpha.SslConfig.CaSource.forNumber(caSource_);
return result == null
? com.google.cloud.alloydb.v1alpha.SslConfig.CaSource.UNRECOGNIZED
: result;
}
/**
*
*
* <pre>
* Optional. Certificate Authority (CA) source. Only CA_SOURCE_MANAGED is
* supported currently, and is the default value.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.CaSource ca_source = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @param value The caSource to set.
* @return This builder for chaining.
*/
public Builder setCaSource(com.google.cloud.alloydb.v1alpha.SslConfig.CaSource value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
caSource_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Optional. Certificate Authority (CA) source. Only CA_SOURCE_MANAGED is
* supported currently, and is the default value.
* </pre>
*
* <code>
* .google.cloud.alloydb.v1alpha.SslConfig.CaSource ca_source = 2 [(.google.api.field_behavior) = OPTIONAL];
* </code>
*
* @return This builder for chaining.
*/
public Builder clearCaSource() {
bitField0_ = (bitField0_ & ~0x00000002);
caSource_ = 0;
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.alloydb.v1alpha.SslConfig)
}
// @@protoc_insertion_point(class_scope:google.cloud.alloydb.v1alpha.SslConfig)
private static final com.google.cloud.alloydb.v1alpha.SslConfig DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.alloydb.v1alpha.SslConfig();
}
public static com.google.cloud.alloydb.v1alpha.SslConfig getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<SslConfig> PARSER =
new com.google.protobuf.AbstractParser<SslConfig>() {
@java.lang.Override
public SslConfig 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<SslConfig> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<SslConfig> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.alloydb.v1alpha.SslConfig getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/google-cloud-java | 35,617 | java-gkehub/proto-google-cloud-gkehub-v1/src/main/java/com/google/cloud/gkehub/v1/ListFeaturesResponse.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/gkehub/v1/service.proto
// Protobuf Java Version: 3.25.8
package com.google.cloud.gkehub.v1;
/**
*
*
* <pre>
* Response message for the `GkeHub.ListFeatures` method.
* </pre>
*
* Protobuf type {@code google.cloud.gkehub.v1.ListFeaturesResponse}
*/
public final class ListFeaturesResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.gkehub.v1.ListFeaturesResponse)
ListFeaturesResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListFeaturesResponse.newBuilder() to construct.
private ListFeaturesResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListFeaturesResponse() {
resources_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListFeaturesResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.gkehub.v1.ServiceProto
.internal_static_google_cloud_gkehub_v1_ListFeaturesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.gkehub.v1.ServiceProto
.internal_static_google_cloud_gkehub_v1_ListFeaturesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.gkehub.v1.ListFeaturesResponse.class,
com.google.cloud.gkehub.v1.ListFeaturesResponse.Builder.class);
}
public static final int RESOURCES_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.cloud.gkehub.v1.Feature> resources_;
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.gkehub.v1.Feature> getResourcesList() {
return resources_;
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.gkehub.v1.FeatureOrBuilder>
getResourcesOrBuilderList() {
return resources_;
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
@java.lang.Override
public int getResourcesCount() {
return resources_.size();
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
@java.lang.Override
public com.google.cloud.gkehub.v1.Feature getResources(int index) {
return resources_.get(index);
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
@java.lang.Override
public com.google.cloud.gkehub.v1.FeatureOrBuilder getResourcesOrBuilder(int index) {
return resources_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to request the next page of resources from the
* `ListFeatures` method. The value of an empty string means
* that there are no more resources to return.
* </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 request the next page of resources from the
* `ListFeatures` method. The value of an empty string means
* that there are no more resources to return.
* </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 < resources_.size(); i++) {
output.writeMessage(1, resources_.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 < resources_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, resources_.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.gkehub.v1.ListFeaturesResponse)) {
return super.equals(obj);
}
com.google.cloud.gkehub.v1.ListFeaturesResponse other =
(com.google.cloud.gkehub.v1.ListFeaturesResponse) obj;
if (!getResourcesList().equals(other.getResourcesList())) 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 (getResourcesCount() > 0) {
hash = (37 * hash) + RESOURCES_FIELD_NUMBER;
hash = (53 * hash) + getResourcesList().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.gkehub.v1.ListFeaturesResponse parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.gkehub.v1.ListFeaturesResponse 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.gkehub.v1.ListFeaturesResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.gkehub.v1.ListFeaturesResponse 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.gkehub.v1.ListFeaturesResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.gkehub.v1.ListFeaturesResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.gkehub.v1.ListFeaturesResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.gkehub.v1.ListFeaturesResponse 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.gkehub.v1.ListFeaturesResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.gkehub.v1.ListFeaturesResponse 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.gkehub.v1.ListFeaturesResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.gkehub.v1.ListFeaturesResponse 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.gkehub.v1.ListFeaturesResponse 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 the `GkeHub.ListFeatures` method.
* </pre>
*
* Protobuf type {@code google.cloud.gkehub.v1.ListFeaturesResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.gkehub.v1.ListFeaturesResponse)
com.google.cloud.gkehub.v1.ListFeaturesResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.gkehub.v1.ServiceProto
.internal_static_google_cloud_gkehub_v1_ListFeaturesResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.gkehub.v1.ServiceProto
.internal_static_google_cloud_gkehub_v1_ListFeaturesResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.gkehub.v1.ListFeaturesResponse.class,
com.google.cloud.gkehub.v1.ListFeaturesResponse.Builder.class);
}
// Construct using com.google.cloud.gkehub.v1.ListFeaturesResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (resourcesBuilder_ == null) {
resources_ = java.util.Collections.emptyList();
} else {
resources_ = null;
resourcesBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.gkehub.v1.ServiceProto
.internal_static_google_cloud_gkehub_v1_ListFeaturesResponse_descriptor;
}
@java.lang.Override
public com.google.cloud.gkehub.v1.ListFeaturesResponse getDefaultInstanceForType() {
return com.google.cloud.gkehub.v1.ListFeaturesResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.gkehub.v1.ListFeaturesResponse build() {
com.google.cloud.gkehub.v1.ListFeaturesResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.gkehub.v1.ListFeaturesResponse buildPartial() {
com.google.cloud.gkehub.v1.ListFeaturesResponse result =
new com.google.cloud.gkehub.v1.ListFeaturesResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(
com.google.cloud.gkehub.v1.ListFeaturesResponse result) {
if (resourcesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
resources_ = java.util.Collections.unmodifiableList(resources_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.resources_ = resources_;
} else {
result.resources_ = resourcesBuilder_.build();
}
}
private void buildPartial0(com.google.cloud.gkehub.v1.ListFeaturesResponse 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.gkehub.v1.ListFeaturesResponse) {
return mergeFrom((com.google.cloud.gkehub.v1.ListFeaturesResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.gkehub.v1.ListFeaturesResponse other) {
if (other == com.google.cloud.gkehub.v1.ListFeaturesResponse.getDefaultInstance())
return this;
if (resourcesBuilder_ == null) {
if (!other.resources_.isEmpty()) {
if (resources_.isEmpty()) {
resources_ = other.resources_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureResourcesIsMutable();
resources_.addAll(other.resources_);
}
onChanged();
}
} else {
if (!other.resources_.isEmpty()) {
if (resourcesBuilder_.isEmpty()) {
resourcesBuilder_.dispose();
resourcesBuilder_ = null;
resources_ = other.resources_;
bitField0_ = (bitField0_ & ~0x00000001);
resourcesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getResourcesFieldBuilder()
: null;
} else {
resourcesBuilder_.addAllMessages(other.resources_);
}
}
}
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.gkehub.v1.Feature m =
input.readMessage(
com.google.cloud.gkehub.v1.Feature.parser(), extensionRegistry);
if (resourcesBuilder_ == null) {
ensureResourcesIsMutable();
resources_.add(m);
} else {
resourcesBuilder_.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.gkehub.v1.Feature> resources_ =
java.util.Collections.emptyList();
private void ensureResourcesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
resources_ = new java.util.ArrayList<com.google.cloud.gkehub.v1.Feature>(resources_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.gkehub.v1.Feature,
com.google.cloud.gkehub.v1.Feature.Builder,
com.google.cloud.gkehub.v1.FeatureOrBuilder>
resourcesBuilder_;
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public java.util.List<com.google.cloud.gkehub.v1.Feature> getResourcesList() {
if (resourcesBuilder_ == null) {
return java.util.Collections.unmodifiableList(resources_);
} else {
return resourcesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public int getResourcesCount() {
if (resourcesBuilder_ == null) {
return resources_.size();
} else {
return resourcesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public com.google.cloud.gkehub.v1.Feature getResources(int index) {
if (resourcesBuilder_ == null) {
return resources_.get(index);
} else {
return resourcesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public Builder setResources(int index, com.google.cloud.gkehub.v1.Feature value) {
if (resourcesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureResourcesIsMutable();
resources_.set(index, value);
onChanged();
} else {
resourcesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public Builder setResources(
int index, com.google.cloud.gkehub.v1.Feature.Builder builderForValue) {
if (resourcesBuilder_ == null) {
ensureResourcesIsMutable();
resources_.set(index, builderForValue.build());
onChanged();
} else {
resourcesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public Builder addResources(com.google.cloud.gkehub.v1.Feature value) {
if (resourcesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureResourcesIsMutable();
resources_.add(value);
onChanged();
} else {
resourcesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public Builder addResources(int index, com.google.cloud.gkehub.v1.Feature value) {
if (resourcesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureResourcesIsMutable();
resources_.add(index, value);
onChanged();
} else {
resourcesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public Builder addResources(com.google.cloud.gkehub.v1.Feature.Builder builderForValue) {
if (resourcesBuilder_ == null) {
ensureResourcesIsMutable();
resources_.add(builderForValue.build());
onChanged();
} else {
resourcesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public Builder addResources(
int index, com.google.cloud.gkehub.v1.Feature.Builder builderForValue) {
if (resourcesBuilder_ == null) {
ensureResourcesIsMutable();
resources_.add(index, builderForValue.build());
onChanged();
} else {
resourcesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public Builder addAllResources(
java.lang.Iterable<? extends com.google.cloud.gkehub.v1.Feature> values) {
if (resourcesBuilder_ == null) {
ensureResourcesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, resources_);
onChanged();
} else {
resourcesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public Builder clearResources() {
if (resourcesBuilder_ == null) {
resources_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
resourcesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public Builder removeResources(int index) {
if (resourcesBuilder_ == null) {
ensureResourcesIsMutable();
resources_.remove(index);
onChanged();
} else {
resourcesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public com.google.cloud.gkehub.v1.Feature.Builder getResourcesBuilder(int index) {
return getResourcesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public com.google.cloud.gkehub.v1.FeatureOrBuilder getResourcesOrBuilder(int index) {
if (resourcesBuilder_ == null) {
return resources_.get(index);
} else {
return resourcesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public java.util.List<? extends com.google.cloud.gkehub.v1.FeatureOrBuilder>
getResourcesOrBuilderList() {
if (resourcesBuilder_ != null) {
return resourcesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(resources_);
}
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public com.google.cloud.gkehub.v1.Feature.Builder addResourcesBuilder() {
return getResourcesFieldBuilder()
.addBuilder(com.google.cloud.gkehub.v1.Feature.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public com.google.cloud.gkehub.v1.Feature.Builder addResourcesBuilder(int index) {
return getResourcesFieldBuilder()
.addBuilder(index, com.google.cloud.gkehub.v1.Feature.getDefaultInstance());
}
/**
*
*
* <pre>
* The list of matching Features
* </pre>
*
* <code>repeated .google.cloud.gkehub.v1.Feature resources = 1;</code>
*/
public java.util.List<com.google.cloud.gkehub.v1.Feature.Builder> getResourcesBuilderList() {
return getResourcesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.gkehub.v1.Feature,
com.google.cloud.gkehub.v1.Feature.Builder,
com.google.cloud.gkehub.v1.FeatureOrBuilder>
getResourcesFieldBuilder() {
if (resourcesBuilder_ == null) {
resourcesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.gkehub.v1.Feature,
com.google.cloud.gkehub.v1.Feature.Builder,
com.google.cloud.gkehub.v1.FeatureOrBuilder>(
resources_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
resources_ = null;
}
return resourcesBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* A token to request the next page of resources from the
* `ListFeatures` method. The value of an empty string means
* that there are no more resources to return.
* </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 request the next page of resources from the
* `ListFeatures` method. The value of an empty string means
* that there are no more resources to return.
* </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 request the next page of resources from the
* `ListFeatures` method. The value of an empty string means
* that there are no more resources to return.
* </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 request the next page of resources from the
* `ListFeatures` method. The value of an empty string means
* that there are no more resources to return.
* </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 request the next page of resources from the
* `ListFeatures` method. The value of an empty string means
* that there are no more resources to return.
* </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.gkehub.v1.ListFeaturesResponse)
}
// @@protoc_insertion_point(class_scope:google.cloud.gkehub.v1.ListFeaturesResponse)
private static final com.google.cloud.gkehub.v1.ListFeaturesResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.gkehub.v1.ListFeaturesResponse();
}
public static com.google.cloud.gkehub.v1.ListFeaturesResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListFeaturesResponse> PARSER =
new com.google.protobuf.AbstractParser<ListFeaturesResponse>() {
@java.lang.Override
public ListFeaturesResponse 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<ListFeaturesResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListFeaturesResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.gkehub.v1.ListFeaturesResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
googleapis/sdk-platform-java | 35,629 | java-common-protos/proto-google-common-protos/src/main/java/com/google/longrunning/ListOperationsResponse.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/longrunning/operations.proto
// Protobuf Java Version: 3.25.8
package com.google.longrunning;
/**
*
*
* <pre>
* The response message for
* [Operations.ListOperations][google.longrunning.Operations.ListOperations].
* </pre>
*
* Protobuf type {@code google.longrunning.ListOperationsResponse}
*/
public final class ListOperationsResponse extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.longrunning.ListOperationsResponse)
ListOperationsResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use ListOperationsResponse.newBuilder() to construct.
private ListOperationsResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ListOperationsResponse() {
operations_ = java.util.Collections.emptyList();
nextPageToken_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new ListOperationsResponse();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.longrunning.OperationsProto
.internal_static_google_longrunning_ListOperationsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.longrunning.OperationsProto
.internal_static_google_longrunning_ListOperationsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.longrunning.ListOperationsResponse.class,
com.google.longrunning.ListOperationsResponse.Builder.class);
}
public static final int OPERATIONS_FIELD_NUMBER = 1;
@SuppressWarnings("serial")
private java.util.List<com.google.longrunning.Operation> operations_;
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
@java.lang.Override
public java.util.List<com.google.longrunning.Operation> getOperationsList() {
return operations_;
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.longrunning.OperationOrBuilder>
getOperationsOrBuilderList() {
return operations_;
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
@java.lang.Override
public int getOperationsCount() {
return operations_.size();
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
@java.lang.Override
public com.google.longrunning.Operation getOperations(int index) {
return operations_.get(index);
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
@java.lang.Override
public com.google.longrunning.OperationOrBuilder getOperationsOrBuilder(int index) {
return operations_.get(index);
}
public static final int NEXT_PAGE_TOKEN_FIELD_NUMBER = 2;
@SuppressWarnings("serial")
private volatile java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* The standard List 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 standard List 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 < operations_.size(); i++) {
output.writeMessage(1, operations_.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 < operations_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, operations_.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.longrunning.ListOperationsResponse)) {
return super.equals(obj);
}
com.google.longrunning.ListOperationsResponse other =
(com.google.longrunning.ListOperationsResponse) obj;
if (!getOperationsList().equals(other.getOperationsList())) 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 (getOperationsCount() > 0) {
hash = (37 * hash) + OPERATIONS_FIELD_NUMBER;
hash = (53 * hash) + getOperationsList().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.longrunning.ListOperationsResponse parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.longrunning.ListOperationsResponse parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.longrunning.ListOperationsResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.longrunning.ListOperationsResponse 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.longrunning.ListOperationsResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.longrunning.ListOperationsResponse parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.longrunning.ListOperationsResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.longrunning.ListOperationsResponse 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.longrunning.ListOperationsResponse parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.longrunning.ListOperationsResponse 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.longrunning.ListOperationsResponse parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.longrunning.ListOperationsResponse 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.longrunning.ListOperationsResponse 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 message for
* [Operations.ListOperations][google.longrunning.Operations.ListOperations].
* </pre>
*
* Protobuf type {@code google.longrunning.ListOperationsResponse}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.longrunning.ListOperationsResponse)
com.google.longrunning.ListOperationsResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.longrunning.OperationsProto
.internal_static_google_longrunning_ListOperationsResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.longrunning.OperationsProto
.internal_static_google_longrunning_ListOperationsResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.longrunning.ListOperationsResponse.class,
com.google.longrunning.ListOperationsResponse.Builder.class);
}
// Construct using com.google.longrunning.ListOperationsResponse.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
if (operationsBuilder_ == null) {
operations_ = java.util.Collections.emptyList();
} else {
operations_ = null;
operationsBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
nextPageToken_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.longrunning.OperationsProto
.internal_static_google_longrunning_ListOperationsResponse_descriptor;
}
@java.lang.Override
public com.google.longrunning.ListOperationsResponse getDefaultInstanceForType() {
return com.google.longrunning.ListOperationsResponse.getDefaultInstance();
}
@java.lang.Override
public com.google.longrunning.ListOperationsResponse build() {
com.google.longrunning.ListOperationsResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.longrunning.ListOperationsResponse buildPartial() {
com.google.longrunning.ListOperationsResponse result =
new com.google.longrunning.ListOperationsResponse(this);
buildPartialRepeatedFields(result);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartialRepeatedFields(com.google.longrunning.ListOperationsResponse result) {
if (operationsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
operations_ = java.util.Collections.unmodifiableList(operations_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.operations_ = operations_;
} else {
result.operations_ = operationsBuilder_.build();
}
}
private void buildPartial0(com.google.longrunning.ListOperationsResponse 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.longrunning.ListOperationsResponse) {
return mergeFrom((com.google.longrunning.ListOperationsResponse) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.longrunning.ListOperationsResponse other) {
if (other == com.google.longrunning.ListOperationsResponse.getDefaultInstance()) return this;
if (operationsBuilder_ == null) {
if (!other.operations_.isEmpty()) {
if (operations_.isEmpty()) {
operations_ = other.operations_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureOperationsIsMutable();
operations_.addAll(other.operations_);
}
onChanged();
}
} else {
if (!other.operations_.isEmpty()) {
if (operationsBuilder_.isEmpty()) {
operationsBuilder_.dispose();
operationsBuilder_ = null;
operations_ = other.operations_;
bitField0_ = (bitField0_ & ~0x00000001);
operationsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getOperationsFieldBuilder()
: null;
} else {
operationsBuilder_.addAllMessages(other.operations_);
}
}
}
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.longrunning.Operation m =
input.readMessage(com.google.longrunning.Operation.parser(), extensionRegistry);
if (operationsBuilder_ == null) {
ensureOperationsIsMutable();
operations_.add(m);
} else {
operationsBuilder_.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.longrunning.Operation> operations_ =
java.util.Collections.emptyList();
private void ensureOperationsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
operations_ = new java.util.ArrayList<com.google.longrunning.Operation>(operations_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.longrunning.Operation,
com.google.longrunning.Operation.Builder,
com.google.longrunning.OperationOrBuilder>
operationsBuilder_;
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public java.util.List<com.google.longrunning.Operation> getOperationsList() {
if (operationsBuilder_ == null) {
return java.util.Collections.unmodifiableList(operations_);
} else {
return operationsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public int getOperationsCount() {
if (operationsBuilder_ == null) {
return operations_.size();
} else {
return operationsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public com.google.longrunning.Operation getOperations(int index) {
if (operationsBuilder_ == null) {
return operations_.get(index);
} else {
return operationsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public Builder setOperations(int index, com.google.longrunning.Operation value) {
if (operationsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOperationsIsMutable();
operations_.set(index, value);
onChanged();
} else {
operationsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public Builder setOperations(
int index, com.google.longrunning.Operation.Builder builderForValue) {
if (operationsBuilder_ == null) {
ensureOperationsIsMutable();
operations_.set(index, builderForValue.build());
onChanged();
} else {
operationsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public Builder addOperations(com.google.longrunning.Operation value) {
if (operationsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOperationsIsMutable();
operations_.add(value);
onChanged();
} else {
operationsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public Builder addOperations(int index, com.google.longrunning.Operation value) {
if (operationsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureOperationsIsMutable();
operations_.add(index, value);
onChanged();
} else {
operationsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public Builder addOperations(com.google.longrunning.Operation.Builder builderForValue) {
if (operationsBuilder_ == null) {
ensureOperationsIsMutable();
operations_.add(builderForValue.build());
onChanged();
} else {
operationsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public Builder addOperations(
int index, com.google.longrunning.Operation.Builder builderForValue) {
if (operationsBuilder_ == null) {
ensureOperationsIsMutable();
operations_.add(index, builderForValue.build());
onChanged();
} else {
operationsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public Builder addAllOperations(
java.lang.Iterable<? extends com.google.longrunning.Operation> values) {
if (operationsBuilder_ == null) {
ensureOperationsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, operations_);
onChanged();
} else {
operationsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public Builder clearOperations() {
if (operationsBuilder_ == null) {
operations_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
operationsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public Builder removeOperations(int index) {
if (operationsBuilder_ == null) {
ensureOperationsIsMutable();
operations_.remove(index);
onChanged();
} else {
operationsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public com.google.longrunning.Operation.Builder getOperationsBuilder(int index) {
return getOperationsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public com.google.longrunning.OperationOrBuilder getOperationsOrBuilder(int index) {
if (operationsBuilder_ == null) {
return operations_.get(index);
} else {
return operationsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public java.util.List<? extends com.google.longrunning.OperationOrBuilder>
getOperationsOrBuilderList() {
if (operationsBuilder_ != null) {
return operationsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(operations_);
}
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public com.google.longrunning.Operation.Builder addOperationsBuilder() {
return getOperationsFieldBuilder()
.addBuilder(com.google.longrunning.Operation.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public com.google.longrunning.Operation.Builder addOperationsBuilder(int index) {
return getOperationsFieldBuilder()
.addBuilder(index, com.google.longrunning.Operation.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of operations that matches the specified filter in the request.
* </pre>
*
* <code>repeated .google.longrunning.Operation operations = 1;</code>
*/
public java.util.List<com.google.longrunning.Operation.Builder> getOperationsBuilderList() {
return getOperationsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.longrunning.Operation,
com.google.longrunning.Operation.Builder,
com.google.longrunning.OperationOrBuilder>
getOperationsFieldBuilder() {
if (operationsBuilder_ == null) {
operationsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.longrunning.Operation,
com.google.longrunning.Operation.Builder,
com.google.longrunning.OperationOrBuilder>(
operations_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
operations_ = null;
}
return operationsBuilder_;
}
private java.lang.Object nextPageToken_ = "";
/**
*
*
* <pre>
* The standard List 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 standard List 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 standard List 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 standard List 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 standard List 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.longrunning.ListOperationsResponse)
}
// @@protoc_insertion_point(class_scope:google.longrunning.ListOperationsResponse)
private static final com.google.longrunning.ListOperationsResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.longrunning.ListOperationsResponse();
}
public static com.google.longrunning.ListOperationsResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ListOperationsResponse> PARSER =
new com.google.protobuf.AbstractParser<ListOperationsResponse>() {
@java.lang.Override
public ListOperationsResponse 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<ListOperationsResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ListOperationsResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.longrunning.ListOperationsResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.